auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void setSessionRollbackCount(int count) { sessionRollbackCount = count; }

Target:
public synchronized void setSessionRollbackCount(int count) { sessionRollbackCount = count; }
Source:
public ExportInfo exportInfo() { List<String> pages = listPaths(perspectivesFS, p -> p.endsWith(FILE_EXT)).stream() .map(p -> p.getName(p.getNameCount() - 2)) .map(Object::toString) .collect(Collectors.toList()); List<DataSetDef> datasetsDefs = listPaths(datasetsFS, p -> p.endsWith(DATASET_EXT)).stream() .map(this::getDataSetFileContent) .map(this::parseDataSetDefinition) .filter(DataSetDef::isPublic) .collect(Collectors.toList()); boolean connectedToDashbuilder = isExternalServerConfigured(); return new ExportInfo(datasetsDefs, pages, connectedToDashbuilder); }

Target:
public ExportInfo exportInfo() { List<String> pages = listPaths(perspectivesFS, p -> p.endsWith(FILE_EXT)).stream() .map(p -> p.getName(p.getNameCount() - 2)) .map(Object::toString) .collect(Collectors.toList()); List<DataSetDef> datasetsDefs = listPaths(datasetsFS, p -> p.endsWith(DATASET_EXT)).stream() .map(this::getDataSetFileContent) .map(this::parseDataSetDefinition) .filter(DataSetDef::isPublic) .collect(Collectors.toList()); return new ExportInfo(datasetsDefs, pages, isExternalServerConfigured()); }
Source:
private void provisionServicesForDiscoverableServers( Map<String, ? extends ServerConfig> servers) { servers.forEach( (k, server) -> { if (server.isDiscoverable() && server.getAttributes().containsKey(SERVER_NAME_ATTRIBUTE)) { ServicePort servicePort = getServicePort(server); Service service = new ServerServiceBuilder() .withName(server.getAttributes().get(SERVER_NAME_ATTRIBUTE)) .withMachineName(machineName) .withSelectorEntry(CHE_ORIGINAL_NAME_LABEL, pod.getMetadata().getName()) .withPorts(Collections.singletonList(servicePort)) .withServers(Collections.singletonMap(k, server)) .build(); k8sEnv.getServices().put(service.getMetadata().getName(), service); } }); }

Target:
private void provisionServicesForDiscoverableServers( Map<String, ? extends ServerConfig> servers) { for (String serverName : servers.keySet()) { ServerConfig server = servers.get(serverName); if (server.getAttributes().containsKey(SERVER_NAME_ATTRIBUTE)) { String endpointName = server.getAttributes().remove(SERVER_NAME_ATTRIBUTE); if (server.isDiscoverable()) { Service service = new ServerServiceBuilder() .withName(endpointName) .withMachineName(machineName) .withSelectorEntry(CHE_ORIGINAL_NAME_LABEL, pod.getMetadata().getName()) .withPorts(Collections.singletonList(getServicePort(server))) .withServers(Collections.singletonMap(serverName, server)) .build(); k8sEnv.getServices().put(service.getMetadata().getName(), service); } } } }
Source:
public void createFullTextResource() throws IOException, JsonParseException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { String requestBody = getJsonStringInput(DESCRIBING_CHO); Annotation storedAnno = createDescribing(requestBody); assertTrue(storedAnno.getMotivation().equals(MotivationTypes.DESCRIBING.name().toLowerCase())); assertEquals(storedAnno.getBody().getInternalType(), BodyInternalTypes.TEXT.name()); }

Target:
public void createFullTextResource() throws IOException, JsonParseException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { String requestBody = getJsonStringInput(DESCRIBING_CHO); ResponseEntity<String> response = getApiClient().createAnnotation( getApiKey(), WebAnnotationFields.PROVIDER_WEBANNO, null, true, requestBody, TEST_USER_TOKEN, null ); assertNotNull(response.getBody()); assertEquals(response.getStatusCode(), HttpStatus.CREATED); Annotation storedAnno = getApiClient().parseResponseBody(response); assertTrue(storedAnno.getMotivation().equals(MotivationTypes.DESCRIBING.name().toLowerCase())); assertEquals(storedAnno.getBody().getInternalType(), BodyInternalTypes.TEXT.name()); }
Source:
public void testDescribableRoundTrip() throws Exception { DescribableModel<JUnitResultArchiver> model = new DescribableModel<JUnitResultArchiver>(JUnitResultArchiver.class); Map<String,Object> args = new TreeMap<String,Object>(); args.put("testResults", "**/TEST-*.xml"); JUnitResultArchiver j = model.instantiate(args); assertEquals("**/TEST-*.xml", j.getTestResults()); assertFalse(j.isAllowEmptyResults()); assertFalse(j.isKeepLongStdio()); assertEquals(1.0, j.getHealthScaleFactor(), 0); assertTrue(j.getTestDataPublishers().isEmpty()); assertEquals(args, model.uninstantiate(model.instantiate(args))); args.put("testDataPublishers", Collections.<TestDataPublisher>singletonList(new MockTestDataPublisher("test"))); Map<String,Object> explicit = model.uninstantiate(model.instantiate(args)); JUnitResultArchiver j2 = model.instantiate(explicit); assertFalse(j2.getTestDataPublishers().isEmpty()); assertEquals(explicit, model.uninstantiate(model.instantiate(explicit))); Map<String,String> describedPublisher = new HashMap<String, String>(); describedPublisher.put("$class", "MockTestDataPublisher"); describedPublisher.put("name", "test"); args.put("testDataPublishers", Collections.singletonList(describedPublisher)); Map<String,Object> described = model.uninstantiate(model.instantiate(args)); JUnitResultArchiver j3 = model.instantiate(described); assertFalse(j3.getTestDataPublishers().isEmpty()); assertEquals(described, model.uninstantiate(model.instantiate(described))); }

