auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static void writePolyline(Geometry geometry, SliceOutput output, boolean inGeometryCollection) { requireNonNull(geometry, "polyline is null"); requireNonNull(output, "output is null"); int numParts; int numPoints = geometry.getNumPoints(); switch (geometry.getGeometryType()) { case JTS_MULTI_LINESTRING: numParts = geometry.getNumGeometries(); break; case JTS_LINESTRING: numParts = numPoints > 0 ? 1 : 0; break; default: <START> throw new IllegalArgumentException("Expected Polygon or MultiPolygon, but got " + geometry.getGeometryType()); <END> } if (inGeometryCollection) { output.writeInt(SIZE_OF_INT + SIZE_OF_DOUBLE * 4 + SIZE_OF_INT * 2 + SIZE_OF_INT * numParts + SIZE_OF_DOUBLE * 2 * numPoints); } else { switch (geometry.getGeometryType()) { case JTS_LINESTRING: output.writeByte(GeometryUtils.GeometryTypeName.LINE_STRING.code()); break; case JTS_MULTI_LINESTRING: output.writeByte(GeometryUtils.GeometryTypeName.MULTI_LINE_STRING.code()); break; } } output.writeInt(EsriShapeType.POLYLINE.code); writeEnvelope(geometry.getEnvelopeInternal(), output); output.writeInt(numParts); output.writeInt(numPoints); if (numParts > 0) { output.writeInt(0); for (int i = 0; i < numParts - 1; i++) { output.writeInt(geometry.getGeometryN(i).getNumPoints()); } } writeCoordinates(geometry.getCoordinates(), output); }</code><technical_language>s/Polygon/LineString s/MultiPolygon/MultiLineString</technical_language>

Target:
private static void writePolyline(Geometry geometry, SliceOutput output, boolean inGeometryCollection) { requireNonNull(geometry, "polyline is null"); requireNonNull(output, "output is null"); int numParts; int numPoints = geometry.getNumPoints(); switch (geometry.getGeometryType()) { case JTS_MULTI_LINESTRING: numParts = geometry.getNumGeometries(); break; case JTS_LINESTRING: numParts = numPoints > 0 ? 1 : 0; break; default: throw new IllegalArgumentException("Expected LineString or MultiLineString, but got " + geometry.getGeometryType()); } if (inGeometryCollection) { output.writeInt(SIZE_OF_INT + SIZE_OF_DOUBLE * 4 + SIZE_OF_INT * 2 + SIZE_OF_INT * numParts + SIZE_OF_DOUBLE * 2 * numPoints); } else { switch (geometry.getGeometryType()) { case JTS_LINESTRING: output.writeByte(GeometryUtils.GeometryTypeName.LINE_STRING.code()); break; case JTS_MULTI_LINESTRING: output.writeByte(GeometryUtils.GeometryTypeName.MULTI_LINE_STRING.code()); break; } } output.writeInt(EsriShapeType.POLYLINE.code); writeEnvelope(geometry.getEnvelopeInternal(), output); output.writeInt(numParts); output.writeInt(numPoints); if (numParts > 0) { output.writeInt(0); for (int i = 0; i < numParts - 1; i++) { output.writeInt(geometry.getGeometryN(i).getNumPoints()); } } writeCoordinates(geometry.getCoordinates(), output); }
Source:
<code>private void buildActivationCondition(final PropertyNode node, final PropertyNode origin, final int level) { if (node == null) { return; } node.getProperty().getCondition() .forEach(c -> { final String targetPath = pathResolver.resolvePath(node.getProperty().getPath(), c.getTarget()); if (targetPath != null && !targetPath.isEmpty()) { c.setTargetPath(targetPath); activations.computeIfAbsent(origin.getProperty().getPath(), (key) -> new HashMap<>()); activations.get(origin.getProperty().getPath()).computeIfAbsent(level, (k) -> new ArrayList<>()); activations.get(origin.getProperty().getPath()).get(level).add(c); <START> } <END> }); final int l = level + 1; buildActivationCondition(node.getParent(), origin, l); }</code><technical_language>is ok ignore unresolved parameter silently. is worth log in Debug mode</technical_language>

Target:
private void buildActivationCondition(final PropertyNode node, final PropertyNode origin, final int level) { if (node == null) { return; } node.getProperty().getCondition() .forEach(c -> { final Optional<String> targetPath = pathResolver.resolvePath(node.getProperty().getPath(), c.getTarget()); if (targetPath.isPresent()) { c.setTargetPath(targetPath.get()); activations.computeIfAbsent(origin.getProperty().getPath(), (key) -> new HashMap<>()); activations.get(origin.getProperty().getPath()).computeIfAbsent(level, (k) -> new ArrayList<>()); activations.get(origin.getProperty().getPath()).get(level).add(c); } else { LOGGER.warn("can't find target property '" + c.getTarget() + "' used on property '" + c.getSourcePath() + "'"); } }); final int l = level + 1; buildActivationCondition(node.getParent(), origin, l); }
Source:
<code>private boolean newValueAlreadyExpired(K key, V oldValue, V newValue) { if (newValue == null) { return false; } final Duration duration; if (oldValue == null) { try { Expiry<? super K, ? super V> expiry = runtimeConfiguration.getExpiry(); <START> duration = expiry.getExpiryForCreation(key, newValue); <END> } catch (RuntimeException re) { logger.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); return true; } } else { try { ValueSupplier<V> oldSupplier = supplierOf(oldValue); duration = runtimeConfiguration.getExpiry().getExpiryForUpdate(key, oldSupplier, newValue); } catch (RuntimeException re) { logger.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); return true; } } return Duration.ZERO.equals(duration); }</code><technical_language>reason for this change</technical_language>

