auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testDebugDraw() { drawable.debugDraw(graphicsContext, collisionArea); Mockito.verify(graphicsContext).fillText("angle: 42.0", 69D, 1003D); Mockito.verify(graphicsContext).fillText("size: 33.0", 69D, 988D); Mockito.verify(graphicsContext).fillOval(0, 0, 1, 1); Mockito.verify(graphicsContext).fillOval(100, 100, 1, 1); Mockito.verify(graphicsContext).fillOval(200, 200, 1, 1); Mockito.verify(graphicsContext).fillOval(69D, 1024D, 2, 2); Mockito.verify(graphicsContext).fillOval(1D, 1D, 2, 2); Mockito.verify(graphicsContext).fillOval(2D, 2D, 2, 2); Mockito.verify(graphicsContext).fillOval(3D, 3D, 2, 2); Mockito.verify(graphicsContext).fillOval(4D, 4D, 2, 2); }

Target:
public void testDebugDraw() { drawable.debugDraw(graphicsContext, collisionArea); verify(graphicsContext).fillText("angle: 42.0", 69D, 1003D); verify(graphicsContext).fillText("size: 33.0", 69D, 988D); verify(graphicsContext).fillOval(0, 0, 1, 1); verify(graphicsContext).fillOval(100, 100, 1, 1); verify(graphicsContext).fillOval(200, 200, 1, 1); verify(graphicsContext).fillOval(69D, 1024D, 2, 2); verify(graphicsContext).fillOval(1D, 1D, 2, 2); verify(graphicsContext).fillOval(2D, 2D, 2, 2); verify(graphicsContext).fillOval(3D, 3D, 2, 2); verify(graphicsContext).fillOval(4D, 4D, 2, 2); }
Source:
public boolean install(Resource r, ResourceLocation location, Reference ref, ResourceTable table, AndroidCommCarePlatform platform, boolean upgrade) throws UnresolvedResourceException, UnfullfilledRequirementsException { super.install(r, location, ref, table, platform, upgrade); try { Reference local = ReferenceManager.instance().DeriveReference(localLocation); ProfileParser parser = new ProfileParser(local.getStream(), platform, table, r.getRecordGuid(), Resource.RESOURCE_STATUS_UNINITIALIZED, false); Profile p = parser.parse(); if (!upgrade) { initProperties(p); checkDuplicate(p); } checkAppTarget(); table.commitCompoundResource(r, upgrade ? Resource.RESOURCE_STATUS_UPGRADE : Resource.RESOURCE_STATUS_INSTALLED, p.getVersion()); return true; } catch (XmlPullParserException | InvalidReferenceException | IOException e) { e.printStackTrace(); } catch (InvalidStructureException e) { throw new UnresolvedResourceException(r, "Invalid content in the Profile Definition: " + e.getMessage(), true); } return false; }

Target:
public boolean install(Resource r, ResourceLocation location, Reference ref, ResourceTable table, AndroidCommCarePlatform platform, boolean upgrade) throws UnresolvedResourceException, UnfullfilledRequirementsException { super.install(r, location, ref, table, platform, upgrade); try { Reference local = ReferenceManager.instance().DeriveReference(localLocation); ProfileParser parser = new ProfileParser(local.getStream(), platform, table, r.getRecordGuid(), Resource.RESOURCE_STATUS_UNINITIALIZED, false); Profile p = parser.parse(); if (!upgrade) { initProperties(p); checkDuplicate(p); checkAppTarget(); } table.commitCompoundResource(r, upgrade ? Resource.RESOURCE_STATUS_UPGRADE : Resource.RESOURCE_STATUS_INSTALLED, p.getVersion()); return true; } catch (XmlPullParserException | InvalidReferenceException | IOException e) { e.printStackTrace(); } catch (InvalidStructureException e) { throw new UnresolvedResourceException(r, "Invalid content in the Profile Definition: " + e.getMessage(), true); } return false; }
Source:
public AsyncRabbitTemplate(ConnectionFactory connectionFactory, String exchange, String routingKey) { Assert.notNull(connectionFactory, "'connectionFactory' cannot be null"); Assert.notNull(routingKey, "'routingKey' cannot be null"); this.template = new RabbitTemplate(connectionFactory); this.template.setExchange(exchange == null ? "" : exchange); this.template.setRoutingKey(routingKey); this.container = null; this.replyAddress = null; this.directReplyToContainer = new DirectReplyToMessageListenerContainer(this.template.getConnectionFactory()); this.directReplyToContainer.setQueueNames(Address.AMQ_RABBITMQ_REPLY_TO); this.directReplyToContainer.setChannelAwareMessageListener(this); }

Target:
public AsyncRabbitTemplate(ConnectionFactory connectionFactory, String exchange, String routingKey) { Assert.notNull(connectionFactory, "'connectionFactory' cannot be null"); Assert.notNull(routingKey, "'routingKey' cannot be null"); this.template = new RabbitTemplate(connectionFactory); this.template.setExchange(exchange == null ? "" : exchange); this.template.setRoutingKey(routingKey); this.container = null; this.replyAddress = null; this.directReplyToContainer = new DirectReplyToMessageListenerContainer(this.template.getConnectionFactory()); this.directReplyToContainer.setChannelAwareMessageListener(this); }
Source:
public void onMediaUploadFailed(final String mediaId, final String errorMessage) { mWebView.post(new Runnable() { @Override public void run() { mWebView.execJavaScriptFromString("ZSSEditor.markImageUploadFailed(" + mediaId + ", '" + errorMessage + "');"); mFailedMediaIds.add(mediaId); mUploadingMediaIds.remove(mediaId); } }); }

Target:
public void onMediaUploadFailed(final String mediaId, final String errorMessage) { mWebView.post(new Runnable() { @Override public void run() { mWebView.execJavaScriptFromString("ZSSEditor.markImageUploadFailed(" + mediaId + ", '" + errorMessage.replace("'", "\\'").replace("\"", "\\\"") + "');"); mFailedMediaIds.add(mediaId); mUploadingMediaIds.remove(mediaId); } }); }
Source:
public void put(String orcid, OrcidProfile orcidProfile) { try { profileCache.acquireWriteLockOnKey(orcid); profileCache.put(new Element(new OrcidCacheKey(orcid, releaseName), orcidProfile)); } finally { profileCache.releaseWriteLockOnKey(orcid); } }