Target:
public void testDescribableRoundTrip() throws Exception { DescribableModel<JUnitResultArchiver> model = new DescribableModel<JUnitResultArchiver>(JUnitResultArchiver.class); Map<String,Object> args = new TreeMap<String,Object>(); args.put("testResults", "**/TEST-*.xml"); JUnitResultArchiver j = model.instantiate(args); assertEquals("**/TEST-*.xml", j.getTestResults()); assertFalse(j.isAllowEmptyResults()); assertFalse(j.isKeepLongStdio()); assertEquals(1.0, j.getHealthScaleFactor(), 0); assertTrue(j.getTestDataPublishers().isEmpty()); assertEquals(args, model.uninstantiate(model.instantiate(args))); Map<String,Object> describedPublisher = new HashMap<String, Object>(); describedPublisher.put("$class", "MockTestDataPublisher"); describedPublisher.put("name", "test"); args.put("testDataPublishers", Collections.singletonList(describedPublisher)); Map<String,Object> described = model.uninstantiate(model.instantiate(args)); JUnitResultArchiver j2 = model.instantiate(described); List<TestDataPublisher> testDataPublishers = j2.getTestDataPublishers(); assertFalse(testDataPublishers.isEmpty()); assertEquals(1, testDataPublishers.size()); assertEquals(MockTestDataPublisher.class, testDataPublishers.get(0).getClass()); assertEquals("test", ((MockTestDataPublisher)testDataPublishers.get(0)).getName()); assertEquals(described, model.uninstantiate(model.instantiate(described))); }
Source:
public void setCsrfIgnoreUris(Set<String> csrfIgnoreUris) { if (csrfIgnoreUris == null) { this.csrfIgnoreUris = emptySet(); } else { Set<UriPatten> csrfIgnoreUriPatterns = new HashSet<>(); for (String csrfUri : csrfIgnoreUris) { if (csrfUri == null) { LOGGER.error("CSRF ignore URI is null"); throw new IllegalArgumentException("CSRF ignore URI cannot be null."); } else if (csrfUri.isEmpty()) { LOGGER.error("CSRF ignore URI is empty"); throw new IllegalArgumentException("CSRF ignore URI cannot be empty."); } try { csrfIgnoreUriPatterns.add(new UriPatten(csrfUri)); } catch (IllegalArgumentException e) { String error = "CSRF ignore URI is an invalid URI pattern"; LOGGER.error(error); throw new IllegalArgumentException(error, e); } } this.csrfIgnoreUris = unmodifiableSet(csrfIgnoreUriPatterns); } }