Target:
private boolean newValueAlreadyExpired(K key, V oldValue, V newValue) { if (newValue == null) { return false; } final Duration duration; if (oldValue == null) { try { duration = runtimeConfiguration.getExpiry().getExpiryForCreation(key, newValue); } catch (RuntimeException re) { logger.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); return true; } } else { try { duration = runtimeConfiguration.getExpiry().getExpiryForUpdate(key, supplierOf(oldValue), newValue); } catch (RuntimeException re) { logger.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); return true; } } return Duration.ZERO.equals(duration); }
Source:
<code>public void createGame(boolean isHosting, String ipAddress, int port, int players) { logger.info("Creating game"); this.isHost = isHosting; closeNewGameDialog(); if(isHost){ router = Router.getHostRouter(port, players); dialog = new HostGameDialog(view,this); }else{ router = Router.getClientRouter(ipAddress, port); dialog = new JoinGameDialog(view,this); } router.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent changeEvent) { if (changeEvent.getSource().getClass().equals(SevenWondersGame.class)) { handleGameChange(); <START> } else if (changeEvent.getSource().getClass().equals(HumanPlayer.class)){ <END> handlePlayerChange(); } else { handleRouterChange(); } } }); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { dialog.setVisible(true); } }); }</code><technical_language>this instanceof is for</technical_language>

Target:
public void createGame(boolean isHosting, String ipAddress, int port, int players) { logger.info("Creating game"); this.isHost = isHosting; closeNewGameDialog(); if(isHost){ router = Router.getHostRouter(port, players); dialog = new HostGameDialog(view,this); }else{ router = Router.getClientRouter(ipAddress, port); dialog = new JoinGameDialog(view,this); } router.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent changeEvent) { if (changeEvent.getSource() instanceof SevenWondersGame) { handleGameChange(); } else if (changeEvent.getSource() instanceof Player){ handlePlayerChange(); } else if (changeEvent.getSource() instanceof Router){ handleRouterChange(); } else { logger.error("Unknown change source!"); } } }); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { dialog.setVisible(true); } }); }
Source:
<code>public static IValue getValueOfInitializer(IASTInitializer init, IType type) { IASTInitializerClause clause= null; if (init instanceof IASTEqualsInitializer) { clause= ((IASTEqualsInitializer) init).getInitializerClause(); } else if (init instanceof ICPPASTConstructorInitializer) { IASTInitializerClause[] args= ((ICPPASTConstructorInitializer) init).getArguments(); if (args.length == 1 && args[0] instanceof IASTExpression) { IType typeUpToPointers= SemanticUtil.getUltimateTypeUptoPointers(type); if (typeUpToPointers instanceof IPointerType || typeUpToPointers instanceof IBasicType) { clause= args[0]; } } } else if (init instanceof ICPPASTInitializerList) { ICPPASTInitializerList list= (ICPPASTInitializerList) init; switch (list.getSize()) { case 0: return IntegralValue.create(0); case 1: clause= list.getClauses()[0]; break; default: <START> return ((ICPPEvaluationOwner) init).getEvaluation().getValue(clause); <END> } } if (clause instanceof IASTExpression) { return ValueFactory.create((IASTExpression) clause); } if (clause instanceof ICPPASTInitializerList) { return ((ICPPEvaluationOwner) clause).getEvaluation().getValue(clause); } return IntegralValue.UNKNOWN; }</code><technical_language>"clause" is null - "init" instead</technical_language>

Target:
public static IValue getValueOfInitializer(IASTInitializer init, IType type) { IASTInitializerClause clause= null; if (init instanceof IASTEqualsInitializer) { clause= ((IASTEqualsInitializer) init).getInitializerClause(); } else if (init instanceof ICPPASTConstructorInitializer) { IASTInitializerClause[] args= ((ICPPASTConstructorInitializer) init).getArguments(); if (args.length == 1 && args[0] instanceof IASTExpression) { IType typeUpToPointers= SemanticUtil.getUltimateTypeUptoPointers(type); if (typeUpToPointers instanceof IPointerType || typeUpToPointers instanceof IBasicType) { clause= args[0]; } } } else if (init instanceof ICPPASTInitializerList) { ICPPASTInitializerList list= (ICPPASTInitializerList) init; switch (list.getSize()) { case 0: return IntegralValue.create(0); case 1: clause= list.getClauses()[0]; break; default: return ((ICPPEvaluationOwner) init).getEvaluation().getValue(init); } } if (clause instanceof IASTExpression) { return ValueFactory.create((IASTExpression) clause); } if (clause instanceof ICPPASTInitializerList) { return ((ICPPEvaluationOwner) clause).getEvaluation().getValue(clause); } return IntegralValue.UNKNOWN; }
Source:
<code>Page() throws IOException { Document hostDoc = HtmlDomUtil.clone(template); css = injectCssFile(hostDoc, "gerrit_sitecss", site.site_css); header = injectXmlFile(hostDoc, "gerrit_header", site.site_header); footer = injectXmlFile(hostDoc, "gerrit_footer", site.site_footer); final HostPageData pageData = new HostPageData(); final List<String> webUiPluginUrls = new ArrayList<String>(); for (RegisteredWebUiPlugin plugin : webUiPlugins.get()) { webUiPluginUrls.add(plugin.getFullPath()); } <START> pageData.plugnis = webUiPluginUrls.toArray(new String[webUiPluginUrls.size()]); <END> pageData.config = config; final StringWriter w = new StringWriter(); w.write("var " + HPD_ID + "="); json(pageData, w); w.write(";"); final Element data = HtmlDomUtil.find(hostDoc, HPD_ID); asScript(data); data.appendChild(hostDoc.createTextNode(w.toString())); data.appendChild(hostDoc.createComment(HPD_ID)); permutations = new HashMap<Permutation, Content>(); for (Permutation p : selector.getPermutations()) { final Document d = HtmlDomUtil.clone(hostDoc); Element nocache = HtmlDomUtil.find(d, "gerrit_module"); nocache.getParentNode().removeChild(nocache); p.inject(d); permutations.put(p, new Content(d)); } Element nocache = HtmlDomUtil.find(hostDoc, "gerrit_module"); asScript(nocache); nocache.setAttribute("src", noCacheName); permutations.put(null, new Content(hostDoc)); }</code><technical_language>populate data here, early. noticed allow respond changes in plugins dynamically loaded reloaded</technical_language>