Target:
public void put(String orcid, OrcidProfile orcidProfile) { Object key = new OrcidCacheKey(orcid, releaseName); try { profileCache.acquireWriteLockOnKey(key); profileCache.put(new Element(key, orcidProfile)); } finally { profileCache.releaseWriteLockOnKey(key); } }
Source:
public synchronized void start() { if (scanDirectoriesFuture == null) { scanDirectoriesFuture = scheduler.scheduleAtFixedRate(() -> { if (scanningNow) { reentered.inc(); return; } scanningNow = true; if (configurationFile != null && configurationFile.exists() && configurationFile.lastModified() > configurationLastRead.getEpochSecond()) { readConfiguration(); } scanLastStarted = Instant.now(); UnreadableDirectories unreadableDirectories = new UnreadableDirectories(); try (StreamCountSpy<Pair<File, Configuration>> newRuns = new StreamCountSpy<>(newRunsScanned); StreamCountSpy<Pair<File, Configuration>> attempted = new StreamCountSpy<>(attemptedDirectories); StreamCountSpy<Pair<File, Configuration>> accepted = new StreamCountSpy<>(acceptedDirectories); AutoCloseable timer = scanTime.start()) { roots.stream() .filter(Configuration::isValid) .flatMap(Configuration::getRuns) .peek(attempted) .filter(entry -> unreadableDirectories.test(entry.getKey())) .peek(accepted) .filter(entry -> isUnprocessed(entry.getKey())) .peek(newRuns) .forEach(entry -> { queueDirectory(entry.getKey(), entry.getValue().getProcessor(), entry.getValue().getTimeZone()); }); } catch (Exception e) { log.error("Error scanning directory.", e); } this.unreadableDirectories = unreadableDirectories; scanningNow = false; }, 1, 15, TimeUnit.MINUTES); } }