Target:
public void setCsrfIgnoreUris(Set<String> csrfIgnoreUris) { if (csrfIgnoreUris == null) { this.csrfIgnoreUris = emptySet(); } else { Set<UriPatten> csrfIgnoreUriPatterns = new HashSet<>(); for (String csrfUri : csrfIgnoreUris) { if (csrfUri == null) { throw new IllegalArgumentException("CSRF ignore URI pattern cannot be null."); } else if (csrfUri.isEmpty()) { throw new IllegalArgumentException("CSRF ignore URI pattern cannot be empty."); } try { csrfIgnoreUriPatterns.add(new UriPatten(csrfUri)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("CSRF ignore URI pattern '" + csrfUri + "' is invalid.", e); } } this.csrfIgnoreUris = unmodifiableSet(csrfIgnoreUriPatterns); } }
Source:
public void createProject() throws ProjectCreationFailedException { validateParameters(); try { final Project.NameKey nameKey = createProjectArgs.getProject(); final String head = createProjectArgs.permissionsOnly ? GitRepositoryManager.REF_CONFIG : createProjectArgs.branch; final Repository repo; try { repo = repoManager.createRepository(nameKey); } catch (RepositoryCaseMismatchException err) { throw new ProjectCreationFailedException("Cannot create " + nameKey.get() + " because the name is already occupied by another project." + " The other project has the same name, only spelled in a" + " different case.", err); } try { replication.replicateNewProject(nameKey, head); final RefUpdate u = repo.updateRef(Constants.HEAD); u.disableRefLog(); u.link(head); createProjectConfig(); if (!createProjectArgs.permissionsOnly && createProjectArgs.createEmptyCommit) { createEmptyCommit(repo, nameKey, createProjectArgs.branch); } } finally { repo.close(); } } catch (Exception e) { final String msg = "Cannot create " + createProjectArgs.getProject(); log.error(msg, e); throw new ProjectCreationFailedException(msg, e); } }

Target:
public void createProject() throws ProjectCreationFailedException { validateParameters(); final Project.NameKey nameKey = createProjectArgs.getProject(); try { final String head = createProjectArgs.permissionsOnly ? GitRepositoryManager.REF_CONFIG : createProjectArgs.branch; final Repository repo = repoManager.createRepository(nameKey); try { replication.replicateNewProject(nameKey, head); final RefUpdate u = repo.updateRef(Constants.HEAD); u.disableRefLog(); u.link(head); createProjectConfig(); if (!createProjectArgs.permissionsOnly && createProjectArgs.createEmptyCommit) { createEmptyCommit(repo, nameKey, createProjectArgs.branch); } } finally { repo.close(); } } catch (RepositoryCaseMismatchException e) { throw new ProjectCreationFailedException("Cannot create " + nameKey.get() + " because the name is already occupied by another project." + " The other project has the same name, only spelled in a" + " different case.", e); } catch (RepositoryNotFoundException badName) { throw new ProjectCreationFailedException("Cannot create " + nameKey, badName); } catch (IllegalStateException err) { try { final Repository repo = repoManager.openRepository(nameKey); try { if (repo.getObjectDatabase().exists()) { throw new ProjectCreationFailedException("project \"" + nameKey + "\" exists"); } } finally { repo.close(); } } catch (RepositoryNotFoundException doesNotExist) { final String msg = "Cannot create " + nameKey; log.error(msg, err); throw new ProjectCreationFailedException(msg, err); } } catch (Exception e) { final String msg = "Cannot create " + nameKey; log.error(msg, e); throw new ProjectCreationFailedException(msg, e); } }
Source:
protected void executeCommand() { if (getLeaseAction().equals(VDSCommandType.AddVmLease)) { ActionReturnValue retVal = runInternalAction(ActionType.GetVmLeaseInfo, getParameters()); if (retVal.getSucceeded() && retVal.getActionReturnValue() != null) { log.info("VM '{}' lease already exists on storage domain '{}': '{}'", getParameters().getVmId(), getParameters().getStorageDomainId(), retVal.getActionReturnValue()); getParameters().setVmLeaseInfo(retVal.getActionReturnValue()); setSucceeded(true); return; } } Guid taskId = persistAsyncTaskPlaceHolder(getParameters().getParentCommand()); VmLeaseVDSParameters params = new VmLeaseVDSParameters(getParameters().getStoragePoolId(), getParameters().getStorageDomainId(), getParameters().getVmId()); VDSReturnValue returnValue = runVdsCommand(getLeaseAction(), params); if (returnValue.getSucceeded()) { getTaskIdList().add( createTask(taskId, returnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getParameters().getStorageDomainId())); } setSucceeded(returnValue.getSucceeded()); }

Target:
protected void executeCommand() { Guid taskId = persistAsyncTaskPlaceHolder(getParameters().getParentCommand()); VmLeaseVDSParameters params = new VmLeaseVDSParameters(getParameters().getStoragePoolId(), getParameters().getStorageDomainId(), getParameters().getVmId()); VDSReturnValue returnValue = runVdsCommand(getLeaseAction(), params); if (returnValue.getSucceeded()) { getTaskIdList().add( createTask(taskId, returnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getParameters().getStorageDomainId())); } setSucceeded(returnValue.getSucceeded()); }
Source:
public Chain getAndAppend(final long key, final ByteBuffer payLoad) throws TimeoutException { return performWaitingForHashInvalidation(key, () -> delegate.getAndAppend(key, payLoad), entity.getTimeouts().getMutativeOperationTimeout().toNanos()); }

Target:
public Chain getAndAppend(final long key, final ByteBuffer payLoad) throws TimeoutException { return performWaitingForHashInvalidation(key, () -> delegate.getAndAppend(key, payLoad), entity.getTimeouts().getMutativeOperationTimeout()); }
Source:
public void test_controlled_no_scope() { val openEntity = entity("123", "abc", "something.bam", "PROJ-CD", "controlled"); Mockito.when(metadataClient.getEntity("123")).thenReturn(openEntity); val scopeStrs = new HashSet<String>(Arrays.asList("test1.download", "test.OTHER-CODE.upload", "test.ALT-CODE.upload", "test.CODE.upload", "test2.download")); List<AuthScope> scopes = _sut.extractScopes(scopeStrs); val result = _sut.verify(scopes, "123"); assertFalse(result); }

Target:
public void test_controlled_no_scope() { val openEntity = entity("123", "abc", "something.bam", "PROJ-CD", "controlled"); when(metadataService.getEntity("123")).thenReturn(openEntity); val scopeStrs = new HashSet<String>(Arrays.asList("test1.download", "test.OTHER-CODE.upload", "test.ALT-CODE.upload", "test.CODE.upload", "test2.download")); List<AuthScope> scopes = sut.extractScopes(scopeStrs); val result = sut.verify(scopes, "123"); assertFalse(result); }
Source:
protected Iterable<Tree> children() { ImmutableList.Builder<Tree> iteratorBuilder = ImmutableList.<Tree>builder(); iteratorBuilder.add(directiveKeyword(), typeName, withKeyword); iteratorBuilder.addAll(typeNames.children()); iteratorBuilder.add(semicolonToken()); return iteratorBuilder.build(); }

Target:
protected Iterable<Tree> children() { return Collections.unmodifiableList(Arrays.asList( directiveKeyword(), typeName, withKeyword, typeNames, semicolonToken())); }
Source:
public void initFromTensorFlow(NodeDef nodeDef, SameDiff initWith, Map<String, AttrValue> attributesForNode, GraphDef graph) { int idx = -1; int cnt = 0; int concatDimension = 0; for (int i = 0; i < nodeDef.getInputCount(); i++) { val input = nodeDef.getInput(i); val variable = initWith.getVariable(input); if (variable != null && variable.getArr() == null) { idx = cnt; if(variable.getShape() != null) concatDimension = variable.getShape()[0]; break; } else if (variable != null) { val arr = variable.getArr(); if (arr.length() == 1) { concatDimension = arr.getInt(0); idx = cnt; break; } } cnt++; } if (idx < 0) throw new ND4JIllegalStateException("Can't find dimension for concatenatiion"); if (concatDimension == 3) concatDimension = 1; this.concatDimension = concatDimension; log.debug("Concat dimension: {}", concatDimension); }

Target:
public void initFromTensorFlow(NodeDef nodeDef, SameDiff initWith, Map<String, AttrValue> attributesForNode, GraphDef graph) { }
Source:
protected Ack doPost(CommandEnvelope envelope) { final CommandDispatcher<?> dispatcher = getDispatcher(envelope); Ack result; try { dispatcher.dispatch(envelope); commandStore.setCommandStatusOk(envelope); result = acknowledge(envelope.getId()); } catch (RuntimeException e) { final Throwable cause = getRootCause(e); commandStore.updateCommandStatus(envelope, cause, log); if (causedByRejection(e)) { final ThrowableMessage throwableMessage = (ThrowableMessage) cause; final Rejection rejection = toRejection(throwableMessage, envelope.getCommand()); final Class<?> rejectionClass = AnyPacker.unpack(rejection.getMessage()) .getClass(); Log.log().info("Posting rejection to RejectionBus.", rejectionClass.getName()); rejectionBus().post(rejection); result = reject(envelope.getId(), rejection); } else { final Error error = toError(cause); result = reject(envelope.getId(), error); } } return result; }

Target:
protected Ack doPost(CommandEnvelope envelope) { final CommandDispatcher<?> dispatcher = getDispatcher(envelope); Ack result; try { dispatcher.dispatch(envelope); commandStore.setCommandStatusOk(envelope); result = acknowledge(envelope.getId()); } catch (RuntimeException e) { final Throwable cause = getRootCause(e); commandStore.updateCommandStatus(envelope, cause, log); if (causedByRejection(e)) { final ThrowableMessage throwableMessage = (ThrowableMessage) cause; final Rejection rejection = toRejection(throwableMessage, envelope.getCommand()); final Class<?> rejectionClass = AnyPacker.unpack(rejection.getMessage()) .getClass(); Log.log().trace("Posting rejection to RejectionBus.", rejectionClass.getName()); rejectionBus().post(rejection); result = reject(envelope.getId(), rejection); } else { final Error error = toError(cause); result = reject(envelope.getId(), error); } } return result; }
Source:
public void setAlternateIpHeaders(final String... alternateIpHeaders) { Objects.requireNonNull(alternateIpHeaders, "Ip headers must be not null"); this.alternateIpHeaders = Arrays.asList(alternateIpHeaders); }

Target:
public void setAlternateIpHeaders(final String... alternateIpHeaders) { CommonHelper.assertNotNull("alternateIpHeaders", alternateIpHeaders); this.alternateIpHeaders = Arrays.asList(alternateIpHeaders); }
Source:
private void generateNewJobModel(List<String> processors) { List<String> currentProcessorsIds; if (processors.size() > 0) { currentProcessorsIds = zkUtils.getActiveProcessorsIDs(processors); } else { currentProcessorsIds = zkUtils.getSortedActiveProcessorsIDs(); } String currentJMVersion = zkUtils.getJobModelVersion(); String nextJMVersion; if (currentJMVersion == null) { LOGGER.info("pid=" + processorId + "generating first version of the model"); nextJMVersion = "1"; } else { nextJMVersion = Integer.toString(Integer.valueOf(currentJMVersion) + 1); } LOGGER.info("pid=" + processorId + "generating new model. Version = " + nextJMVersion); List<String> containerIds = new ArrayList<>(currentProcessorsIds.size()); for (String processorPid : currentProcessorsIds) { containerIds.add(processorPid); } LOGGER.info("generate new job model: processorsIds: " + Arrays.toString(containerIds.toArray())); JobModel jobModel = JobModelManager.readJobModel(this.config, Collections.emptyMap(), null, streamMetadataCache, containerIds); LOGGER.info("pid=" + processorId + "Generated jobModel: " + jobModel); zkUtils.publishJobModel(nextJMVersion, jobModel); LOGGER.info("pid=" + processorId + "published new JobModel ver=" + nextJMVersion + ";jm=" + jobModel); BarrierForVersionUpgrade barrier = coordinationUtils.getBarrier( JOB_MODEL_UPGRADE_BARRIER); barrier.start(nextJMVersion, currentProcessorsIds); zkUtils.publishJobModelVersion(currentJMVersion, nextJMVersion); LOGGER.info("pid=" + processorId + "published new JobModel ver=" + nextJMVersion); }

Target:
private void generateNewJobModel(List<String> processors) { List<String> currentProcessorsIds; if (processors.size() > 0) { currentProcessorsIds = zkUtils.getActiveProcessorsIDs(processors); } else { currentProcessorsIds = zkUtils.getSortedActiveProcessorsIDs(); } String currentJMVersion = zkUtils.getJobModelVersion(); String nextJMVersion; if (currentJMVersion == null) { LOG.info("pid=" + processorId + "generating first version of the model"); nextJMVersion = "1"; } else { nextJMVersion = Integer.toString(Integer.valueOf(currentJMVersion) + 1); } LOG.info("pid=" + processorId + "generating new model. Version = " + nextJMVersion); List<String> containerIds = new ArrayList<>(currentProcessorsIds.size()); for (String processorPid : currentProcessorsIds) { containerIds.add(processorPid); } LOG.info("generate new job model: processorsIds: " + Arrays.toString(containerIds.toArray())); JobModel jobModel = JobModelManager.readJobModel(this.config, Collections.emptyMap(), null, streamMetadataCache, containerIds); LOG.info("pid=" + processorId + "Generated jobModel: " + jobModel); zkUtils.publishJobModel(nextJMVersion, jobModel); BarrierForVersionUpgrade barrier = coordinationUtils.getBarrier( JOB_MODEL_UPGRADE_BARRIER); barrier.start(nextJMVersion, currentProcessorsIds); zkUtils.publishJobModelVersion(currentJMVersion, nextJMVersion); LOG.info("pid=" + processorId + "published new JobModel ver=" + nextJMVersion); }
Source:
private boolean isNonClientTransaction(GlobalTransaction gtx) { return globalTxTable.values().stream() .map(TxFunctions.mapTxStateToGlobalTransaction()) .noneMatch(TxFunctions.equalsGlobalTransaction(gtx)); }

Target:
private boolean isNonClientTransaction(GlobalTransaction gtx) { return !(gtx.getAddress() instanceof ClientAddress); }
Source:
public void sendRequest(String requestType, String endPoint, String foo, String loginInfo, String baseData, String baz, String type, DataTable modifications) throws Exception { String retrievedData = commonspec.retrieveData(baseData, type); commonspec.getLogger().debug("Modifying data as {}", retrievedData, type); String modifiedData; modifiedData = commonspec.modifyData(retrievedData, type, modifications).toString(); String user = null; String password = null; if (loginInfo != null) { user = loginInfo.substring(0, loginInfo.indexOf(':')); password = loginInfo.substring(loginInfo.indexOf(':') + 1, loginInfo.length()); } commonspec.getLogger().debug("Generating request to with data as {}", requestType, endPoint, modifiedData, type); Future<Response> response = commonspec.generateRequest(requestType, false, user, password, endPoint, modifiedData, type, ""); commonspec.getLogger().debug("Saving response"); commonspec.setResponse(requestType, response.get()); }

Target:
public void sendRequest(String requestType, String endPoint, String foo, String loginInfo, String baseData, String baz, String type, DataTable modifications) throws Exception { String retrievedData = commonspec.retrieveData(baseData, type); commonspec.getLogger().debug("Modifying data as {}", retrievedData, type); String modifiedData = commonspec.modifyData(retrievedData, type, modifications).toString(); String user = null; String password = null; if (loginInfo != null) { user = loginInfo.substring(0, loginInfo.indexOf(':')); password = loginInfo.substring(loginInfo.indexOf(':') + 1, loginInfo.length()); } commonspec.getLogger().debug("Generating request to with data as {}", requestType, endPoint, modifiedData, type); Future<Response> response = commonspec.generateRequest(requestType, false, user, password, endPoint, modifiedData, type, ""); commonspec.getLogger().debug("Saving response"); commonspec.setResponse(requestType, response.get()); }
Source:
private static boolean handlePushDownSingleDistinctCount(ImmutableList.Builder<AggregationColumnNode> nodeBuilder, AggregationNode aggregationNode, VariableReferenceExpression outputColumn, AggregationNode.Aggregation aggregation) { if (aggregation.getCall().getDisplayName().equalsIgnoreCase(COUNT_FUNCTION_NAME)) { List<RowExpression> arguments = aggregation.getCall().getArguments(); if (arguments.size() == 1) { RowExpression aggregationArgument = arguments.get(0); if (aggregationNode.getSource() instanceof AggregationNode) { AggregationNode sourceAggregationNode = (AggregationNode) aggregationNode.getSource(); Set<String> sourceAggregationGroupSet = getGroupKeys(sourceAggregationNode.getGroupingKeys()); Set<String> aggregationGroupSet = getGroupKeys(aggregationNode.getGroupingKeys()); aggregationGroupSet.add(aggregationArgument.toString()); if (sourceAggregationGroupSet.containsAll(aggregationGroupSet) && aggregationGroupSet.containsAll(sourceAggregationGroupSet)) { nodeBuilder.add( new AggregationFunctionColumnNode( outputColumn, new CallExpression( DISTINCT_COUNT_FUNCTION_NAME, aggregation.getFunctionHandle(), BigintType.BIGINT, ImmutableList.of(aggregationArgument)))); return true; } } } } return false; }

Target:
private static boolean handlePushDownSingleDistinctCount(ImmutableList.Builder<AggregationColumnNode> nodeBuilder, AggregationNode aggregationNode, VariableReferenceExpression outputColumn, AggregationNode.Aggregation aggregation) { if (!aggregation.getCall().getDisplayName().equalsIgnoreCase(COUNT_FUNCTION_NAME)) { return false; } List<RowExpression> arguments = aggregation.getCall().getArguments(); if (arguments.size() != 1) { return false; } RowExpression aggregationArgument = arguments.get(0); if (!(aggregationNode.getSource() instanceof AggregationNode)) { return false; } AggregationNode sourceAggregationNode = (AggregationNode) aggregationNode.getSource(); Set<String> sourceAggregationGroupSet = getGroupKeys(sourceAggregationNode.getGroupingKeys()); Set<String> aggregationGroupSet = getGroupKeys(aggregationNode.getGroupingKeys()); aggregationGroupSet.add(aggregationArgument.toString()); if (!sourceAggregationGroupSet.containsAll(aggregationGroupSet) && aggregationGroupSet.containsAll(sourceAggregationGroupSet)) { return false; } nodeBuilder.add( new AggregationFunctionColumnNode( outputColumn, new CallExpression( PINOT_DISTINCT_COUNT_FUNCTION_NAME, aggregation.getFunctionHandle(), aggregation.getCall().getType(), ImmutableList.of(aggregationArgument)))); return true; }
Source:
ServiceTerminator(EventService eventService, Set<ServiceTermination> terminations) { this.eventService = eventService; ArrayList<ServiceTermination> terminationsList = new ArrayList<>(terminations); Collections.sort(terminationsList, new ServiceTerminationComparator(terminations)); this.terminations = terminationsList; }

Target:
ServiceTerminator(EventService eventService, Set<ServiceTermination> terminations) { this.eventService = eventService; this.terminations = ImmutableSortedSet.copyOf(new ServiceTerminationComparator(terminations), terminations); }
Source:
public void testLabelsUnderline() throws Exception { File property = new File(TestData.getResource(this, "nonStraightLines.properties").toURI()); PropertyDataStore dataStore = new PropertyDataStore(property.getParentFile()); SimpleFeatureSource featureSource = dataStore.getFeatureSource("nonStraightLines"); ReferencedEnvelope bounds = featureSource.getBounds(); bounds.expandBy(1, 1); Style style = RendererBaseTest.loadStyle(this, "underlineStyle.sld"); MapContent mapContent = new MapContent(); mapContent.addLayer(new FeatureLayer(featureSource, style)); StreamingRenderer renderer = new StreamingRenderer(); renderer.setMapContent(mapContent); renderer.setJava2DHints(new RenderingHints(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON)); BufferedImage image = new BufferedImage(1000, 1000, BufferedImage.TYPE_3BYTE_BGR); Graphics2D graphics = image.createGraphics(); graphics.setColor(Color.LIGHT_GRAY); graphics.fillRect(0, 0, image.getWidth(), image.getHeight()); renderer.paint(graphics, new Rectangle(0, 0, image.getWidth(), image.getHeight()), bounds); File reference = new File("./src/test/resources/org/geotools/renderer/lite/test-data/underlineStyle.sld.png"); ImageAssert.assertEquals(reference, image, 100); }

Target:
public void testLabelsUnderline() throws Exception { File property = new File(TestData.getResource(this, "nonStraightLines.properties").toURI()); PropertyDataStore dataStore = new PropertyDataStore(property.getParentFile()); SimpleFeatureSource featureSource = dataStore.getFeatureSource("nonStraightLines"); ReferencedEnvelope bounds = featureSource.getBounds(); bounds.expandBy(1, 1); Style style = RendererBaseTest.loadStyle(this, "underlineStyle.sld"); MapContent mapContent = new MapContent(); mapContent.addLayer(new FeatureLayer(featureSource, style)); StreamingRenderer renderer = new StreamingRenderer(); renderer.setMapContent(mapContent); renderer.setJava2DHints(new RenderingHints(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON)); BufferedImage image = new BufferedImage(1000, 1000, BufferedImage.TYPE_3BYTE_BGR); Graphics2D graphics = image.createGraphics(); graphics.setColor(Color.LIGHT_GRAY); graphics.fillRect(0, 0, image.getWidth(), image.getHeight()); renderer.paint(graphics, new Rectangle(0, 0, image.getWidth(), image.getHeight()), bounds); File reference = new File("./src/test/resources/org/geotools/renderer/lite/test-data/underlineStyle.sld.png"); ImageAssert.assertEquals(reference, image, 1200); }
Source:
public void testNettyDockerCmdExecFactoryConfigWithoutApiVersion() throws Exception { NettyDockerCmdExecFactory factory = new NettyDockerCmdExecFactory(); Builder configBuilder = DefaultDockerClientConfig.createDefaultConfigBuilder().withDockerHost("tcp://localhost:2378"); DockerClient client = DockerClientBuilder.getInstance(configBuilder) .withDockerCmdExecFactory(factory) .build(); FakeDockerServer server = new FakeDockerServer(2378); server.start(); try { client.versionCmd().exec(); List<HttpRequest> requests = server.getRequests(); assertEquals(requests.size(), 1); assertEquals(requests.get(0).uri(), "/version"); } finally { server.stop(); } }

Target:
public void testNettyDockerCmdExecFactoryConfigWithoutApiVersion() throws Exception { int dockerPort = getFreePort(); NettyDockerCmdExecFactory factory = new NettyDockerCmdExecFactory(); Builder configBuilder = DefaultDockerClientConfig.createDefaultConfigBuilder().withDockerHost("tcp://localhost:" + dockerPort); DockerClient client = DockerClientBuilder.getInstance(configBuilder) .withDockerCmdExecFactory(factory) .build(); FakeDockerServer server = new FakeDockerServer(dockerPort); server.start(); try { client.versionCmd().exec(); List<HttpRequest> requests = server.getRequests(); assertEquals(requests.size(), 1); assertEquals(requests.get(0).uri(), "/version"); } finally { server.stop(); } }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BoolExpression other = (BoolExpression) obj; return Objects.equals(mustClauses, other.mustClauses) && Objects.equals(mustNotClauses, other.mustNotClauses) && Objects.equals(shouldClauses, other.shouldClauses) && Objects.equals(filterClauses, other.filterClauses) && Objects.equals(minShouldMatch, other.minShouldMatch); }

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BoolExpression other = (BoolExpression) obj; return Objects.equals(mustClauses, other.mustClauses) && Objects.equals(mustNotClauses, other.mustNotClauses) && Objects.equals(shouldClauses, other.shouldClauses) && Objects.equals(filterClauses, other.filterClauses) && minShouldMatch == other.minShouldMatch; }
Source:
private void registerEndpoints() { env.register(remoteLockService); env.register(timestampService); if (config.leader().isPresent()) { localPaxosServices = Leaders.createAndRegisterLocalServices(env, config.leader().get(), userAgent); } env.register(persistentLockService); env.register(new CheckAndSetExceptionMapper()); env.register(sweeperService); }