Target:
Page() throws IOException { Document hostDoc = HtmlDomUtil.clone(template); css = injectCssFile(hostDoc, "gerrit_sitecss", site.site_css); header = injectXmlFile(hostDoc, "gerrit_header", site.site_header); footer = injectXmlFile(hostDoc, "gerrit_footer", site.site_footer); final HostPageData pageData = new HostPageData(); pageData.plugnisUrls =getPluginUrls(); pageData.config = config; final StringWriter w = new StringWriter(); w.write("var " + HPD_ID + "="); json(pageData, w); w.write(";"); final Element data = HtmlDomUtil.find(hostDoc, HPD_ID); asScript(data); data.appendChild(hostDoc.createTextNode(w.toString())); data.appendChild(hostDoc.createComment(HPD_ID)); permutations = new HashMap<Permutation, Content>(); for (Permutation p : selector.getPermutations()) { final Document d = HtmlDomUtil.clone(hostDoc); Element nocache = HtmlDomUtil.find(d, "gerrit_module"); nocache.getParentNode().removeChild(nocache); p.inject(d); permutations.put(p, new Content(d)); } Element nocache = HtmlDomUtil.find(hostDoc, "gerrit_module"); asScript(nocache); nocache.setAttribute("src", noCacheName); permutations.put(null, new Content(hostDoc)); }
Source:
<code>protected Boolean isForwardAllowed(final TaskInstance task, final IdentityProvider identityProvider) { <START> if (TaskStatus.TASK_STATUS_READY.equals(task.getStatus())) { <END> if (currentUserIsPotentialOwner(identityProvider, task)) { return true; } if (currentUserIsBusinessAdministrator(identityProvider, task)) { return true; } } else if (TaskStatus.TASK_STATUS_IN_PROGRESS.equals(task.getStatus()) || TaskStatus.TASK_STATUS_RESERVED.equals(task.getStatus())) { if (currentUserIsOwner(identityProvider, task)) { return true; } if (currentUserIsBusinessAdministrator(identityProvider, task)) { return true; } } return false; }</code><technical_language>implementation of isForwardAllowed isDelegationAllowed identical. If criteria supposed for both, implement in a single method, diverge in time. Consider introducing private method call (to distinction forwarding delegating a task)</technical_language>

Target:
protected Boolean isForwardAllowed(final TaskInstance task, final IdentityProvider identityProvider) { return isReassignmentAllowed(task, identityProvider); }
Source:
<code>public boolean disableLegacySafetyChecksWarningPotentialDataCorruption() { <START> return !useAsyncLockService(); <END> }</code><technical_language>do want this false default</technical_language>

Target:
public boolean disableLegacySafetyChecksWarningPotentialDataCorruption() { return false; }
Source:
<code>public SimpleSessionFactoryBuilder setTcclLookupPrecedenceBefore() { <START> return onBootstraServiceRegistryBuilder( builder -> builder.applyClassLoader( new TcclLookupPrecedenceClassLoader() ) ); <END> }</code><technical_language>this. implementing classloader change TCCL precedence in Hibernate ORM, is a feature is exposed SPIs org.hibernate.boot.registry.BootstrapServiceRegistryBuilder#applyTcclLookupPrecedence. a fair amount of risk involved in deviating users' environment be: tests end representative. Yes, TcclLookupPrecedence is marked internal, exposed in org.hibernate.boot.registry.BootstrapServiceRegistryBuilder is SPI. in this case implementation type is leaking Hibernate ORM's SPI. problem is in ORM, in code. If want limit usage of TcclLookupPrecedence, advise apply changes this method, give here, calling applyTcclLookupPrecedence( TcclLookupPrecedence.BEFORE ) directly. If Hibernate ORM breaks this SPI, well, fall solution. a big deal, this is test code a compatibility break affect users</technical_language>

Target:
public SimpleSessionFactoryBuilder setTcclLookupPrecedenceBefore() { return onBootstraServiceRegistryBuilder( builder -> builder.applyTcclLookupPrecedence( TcclLookupPrecedence.BEFORE ) ); }
Source:
<code>public String getMessage(FormApiException exception) { if (exception.getType() == FormApiException.Type.UNKNOWN_HOST) { <START> return TranslationHandler.getString(Collect.getInstance(), R.string.unknown_host_error, exception.getServerUrl()) + " " + TranslationHandler.getString(Collect.getInstance(), R.string.report_to_project_lead); <END> } return TranslationHandler.getString(Collect.getInstance(), R.string.report_to_project_lead); }</code><technical_language>I nice for this object in Context a constructor dependency rely Collect.getInstance()</technical_language>

Target:
public String getMessage(FormApiException exception) { switch (exception.getType()) { case UNREACHABLE: return TranslationHandler.getString(context, R.string.unreachable_error, exception.getServerUrl()) + " " + TranslationHandler.getString(context, R.string.report_to_project_lead); case SECURITY_ERROR: return TranslationHandler.getString(context, R.string.security_error, exception.getServerUrl()) + " " + TranslationHandler.getString(context, R.string.report_to_project_lead); default: return TranslationHandler.getString(context, R.string.report_to_project_lead); } }
Source:
<code>private String getClockForPlot(List<WorkloadTaskData> resultData) { <START> String clock = resultData.iterator().next().getClock(); <END> for (ClockTranslatorForPlots cc : ClockTranslatorForPlots.values()) { if (clock.contains(cc.getContent())) return cc.getResult(); } return clock; }</code><technical_language>if result is empty</technical_language>

Target:
private String getClockForPlot(List<WorkloadTaskData> resultData) { String clock = "-"; if (resultData.size() > 0) { clock = resultData.get(0).getClock(); if (clockDictionary != null) { for (String key : clockDictionary.keySet()) { if (clock.contains(key)) { return clockDictionary.get(key); } } } } return clock; }
Source:
<code>public void massUpdateStatisticsForVds(Collection<VdsNetworkStatistics> statistics) { try { <START> List<MapSqlParameterSource> executions = new ArrayList<MapSqlParameterSource>(); <END> for (VdsNetworkStatistics stats : statistics) { executions.add(getCustomMapSqlParameterSource() .addValue("id", stats.getId()) .addValue("rx_drop", stats.getReceiveDropRate()) .addValue("rx_rate", stats.getReceiveRate()) .addValue("tx_drop", stats.getTransmitDropRate()) .addValue("tx_rate", stats.getTransmitRate()) .addValue("iface_status", stats.getStatus()) .addValue("vds_id", stats.getVdsId())); } getCallsHandler().executeStoredProcAsBatch("Updatevds_interface_statistics", executions); } catch (Exception e) { log.error("Can't update Vds Statistics", e); } }</code><technical_language>Initialize statistics.size()</technical_language>