Target:
public synchronized void start() { if (scanDirectoriesFuture == null) { scanDirectoriesFuture = scheduler.scheduleAtFixedRate(() -> { if (scanningNow) { reentered.inc(); return; } scanningNow = true; if (configurationFile != null && configurationFile.exists() && configurationFile.lastModified() > configurationLastRead.getEpochSecond()) { readConfiguration(); } scanLastStarted = Instant.now(); UnreadableDirectories newUnreadableDirectories = new UnreadableDirectories(); try (StreamCountSpy<Pair<File, Configuration>> newRuns = new StreamCountSpy<>(newRunsScanned); StreamCountSpy<Pair<File, Configuration>> attempted = new StreamCountSpy<>(attemptedDirectories); StreamCountSpy<Pair<File, Configuration>> accepted = new StreamCountSpy<>(acceptedDirectories); AutoCloseable timer = scanTime.start()) { roots.stream() .filter(Configuration::isValid) .flatMap(Configuration::getRuns) .peek(attempted) .filter(entry -> newUnreadableDirectories.test(entry.getKey())) .peek(accepted) .filter(entry -> isUnprocessed(entry.getKey())) .peek(newRuns) .forEach(entry -> { queueDirectory(entry.getKey(), entry.getValue().getProcessor(), entry.getValue().getTimeZone()); }); } catch (Exception e) { log.error("Error scanning directory.", e); } unreadableDirectories = newUnreadableDirectories; scanningNow = false; }, 1, 15, TimeUnit.MINUTES); } }
Source:
public void testRebind() throws Exception { origApp.createAndManageChild(EntitySpec.create(PostgreSqlNode.class) .configure("mongodbConfTemplateUrl", "classpath:/ origApp.start(ImmutableList.of(loc)); rebind(); final PostgreSqlNode newEntity = (PostgreSqlNode) Iterables.find(newApp.getChildren(), Predicates.instanceOf(PostgreSqlNode.class)); EntityTestUtils.assertAttributeEqualsEventually(newEntity, PostgreSqlNode.SERVICE_UP, true); newEntity.stop(); EntityTestUtils.assertAttributeEqualsEventually(newEntity, PostgreSqlNode.SERVICE_UP, false); }

Target:
public void testRebind() throws Exception { origApp.createAndManageChild(EntitySpec.create(PostgreSqlNode.class)); origApp.start(ImmutableList.of(loc)); rebind(); final PostgreSqlNode newEntity = (PostgreSqlNode) Iterables.find(newApp.getChildren(), Predicates.instanceOf(PostgreSqlNode.class)); EntityTestUtils.assertAttributeEqualsEventually(newEntity, PostgreSqlNode.SERVICE_UP, true); newEntity.stop(); EntityTestUtils.assertAttributeEqualsEventually(newEntity, PostgreSqlNode.SERVICE_UP, false); }
Source:
protected void assertSiteUrlBase(Map<String, Object> row) { throw new UnsupportedOperationException("Not supported yet."); }

Target:
protected void assertSiteUrlBase(Map<String, Object> row) { assertUrl(OrganizationColumn.KEY_ORGANIZATION_SUMMARY_WQP_URL, row); }
Source:
private String createBookmarkReport(IMarker[] markers) { StringBuilder report = new StringBuilder(); report.append(BookmarkMessages.ColumnDescription_header + '\t'); report.append(BookmarkMessages.ColumnResource_header + '\t'); report.append(BookmarkMessages.ColumnFolder_header + '\t'); report.append(BookmarkMessages.ColumnLocation_header); report.append(System.getProperty("line.separator")); for (IMarker marker : markers) { report.append(MarkerUtil.getMessage(marker) + '\t'); report.append(MarkerUtil.getResourceName(marker) + '\t'); report.append(MarkerUtil.getContainerName(marker) + '\t'); int line = MarkerUtil.getLineNumber(marker); report.append(NLS.bind(BookmarkMessages.LineIndicator_text, String.valueOf(line))); report.append(System.getProperty("line.separator")); } return report.toString(); }

Target:
private String createBookmarkReport(IMarker[] markers) { StringBuilder report = new StringBuilder(); report.append(BookmarkMessages.ColumnDescription_header).append('\t'); report.append(BookmarkMessages.ColumnResource_header).append('\t'); report.append(BookmarkMessages.ColumnFolder_header).append('\t'); report.append(BookmarkMessages.ColumnLocation_header); report.append(System.getProperty("line.separator")); for (IMarker marker : markers) { report.append(MarkerUtil.getMessage(marker)).append('\t'); report.append(MarkerUtil.getResourceName(marker)).append('\t'); report.append(MarkerUtil.getContainerName(marker)).append('\t'); int line = MarkerUtil.getLineNumber(marker); report.append(NLS.bind(BookmarkMessages.LineIndicator_text, String.valueOf(line))); report.append(System.getProperty("line.separator")); } return report.toString(); }
Source:
private void reportIssue(Tree tree) { ExpressionTree expression = getDenominator(tree); String operation = tree.is(Tree.Kind.REMAINDER, Tree.Kind.REMAINDER_ASSIGNMENT) ? "modulation" : "division"; String expressionName; String flowMessage; if (expression.is(Tree.Kind.IDENTIFIER)) { String name = ((IdentifierTree) expression).name(); expressionName = "'" + name + "'"; flowMessage = name + " is divided by zero"; } else { expressionName = "this expression"; flowMessage = "this expression contains division by zero"; } context.reportIssue(expression, DivisionByZeroCheck.this, String.format("Make sure %s can't be zero before doing this %s.", expressionName, operation), Flows.singleton(flowMessage, tree)); programState = null; }

Target:
private void reportIssue(Tree tree) { ExpressionTree expression = getDenominator(tree); String operation = tree.is(Tree.Kind.REMAINDER, Tree.Kind.REMAINDER_ASSIGNMENT) ? "modulation" : "division"; String expressionName; String flowMessage; if (expression.is(Tree.Kind.IDENTIFIER)) { String name = ((IdentifierTree) expression).name(); expressionName = "'" + name + "'"; flowMessage = name + " is divided by zero"; } else { expressionName = "this expression"; flowMessage = "this expression contains division by zero"; } context.reportIssue(expression, DivisionByZeroCheck.this, "Make sure " + expressionName + " can't be zero before doing this " + operation + ".", FlowComputation.singleton(flowMessage, tree)); programState = null; }
Source:
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { if (Subject.getSubject(AccessController.getContext()) == null) { servletResponse.sendError(HttpServletResponse.SC_FORBIDDEN); return; } lazyInit(servletRequest, servletResponse); try { createServletRunContext(servletRequest, servletResponse).run(() -> { ServiceTunnelRequest serviceRequest = deserializeServiceRequest(); ServiceTunnelResponse serviceResponse = doPost(serviceRequest); IRestorer interruption = ThreadInterruption.clear(); try { serializeServiceResponse(serviceResponse); } finally { interruption.restore(); } }, DefaultExceptionTranslator.class); } catch (Throwable e) { if (isConnectionError(e)) { LOG.debug("Connection Error", e); } else if (isInterruption(e)) { LOG.info("Interruption", e); servletResponse.sendError(HttpServletResponse.SC_ACCEPTED, "Request processing was interrupted"); } else if (e instanceof DuplicateRequestException) { LOG.warn("Duplicate Request", e); servletResponse.sendError(HttpServletResponse.SC_CONFLICT, "Request is a duplicate"); } else { LOG.error("Client={}@{}/{}", servletRequest.getRemoteUser(), servletRequest.getRemoteAddr(), servletRequest.getRemoteHost(), e); servletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }

Target:
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { if (Subject.getSubject(AccessController.getContext()) == null) { servletResponse.sendError(HttpServletResponse.SC_FORBIDDEN); return; } lazyInit(servletRequest, servletResponse); try { createServletRunContext(servletRequest, servletResponse).run(() -> { ServiceTunnelRequest serviceRequest = deserializeServiceRequest(); ServiceTunnelResponse serviceResponse = doPost(serviceRequest); IRestorer interruption = ThreadInterruption.clear(); try { serializeServiceResponse(serviceResponse); } finally { interruption.restore(); } }, DefaultExceptionTranslator.class); } catch (Throwable e) { if (isConnectionError(e)) { LOG.debug("Connection Error", e); } else if (isInterruption(e)) { LOG.info("Interruption", e); servletResponse.setStatus(HttpServletResponse.SC_ACCEPTED, "Request processing was interrupted"); } else if (e instanceof DuplicateRequestException) { LOG.warn("Duplicate Request", e); servletResponse.sendError(HttpServletResponse.SC_CONFLICT, "Request is a duplicate"); } else { LOG.error("Client={}@{}/{}", servletRequest.getRemoteUser(), servletRequest.getRemoteAddr(), servletRequest.getRemoteHost(), e); servletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }
Source:
private void buildFieldReadAccessInvocation(BlockBuilder blockBuilder, IdentifierGenerator idGenerator, Tree tree) { Optional<Expression.FieldAccess> fieldAccess = buildFieldAccess(idGenerator, tree); if (fieldAccess.isPresent()) { Expression.Variable aux = variableWithId(idGenerator.newId()); blockBuilder.assignTo(aux, call("__id").withArgs(fieldAccess.get()), location(tree)); idGenerator.varForExpression(tree, aux.id()); } }

Target:
private void buildFieldReadAccessInvocation(BlockBuilder blockBuilder, IdentifierGenerator idGenerator, Tree tree) { buildFieldAccess(idGenerator, tree).ifPresent(fieldAccess -> { Expression.Variable aux = variableWithId(idGenerator.newId()); blockBuilder.assignTo(aux, call("__id").withArgs(fieldAccess), location(tree)); idGenerator.varForExpression(tree, aux.id()); }); }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (getTag() == null ? 0 : getTag().hashCode()); return result; }

Target:
public int hashCode() { return 31 * super.hashCode() + (getTag() == null ? 0 : getTag().hashCode()); }
Source:
private String getArticleTitle(Doi doi) { String articleTitle; if (articleTitles.containsKey(doi)) { articleTitle = articleTitles.get(doi); } else { ArticleTable article; try { article = articleCrudService.getArticle(ArticleIdentifier.create(doi)); } catch (NoSuchArticleIdException e) { articleTitles.put(doi, null); return null; } ArticleIngestion ingestion; try { ingestion = articleCrudService.getLatestArticleRevision(article).getIngestion(); } catch (NoSuchArticleIdException e) { log.error("Could not retrieve latest revision for " + article.getDoi(), e); throw new RuntimeException(e); } ArticleXml targetArticleXml; try { targetArticleXml = new ArticleXml(articleCrudService.getManuscriptXml(ingestion)); } catch (IOException e) { log.error("Could not retrieve manuscript for " + ingestion, e); throw new RuntimeException(e); } articleTitle = targetArticleXml.parseTitle(); articleTitles.put(doi, articleTitle); } return articleTitle; }

Target:
private String getArticleTitle(Doi doi) { ArticleTable article; try { article = articleCrudService.getArticle(ArticleIdentifier.create(doi)); } catch (NoSuchArticleIdException e) { log.error("Could not retrieve article for " + doi, e); throw new RuntimeException(e); } ArticleIngestion ingestion; try { ingestion = articleCrudService.getLatestArticleRevision(article).getIngestion(); } catch (NoSuchArticleIdException e) { log.error("Could not retrieve latest revision for " + article.getDoi(), e); throw new RuntimeException(e); } ArticleXml targetArticleXml; try { targetArticleXml = new ArticleXml(articleCrudService.getManuscriptXml(ingestion)); } catch (IOException e) { log.error("Could not retrieve manuscript for " + ingestion, e); throw new RuntimeException(e); } return targetArticleXml.parseTitle(); }
Source:
public BigtableBufferedMutator( Configuration configuration, TableName tableName, int maxInflightRpcs, long maxHeapSize, BigtableDataClient client, BigtableOptions options, ExecutorService executorService, BufferedMutator.ExceptionListener listener) { this.sizeManager = new HeapSizeManager(maxHeapSize, maxInflightRpcs); this.configuration = configuration; this.tableName = tableName; this.exceptionListener = listener; this.host = options.getDataHost().toString(); PutAdapter putAdapter = new PutAdapter(configuration.getInt("hbase.client.keyvalue.maxsize", -1)); RowMutationsAdapter rowMutationsAdapter = new RowMutationsAdapter(Adapters.createMutationsAdapter(putAdapter)); ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService); batchExecutor = new BatchExecutor( client, options, options.getClusterName().toTableName(tableName.getNameAsString()), listeningExecutorService, putAdapter, rowMutationsAdapter); }

Target:
public BigtableBufferedMutator( Configuration configuration, TableName tableName, int maxInflightRpcs, long maxHeapSize, BigtableDataClient client, BigtableOptions options, ExecutorService executorService, BufferedMutator.ExceptionListener listener) { this.sizeManager = new HeapSizeManager(maxHeapSize, maxInflightRpcs); this.configuration = configuration; this.tableName = tableName; this.exceptionListener = listener; this.host = options.getDataHost().toString(); PutAdapter putAdapter = Adapters.createPutAdapter(configuration); RowMutationsAdapter rowMutationsAdapter = new RowMutationsAdapter(Adapters.createMutationsAdapter(putAdapter)); ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService); batchExecutor = new BatchExecutor( client, options, options.getClusterName().toTableName(tableName.getNameAsString()), listeningExecutorService, putAdapter, rowMutationsAdapter); }
Source:
public Object invoke(Signature function, ConnectorSession session, List<Object> arguments) { ScalarFunctionImplementation implementation = registry.getScalarFunctionImplementation(function); MethodHandle method = implementation.getMethodHandle(); if (method.type().parameterCount() > 0 && method.type().parameterType(0) == ConnectorSession.class) { method = method.bindTo(session); } Iterator<Object> iterator = arguments.iterator(); List<Object> actualArguments = new ArrayList<>(arguments.size() + 1); for (int i = 0; i < method.type().parameterCount(); i++) { Class<?> parameterType = method.type().parameterType(i); checkArgument(iterator.hasNext(), "Not enough arguments provided for method: %s", method.type()); Object argument = iterator.next(); if (implementation.getNullFlags().get(i)) { boolean isNull = argument == null; if (isNull) { argument = Defaults.defaultValue(parameterType); } actualArguments.add(argument); actualArguments.add(isNull); i++; } else { actualArguments.add(argument); } } checkArgument(!iterator.hasNext(), "Too many arguments provided for method: %s", method.type()); try { return method.invokeWithArguments(actualArguments); } catch (Throwable throwable) { throw Throwables.propagate(throwable); } }

Target:
public Object invoke(Signature function, ConnectorSession session, List<Object> arguments) { ScalarFunctionImplementation implementation = registry.getScalarFunctionImplementation(function); MethodHandle method = implementation.getMethodHandle(); method = bindInstanceFactory(method, implementation); if (method.type().parameterCount() > 0 && method.type().parameterType(0) == ConnectorSession.class) { method = method.bindTo(session); } List<Object> actualArguments = new ArrayList<>(); for (int i = 0; i < arguments.size(); i++) { Object argument = arguments.get(i); Optional<Class> lambdaArgument = implementation.getLambdaInterface().get(i); if (lambdaArgument.isPresent() && !MethodHandle.class.equals(lambdaArgument.get())) { argument = asInterfaceInstance(lambdaArgument.get(), (MethodHandle) argument); } if (implementation.getNullFlags().get(i)) { boolean isNull = argument == null; if (isNull) { argument = Defaults.defaultValue(method.type().parameterType(actualArguments.size())); } actualArguments.add(argument); actualArguments.add(isNull); } else { actualArguments.add(argument); } } try { return method.invokeWithArguments(actualArguments); } catch (Throwable throwable) { throw Throwables.propagate(throwable); } }
Source:
private CheServicesEnvironmentImpl asCheEnvironment(ComposeEnvironment composeEnvironment) { Map<String, CheServiceImpl> services = Maps.newHashMapWithExpectedSize(composeEnvironment.getServices().size()); for (Map.Entry<String, ComposeServiceImpl> composeServiceEntry : composeEnvironment.getServices() .entrySet()) { ComposeServiceImpl service = composeServiceEntry.getValue(); CheServiceBuildContextImpl buildContext = null; if (service.getBuild() != null) { buildContext = new CheServiceBuildContextImpl().withContext(service.getBuild().getContext()) .withDockerfilePath(service.getBuild().getDockerfile()) .withArgs(service.getBuild().getArgs()); } CheServiceImpl cheService = new CheServiceImpl().withBuild(buildContext) .withCommand(service.getCommand()) .withContainerName(service.getContainerName()) .withDependsOn(service.getDependsOn()) .withEntrypoint(service.getEntrypoint()) .withEnvironment(service.getEnvironment()) .withExpose(service.getExpose()) .withImage(service.getImage()) .withLabels(service.getLabels()) .withLinks(service.getLinks()) .withMemLimit(service.getMemLimit()) .withNetworks(service.getNetworks()) .withPorts(service.getPorts()) .withVolumes(service.getVolumes()) .withVolumesFrom(service.getVolumesFrom()); services.put(composeServiceEntry.getKey(), cheService); } return new CheServicesEnvironmentImpl().withServices(services); }

Target:
private CheServicesEnvironmentImpl asCheEnvironment(ComposeEnvironment composeEnvironment) { Map<String, CheServiceImpl> services = Maps.newHashMapWithExpectedSize(composeEnvironment.getServices().size()); for (Map.Entry<String, ComposeServiceImpl> composeServiceEntry : composeEnvironment.getServices() .entrySet()) { ComposeServiceImpl service = composeServiceEntry.getValue(); CheServiceImpl cheService = new CheServiceImpl().withCommand(service.getCommand()) .withContainerName(service.getContainerName()) .withDependsOn(service.getDependsOn()) .withEntrypoint(service.getEntrypoint()) .withEnvironment(service.getEnvironment()) .withExpose(service.getExpose()) .withImage(service.getImage()) .withLabels(service.getLabels()) .withLinks(service.getLinks()) .withMemLimit(service.getMemLimit()) .withNetworks(service.getNetworks()) .withPorts(service.getPorts()) .withVolumes(service.getVolumes()) .withVolumesFrom(service.getVolumesFrom()); if (service.getBuild() != null) { cheService.setBuild(new CheServiceBuildContextImpl().withContext(service.getBuild().getContext()) .withDockerfilePath(service.getBuild().getDockerfile()) .withArgs(service.getBuild().getArgs())); } services.put(composeServiceEntry.getKey(), cheService); } return new CheServicesEnvironmentImpl(services); }
Source:
public final void createTable(final TableDesc desc) throws DuplicateTableException, InsufficientPrivilegeException { try { final BlockingInterface stub = getStub(); final ReturnState state = stub.createTable(null, desc.getProto()); throwsIfThisError(state, DuplicateTableException.class); throwsIfThisError(state, InsufficientPrivilegeException.class); ensureOk(state); } catch (ServiceException e) { throw new RuntimeException(e); } }

Target:
public final void createTable(final TableDesc desc) throws UndefinedDatabaseException, DuplicateTableException, InsufficientPrivilegeException { try { final BlockingInterface stub = getStub(); final ReturnState state = stub.createTable(null, desc.getProto()); throwsIfThisError(state, UndefinedDatabaseException.class); throwsIfThisError(state, DuplicateTableException.class); throwsIfThisError(state, InsufficientPrivilegeException.class); ensureOk(state); } catch (ServiceException e) { throw new RuntimeException(e); } }
Source:
public void testPackageWithTestPrefix() throws Throwable { VirtualFile file = WriteCommandAction.runWriteCommandAction(myFixture.getProject(), new ThrowableComputable<VirtualFile, Throwable>() { @NotNull @Override public VirtualFile compute() throws Throwable { myFixture.getTempDirFixture().createFile("pack1/pack1_test.go", "package pack1_test; func Test() {}"); return myFixture.getTempDirFixture().createFile("pack2/pack2_test.go", "package pack2_test; import \"testing\"; func TestTest(*testing.T) {<error>pack1_test</error>.Test()}"); } }); GoModuleLibrariesService.getInstance(myFixture.getModule()).setLibraryRootUrls(file.getParent().getParent().getUrl()); myFixture.configureFromExistingVirtualFile(file); myFixture.checkHighlighting(); }

Target:
public void testPackageWithTestPrefix() { myFixture.addFileToProject("pack1/pack1_test.go", "package pack1_test; func Test() {}"); PsiFile file = myFixture.addFileToProject("pack2/pack2_test.go", "package pack2_test; import \"testing\"; func TestTest(*testing.T) {<error>pack1_test</error>.Test()}"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.checkHighlighting(); }
Source:
public APIResult submitAndScheduleExtensionJob(final String extensionName, final String jobName, final String configPath, final String doAsUser) { InputStream configStream = getServletInputStream(configPath); if (!validateExtension(extensionName, jobName, configStream)) { return null; } ClientResponse clientResponse = new ResourceBuilder() .path(ExtensionOperations.SUBMIT_AND_SCHEDULE.path, extensionName) .addQueryParam(DO_AS_OPT, doAsUser) .call(ExtensionOperations.SUBMIT_AND_SCHEDULE, configStream); return getResponse(APIResult.class, clientResponse); }

Target:
public APIResult submitAndScheduleExtensionJob(final String extensionName, final String jobName, final String configPath, final String doAsUser) { FormDataMultiPart entitiesForm = getEntitiesForm(extensionName, jobName, configPath); ClientResponse clientResponse = new ResourceBuilder() .path(ExtensionOperations.SUBMIT_AND_SCHEDULE.path, extensionName) .addQueryParam(DO_AS_OPT, doAsUser) .call(ExtensionOperations.SUBMIT_AND_SCHEDULE, entitiesForm); return getResponse(APIResult.class, clientResponse); }
Source:
public synchronized boolean updateLastSeenEpochIfNewer(TopicPartition topicPartition, int leaderEpoch) { Objects.requireNonNull(topicPartition, "TopicPartition cannot be null"); if (leaderEpoch < 0) throw new IllegalArgumentException("Invalid leader epoch " + leaderEpoch + " (must be non-negative)"); Integer oldEpoch = lastSeenLeaderEpochs.get(topicPartition); log.trace("Determining if we should replace existing epoch with new epoch {}", oldEpoch, leaderEpoch); final boolean updated; if (oldEpoch == null) { log.debug("Not replacing null epoch with new epoch for partition {}", leaderEpoch, topicPartition); updated = false; } else { if (leaderEpoch > oldEpoch) { log.debug("Updating last seen epoch from to for partition {}", oldEpoch, leaderEpoch, topicPartition); lastSeenLeaderEpochs.put(topicPartition, leaderEpoch); updated = true; } else { log.debug("Not replacing existing epoch with new epoch for partition {}", oldEpoch, leaderEpoch, topicPartition); updated = false; } } this.needFullUpdate = this.needFullUpdate || updated; return updated; }

Target:
public synchronized boolean updateLastSeenEpochIfNewer(TopicPartition topicPartition, int leaderEpoch) { Objects.requireNonNull(topicPartition, "TopicPartition cannot be null"); if (leaderEpoch < 0) throw new IllegalArgumentException("Invalid leader epoch " + leaderEpoch + " (must be non-negative)"); Integer oldEpoch = lastSeenLeaderEpochs.get(topicPartition); log.trace("Determining if we should replace existing epoch with new epoch for partition {}", oldEpoch, leaderEpoch, topicPartition); final boolean updated; if (oldEpoch == null) { log.debug("Not replacing null epoch with new epoch for partition {}", leaderEpoch, topicPartition); updated = false; } else if (leaderEpoch > oldEpoch) { log.debug("Updating last seen epoch from to for partition {}", oldEpoch, leaderEpoch, topicPartition); lastSeenLeaderEpochs.put(topicPartition, leaderEpoch); updated = true; } else { log.debug("Not replacing existing epoch with new epoch for partition {}", oldEpoch, leaderEpoch, topicPartition); updated = false; } this.needFullUpdate = this.needFullUpdate || updated; return updated; }
Source:
@Override public ControlFlowGraph getCfg() { return constructor.getMarker(ControlFlowGraph.class); }

Target:
@Override public ControlFlowGraph getCfg() { ControlFlowGraph cfg = constructor.getMarker(ControlFlowGraph.class); assert cfg != null; return cfg; }
Source:
public void setInSlot(Object slot, IsWidget content) { if (slot == MainSectionPresenter.TYPE_SetHeader) { setPanelContent(headerPanel, content); } else if (slot == MainSectionPresenter.TYPE_SetMainContent) { if (!placeholderRemoved) { removeHostPagePlaceholder(); placeholderRemoved = true; } setPanelContent(mainContentPanel, content); } else { super.setInSlot(slot, content); } }

Target:
public void setInSlot(Object slot, IsWidget content) { if (slot == MainSectionPresenter.TYPE_SetHeader) { setPanelContent(headerPanel, content); } else if (slot == MainSectionPresenter.TYPE_SetMainContent) { setPanelContent(mainContentPanel, content); } else { super.setInSlot(slot, content); } }
Source:
private static Object convertAttribute(Attribute attribute, AttributeDescriptor descriptor) { if (descriptor.isMultiValued()) { List<Object> values = new ArrayList<>(); for (Serializable value : attribute.getValues()) { values.add( convertValue(attribute.getName(), value, descriptor.getType().getAttributeFormat())); } return values; } else { return convertValue( attribute.getName(), attribute.getValue(), descriptor.getType().getAttributeFormat()); } }

Target:
private Serializable convertAttribute(Attribute attribute, AttributeDescriptor descriptor) { if (descriptor.isMultiValued()) { List<Serializable> values = new ArrayList<>(); for (Serializable value : attribute.getValues()) { Serializable convertedValue = convertValue(attribute.getName(), value, descriptor.getType().getAttributeFormat()); if (convertedValue != null) { values.add(convertedValue); } } return StringUtils.join(values, ","); } else { return convertValue( attribute.getName(), attribute.getValue(), descriptor.getType().getAttributeFormat()); } }
Source:
private Object applyUpdateUnsafe(SMRRecord record) { log.trace("Apply[{}] of {}@{} ({})", this, record.getSMRMethod(), Address.isAddress(record.getGlobalAddress()) ? record.getGlobalAddress() : "OPT", record.getSMRArguments()); ICorfuSMRUpcallTarget<T> target = upcallTargetMap.get(record.getSMRMethod()); if (target == null) { throw new RuntimeException("Unknown upcall " + record.getSMRMethod()); } if (record.getGlobalAddress() >= rt.getAddressSpaceView().getCompactionMark() && (!record.isUndoable() || !Address.isAddress(record.getGlobalAddress()))) { IUndoRecordFunction<T> undoRecordTarget = undoRecordFunctionMap.get(record.getSMRMethod()); if (undoRecordTarget != null) { record.setUndoRecord(undoRecordTarget .getUndoRecord(object, record.getSMRArguments())); log.trace("Apply[{}] Undo->{}", this, record.getUndoRecord()); } else if (resetSet.contains(record.getSMRMethod())) { record.setUndoRecord(object); object = newObjectFn.get(); log.trace("Apply[{}] Undo->RESET", this); } } return target.upcall(object, record.getSMRArguments()); }

Target:
private Object applyUpdateUnsafe(SMRRecord record) { log.trace("Apply[{}] of {}@{} ({})", this, record.getSMRMethod(), Address.isAddress(record.getGlobalAddress()) ? record.getGlobalAddress() : "OPT", record.getSMRArguments()); ICorfuSMRUpcallTarget<T> target = upcallTargetMap.get(record.getSMRMethod()); if (target == null) { throw new RuntimeException("Unknown upcall " + record.getSMRMethod()); } if (!Address.isAddress(record.getGlobalAddress()) || !record.isUndoable() && record.getGlobalAddress() >= rt.getAddressSpaceView().getCompactionMark().get()) { IUndoRecordFunction<T> undoRecordTarget = undoRecordFunctionMap.get(record.getSMRMethod()); if (undoRecordTarget != null) { record.setUndoRecord(undoRecordTarget .getUndoRecord(object, record.getSMRArguments())); log.trace("Apply[{}] Undo->{}", this, record.getUndoRecord()); } else if (resetSet.contains(record.getSMRMethod())) { record.setUndoRecord(object); object = newObjectFn.get(); log.trace("Apply[{}] Undo->RESET", this); } } return target.upcall(object, record.getSMRArguments()); }
Source:
public RuleModel unmarshalUsingDSL( final String str, final List<String> globals, final PackageDataModelOracle dmo, final String... dsls ) { return unmarshalUsingDSL( str, globals, dmo, null, dsls ); }

Target:
public RuleModel unmarshalUsingDSL(final String str, final List<String> globals, final PackageDataModelOracle dmo, final String... dsls) { return unmarshalUsingDSL(str, globals, dmo, Collections.emptyList(), dsls); }
Source:
private static boolean matches(String refName, String refPattern) { if (!refPattern.endsWith("*")) { return refName.equals(refPattern); } else { return refName.startsWith( refPattern.substring(0, refPattern.length() - 1)); } }

Target:
public static boolean matches(String refName, String refPattern) { if (refPattern.endsWith("/*")) { return refName.startsWith( refPattern.substring(0, refPattern.length() - 1)); } else { return refName.equals(refPattern); } }
Source:
public SqlSessionTemplate fudianSqlSessionTemplate(@Qualifier("fudianSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); }

Target:
public SqlSessionTemplate fudianSqlSessionTemplate(@Qualifier("fudianSqlSessionFactory") SqlSessionFactory sqlSessionFactory){ return new SqlSessionTemplate(sqlSessionFactory); }
Source:
private void lookupClient() { try { log.tracef( "Retrieving MongoDatabase from JNDI at %1$s", configuration.getNativeClientResource() ); Driver driver = (Driver) jndiService.locate( configuration.getNativeClientResource() ); this.client = new BoltNeo4jClient( driver ); } catch (RuntimeException e) { throw log.errorOnFetchJndiClientProperty( configuration.getNativeClientResource() ); } this.jndiService = null; }

Target:
private void lookupClient() { try { log.tracef( "Retrieving MongoDatabase from JNDI at %1$s", configuration.getNativeClientResource() ); Driver driver = (Driver) jndiService.locate( configuration.getNativeClientResource() ); this.client = new BoltNeo4jClient( driver ); } catch (RuntimeException e) { throw log.errorOnFetchJndiClientProperty( configuration.getNativeClientResource() ); } }
Source:
protected Boolean doInBackground(ArrayList<HybridFileParcelable>... files) { boolean success = true; this.files = files[0]; for (HybridFileParcelable file : files[0]) { Operator deleteOperation = new Operator(new DeleteOperation(context, rootMode, file)); deleteOperation.start(); success = success && deleteOperation.hasFailed(); } return success; }

Target:
protected Boolean doInBackground(ArrayList<HybridFileParcelable>... files) { if(files == null || files[0] == null || files.length != 1) { throw new IllegalArgumentException("execute() parameter must be one list!"); } boolean success = true; this.files = files[0]; for (HybridFileParcelable file : this.files) { Operator deleteOperation = new Operator(new DeleteOperation(context, rootMode, file)); deleteOperation.start(); success = success && deleteOperation.hasFailed(); } return success; }
Source:
private void addNonceParameters(Map<String, Object> attributes, Map<String, Object> additionalParameters) { String nonce = this.stringKeyGenerator.generateKey(); attributes.put(IdTokenClaimNames.NONCE, nonce); try { String nonceHash = createHash(nonce); additionalParameters.put(IdTokenClaimNames.NONCE, nonceHash); } catch (NoSuchAlgorithmException e) { } }

Target:
private void addNonceParameters(Map<String, Object> attributes, Map<String, Object> additionalParameters) { try { String nonce = this.stringKeyGenerator.generateKey(); attributes.put(OidcParameterNames.NONCE, nonce); String nonceHash = createHash(nonce); additionalParameters.put(OidcParameterNames.NONCE, nonceHash); } catch (NoSuchAlgorithmException ignored) { } }
Source:
public FirefoxOptions merge(Capabilities capabilities) { super.merge(capabilities); if (capabilities instanceof FirefoxOptions) { Map options = (Map) capabilities.asMap().get("moz:firefoxOptions"); mergeArguments(options); mergeBooleanPrefs(capabilities); mergeIntPrefs(capabilities); mergeStringPrefs(capabilities); mergeLogLevel(capabilities); } return this; }

Target:
public FirefoxOptions merge(Capabilities capabilities) { super.merge(capabilities); return this; }
Source:
public S hasValue(int expectedValue) { isNotNull(); if (!actual.isPresent()) throw failure(shouldContain(expectedValue)); try { integers.assertEqual(info, actual.getAsInt(), expectedValue); } catch (AssertionError assertionError) { throw Failures.instance().failure(info, shouldContain(actual, expectedValue)); } return myself; }

Target:
public S hasValue(int expectedValue) { isNotNull(); if (!actual.isPresent()) throw failure(shouldContain(expectedValue)); if (expectedValue != actual.getAsInt()) throw Failures.instance().failure(info, shouldContain(actual, expectedValue)); return myself; }
Source:
private void jobPropertiesCheck() { String maxXms = props.getString(JOB_MAX_XMS, MAX_XMS_DEFAULT); String maxXmx = props.getString(JOB_MAX_XMX, MAX_XMX_DEFAULT); long sizeMaxXms = azkaban.utils.Utils.parseMemString2KB(maxXms); long sizeMaxXmx = azkaban.utils.Utils.parseMemString2KB(maxXmx); for (String jobName : jobPropsMap.keySet()) { Props jobProps = jobPropsMap.get(jobName); String xms = jobProps.getString(XMS, null); if (xms != null && azkaban.utils.Utils.parseMemString2KB(xms) > sizeMaxXms) { errors.add(String.format("%s: Xms value has exceeded the allowed limit (max Xms = %s)", jobName, maxXms)); } String xmx = jobProps.getString(XMX, null); if (xmx != null && azkaban.utils.Utils.parseMemString2KB(xmx) > sizeMaxXmx) { errors.add(String.format("%s: Xmx value has exceeded the allowed limit (max Xmx = %s)", jobName, maxXmx)); } } }

Target:
private void jobPropertiesCheck() { String maxXms = props.getString(JOB_MAX_XMS, MAX_XMS_DEFAULT); String maxXmx = props.getString(JOB_MAX_XMX, MAX_XMX_DEFAULT); long sizeMaxXms = azkaban.utils.Utils.parseMemString(maxXms); long sizeMaxXmx = azkaban.utils.Utils.parseMemString(maxXmx); for (String jobName : jobPropsMap.keySet()) { Props resolvedJobProps = PropsUtils.resolveProps(jobPropsMap.get(jobName)); String xms = resolvedJobProps.getString(XMS, null); if (xms != null && azkaban.utils.Utils.parseMemString(xms) > sizeMaxXms) { errors.add(String.format("%s: Xms value has exceeded the allowed limit (max Xms = %s)", jobName, maxXms)); } String xmx = resolvedJobProps.getString(XMX, null); if (xmx != null && azkaban.utils.Utils.parseMemString(xmx) > sizeMaxXmx) { errors.add(String.format("%s: Xmx value has exceeded the allowed limit (max Xmx = %s)", jobName, maxXmx)); } } }
Source:
private Span[] overrideDefaultType(Span[] names) { for (int i = 0; i < names.length; i++) { Span n = names[i]; if (Objects.isNull(n.getType())) { names[i] = new Span(n.getStart(), n.getEnd(), this.defaultType, n.getProb()); } } return names; }

Target:
private void overrideDefaultType(Span[] names) { for (int i = 0; i < names.length; i++) { Span n = names[i]; if (Objects.isNull(n.getType())) { names[i] = new Span(n.getStart(), n.getEnd(), this.defaultType, n.getProb()); } } }
Source:
public void registerJsonShouldContainEntryView() throws Throwable { populateRegisterRegisterEntries(); Response registerRegisterEntryResponse = getRequest("register", "/register/address.json"); assertThat(registerRegisterEntryResponse.getStatus(), equalTo(200)); cleanDatabaseRule.before(); populateAddressRegisterEntries(); Response addressRegisterResourceResponse = getRequest("address", "/register.json"); assertThat(addressRegisterResourceResponse.getStatus(), equalTo(200)); String addressRegisterResourceJsonResponse = addressRegisterResourceResponse.readEntity(String.class); assertThat(addressRegisterResourceJsonResponse, containsString("\"total-entries\":5")); assertThat(addressRegisterResourceJsonResponse, containsString("\"total-records\":3")); assertThat(addressRegisterResourceJsonResponse, containsString("\"total-items\":5")); assertThat(addressRegisterResourceJsonResponse, containsString("\"last-updated\":")); String registerRegisterEntryJsonResponse = registerRegisterEntryResponse.readEntity(String.class); assertThat(addressRegisterResourceJsonResponse, containsString(registerRegisterEntryJsonResponse)); }

Target:
public void registerJsonShouldContainEntryView() throws Throwable { populateRegisterRegisterEntries(); Response registerRegisterEntryResponse = getRequest("register", "/register/address.json"); assertThat(registerRegisterEntryResponse.getStatus(), equalTo(200)); cleanDatabaseRule.before(); populateAddressRegisterEntries(); Response addressRegisterResourceResponse = getRequest("address", "/register.json"); assertThat(addressRegisterResourceResponse.getStatus(), equalTo(200)); JsonNode registerJson = addressRegisterResourceResponse.readEntity(JsonNode.class); assertThat(registerJson.get("total-entries").intValue(), equalTo(5)); assertThat(registerJson.get("total-records").intValue(), equalTo(3)); assertThat(registerJson.get("total-items").intValue(), equalTo(5)); verifyStringIsAnISODate(registerJson.get("last-updated").textValue()); JsonNode registerRecordJson = registerRegisterEntryResponse.readEntity(JsonNode.class); assertThat(registerJson.get("record"), equalTo(registerRecordJson)); }
Source:
public List<String> getClassPath() { if (PantsUtil.isPantsProject(myProject)) { throw new RuntimeException(PantsConstants.EXTERNAL_BUILDER_ERROR); } return new ArrayList<>(); }

Target:
public List<String> getClassPath() { if (PantsUtil.isPantsProject(myProject)) { throw new RuntimeException(PantsConstants.EXTERNAL_BUILDER_ERROR); } return Lists.newArrayList(); }
Source:
public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) { for (Object bsmArg : bsmArgs) { if (bsmArg instanceof Handle) { Handle dynamicLambdaHandle = (Handle) bsmArg; dynamicLambdaHandles.add(dynamicLambdaHandle); } } }

Target:
public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) { if (META_FACTORY.equals(bsm)) { Handle dynamicLambdaHandle = (Handle) bsmArgs[1]; dynamicLambdaHandles.add(dynamicLambdaHandle); } }
Source:
public OrcSchema(Reader reader) throws IOException { mAlluxioSchema = new ArrayList<>(); final List<String> fieldNames = reader.getSchema().getFieldNames(); for (int i = 0; i < fieldNames.size(); i++) { final String fieldName = fieldNames.get(i); final String type = getType(reader.getSchema().getChildren().get(i)); mAlluxioSchema.add(new FieldSchema(i, fieldName, type, "")); } mWriteSchema = SchemaConversionUtils.buildWriteSchema(mAlluxioSchema); }

Target:
public OrcSchema(Reader reader) throws IOException { final List<String> fieldNames = reader.getSchema().getFieldNames(); mAlluxioSchema = new ArrayList<>(fieldNames.size()); for (int i = 0; i < fieldNames.size(); i++) { final String fieldName = fieldNames.get(i); final String type = getType(reader.getSchema().getChildren().get(i)); mAlluxioSchema.add(new FieldSchema(i, fieldName, type, "")); } mWriteSchema = SchemaConversionUtils.buildWriteSchema(mAlluxioSchema); }
Source:
public static String checkFileCharset(File propsFile) throws IOException { String[] charsetsToBeTested = {"US-ASCII", "UTF-8", "ISO-8859-1"}; for (String charsetName : charsetsToBeTested) { Charset charsetDet = Charset.forName(charsetName); CharsetDecoder decoder = charsetDet.newDecoder(); decoder.reset(); BufferedInputStream input = new BufferedInputStream(new FileInputStream(propsFile)); byte[] buffer = new byte[512]; boolean identified = true; while ((input.read(buffer) != -1) && (identified)) { try { decoder.decode(ByteBuffer.wrap(buffer)); identified = true; } catch (CharacterCodingException e) { identified = false; } } if (identified == true){ return charsetName;} } return null; }

Target:
public static Charset checkFileCharset(File propsFile) throws IOException { List<Charset> charsetsToBeTested = Arrays.asList(US_ASCII, UTF_8, ISO_8859_1); for (Charset charsetTest : charsetsToBeTested) { CharsetDecoder decoder = charsetTest.newDecoder(); decoder.reset(); boolean identified = true; try (BufferedInputStream input = new BufferedInputStream(new FileInputStream(propsFile))) { byte[] buffer = new byte[512]; while ((input.read(buffer) != -1) && (identified)) { try { decoder.decode(ByteBuffer.wrap(buffer)); identified = true; } catch (CharacterCodingException e) { identified = false; } } } if (identified == true){ return charsetTest; } } return null; }