Target:
private void registerEndpoints() { if (config.leader().isPresent()) { registerTimestampAndLockEndpoints(); localPaxosServices = Leaders.createAndRegisterLocalServices(env, config.leader().get(), userAgent); } else if (!((config.timestamp().isPresent() && config.lock().isPresent()) || config.timelock().isPresent())) { registerTimestampAndLockEndpoints(); } env.register(persistentLockService); env.register(new CheckAndSetExceptionMapper()); env.register(sweeperService); }
Source:
private void addOrUpdateAttributeInstance(final Case openCase, Map<ArtifactKey, CorrelationAttributeInstance> artifactInstances, AbstractFile caseDbFile) throws TskCoreException, EamDbException { CorrelationCase caze = new CorrelationCase(openCase.getNumber(), openCase.getDisplayName()); CorrelationDataSource dataSource = CorrelationDataSource.fromTSKDataSource(caze, caseDbFile.getDataSource()); String filePath = caseDbFile.getParentPath() + caseDbFile.getName(); ArtifactKey instKey = new ArtifactKey(dataSource.getDeviceID(), filePath); CorrelationAttributeInstance caseDbInstance = new CorrelationAttributeInstance(caze, dataSource, filePath, "", caseDbFile.getKnown()); TskData.FileKnown knownStatus = caseDbInstance.getKnownStatus(); if (knownStatus.compareTo(TskData.FileKnown.KNOWN) != 0 && knownStatus.compareTo(TskData.FileKnown.BAD) != 0) { List<ContentTag> fileMatchTags = openCase.getServices().getTagsManager().getContentTagsByContent(caseDbFile); for (ContentTag tag : fileMatchTags) { TskData.FileKnown tagKnownStatus = tag.getName().getKnownStatus(); if (tagKnownStatus.compareTo(TskData.FileKnown.KNOWN) == 0 || tagKnownStatus.compareTo(TskData.FileKnown.BAD) == 0) { caseDbInstance.setKnownStatus(TskData.FileKnown.BAD); break; } } } if (knownStatus.compareTo(TskData.FileKnown.KNOWN) == 0 || knownStatus.compareTo(TskData.FileKnown.BAD) == 0 || !artifactInstances.containsKey(instKey)) { artifactInstances.put(instKey, caseDbInstance); } }