Target:
public void massUpdateStatisticsForVds( Collection<VdsNetworkStatistics> statistics) { List<MapSqlParameterSource> executions = new ArrayList<MapSqlParameterSource>(statistics.size()); for (VdsNetworkStatistics stats : statistics) { executions.add(getCustomMapSqlParameterSource() .addValue("id", stats.getId()) .addValue("rx_drop", stats.getReceiveDropRate()) .addValue("rx_rate", stats.getReceiveRate()) .addValue("tx_drop", stats.getTransmitDropRate()) .addValue("tx_rate", stats.getTransmitRate()) .addValue("iface_status", stats.getStatus()) .addValue("vds_id", stats.getVdsId())); } getCallsHandler().executeStoredProcAsBatch("Updatevds_interface_statistics", executions); }
Source:
<code>public List<String> getDnsDetails(Network network) { List<String> dnsServers = null; Boolean configureDns = Boolean.valueOf(_configDao.getValue(NuageVspManager.NuageVspConfigDns.key())); if (configureDns) { Boolean configureExternalDns = Boolean.valueOf(_configDao.getValue(NuageVspManager.NuageVspDnsExternal.key())); DataCenterVO dc = _dataCenterDao.findById(network.getDataCenterId()); dnsServers = new ArrayList<String>(); if (configureExternalDns) { if (dc.getDns1() != null && dc.getDns1().length() > 0) { dnsServers.add(dc.getDns1()); } if (dc.getDns2() != null && dc.getDns2().length() > 0) { dnsServers.add(dc.getDns2()); } } else { if (dc.getInternalDns1() != null && dc.getInternalDns1().length() > 0) { dnsServers.add(dc.getInternalDns1()); } if (dc.getInternalDns2() != null && dc.getInternalDns2().length() > 0) { dnsServers.add(dc.getInternalDns2()); <START> } <END> } } return dnsServers; }</code><technical_language>com.google.common.base.Strings.isNullOrBlank check if strings blank null in of if conditions above</technical_language>

Target:
public List<String> getDnsDetails(Network network) { Boolean configureDns = Boolean.valueOf(_configDao.getValue(NuageVspManager.NuageVspConfigDns.key())); if (!configureDns) { return Lists.newArrayList(); } Boolean configureExternalDns = Boolean.valueOf(_configDao.getValue(NuageVspManager.NuageVspDnsExternal.key())); DataCenterVO dc = _dataCenterDao.findById(network.getDataCenterId()); List<String> dnsServers = new ArrayList<String>(); if (configureExternalDns) { if (!Strings.isNullOrEmpty(dc.getDns1())) { dnsServers.add(dc.getDns1()); } if (!Strings.isNullOrEmpty(dc.getDns2())) { dnsServers.add(dc.getDns2()); } } else { if (!Strings.isNullOrEmpty(dc.getInternalDns1())) { dnsServers.add(dc.getInternalDns1()); } if (!Strings.isNullOrEmpty(dc.getInternalDns2())) { dnsServers.add(dc.getInternalDns2()); } } return dnsServers; }
Source:
<code>public void close() throws JUnitException { final ExecutorService executor = getPool(); executor.shutdown(); try { executor.awaitTermination(1, TimeUnit.MINUTES); } catch (final InterruptedException ie) { <START> throw new JUnitException("Interrupted while waiting for forked tests to complete; " + ie.getMessage(), <END> ie); } }</code><technical_language>complete due CountDownLatch, they</technical_language>

Target:
public void close() { executorService.shutdown(); Logger logger = LoggerFactory.getLogger(getClass()); try { if (!executorService.awaitTermination(1, TimeUnit.MINUTES)) { logger.warn(() -> "Timed out while waiting for tests to complete."); } } catch (InterruptedException e) { logger.warn(e, () -> "Interrupted while waiting for tests to complete."); Thread.currentThread().interrupt(); } }
Source:
<code>public AtomicObjectFactory(Cache<Object, Object> c, int m) throws InvalidCacheUsageException{ cache = c; maxSize = m; registeredContainers= new LinkedHashMap<ContainerSignature,Container>(){ @Override protected boolean removeEldestEntry(final java.util.Map.Entry<ContainerSignature,Container> eldest) { if(maxSize!=0 && this.size() >= maxSize){ evictionExecutor.submit(new Callable<Void>() { @Override public Void call() throws IOException { try { <START> log.debug("Disposing " + eldest.getValue().toString()); <END> eldest.getValue().dispose(false); } catch (Exception e) { e.printStackTrace(); } return null; } }); return true; } return false; } }; log = LogFactory.getLog(this.getClass()); }</code><technical_language>wrap call a log.isDebugEnabled please, Formatter-enabled methods</technical_language>

Target:
public AtomicObjectFactory(Cache<Object, Object> c, int m) throws InvalidCacheUsageException{ cache = c; maxSize = m; registeredContainers= new LinkedHashMap<ContainerSignature,Container>(){ @Override protected boolean removeEldestEntry(final java.util.Map.Entry<ContainerSignature,Container> eldest) { if(maxSize!=0 && this.size() >= maxSize){ evictionExecutor.submit(new Callable<Void>() { @Override public Void call() throws IOException { try { if (log.isDebugEnabled()) log.debugf("Disposing %s", eldest.getValue().toString()); eldest.getValue().dispose(false); } catch (Exception e) { e.printStackTrace(); } return null; } }); return true; } return false; } }; log = LogFactory.getLog(this.getClass()); }
Source:
<code>public BatchRefUpdate addCommand(ReceiveCommand... cmd) { <START> commands.addAll(Arrays.asList(cmd)); <END> classifiedUpdates = false; return this; }</code><technical_language>addCommand(Arrays.asList(cmd))</technical_language>

Target:
public BatchRefUpdate addCommand(ReceiveCommand... cmd) { return addCommand(Arrays.asList(cmd)); }
Source:
<code>public void testCloseMultipleBlocks() { azureBlobOutputStream.write(bytes, 0, THRESHOLD); azureBlobOutputStream.write(bytes, 0, THRESHOLD); int blockNum = 0; String blockId = String.format("%05d", blockNum); String blockIdEncoded = Base64.getEncoder().encodeToString(blockId.getBytes()); int blockNum1 = 1; String blockId1 = String.format("%05d", blockNum1); String blockIdEncoded1 = Base64.getEncoder().encodeToString(blockId1.getBytes()); PowerMockito.doAnswer(invocation -> { ArrayList<String> blockListArg = (ArrayList<String>) invocation.getArguments()[0]; <START> String blockIdArg = (String) blockListArg.toArray()[0]; String blockIdArg1 = (String) blockListArg.toArray()[1]; Assert.assertEquals(blockIdEncoded, blockIdArg); Assert.assertEquals(blockIdEncoded1, blockIdArg1); <END> Map<String, String> blobMetadata = (Map<String, String>) invocation.getArguments()[2]; Assert.assertEquals(blobMetadata.get(AzureBlobOutputStream.BLOB_RAW_SIZE_BYTES_METADATA), Long.toString(2 * THRESHOLD)); return Mono.just(new SimpleResponse(null, 200, null, null)); }).when(mockBlobAsyncClient).commitBlockListWithResponse(anyList(), any(), any(), any(), any()); azureBlobOutputStream.close(); verify(mockMetrics).updateAzureCommitMetrics(); }</code><technical_language>this replaced Assert.assertEquals(Arrays.asList(blockIdEncoded, blockIdEncoded1), blockListArg)</technical_language>

Target:
public void testCloseMultipleBlocks() { azureBlobOutputStream.write(BYTES, 0, THRESHOLD); azureBlobOutputStream.write(BYTES, 0, THRESHOLD); int blockNum = 0; String blockId = String.format("%05d", blockNum); String blockIdEncoded = Base64.getEncoder().encodeToString(blockId.getBytes()); int blockNum1 = 1; String blockId1 = String.format("%05d", blockNum1); String blockIdEncoded1 = Base64.getEncoder().encodeToString(blockId1.getBytes()); PowerMockito.doAnswer(invocation -> { ArrayList<String> blockListArg = (ArrayList<String>) invocation.getArguments()[0]; Assert.assertEquals(Arrays.asList(blockIdEncoded, blockIdEncoded1), blockListArg); Map<String, String> blobMetadata = (Map<String, String>) invocation.getArguments()[2]; Assert.assertEquals(blobMetadata.get(AzureBlobOutputStream.BLOB_RAW_SIZE_BYTES_METADATA), Long.toString(2 * THRESHOLD)); return Mono.just(new SimpleResponse(null, 200, null, null)); }).when(mockBlobAsyncClient).commitBlockListWithResponse(anyList(), any(), any(), any(), any()); azureBlobOutputStream.close(); verify(mockMetrics).updateAzureCommitMetrics(); }
Source:
<code>public Object apply(ChangeResource rsrc) throws BadRequestException, <START> OrmException, NoSuchChangeException { <END> Map<Account.Id, ReviewerResource> reviewers = Maps.newLinkedHashMap(); ReviewDb db = dbProvider.get(); Change.Id changeId = rsrc.getChange().getId(); for (PatchSetApproval patchSetApproval : db.patchSetApprovals().byChange(changeId)) { Account.Id accountId = patchSetApproval.getAccountId(); if (!reviewers.containsKey(accountId)) { Account account = accountCache.get(accountId).getAccount(); reviewers.put(accountId, resourceFactory.create(rsrc, account)); } } return json.format(reviewers.values()); }</code><technical_language>throw</technical_language>

Target:
public Object apply(ChangeResource rsrc) throws BadRequestException, OrmException { Map<Account.Id, ReviewerResource> reviewers = Maps.newLinkedHashMap(); ReviewDb db = dbProvider.get(); Change.Id changeId = rsrc.getChange().getId(); for (PatchSetApproval patchSetApproval : db.patchSetApprovals().byChange(changeId)) { Account.Id accountId = patchSetApproval.getAccountId(); if (!reviewers.containsKey(accountId)) { Account account = accountCache.get(accountId).getAccount(); reviewers.put(accountId, resourceFactory.create(rsrc, account)); } } return json.format(reviewers.values()); }
Source:
<code>public void testWorkdirIsParent_CreateRepositoryFromGitDirOnlyWithBareConfigFalse() throws Exception { File gitDir = getFile("workdir", "repoWithBareConfigTrue", "child"); <START> Repository repo = new Repository(gitDir, null); <END> repo.getConfig().setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_BARE, false); repo.getConfig().save(); repo = new Repository(gitDir, null); String workdir = repo.getWorkDir().getName(); assertEquals("repoWithBareConfigTrue", workdir); }</code><technical_language>I a couple of helper methods tests easier read: private void setBare(File gitDir, boolean bare) { Repository repo = new Repository(gitDir, null); repo.getConfig().setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_BARE, bare); repo.getConfig().save(); } private void setWorkTree(File gitDir, File workTree) { Repository repo = new Repository(gitDir, null); repo.getConfig().setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_WORKTREE, workTree.getAbsolutePath()); repo.getConfig().save(); } tests a bit more declarative setup condition tested</technical_language>

Target:
public void testWorkdirIsParent_CreateRepositoryFromGitDirOnlyWithBareConfigFalse() throws Exception { File gitDir = getFile("workdir", "repoWithBareConfigTrue", "child"); setBare(gitDir, false); Repository repo = new Repository(gitDir, null); assertWorkdirPath(repo, "workdir", "repoWithBareConfigTrue"); }
Source:
<code>static void initialize(String rootPath, PageStoreType storeType) throws IOException { Path storePath = Paths.get(rootPath, storeType.name()); <START> Files.createDirectories(storePath); <END> LOG.info("Clean cache directory {}", rootPath); try (Stream<Path> stream = Files.list(Paths.get(rootPath))) { stream.filter(path -> !storePath.equals(path)) .map(Path::toString) .map(File::new) .forEach(FileUtils::deleteQuietly); } }</code><technical_language>correct throw IOE failed create storePath. However, throw IOE if failed clean other dirs</technical_language>