Target:
private void addOrUpdateAttributeInstance(final Case openCase, Map<ArtifactKey, CorrelationAttributeInstance> artifactInstances, AbstractFile caseDbFile) throws TskCoreException, EamDbException { CorrelationCase caze = new CorrelationCase(openCase.getNumber(), openCase.getDisplayName()); CorrelationDataSource dataSource = CorrelationDataSource.fromTSKDataSource(caze, caseDbFile.getDataSource()); String filePath = caseDbFile.getParentPath() + caseDbFile.getName(); ArtifactKey instKey = new ArtifactKey(dataSource.getDeviceID(), filePath); CorrelationAttributeInstance caseDbInstance = new CorrelationAttributeInstance(caze, dataSource, filePath, "", caseDbFile.getKnown()); TskData.FileKnown knownStatus = caseDbInstance.getKnownStatus(); TskData.FileKnown knownBad = TskData.FileKnown.BAD; if (!knownStatus.equals(knownBad)) { List<ContentTag> fileMatchTags = openCase.getServices().getTagsManager().getContentTagsByContent(caseDbFile); for (ContentTag tag : fileMatchTags) { TskData.FileKnown tagKnownStatus = tag.getName().getKnownStatus(); if (tagKnownStatus.equals(knownBad)) { caseDbInstance.setKnownStatus(knownBad); break; } } } if (caseDbInstance.getKnownStatus().equals(knownBad) || !artifactInstances.containsKey(instKey)) { artifactInstances.put(instKey, caseDbInstance); } }
Source:
protected StringBuilder newDeprecatedMessage() { StringBuilder builder = new StringBuilder().append("Property '") .append(getXPath()) .append("' is marked as deprecated from '") .append(getSchema().getName()) .append("' schema"); Property deprecatedParent = getDeprecatedParent(); if (deprecatedParent != this) { builder.append(" because property '") .append(deprecatedParent.getXPath()) .append("' is marked as deprecated"); } return builder.append(", don't use it anymore.\n"); }

Target:
protected StringBuilder newDeprecatedMessage() { StringBuilder builder = new StringBuilder().append("Property '") .append(getXPath()) .append("' is marked as deprecated from '") .append(getSchema().getName()) .append("' schema"); Property deprecatedParent = getDeprecatedParent(); if (deprecatedParent != this) { builder.append(" because property '") .append(deprecatedParent.getXPath()) .append("' is marked as deprecated"); } return builder.append(", don't use it anymore. "); }
Source:
static public int rapidParseInt(final String input) { final int len = input.length(); int val = 0; int i = 0; boolean isNegative = false; if (0 < len && '-' == input.charAt(0)) { i = 1; isNegative = true; } for (; i < len; ++i) { final char ch = input.charAt(i); if (Character.isDigit(ch)) { val = (val * 10) + (ch - 48); } else { break; } } if (isNegative) val = -val; return val; }

Target:
public static int rapidParseInt(final String input) { final int len = input.length(); int val = 0; int i = 0; boolean isNegative = false; if (0 < len && '-' == input.charAt(0)) { i = 1; isNegative = true; } for (; i < len; ++i) { final char ch = input.charAt(i); if (Character.isDigit(ch)) { val = (val * 10) + (ch - 48); } else { break; } } if (isNegative) val = -val; return val; }
Source:
private synchronized void receiveMessages() { if (receiverSubscription.get() != null) { receiverSubscription.get().request(1); return; } ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.receiveMessages() .parallel(processorOptions.getMaxConcurrentCalls()) .runOn(Schedulers.boundedElastic()) .subscribe(new Subscriber<ServiceBusReceivedMessageContext>() { @Override public void onSubscribe(Subscription subscription) { receiverSubscription.set(subscription); receiverSubscription.get().request(1); } @Override public void onNext(ServiceBusReceivedMessageContext serviceBusReceivedMessageContext) { if (serviceBusReceivedMessageContext.hasError()) { handleError(serviceBusReceivedMessageContext.getThrowable()); } else { try { ServiceBusProcessorMessageContext serviceBusProcessorMessageContext = new ServiceBusProcessorMessageContext(receiverClient, serviceBusReceivedMessageContext); processMessage.accept(serviceBusProcessorMessageContext); } catch (Exception exception) { handleError(exception); } } if (isRunning.get()) { logger.verbose("Requesting 1 more message from upstream"); receiverSubscription.get().request(1); } } @Override public void onError(Throwable throwable) { logger.info("Error receiving messages.", throwable); handleError(throwable); if (isRunning.get()) { restartMessageReceiver(); } } @Override public void onComplete() { logger.info("Completed receiving messages."); if (isRunning.get()) { restartMessageReceiver(); } } }); }