Target:
static void initialize(String rootPath, PageStoreType storeType) throws IOException { Path storePath = getStorePath(storeType, rootPath); Files.createDirectories(storePath); LOG.info("Clean cache directory {}", rootPath); try (Stream<Path> stream = Files.list(Paths.get(rootPath))) { stream.filter(path -> !storePath.equals(path)) .forEach(path -> { try { FileUtils.deletePathRecursively(path.toString()); } catch (IOException e) { LOG.warn("failed to delete in cache directory: {}", path, e.toString()); } }); } }
Source:
<code>private RouterConfig createRouterConfig(boolean crossColoEnabled, int successTarget, int parallelism, int maxInflightNum, String customPercentiles, boolean excludeTimeout) { Properties props = new Properties(); props.setProperty("router.hostname", "localhost"); props.setProperty("router.datacenter.name", localDcName); props.setProperty("router.get.cross.dc.enabled", Boolean.toString(crossColoEnabled)); props.setProperty("router.get.success.target", Integer.toString(successTarget)); props.setProperty("router.get.request.parallelism", Integer.toString(parallelism)); props.setProperty("router.get.include.non.originating.dc.replicas", "true"); props.setProperty("router.get.replicas.required", Integer.toString(Integer.MAX_VALUE)); props.setProperty("router.latency.tolerance.quantile", Double.toString(QUANTILE)); props.setProperty("router.operation.tracker.metric.scope", trackerScope.toString()); <START> props.setProperty("router.adaptive.tracker.max.inflight.requests", Integer.toString(maxInflightNum)); <END> props.setProperty("router.operation.tracker.exclude.timeout.enabled", Boolean.toString(excludeTimeout)); if (customPercentiles != null) { props.setProperty("router.operation.tracker.custom.percentiles", customPercentiles); } return new RouterConfig(new VerifiableProperties(props)); }</code><technical_language>change changing config key</technical_language>

Target:
private RouterConfig createRouterConfig(boolean crossColoEnabled, int successTarget, int parallelism, int maxInflightNum, String customPercentiles, boolean excludeTimeout) { Properties props = new Properties(); props.setProperty("router.hostname", "localhost"); props.setProperty("router.datacenter.name", localDcName); props.setProperty("router.get.cross.dc.enabled", Boolean.toString(crossColoEnabled)); props.setProperty("router.get.success.target", Integer.toString(successTarget)); props.setProperty("router.get.request.parallelism", Integer.toString(parallelism)); props.setProperty("router.get.include.non.originating.dc.replicas", "true"); props.setProperty("router.get.replicas.required", Integer.toString(Integer.MAX_VALUE)); props.setProperty("router.latency.tolerance.quantile", Double.toString(QUANTILE)); props.setProperty("router.operation.tracker.metric.scope", trackerScope.toString()); props.setProperty("router.operation.tracker.max.inflight.requests", Integer.toString(maxInflightNum)); props.setProperty("router.operation.tracker.exclude.timeout.enabled", Boolean.toString(excludeTimeout)); if (customPercentiles != null) { props.setProperty("router.operation.tracker.custom.percentiles", customPercentiles); } return new RouterConfig(new VerifiableProperties(props)); }
Source:
<code>public boolean configure(final StaplerRequest req, final JSONObject formData) throws FormException { this.setApiKey(formData.getString("apiKey")); this.setHostname(formData.getString("hostname")); this.setBlacklist(formData.getString("blacklist")); this.setWhitelist(formData.getString("whitelist")); if ( formData.getString("tagNode").equals("true") ) { this.setTagNode(true); } else { this.setTagNode(false); } <START> if ( formData.getString("jobRegex").equals("true") ) { <END> this.setJobRegex(true); } else { this.setJobRegex(false); } daemonHost = formData.getString("daemonHost"); if (client != null) { try { client.stop(); String hp = daemonHost.split(":")[0]; int pp = Integer.parseInt(daemonHost.split(":")[1]); client = new NonBlockingStatsDClient("jenkins.job", hp, pp); logger.finer(String.format("Created new DogStatsD client (%s:%S)!", hp, pp)); } catch (Exception e) { logger.severe(String.format("Unable to create new StatsDClient. Exception: %s", e.toString())); } } targetMetricURL = formData.getString("targetMetricURL"); save(); return super.configure(req, formData); }</code><technical_language>in case is a null, do "true".equals(formData.getString("jobRegex"))</technical_language>

Target:
public boolean configure(final StaplerRequest req, final JSONObject formData) throws FormException { this.setApiKey(formData.getString("apiKey")); this.setHostname(formData.getString("hostname")); this.setBlacklist(formData.getString("blacklist")); this.setWhitelist(formData.getString("whitelist")); this.setGlobalJobTags(formData.getString("globalJobTags")); if ( formData.getString("tagNode").equals("true") ) { this.setTagNode(true); } else { this.setTagNode(false); } daemonHost = formData.getString("daemonHost"); if (client != null) { try { client.stop(); String hp = daemonHost.split(":")[0]; int pp = Integer.parseInt(daemonHost.split(":")[1]); client = new NonBlockingStatsDClient("jenkins.job", hp, pp); logger.finer(String.format("Created new DogStatsD client (%s:%S)!", hp, pp)); } catch (Exception e) { logger.severe(String.format("Unable to create new StatsDClient. Exception: %s", e.toString())); } } targetMetricURL = formData.getString("targetMetricURL"); save(); return super.configure(req, formData); }
Source:
<code>public void testHdfsUri() throws Exception { URI expected; <START> if (hdfsHost != null) { <END> expected = URI.create("repo:hdfs://" + hdfsHost + ":" + hdfsPort + "/datasets/ns"); } else { expected = URI.create("repo:file:/datasets/ns"); } URI actual = command.getLegacyRepoUri( URI.create("dataset:hdfs:/datasets/ns/events"), "ns"); Assert.assertEquals("Unexpected repository URI", expected, actual); }</code><technical_language>hdfsHost set? mini cluster config</technical_language>