Target:
private synchronized void receiveMessages() { if (receiverSubscription.get() != null) { receiverSubscription.get().request(1); return; } ServiceBusReceiverAsyncClient receiverClient = asyncClient.get(); receiverClient.receiveMessages() .parallel(processorOptions.getMaxConcurrentCalls()) .runOn(Schedulers.boundedElastic()) .subscribe(new Subscriber<ServiceBusReceivedMessageContext>() { @Override public void onSubscribe(Subscription subscription) { receiverSubscription.set(subscription); receiverSubscription.get().request(1); } @Override public void onNext(ServiceBusReceivedMessageContext serviceBusReceivedMessageContext) { if (serviceBusReceivedMessageContext.hasError()) { handleError(serviceBusReceivedMessageContext.getThrowable()); } else { try { ServiceBusProcessorMessageContext serviceBusProcessorMessageContext = new ServiceBusProcessorMessageContext(receiverClient, serviceBusReceivedMessageContext); processMessage.accept(serviceBusProcessorMessageContext); } catch (Exception ex) { handleError(ex); logger.warning("Error when processing message. Abandoning message.", ex); abandonMessage(serviceBusReceivedMessageContext, receiverClient); } } if (isRunning.get()) { logger.verbose("Requesting 1 more message from upstream"); receiverSubscription.get().request(1); } } @Override public void onError(Throwable throwable) { logger.info("Error receiving messages.", throwable); handleError(throwable); if (isRunning.get()) { restartMessageReceiver(); } } @Override public void onComplete() { logger.info("Completed receiving messages."); if (isRunning.get()) { restartMessageReceiver(); } } }); }
Source:
public void run() { final Timer.Context timerCtx = rollupLocatorExecuteTimer.time(); try { getGranularity().finer(); } catch (Exception ex) { log.error("No finer granularity available than " + getGranularity()); return; } if (log.isTraceEnabled()) log.trace("Getting locators for @ {}", new Object[]{parentSlotKey, parentRange.toString(), scheduleCtx.getCurrentTimeMillis()}); long waitStart = System.currentTimeMillis(); int rollCount = 0; final RollupExecutionContext executionContext = createRollupExecutionContext(); final RollupBatchWriter rollupBatchWriter = createRollupBatchWriter(executionContext); Set<Locator> locators = getLocators(executionContext); log.debug("locators retrieved: {}", locators.size()); for (Locator locator : locators) { rollCount = processLocator(rollCount, executionContext, rollupBatchWriter, locator); } drainExecutionContext(waitStart, rollCount, executionContext, rollupBatchWriter); timerCtx.stop(); }

Target:
public void run() { final Timer.Context timerCtx = rollupLocatorExecuteTimer.time(); try { getGranularity().finer(); } catch (Exception ex) { log.error("No finer granularity available than " + getGranularity()); return; } if (log.isTraceEnabled()) log.trace("Getting locators for @ {}", new Object[]{parentSlotKey, parentRange.toString(), scheduleCtx.getCurrentTimeMillis()}); long waitStart = System.currentTimeMillis(); int rollCount = 0; final RollupExecutionContext executionContext = createRollupExecutionContext(); final RollupBatchWriter rollupBatchWriter = createRollupBatchWriter(executionContext); Set<Locator> locators = getLocators(executionContext); if (log.isTraceEnabled()) log.trace("locators retrieved: {}", locators.size()); for (Locator locator : locators) { rollCount = processLocator(rollCount, executionContext, rollupBatchWriter, locator); } drainExecutionContext(waitStart, rollCount, executionContext, rollupBatchWriter); timerCtx.stop(); }
Source:
public void receiveCommand(Item item, Command command, ZWaveNode node, ZWaveWakeUpCommandClass commandClass, int endpointId, Map<String, String> arguments) { ZWaveCommandConverter<?, ?> converter = this.getCommandConverter(command.getClass()); if (converter == null) { logger.warn("NODE {}: No converter found for item={}, type={}, endpoint={}, ignoring command.", node.getNodeId(), item.getName(), command.getClass().getSimpleName(), endpointId); return; } ZWaveProductDatabase database = new ZWaveProductDatabase(); if (database.FindProduct(node.getManufacturer(), node.getDeviceType(), node.getDeviceId(), node.getApplicationVersion()) == false) { logger.error("NODE {}: database can't find product.", node.getNodeId()); return; } SerialMessage serialMessage = commandClass .setInterval((Integer) converter.convertFromCommandToValue(item, command)); if (serialMessage == null) { logger.warn("NODE {}: Generating message failed for command class = {}, endpoint = {}", node.getNodeId(), commandClass.getCommandClass().getLabel(), endpointId); return; } this.getController().sendData(serialMessage); serialMessage = commandClass.getIntervalMessage(); this.getController().sendData(serialMessage); if (command instanceof State) { this.getEventPublisher().postUpdate(item.getName(), (State) command); } }