Target:
public void testHdfsUri() throws Exception { Assume.assumeTrue(hdfsIsDefault); URI expected = URI.create("repo:hdfs://" + hdfsHost + ":" + hdfsPort + "/datasets/ns"); URI actual = command.getLegacyRepoUri( URI.create("dataset:hdfs:/datasets/ns/events"), "ns"); Assert.assertEquals("Unexpected repository URI", expected, actual); }
Source:
<code>public IInputOrder getInputOrder(String path) { for (InputOrder io : getInputOrderList()) { String ioPath = (new <START> Path(io.getPath())).toOSString(); <END> if (path.compareToIgnoreCase(ioPath) == 0) { return io; } } return null; }</code><technical_language>Guy, missed question patch? copied here: "Why toOSString? familiar this code I called in CDT code. path parameter os separators? sounds this host dependent. thinking of a case host is Windows toolchain works remotely Linux."</technical_language>

Target:
public IInputOrder getInputOrder(String path) { for (InputOrder io : getInputOrderList()) { if (path.compareToIgnoreCase(io.getPath()) == 0) { return io; } } return null; }
Source:
<code>private void launchTcpSlaveAgentListener() throws IOException { if(tcpSlaveAgentListener != null && tcpSlaveAgentListener.configuredPort!=slaveAgentPort) { tcpSlaveAgentListener.shutdown(); tcpSlaveAgentListener = null; } if(slaveAgentPort!=-1 && tcpSlaveAgentListener == null) { String administrativeMonitorId = getClass().getName()+".tcpBind"; try { tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); AdministrativeMonitor previousMonitor = null; for(AdministrativeMonitor am : AdministrativeMonitor.all()) { if (administrativeMonitorId.equals(am.id)) { previousMonitor = am; break; } } if (previousMonitor != null) { <START> AdministrativeMonitor.all().remove(previousMonitor); <END> } } catch (BindException e) { new AdministrativeError(administrativeMonitorId, "Failed to listen to incoming slave connection", "Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.",e); } } }</code><technical_language>If move remove loop need previousMonitor variable monitors conflicting ID time (in scenario ware several)</technical_language>

Target:
private void launchTcpSlaveAgentListener() throws IOException { synchronized(tcpSlaveAgentListenerLock) { if (tcpSlaveAgentListener != null && tcpSlaveAgentListener.configuredPort != slaveAgentPort) { tcpSlaveAgentListener.shutdown(); tcpSlaveAgentListener = null; } if (slaveAgentPort != -1 && tcpSlaveAgentListener == null) { String administrativeMonitorId = getClass().getName() + ".tcpBind"; try { tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); for (Iterator<AdministrativeMonitor> it = AdministrativeMonitor.all().iterator(); it.hasNext(); ) { AdministrativeMonitor am = it.next(); if (administrativeMonitorId.equals(am.id)) { it.remove(); } } } catch (BindException e) { new AdministrativeError(administrativeMonitorId, "Failed to listen to incoming slave connection", "Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.", e); } } } }
Source:
<code>private void initializeAdminsAndAddCluster() { clusterName = staticClusterMap.partitionLayout.getClusterName(); for (Map.Entry<String, String> entry : dataCenterToZkAddress.entrySet()) { ZKHelixAdmin admin = new ZKHelixAdmin(entry.getValue()); adminForDc.put(entry.getKey(), admin); if (!admin.getClusters().contains(clusterName)) { admin.addCluster(clusterName); admin.addStateModelDef(clusterName, "LeaderStandby", <START> BuiltInStateModelDefinitions.LeaderStandby.getStateModelDefinition()); <END> } } }</code><technical_language>do is diff this call LeaderStandbySMD.build()</technical_language>

Target:
private void initializeAdminsAndAddCluster() { for (Map.Entry<String, String> entry : dataCenterToZkAddress.entrySet()) { ZKHelixAdmin admin = new ZKHelixAdmin(entry.getValue()); adminForDc.put(entry.getKey(), admin); if (!admin.getClusters().contains(clusterName)) { admin.addCluster(clusterName); admin.addStateModelDef(clusterName, LeaderStandbySMD.name, LeaderStandbySMD.build()); } } }
Source:
<code>public void testSerDe() throws Exception { SslConfiguration serialized = SslConfiguration.builder() .trustStorePath(Paths.get("/truststore.jks")) .trustStoreType(SslConfiguration.StoreType.JKS) .keyStorePath(Paths.get("/keystore.jks")) .keyStoreType(SslConfiguration.StoreType.JKS) .keyStoreKeyAlias("alias") .keyStorePassword("password") .build(); <START> String deserializedCamelCase = "{\"trustStorePath\":\"file:/ END> + "\"keyStorePath\":\"file:/ + "\"keyStoreType\":\"JKS\",\"keyStoreKeyAlias\":\"alias\"}"; String deserializedKebabCase = "{\"trust-store-path\":\"file:/ + "\"key-store-path\":\"file:/ + "\"key-store-type\":\"JKS\",\"key-store-key-alias\":\"alias\"}"; assertThat(ObjectMappers.newClientObjectMapper().writeValueAsString(serialized)) .isEqualTo(deserializedCamelCase); assertThat(ObjectMappers.newClientObjectMapper().readValue(deserializedCamelCase, SslConfiguration.class)) .isEqualTo(serialized); assertThat(ObjectMappers.newClientObjectMapper().readValue(deserializedKebabCase, SslConfiguration.class)) .isEqualTo(serialized); }</code><technical_language>jackson versions deserialize this? (asking some services (SMM?) SslConfiguration class wire, I believe)</technical_language>