Target:
public void receiveCommand(Item item, Command command, ZWaveNode node, ZWaveWakeUpCommandClass commandClass, int endpointId, Map<String, String> arguments) { ZWaveCommandConverter<?, ?> converter = this.getCommandConverter(command.getClass()); if (converter == null) { logger.warn("NODE {}: No converter found for item={}, type={}, endpoint={}, ignoring command.", node.getNodeId(), item.getName(), command.getClass().getSimpleName(), endpointId); return; } SerialMessage serialMessage = commandClass .setInterval((Integer) converter.convertFromCommandToValue(item, command)); if (serialMessage == null) { logger.warn("NODE {}: Generating message failed for command class = {}, endpoint = {}", node.getNodeId(), commandClass.getCommandClass().getLabel(), endpointId); return; } this.getController().sendData(serialMessage); serialMessage = commandClass.getIntervalMessage(); this.getController().sendData(serialMessage); if (command instanceof State) { this.getEventPublisher().postUpdate(item.getName(), (State) command); } }
Source:
protected void render0(FunctionRenderContext context) { Object[] jsonPathElements = new Object[context.getArgumentsSize()]; jsonPathElements[0] = "val"; for (int i = 1; i < context.getArgumentsSize(); i++) { try { jsonPathElements[i] = Integer.parseInt(JpqlFunctionUtil.unquoteSingleQuotes(context.getArgument(i))); } catch (NumberFormatException e) { jsonPathElements[i] = JpqlFunctionUtil.unquoteDoubleQuotes(JpqlFunctionUtil.unquoteSingleQuotes(context.getArgument(i))); } } String jsonPath = AbstractJsonGetFunction.toJsonPath(jsonPathElements, jsonPathElements.length, false); context.addChunk("json_query(concat('{\"val\":', concat("); context.addArgument(0); context.addChunk(", '}'))"); context.addChunk(",'"); context.addChunk(jsonPath); context.addChunk("' OMIT QUOTES)"); }

Target:
protected void render0(FunctionRenderContext context) { List<Object> jsonPathElements = AbstractJsonGetFunction.retrieveJsonPathElements(context, 1); jsonPathElements.add(0, "val"); String jsonPath = AbstractJsonGetFunction.toJsonPath(jsonPathElements, jsonPathElements.size(), false); context.addChunk("json_query(concat('{\"val\":', concat("); context.addArgument(0); context.addChunk(", '}'))"); context.addChunk(",'"); context.addChunk(jsonPath); context.addChunk("' OMIT QUOTES)"); }
Source:
@Override protected void onResume() { super.onResume(); testSuite.setTestList((AbstractTest[]) null); testSuite.getTestList(getPreferenceManager()); Integer runTime = testSuite.getRuntime(getPreferenceManager()); if (runTime.equals(PreferenceManager.MAX_RUNTIME_DISABLED)) runTime = 3600; runtime.setText(getString(R.string.twoParam, testSuite.getDataUsage(), getString(R.string.Dashboard_Card_Seconds, runTime.toString()))); }

Target:
@Override protected void onResume() { super.onResume(); testSuite.setTestList((AbstractTest[]) null); testSuite.getTestList(getPreferenceManager()); runtime.setText(getString(R.string.twoParam, testSuite.getDataUsage(), getString(R.string.Dashboard_Card_Seconds, testSuite.getRuntime(getPreferenceManager()).toString()))); }
Source:
public ExtractedMetadata doParseWithTimeout(final InputStream is, final long timeoutInMs) throws IOException { final int parseNumber = nextParseNumber.getAndIncrement(); final Thread t = Thread.currentThread(); final TimerTask killTaskHard = new TimerTask() { @Override public void run() { synchronized (parseNumbersInProgress) { if(parseNumbersInProgress.contains(parseNumber)) { logger.info("Killing parsing thread because it's taking too long", t.getId()); t.stop(); } } } }; final TimerTask killTaskSoftly = new TimerTask() { @Override public void run() { synchronized (parseNumbersInProgress) { if(parseNumbersInProgress.contains(parseNumber)) { logger.info("Interrupting parsing thread because it's taking too long", t.getId()); t.interrupt(); parserKillerTimer.schedule(killTaskHard, 2*timeoutInMs); } } } }; synchronized (parseNumbersInProgress) { parseNumbersInProgress.add(parseNumber); } final ExtractedMetadata result; final boolean wasInterrupted; parserKillerTimer.schedule(killTaskSoftly, timeoutInMs); try { try { result = doParse(is); } catch(final ThreadDeath e) { throw new RuntimeException("Science-parse killer got impatient", e); } } finally { synchronized (parseNumbersInProgress) { parseNumbersInProgress.remove(parseNumber); } wasInterrupted = Thread.interrupted(); } if(wasInterrupted) logger.info("Overriding interruption of parsing thread because it finished before we could react", t.getId()); assert !Thread.interrupted(); return result; }

Target:
public ExtractedMetadata doParseWithTimeout(final InputStream is, final long timeoutInMs) throws IOException { final int parseNumber = nextParseNumber.getAndIncrement(); final Thread t = Thread.currentThread(); final TimerTask killTaskHard = new TimerTask() { @Override public void run() { synchronized (parseNumbersInProgress) { if(parseNumbersInProgress.contains(parseNumber)) { logger.info("Killing parsing thread because it's taking too long", t.getId()); t.stop(); } } } }; final TimerTask killTaskSoftly = new TimerTask() { @Override public void run() { synchronized (parseNumbersInProgress) { if(parseNumbersInProgress.contains(parseNumber)) { logger.info("Interrupting parsing thread because it's taking too long", t.getId()); t.interrupt(); } } } }; synchronized (parseNumbersInProgress) { parseNumbersInProgress.add(parseNumber); } final ExtractedMetadata result; final boolean wasInterrupted; parserKillerTimer.schedule(killTaskSoftly, timeoutInMs); parserKillerTimer.schedule(killTaskHard, 3*timeoutInMs); try { try { result = doParse(is); } catch(final ThreadDeath e) { throw new RuntimeException("Science-parse killer got impatient", e); } } finally { synchronized (parseNumbersInProgress) { parseNumbersInProgress.remove(parseNumber); } wasInterrupted = Thread.interrupted(); } if(wasInterrupted) logger.info("Overriding interruption of parsing thread because it finished before we could react", t.getId()); assert !Thread.interrupted(); return result; }