Target:
public void testSerDe() throws Exception { SslConfiguration serialized = SslConfiguration.builder() .trustStorePath(Paths.get("truststore.jks")) .trustStoreType(SslConfiguration.StoreType.JKS) .keyStorePath(Paths.get("keystore.jks")) .keyStoreType(SslConfiguration.StoreType.JKS) .keyStoreKeyAlias("alias") .keyStorePassword("password") .build(); String deserializedCamelCase = "{\"trustStorePath\":\"truststore.jks\",\"trustStoreType\":\"JKS\"," + "\"keyStorePath\":\"keystore.jks\",\"keyStorePassword\":\"password\"," + "\"keyStoreType\":\"JKS\",\"keyStoreKeyAlias\":\"alias\"}"; String deserializedKebabCase = "{\"trust-store-path\":\"truststore.jks\",\"trust-store-type\":\"JKS\"," + "\"key-store-path\":\"keystore.jks\",\"key-store-password\":\"password\"," + "\"key-store-type\":\"JKS\",\"key-store-key-alias\":\"alias\"}"; assertThat(ObjectMappers.newClientObjectMapper().writeValueAsString(serialized)) .isEqualTo(deserializedCamelCase); assertThat(ObjectMappers.newClientObjectMapper().readValue(deserializedCamelCase, SslConfiguration.class)) .isEqualTo(serialized); assertThat(ObjectMappers.newClientObjectMapper().readValue(deserializedKebabCase, SslConfiguration.class)) .isEqualTo(serialized); }
Source:
<code>public Builder parseAnnotationQuery(@Nullable String annotationQuery) { if (annotationQuery == null || annotationQuery.isEmpty()) return this; Map<String, String> map = new LinkedHashMap<>(); for (String ann : annotationQuery.split(" and ", 100)) { int idx = ann.indexOf('='); if (idx == -1) { <START> map.putIfAbsent(ann.trim(), ""); <END> } else { String[] keyValue = ann.split("=", 2); map.put(ann.substring(0, idx).trim(), keyValue.length < 2 ? "" : ann.substring(idx + 1).trim()); } } return annotationQuery(map); }</code><technical_language>this is a JDK 1.8 function failing this type is in core library. suggestion ann = ann.trim(); if (!map.containsKey(ann)) map.put(ann, "");</technical_language>

Target:
public Builder parseAnnotationQuery(@Nullable String annotationQuery) { if (annotationQuery == null || annotationQuery.isEmpty()) return this; Map<String, String> map = new LinkedHashMap<>(); for (String ann : annotationQuery.split(" and ", 100)) { int idx = ann.indexOf('='); if (idx == -1) { ann = ann.trim(); if (!map.containsKey(ann)) map.put(ann, ""); } else { String[] keyValue = ann.split("=", 2); map.put(ann.substring(0, idx).trim(), keyValue.length < 2 ? "" : ann.substring(idx + 1).trim()); } } return annotationQuery(map); }
Source:
<code>private int getContainersFromPreviousAttempts(final RegisterApplicationMasterResponse registerApplicationMasterResponse) { final List<Container> containersFromPreviousAttempts = registerApplicationMasterResponseReflector.getContainersFromPreviousAttempts(registerApplicationMasterResponse); final List<YarnWorkerNode> recoveredWorkers = new ArrayList<>(); log.info("Recovered containers from previous attempts ({}).", containersFromPreviousAttempts.size(), containersFromPreviousAttempts); int maxPriority = 0; for (Container container : containersFromPreviousAttempts) { final YarnWorkerNode worker = new YarnWorkerNode(container, getContainerResourceId(container)); recoveredWorkers.add(worker); <START> maxPriority = Math.max(container.getPriority().getPriority(), maxPriority); <END> } getResourceEventHandler().onPreviousAttemptWorkersRecovered(recoveredWorkers); return maxPriority; }</code><technical_language>I guess is easy calculate TaskExecutorProcessSpec a Container restore priority TaskExecutorProcessSpec mapping</technical_language>

Target:
private void getContainersFromPreviousAttempts(final RegisterApplicationMasterResponse registerApplicationMasterResponse) { final List<Container> containersFromPreviousAttempts = registerApplicationMasterResponseReflector.getContainersFromPreviousAttempts(registerApplicationMasterResponse); final List<YarnWorkerNode> recoveredWorkers = new ArrayList<>(); log.info("Recovered containers from previous attempts ({}).", containersFromPreviousAttempts.size(), containersFromPreviousAttempts); for (Container container : containersFromPreviousAttempts) { final YarnWorkerNode worker = new YarnWorkerNode(container, getContainerResourceId(container)); recoveredWorkers.add(worker); } getResourceEventHandler().onPreviousAttemptWorkersRecovered(recoveredWorkers); }
Source:
<code>static BluetoothSocket tryConnect(BtHRBase base, final BluetoothDevice device, int i) throws IOException { BluetoothSocket sock = null; base.log("tryConnect(method: " + i + ")"); switch (i) { case 0: sock = device.createRfcommSocketToServiceRecord(MY_UUID); break; case 1: sock = device.createInsecureRfcommSocketToServiceRecord(MY_UUID); break; case 2: { Method m; try { m = device.getClass().getMethod("createInsecureRfcommSocket", <START> int.class); <END> m.setAccessible(true); sock = (BluetoothSocket) m.invoke(device, 1); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } if (sock == null) { throw new IOException("Create socket failed!"); } try { sock.connect(); return sock; } catch (IOException ex) { base.log("closeSocket"); closeSocket(sock); throw ex; } }</code><technical_language>this is is ? before: array element a int.class after: int.class</technical_language>

Target:
private static BluetoothSocket tryConnect(BtHRBase base, final BluetoothDevice device, int i) throws IOException { BluetoothSocket sock = null; base.log("tryConnect(method: " + i + ")"); switch (i) { case 0: sock = device.createRfcommSocketToServiceRecord(MY_UUID); break; case 1: sock = device.createInsecureRfcommSocketToServiceRecord(MY_UUID); break; case 2: { Method m; try { m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[]{ int.class }); m.setAccessible(true); sock = (BluetoothSocket) m.invoke(device, 1); } catch (NoSuchMethodException | IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { e.printStackTrace(); } } } if (sock == null) { throw new IOException("Create socket failed!"); } try { sock.connect(); return sock; } catch (IOException ex) { base.log("closeSocket"); closeSocket(sock); throw ex; } }
Source:
<code>public static Properties loadProperties(Class<?> clazz, String resource) throws IOException{ try(Reader is = new InputStreamReader(clazz.getResourceAsStream(resource), "UTF-8")) { Properties prop = new Properties(); prop.load(is); return prop; } catch (IOException e) { throw new IOException( String.format("An error occurred while reading properties file: '%1$s'", resource) <START> ); <END> } }</code><technical_language>io exception get good enough, no? anyway, please include exception rethrowing</technical_language>

Target:
public static Properties loadProperties(Class<?> clazz, String resource) throws IOException { Reader is = new InputStreamReader(clazz.getResourceAsStream(resource), "UTF-8"); Properties prop = new Properties(); prop.load(is); return prop; }