auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void closesAllParts() throws IOException { RqMultipart.Base multi = null; try { final String body = "RqMultipartTest.closesAllParts"; final RqMultipart request = new RqMultipart.Fake( new RqFake(), new RqGreedy( new RqWithHeaders( new RqFake("", "", body), RqMultipartTest.contentLengthHeader( (long) body.getBytes().length ), RqMultipartTest.contentDispositionHeader( "form-data; name=\"name\"" ) ) ), new RqGreedy( new RqWithHeaders( new RqFake("", "", body), RqMultipartTest.contentLengthHeader(0L), RqMultipartTest.contentDispositionHeader( "form-data; name=\"content\"; filename=\"a.bin\"" ) ) ) ); multi = new RqMultipart.Base(request); multi.part("name").iterator().next().body().read(); multi.part("content").iterator().next().body().read(); multi.body().close(); } catch (final IOException ex) { Assert.fail("An IOException was not expected"); } MatcherAssert.assertThat( multi.part("name").iterator().next(), Matchers.notNullValue() ); try { multi.part("name").iterator().next().body().read(); Assert.fail( "An IOException was expected since the Stream is closed" ); } catch (final IOException ex) { MatcherAssert.assertThat( multi.part("content").iterator().next(), Matchers.notNullValue() ); multi.part("content").iterator().next().body().read(); } }

Target:
public void closesAllParts() throws Exception { final String body = "RqMultipartTest.closesAllParts"; final RqMultipart request = new RqMultipart.Fake( new RqFake(), new RqGreedy( new RqWithHeaders( new RqFake("", "", body), RqMultipartTest.contentLengthHeader( (long) body.getBytes().length ), RqMultipartTest.contentDispositionHeader( "form-data; name=\"name\"" ) ) ), new RqGreedy( new RqWithHeaders( new RqFake("", "", body), RqMultipartTest.contentLengthHeader(0L), RqMultipartTest.contentDispositionHeader( "form-data; name=\"content\"; filename=\"a.bin\"" ) ) ) ); final RqMultipart.Base multi = new RqMultipart.Base(request); multi.part("name").iterator().next().body().read(); multi.part("content").iterator().next().body().read(); multi.body().close(); MatcherAssert.assertThat( multi.part("name").iterator().next(), Matchers.notNullValue() ); try { multi.part("name").iterator().next().body().read(); Assert.fail( "An IOException was expected since the Stream is closed" ); } catch (final IOException ex) { MatcherAssert.assertThat( ex.getMessage(), Matchers.containsString("Closed") ); } MatcherAssert.assertThat( multi.part("content").iterator().next(), Matchers.notNullValue() ); try { multi.part("content").iterator().next().body().read(); Assert.fail( "An IOException was expected since the Stream is closed" ); } catch (final IOException ex) { MatcherAssert.assertThat( ex.getMessage(), Matchers.containsString("Closed") ); } }
Source:
public void cwlIncompleteOutput() throws IOException { File file = new File(ResourceHelpers.resourceFilePath("incompleteOutput.cwl")); File json = new File(ResourceHelpers.resourceFilePath("1st-workflow-job.json")); ArrayList<String> args = new ArrayList<String>() {{ add("tool"); add("launch"); add("--local-entry"); add(file.getAbsolutePath()); add("--json"); add(json.getAbsolutePath()); }}; exit.expectSystemExit(); exit.checkAssertionAfterwards( () -> assertTrue("output should include an error message and exit", systemErrRule.getLog().contains(""))); runClientCommand(args, false); }

Target:
public void cwlIncompleteOutput() throws IOException { File file = new File(ResourceHelpers.resourceFilePath("incompleteOutput.cwl")); File json = new File(ResourceHelpers.resourceFilePath("1st-workflow-job.json")); ArrayList<String> args = new ArrayList<String>() {{ add("tool"); add("launch"); add("--local-entry"); add(file.getAbsolutePath()); add("--json"); add(json.getAbsolutePath()); }}; runClientCommand(args, false); assertTrue("output should include an error message", systemErrRule.getLog().contains("The error was: 'NoneType' object is not iterable")); }
Source:
private void syncUpstreams( ) { Collection<UpstreamInfo> upstreamsInBaragon = lbClient.getUpstreams(); Collection<UpstreamInfo> upstreamsInSingularity = getUpstreamsFromActiveTasks(); upstreamsInBaragon.removeAll(upstreamsInSingularity); for (UpstreamInfo upstream: upstreamsInBaragon){ } }

Target:
public void syncUpstreams() { for (SingularityRequestWithState singularityRequestWithState: requestManager.getActiveRequests()){ final SingularityRequest singularityRequest = singularityRequestWithState.getRequest(); lock.runWithRequestLock(() -> syncUpstreamsForService(singularityRequest), singularityRequest.getId(), getClass().getSimpleName()); } }
Source:
public void process(KeyFilter keyFilter, CacheLoaderTask cacheLoaderTask, Executor executor, boolean fetchValue, boolean fetchMetadata) { try { Set<Object> keys = loader.loadAllKeys(null); int batchSize = 1000; ExecutorAllCompletionService eacs = new ExecutorAllCompletionService(executor); final TaskContext taskContext = new TaskContextImpl(); Set<Object> entries = new HashSet<Object>(batchSize); for (Object key : keys) { if (keyFilter == null || keyFilter.shouldLoadKey(key)) entries.add(key); if (entries.size() == batchSize) { final Set<Object> batch = entries; entries = new HashSet<Object>(batchSize); submitProcessTask(cacheLoaderTask, eacs, taskContext, batch, fetchValue, fetchMetadata); } } if (!entries.isEmpty()) { submitProcessTask(cacheLoaderTask, eacs, taskContext, entries, fetchValue, fetchMetadata); } eacs.waitUntilAllCompleted(); if (eacs.isExceptionThrown()) { throw newCacheLoaderException(null); } } catch (CacheLoaderException e) { throw newCacheLoaderException(e); } }

Target:
public void process(KeyFilter keyFilter, CacheLoaderTask cacheLoaderTask, Executor executor, boolean fetchValue, boolean fetchMetadata) { try { Set<Object> keys = loader.loadAllKeys(null); int batchSize = 1000; ExecutorAllCompletionService eacs = new ExecutorAllCompletionService(executor); final TaskContext taskContext = new TaskContextImpl(); Set<Object> entries = new HashSet<Object>(batchSize); for (Object key : keys) { if (keyFilter == null || keyFilter.shouldLoadKey(key)) entries.add(key); if (entries.size() == batchSize) { final Set<Object> batch = entries; entries = new HashSet<Object>(batchSize); submitProcessTask(cacheLoaderTask, eacs, taskContext, batch, fetchValue, fetchMetadata); } } if (!entries.isEmpty()) { submitProcessTask(cacheLoaderTask, eacs, taskContext, entries, fetchValue, fetchMetadata); } eacs.waitUntilAllCompleted(); if (eacs.isExceptionThrown()) { throw newCacheLoaderException(eacs.getFirstException()); } } catch (CacheLoaderException e) { throw newCacheLoaderException(e); } }
Source:
public static Object getMinValueForType(FieldType type) throws Exception { switch (type) { case INTEGER: { return Long.MIN_VALUE; } case BOOLEAN: { return false; } case REAL: { return Double.MIN_VALUE; } case DECIMAL: { return BigDecimal.valueOf(Double.MIN_VALUE); } case STRING: { return minStringValue; } default: System.out.println("Invalid field type for index field."); throw new Exception("Invalid field type for index field."); } }

Target:
public static Object getMinValueForType(FieldType type) throws Exception { switch (type) { case INTEGER: { return Long.MIN_VALUE; } case BOOLEAN: { return false; } case REAL: { return Double.MIN_VALUE; } case DECIMAL: { return BigDecimal.valueOf(Double.MIN_VALUE); } case STRING: { return minStringValue; } default: throw new Exception("Invalid field type for index field."); } }
Source:
protected void createFieldEditors() { addField(new IntegerFieldEditor(WMS_RESPONSE_TIMEOUT, "WMS response timeout", getFieldEditorParent())); }

Target:
protected void createFieldEditors() { addField(new IntegerFieldEditor(WmsPreferenceConstants.WMS_RESPONSE_TIMEOUT, "WMS response timeout", getFieldEditorParent())); }
Source:
private void queueConsoleCommand(String command) throws Throwable { queueConsoleCommand(command, DEFAULT_TIMEOUT, DEFAULT_TIME_UNIT); }

Target:
private void queueConsoleCommand(String command) throws Throwable { queueConsoleCommand(command, TestsPlugin.massageTimeout(DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); }
Source:
public IAtsProgram getProgram(Object artifact) { IAtsProgram program = null; if (artifact instanceof ArtifactReadable) { ArtifactReadable artRead = (ArtifactReadable) artifact; if (artRead.isOfType(AtsArtifactTypes.Program)) { program = new Program(logger, atsServer, (ArtifactReadable) artifact); } } return program; }

Target:
public IAtsProgram getProgram(Object artifact) { IAtsProgram program = null; if (artifact instanceof ArtifactReadable) { ArtifactReadable artRead = (ArtifactReadable) artifact; if (artRead.isOfType(AtsArtifactTypes.Program)) { program = new Program(logger, atsServer, artRead); } } return program; }
Source:
private static Type createVarcharType(RichColumnDescriptor descriptor) { if (descriptor.getHiveType() != null && descriptor.getHiveType().getTypeInfo().getClass() == VarcharTypeInfo.class) { VarcharTypeInfo typeInfo = (VarcharTypeInfo) descriptor.getHiveType().getTypeInfo(); return VarcharType.createVarcharType(typeInfo.getLength()); } else { return VarcharType.VARCHAR; } }

Target:
private static Type createVarcharType(RichColumnDescriptor descriptor) { if (descriptor.getHiveType().isPresent()) { TypeInfo typeInfo = descriptor.getHiveType().get().getTypeInfo(); if (typeInfo instanceof VarcharTypeInfo) { return VarcharType.createVarcharType(((VarcharTypeInfo) typeInfo).getLength()); } } return VarcharType.VARCHAR; }
Source:
public void verifyPinTypeExist(String pinTypeName){ waitForElementVisibleByElement(mapFrame); driver.switchTo().frame(mapFrame); while(createdPinNames.size()-1!=0){ if(createdPinNames .get(createdPinNames.size()-1) .getText() .contains(pinTypeName) ){ Assertion.assertEquals( pinTypeName, createdPinNames.get(createdPinNames.size()-1).getText()); break; } } driver.switchTo().defaultContent(); }

Target:
public void verifyPinTypeExist(String pinTypeName){ waitForElementVisibleByElement(mapFrame); driver.switchTo().frame(mapFrame); while(createdPinNames.size()-1!=0){ if(createdPinNames .get(createdPinNames.size()-1) .getText() .contains(pinTypeName) ){ Assertion.assertEquals( pinTypeName, createdPinNames.get(createdPinNames.size()-1).getText()); } else { PageObjectLogging.log( "verifyPinTypeExist", "Pin type with name " + pinTypeName + " does not exist", true ); } break; } driver.switchTo().defaultContent(); }
Source:
public StatusDTO setManagerCapabilities(Collection<String> capabilities) { if (capabilities != null) { if (this.capabilities == null) { this.capabilities = new HashSet<String>(); } this.capabilities.clear(); this.capabilities.addAll(capabilities); } else { this.capabilities = null; } return this; }

Target:
public StatusDTO setManagerCapabilities(Collection<String> capabilities) { if (capabilities != null) { if (this.capabilities == null) { this.capabilities = new HashSet<>(); } this.capabilities.clear(); this.capabilities.addAll(capabilities); } else { this.capabilities = null; } return this; }
Source:
public void getBlobTest() throws Exception { MvcResult rtn = mockMvc.perform(get(ENDPOINT)) .andExpect(status().isOk()) .andExpect(header().string(HttpConstants.HEADER_CONTENT_DISPOSITION,"attachment; filename=project.zip")) .andReturn(); assertEquals(getCompareFile(PROFILE, "txt", "TestBlob"), extractZipContent(rtn.getResponse().getContentAsByteArray(), "projectTestBlob.txt")); }

Target:
public void getBlobTest() throws Exception { MvcResult rtn = mockMvc.perform(get(ENDPOINT)) .andExpect(status().isOk()) .andExpect(header().string(HttpConstants.HEADER_CONTENT_DISPOSITION,"attachment; filename=project.zip")) .andReturn(); assertEquals(getCompareFile("project/projectTestBlob.txt"), extractZipContent(rtn.getResponse().getContentAsByteArray(), "projectTestBlob.txt")); }
Source:
public void testInvalidHeaderParam() { String[] preferredIDs = { "P-Asserted-Identity:sip:33296112233@provider.com;user=phone\n", "P-Asserted-Identity: <sip:alice@atlanta.com>, <tel:+1-201-555-0123>;user=phone\n" }; for (String preferredID :preferredIDs) { try { System.out.println("preferredID:"+preferredID); HeaderParser hp = createParser(PAssertedIdentityParser.class, preferredID); hp.parse(); fail("Header:"+ preferredID + " cannot be parse, wrong in pattern"); } catch (java.text.ParseException ex) { } } }

Target:
public void testInvalidHeaderParam() { String preferredID = "P-Asserted-Identity:sip:33296112233@provider.com;user=phone\n"; try { HeaderParser hp = createParser(PAssertedIdentityParser.class, preferredID); hp.parse(); fail("Header:"+ preferredID + " cannot be parse, wrong in pattern"); } catch (java.text.ParseException ex) { assertTrue(ex.getMessage().contains("This Header Field cannot has Parameters")); } }
Source:
public void testSingleThread_sync_parallel() throws Exception { Runnable mock = mock(Runnable.class); doAnswer(a -> sleep(500)).when(mock).run(); safeCaller.modified(new HashMap<String, Object>() { private static final long serialVersionUID = 1L; { put("singleThread", "true"); } }); spawn(() -> { assertDurationBetween(50, 450, () -> { safeCaller.create(mock).withTimeout(100).build().run(); }); }); spawn(() -> { assertDurationBelow(20, () -> { safeCaller.create(mock).withTimeout(100).build().run(); }); }); assertDurationBetween(50, 450, () -> { waitForAssert(() -> { verify(mock, times(2)).run(); }); }); }

Target:
public void testSingleThread_sync_parallel() throws Exception { Runnable mock = mock(Runnable.class); doAnswer(a -> sleep(500)).when(mock).run(); configureSingleThread(); spawn(() -> { assertDurationBetween(50, 450, () -> { safeCaller.create(mock).withTimeout(100).build().run(); }); }); spawn(() -> { assertDurationBelow(20, () -> { safeCaller.create(mock).withTimeout(100).build().run(); }); }); assertDurationBetween(50, 450, () -> { waitForAssert(() -> { verify(mock, times(2)).run(); }); }); }
Source:
public void setEditingPattern(final PatternWrapper patternWrapper) { this.patternWrapper = patternWrapper; editingWrapper().setFactField(null); editingWrapper().setFactType(null); editingWrapper().setBoundName(null); editingWrapper().setType(null); fireChangeEvent(patternPage); fireChangeEvent(fieldPage); fireChangeEvent(additionalInfoPage); }

Target:
public void setEditingPattern(final PatternWrapper patternWrapper) { this.patternWrapper = patternWrapper; resetField(); fireChangeEvent(patternPage); fireChangeEvent(fieldPage); fireChangeEvent(additionalInfoPage); }
Source:
public void close() { sketch = null; }

Target:
public void close() { sketch = null; values = null; }
Source:
public LabelTypes getLabelTypes() { List<LabelType> r = Lists.newArrayList(); String destBranch = getChange().getDest().get(); for (LabelType l : getProjectControl().getLabelTypes().getLabelTypes()) { List<String> refs = l.getRefPatterns(); if (refs == null) { r.add(l); } else { for (String refPattern : refs) { if (RefConfigSection.isValid(refPattern) && match(destBranch, refPattern)) { r.add(l); break; } } } } return new LabelTypes(r); }

Target:
public LabelTypes getLabelTypes() { String destBranch = getChange().getDest().get(); List<LabelType> all = getProjectControl().getLabelTypes().getLabelTypes(); List<LabelType> r = Lists.newArrayListWithCapacity(all.size()); for (LabelType l : all) { List<String> refs = l.getRefPatterns(); if (refs == null) { r.add(l); } else { for (String refPattern : refs) { if (RefConfigSection.isValid(refPattern) && match(destBranch, refPattern)) { r.add(l); break; } } } } return new LabelTypes(r); }
Source:
public void setEnvironment() throws Exception { super.init(userMode); storeRestApiBaseUrl = getStoreURLHttps() + "api/am/store/v0.14/"; tokenApiUrl = new URL(getKeyManagerURLHttps() + "oauth2/token"); Map<String, String> dataMap = RESTAPITestUtil.registerOAuthApplication(getKeyManagerURLHttps()); String accessToken = generateOAuthAccessToken(user.getUserName(), user.getPassword(), dataMap.get(RESTAPITestConstants.CONSUMER_KEY), dataMap.get(RESTAPITestConstants.CONSUMER_SECRET)); headers = new HashMap<String, String>(); headers.put("Authorization", "Bearer " + accessToken); headers.put("Content-Type", "application/json"); String url = storeRestApiBaseUrl + "applications"; String payload = "{\n" + " \"throttlingTier\": \"Unlimited\",\n" + " \"description\": \"Application for GIT_1628\",\n" + " \"name\": \"" + applicationName + "_" + user.getUserDomain() + "\",\n" + " \"callbackUrl\": \"<LINK_0>\"\n" + '}'; HttpResponse response = HTTPSClientUtils.doPost(url, headers, payload); if (response.getResponseCode() != 201) { Assert.fail("Application creation failed: Response code is " + response.getResponseCode() + " Response message is '" + response.getData() + '\''); } String json = response.getData(); Gson gson = new Gson(); JsonObject jsonObject = gson.fromJson(json, JsonObject.class); applicationId = jsonObject.get("applicationId").getAsString(); }

Target:
public void setEnvironment() throws Exception { super.init(userMode); storeRestApiBaseUrl = getStoreURLHttps() + "api/am/store/" + APIMIntegrationConstants.REST_API_VERSION + "/"; tokenApiUrl = new URL(getKeyManagerURLHttps() + "oauth2/token"); Map<String, String> dataMap = RESTAPITestUtil.registerOAuthApplication(getKeyManagerURLHttps()); String accessToken = generateOAuthAccessToken(user.getUserName(), user.getPassword(), dataMap.get(RESTAPITestConstants.CONSUMER_KEY), dataMap.get(RESTAPITestConstants.CONSUMER_SECRET)); headers = new HashMap<String, String>(); headers.put("Authorization", "Bearer " + accessToken); headers.put("Content-Type", "application/json"); String url = storeRestApiBaseUrl + "applications"; String payload = "{\n" + " \"throttlingTier\": \"Unlimited\",\n" + " \"description\": \"Application for GIT_1628\",\n" + " \"name\": \"" + applicationName + "_" + user.getUserDomain() + "\",\n" + " \"callbackUrl\": \"<LINK_0>\"\n" + '}'; HttpResponse response = HTTPSClientUtils.doPost(url, headers, payload); if (response.getResponseCode() != 201) { Assert.fail("Application creation failed: Response code is " + response.getResponseCode() + " Response message is '" + response.getData() + '\''); } String json = response.getData(); Gson gson = new Gson(); JsonObject jsonObject = gson.fromJson(json, JsonObject.class); applicationId = jsonObject.get("applicationId").getAsString(); }
Source:
public void registerResponseOperation( @WebParam(targetNamespace = "<LINK_1>", partName = "parameters", name = "RegisterResponse") org.oasis_open.docs.ws_tx.wscoor._2006._06.RegisterResponseType parameters) { MessageContext ctx = webServiceCtx.getMessageContext(); MAP inboundMap = AddressingHelper.inboundMap(ctx); if (inboundMap.getRelatesTo() != null) { WSCLogger.logger.tracev("RegistrationResponsePortTypeImpl received resposne for messageId {0}", inboundMap.getRelatesTo().getRelatesTo()); AsynchronousRegistrationMapper.getInstance().assignResponse(inboundMap.getRelatesTo().getRelatesTo(), parameters); } else { WSCLogger.logger.error("RegistrationResponsePortTypeImpl message received for unknown messageId"); } }

Target:
public void registerResponseOperation( @WebParam(targetNamespace = "<LINK_1>", partName = "parameters", name = "RegisterResponse") org.oasis_open.docs.ws_tx.wscoor._2006._06.RegisterResponseType parameters) { MessageContext ctx = webServiceCtx.getMessageContext(); MAP inboundMap = AddressingHelper.inboundMap(ctx); if (inboundMap.getRelatesTo() != null) { WSCLogger.logger.tracev("RegistrationResponsePortTypeImpl received response for messageId {0}", inboundMap.getRelatesTo().getRelatesTo()); AsynchronousRegistrationMapper.getInstance().assignResponse(inboundMap.getRelatesTo().getRelatesTo(), parameters); } else { WSCLogger.i18NLogger.error_empty_messageId_received_by_async_endpoint(); } }
Source:
private boolean setCurrentFile(TrackedFile file, boolean resetParsing) { try { Preconditions.checkArgument(file == null || file.isOpen()); if (resetParsing || file == null) stopParsing("Parsing is reset by caller."); if (file != null) { long newOffset = file.getChannel().position(); if (currentFile == null || resetParsing) { logger.info("{}: Opening for parsing.", name, file.getPath()); currentBufferFileEnded = true; } else { currentBufferFileEnded = currentBufferFileEnded || (currentFileChannelOffset != newOffset); if (!sameAsCurrentFile(file)) { logger.info("{}: Continuing to parse {}.", name, file.getPath()); } logger.debug("{}: Old offset: {}, new offset: {}", name, currentFileChannelOffset, newOffset); } currentFile = file; currentFileChannel = currentFile.getChannel(); currentFileChannelOffset = currentFileChannel.position(); headerLinesToSkip = currentFileChannelOffset == 0 ? flow.getSkipHeaderLines() : 0; fileFooterPattern = flow.getFleFooterPattern(); return true; } else { return false; } } catch(IOException e) { logger.error("{}: Failed when setting current file to (reset={}).", name, file, resetParsing, e); stopParsing("Unhandled error."); totalUndhandledErrors.incrementAndGet(); return false; } }

Target:
private boolean setCurrentFile(TrackedFile file, boolean resetParsing) { try { Preconditions.checkArgument(file == null || file.isOpen()); if (resetParsing || file == null) stopParsing("Parsing is reset by caller."); if (file != null) { long newOffset = file.getChannel().position(); if (currentFile == null || resetParsing) { logger.info("{}: Opening for parsing.", name, file.getPath()); currentBufferFileEnded = true; } else { currentBufferFileEnded = currentBufferFileEnded || (currentFileChannelOffset != newOffset); if (!sameAsCurrentFile(file)) { logger.info("{}: Continuing to parse {}.", name, file.getPath()); } logger.debug("{}: Old offset: {}, new offset: {}", name, currentFileChannelOffset, newOffset); } currentFile = file; currentFileChannel = currentFile.getChannel(); currentFileChannelOffset = currentFileChannel.position(); headerLinesToSkip = currentFileChannelOffset == 0 ? flow.getSkipHeaderLines() : 0; fileFooterPattern = flow.getFileFooterPattern(); return true; } else { return false; } } catch(IOException e) { logger.error("{}: Failed when setting current file to (reset={}).", name, file, resetParsing, e); stopParsing("Unhandled error."); totalUndhandledErrors.incrementAndGet(); return false; } }
Source:
TaskData getTaskData(AbstractRepositoryConnector connector, IProgressMonitor monitor) throws CoreException { if (taskId != null && taskKey != null && connector.supportsSearchByTaskKey(repository)) { try { return getTaskDataWithKey(connector, monitor); } catch (CoreException | RuntimeException e) { return connector.getTaskData(repository, taskId, monitor); } } else if (taskId != null) { return connector.getTaskData(repository, taskId, monitor); } else if (taskKey != null && connector.supportsSearchByTaskKey(repository)) { return getTaskDataWithKey(connector, monitor); } return null; }

Target:
TaskData getTaskData(AbstractRepositoryConnector connector, IProgressMonitor monitor) throws CoreException { if (taskId != null && taskKey != null && connector.supportsSearchByTaskKey(repository)) { try { TaskData data = getTaskDataWithKey(connector, monitor); if (data != null) { return data; } return connector.getTaskData(repository, taskId, monitor); } catch (CoreException | RuntimeException e) { return connector.getTaskData(repository, taskId, monitor); } } else if (taskId != null) { return connector.getTaskData(repository, taskId, monitor); } else if (taskKey != null && connector.supportsSearchByTaskKey(repository)) { return getTaskDataWithKey(connector, monitor); } return null; }
Source:
void updatePartitionCountMetric() { try { Map<SystemStream, SystemStreamMetadata> currentMetadata = getMetadata(streamsToMonitor, metadataCache); Set<SystemStream> streamsChanged = new HashSet<>(); for (Map.Entry<SystemStream, SystemStreamMetadata> metadataEntry : initialMetadata.entrySet()) { try { SystemStream systemStream = metadataEntry.getKey(); SystemStreamMetadata metadata = metadataEntry.getValue(); int currentPartitionCount = currentMetadata.get(systemStream).getSystemStreamPartitionMetadata().keySet().size(); int prevPartitionCount = metadata.getSystemStreamPartitionMetadata().keySet().size(); Gauge gauge = gauges.get(systemStream); gauge.set(currentPartitionCount - prevPartitionCount); if (currentPartitionCount != prevPartitionCount) { log.info(String.format("Change of partition count detected in stream %s. old partition count: %d, current partition count: %d", systemStream.toString(), prevPartitionCount, currentPartitionCount)); streamsChanged.add(systemStream); } } catch (Exception e) { log.error(String.format("Error comparing partition count differences for stream: %s", metadataEntry.getKey().toString())); } } if (!streamsChanged.isEmpty() && this.callbackMethod != null) { this.callbackMethod.onSystemStreamPartitionChange(streamsChanged); } } catch (Exception e) { log.error("Exception while updating partition count metric.", e); } }

Target:
public void updatePartitionCountMetric() { try { Map<SystemStream, SystemStreamMetadata> currentMetadata = getMetadata(streamsToMonitor, metadataCache); Set<SystemStream> streamsChanged = new HashSet<>(); for (Map.Entry<SystemStream, SystemStreamMetadata> metadataEntry : initialMetadata.entrySet()) { try { SystemStream systemStream = metadataEntry.getKey(); SystemStreamMetadata metadata = metadataEntry.getValue(); int currentPartitionCount = currentMetadata.get(systemStream).getSystemStreamPartitionMetadata().size(); int prevPartitionCount = metadata.getSystemStreamPartitionMetadata().size(); Gauge gauge = gauges.get(systemStream); gauge.set(currentPartitionCount - prevPartitionCount); if (currentPartitionCount != prevPartitionCount) { log.warn(String.format("Change of partition count detected in stream %s. old partition count: %d, current partition count: %d", systemStream.toString(), prevPartitionCount, currentPartitionCount)); streamsChanged.add(systemStream); } } catch (Exception e) { log.error(String.format("Error comparing partition count differences for stream: %s", metadataEntry.getKey().toString())); } } if (!streamsChanged.isEmpty() && this.callbackMethod != null) { this.callbackMethod.onSystemStreamPartitionChange(streamsChanged); } } catch (Exception e) { log.error("Exception while updating partition count metric.", e); } }
Source:
public void canUpdateBusinessService() throws Exception { BusinessService service = new BusinessService(); service.setName("Dummy Service"); service.addReductionKey("key1"); service.addReductionKey("key2-deleteMe"); final Long serviceId = m_businessServiceDao.save(service); m_businessServiceDao.flush(); final String businessServiceDtoXml = "<business-service>" + " <id>" + serviceId + "</id>" + " <name>Dummy Service Updated</name>" + " <reductionKeys>" + " <reductionKey>key1updated</reductionKey>" + " </reductionKeys>" + "</business-service>"; sendData(PUT, MediaType.APPLICATION_XML, "/business-services/" + serviceId, businessServiceDtoXml, 204); assertEquals(1, m_businessServiceDao.findAll().size()); assertEquals("Dummy Service Updated", m_businessServiceDao.findAll().get(0).getName()); assertEquals(1, m_businessServiceDao.findAll().get(0).getReductionKeys().size()); assertTrue(m_businessServiceDao.findAll().get(0).getReductionKeys().contains("key1updated")); }

Target:
public void canUpdateBusinessService() throws Exception { BusinessService service = new BusinessService(); service.setName("Dummy Service"); service.addReductionKey("key1"); service.addReductionKey("key2-deleteMe"); final Long serviceId = m_businessServiceDao.save(service); m_businessServiceDao.flush(); final String businessServiceDtoXml = "<business-service>" + " <id>" + serviceId + "</id>" + " <name>Dummy Service Updated</name>" + " <reductionKeys>" + " <reductionKey>key1updated</reductionKey>" + " </reductionKeys>" + "</business-service>"; sendData(PUT, MediaType.APPLICATION_XML, "/business-services/" + serviceId, businessServiceDtoXml, 204); assertEquals(1, m_businessServiceDao.findAll().size()); assertEquals("Expected that the update BusinessService name is present.", "Dummy Service Updated", m_businessServiceDao.findAll().get(0).getName()); assertEquals("Expected that there is exactly one reductionkey on the BusinessService.", 1, m_businessServiceDao.findAll().get(0).getReductionKeys().size()); assertTrue("Expected that the update reductionkey is present.", m_businessServiceDao.findAll().get(0).getReductionKeys().contains("key1updated")); }
Source:
public void unbindOutputs(BindingService bindingService) { if (log.isDebugEnabled()) { log.debug(String.format("Unbinding outputs for %s:%s", this.channelNamespace, this.type)); } for (Map.Entry<String, BoundElementHolder> channelHolderEntry : this.outputHolders.entrySet()) { if (channelHolderEntry.getValue().isBindable()) { if (log.isDebugEnabled()) { log.debug(String.format("Binding %s:%s:%s", this.channelNamespace, this.type, channelHolderEntry.getKey())); } bindingService.unbindProducers(channelHolderEntry.getKey()); } } }

Target:
public void unbindOutputs(BindingService bindingService) { if (log.isDebugEnabled()) { log.debug(String.format("Unbinding outputs for %s:%s", this.channelNamespace, this.type)); } for (Map.Entry<String, BoundTargetHolder> channelHolderEntry : this.outputHolders.entrySet()) { if (channelHolderEntry.getValue().isBindable()) { if (log.isDebugEnabled()) { log.debug(String.format("Binding %s:%s:%s", this.channelNamespace, this.type, channelHolderEntry.getKey())); } bindingService.unbindProducers(channelHolderEntry.getKey()); } } }
Source:
private ElasticsearchAnalysisDefinitionRegistry createDefaultDefinitionRegistry() { ElasticsearchAnalysisDefinitionRegistryBuilderImpl builder = new ElasticsearchAnalysisDefinitionRegistryBuilderImpl(); String providerClassName = cfg.getProperty( ElasticsearchEnvironment.ANALYZER_DEFINITION_PROVIDER ); if ( providerClassName != null ) { ElasticsearchAnalysisDefinitionProvider provider; try { Class<?> providerClazz = ClassLoaderHelper.classForName( providerClassName, serviceManager ); provider = (ElasticsearchAnalysisDefinitionProvider) ReflectionHelper.createInstance( providerClazz, true ); } catch (RuntimeException e) { throw LOG.invalidElasticsearchAnalyzerDefinitionProvider( providerClassName, e ); } try { provider.register( builder ); } catch (SearchException e) { throw e; } catch (RuntimeException e) { throw LOG.invalidLuceneAnalyzerDefinitionProvider( providerClassName, e ); } } return builder.build(); }

Target:
private SimpleElasticsearchAnalysisDefinitionRegistry createDefaultDefinitionRegistry() { ElasticsearchAnalysisDefinitionRegistryBuilderImpl builder = new ElasticsearchAnalysisDefinitionRegistryBuilderImpl(); String providerClassName = cfg.getProperty( ElasticsearchEnvironment.ANALYZER_DEFINITION_PROVIDER ); if ( providerClassName != null ) { ElasticsearchAnalysisDefinitionProvider provider; try { Class<?> providerClazz = ClassLoaderHelper.classForName( providerClassName, serviceManager ); provider = (ElasticsearchAnalysisDefinitionProvider) ReflectionHelper.createInstance( providerClazz, true ); } catch (RuntimeException e) { throw LOG.invalidElasticsearchAnalyzerDefinitionProvider( providerClassName, e ); } try { provider.register( builder ); } catch (SearchException e) { throw e; } catch (RuntimeException e) { throw LOG.invalidLuceneAnalyzerDefinitionProvider( providerClassName, e ); } } return builder.build(); }
Source:
public Obs getObs(Obs obs, String view) { File file = getComplexDataFile(obs); log.debug("value complex: " + obs.getValueComplex()); log.debug("file path: " + file.getAbsolutePath()); ComplexData complexData = null; if (ComplexObsHandler.RAW_VIEW.equals(view)) { String[] names = obs.getValueComplex().split("\\|"); if (names != null) { String originalFilename = names[0]; originalFilename = originalFilename.replaceAll(",", "").replaceAll(" ", "").replaceAll("file$", ""); try { complexData = new ComplexData(originalFilename, OpenmrsUtil.getFileAsBytes(file)); } catch (IOException e) { log.error("Trying to read file: " + file.getAbsolutePath(), e); } } } else { return null; } Assert.notNull(complexData, "Complex data must not be null"); String mimeType = OpenmrsUtil.getFileMimeType(file); complexData.setMimeType(mimeType); obs.setComplexData(complexData); return obs; }

Target:
public Obs getObs(Obs obs, String view) { File file = getComplexDataFile(obs); log.debug("value complex: " + obs.getValueComplex()); log.debug("file path: " + file.getAbsolutePath()); ComplexData complexData = null; if (ComplexObsHandler.RAW_VIEW.equals(view)) { if(obs.getValueComplex()!=null && !obs.getValueComplex().isEmpty()) { String[] names = obs.getValueComplex().split("\\|"); String originalFilename = names[0]; originalFilename = originalFilename.replaceAll(",", "").replaceAll(" ", "").replaceAll("file$", ""); try { complexData = new ComplexData(originalFilename, OpenmrsUtil.getFileAsBytes(file)); } catch (IOException e) { log.error("Trying to read file: " + file.getAbsolutePath(), e); } } else { log.error("The file must exist!!"); } } else { return null; } Assert.notNull(complexData, "Complex data must not be null"); String mimeType = OpenmrsUtil.getFileMimeType(file); complexData.setMimeType(mimeType); obs.setComplexData(complexData); return obs; }
Source:
public ActionBinding generate() throws UnableToCompleteException { String implName = getSuperTypeName() + SUFFIX; PrintWriter printWriter = getGeneratorUtil().tryCreatePrintWriter(getPackage(), implName); if (printWriter != null) { try { doGenerate(implName, printWriter); registerMetadata(); } finally { printWriter.close(); } } else { getLogger().debug("Action already generated. Returning."); } return createActionBinding(implName); }

Target:
public ActionBinding generate() throws UnableToCompleteException { String implName = getSuperTypeName() + SUFFIX; if (doGenerate(implName)) { registerMetadata(); } return createActionBinding(implName); }
Source:
public static Archive<?> createTestArchive() { WebArchive war = TestUtil.prepareArchive(JaxbMarshallingSoakTest.class.getSimpleName()); war.addClasses(JaxbMarshallingSoakItem.class, TestUtil.class, PortProviderUtil.class, TimeoutUtil.class); Map<String, String> contextParam = new HashMap<>(); contextParam.put("resteasy.async.job.service.enabled", "true"); war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset( new RuntimePermission("modifyThread"), new ReflectPermission("suppressAccessChecks"), new LoggingPermission("control", ""), new PropertyPermission("arquillian.*", "read"), new PropertyPermission("ipv6", "read"), new PropertyPermission("node", "read"), new PropertyPermission("org.jboss.resteasy.port", "read"), new PropertyPermission("ts.timeout.factor", "read"), new RuntimePermission("accessDeclaredMembers"), new RuntimePermission("getClassLoader"), new RuntimePermission("getenv.RESTEASY_PORT"), new SocketPermission(PortProviderUtil.getHost(), "connect,resolve") ), "permissions.xml"); return TestUtil.finishContainerPrepare(war, contextParam, JaxbMarshallingSoakAsyncService.class); }

Target:
public static Archive<?> createTestArchive() { WebArchive war = TestUtil.prepareArchive(JaxbMarshallingSoakTest.class.getSimpleName()); war.addClasses(JaxbMarshallingSoakItem.class, TestUtil.class, PortProviderUtil.class, TimeoutUtil.class); Map<String, String> contextParam = new HashMap<>(); contextParam.put("resteasy.async.job.service.enabled", "true"); war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset( new RuntimePermission("getClassLoader"), new RuntimePermission("modifyThread"), new ReflectPermission("suppressAccessChecks"), new LoggingPermission("control", ""), new PropertyPermission("arquillian.*", "read"), new PropertyPermission("ipv6", "read"), new PropertyPermission("node", "read"), new PropertyPermission("org.jboss.resteasy.port", "read"), new PropertyPermission("ts.timeout.factor", "read"), new RuntimePermission("accessDeclaredMembers"), new RuntimePermission("getenv.RESTEASY_PORT"), new SocketPermission(PortProviderUtil.getHost(), "connect,resolve") ), "permissions.xml"); return TestUtil.finishContainerPrepare(war, contextParam, JaxbMarshallingSoakAsyncService.class); }
Source:
protected File determineActualFile(final HttpServletRequest request, Locale locale) { File file = ServletUtils.makeFileFromSanePath(request.getPathInfo(), base); if (null != file && !ServletUtils.canReadFile(file)) { file = ServletUtils.makeFileFromSanePath(replaceLocaleWithUSLocale(request.getPathInfo(), locale), base); } return file; }

Target:
protected File determineActualFile(final HttpServletRequest request, Locale locale) { File file = ServletUtils.makeFileFromSanePath(request.getPathInfo(), base); if (file != null && !ServletUtils.canReadFile(file)) { file = ServletUtils.makeFileFromSanePath(replaceLocaleWithUSLocale(request.getPathInfo(), locale), base); } return file; }
Source:
private static void assertValidDeviceData(PostPutUserDto postPutUser) { if (postPutUser.deviceName == null) { String hint = "If the device name is not provided, the other properties should not be provided either"; Require.isNull(postPutUser.deviceOperatingSystemStr, () -> InvalidDataException.extraProperty("deviceOperatingSystem", hint)); Require.isNull(postPutUser.deviceAppVersion, () -> InvalidDataException.extraProperty("deviceAppVersion", hint)); Require.isNull(postPutUser.deviceAppVersionCode, () -> InvalidDataException.extraProperty("deviceAppVersionCode", hint)); } else { String hint = "If the device name is provided, the other properties must be present too"; Require.isNonNull(postPutUser.deviceOperatingSystemStr, () -> InvalidDataException.extraProperty("deviceOperatingSystem", hint)); Require.isNonNull(postPutUser.deviceAppVersion, () -> InvalidDataException.extraProperty("deviceAppVersion", hint)); Require.isNonNull(postPutUser.deviceAppVersionCode, () -> InvalidDataException.extraProperty("deviceAppVersionCode", hint)); } }

Target:
private static void assertValidDeviceData(PostPutUserDto postPutUser) { if (postPutUser.deviceName == null) { String hint = "If the device name is not provided, the other properties should not be provided either"; Require.isNull(postPutUser.deviceOperatingSystemStr, () -> InvalidDataException.extraProperty("deviceOperatingSystem", hint)); Require.isNull(postPutUser.deviceAppVersion, () -> InvalidDataException.extraProperty("deviceAppVersion", hint)); Require.isNull(postPutUser.deviceAppVersionCode, () -> InvalidDataException.extraProperty("deviceAppVersionCode", hint)); } else { String hint = "If the device name is provided, the other properties must be present too"; Require.isNonNull(postPutUser.deviceOperatingSystemStr, () -> InvalidDataException.missingProperty("deviceOperatingSystem", hint)); Require.isNonNull(postPutUser.deviceAppVersion, () -> InvalidDataException.missingProperty("deviceAppVersion", hint)); Require.isNonNull(postPutUser.deviceAppVersionCode, () -> InvalidDataException.missingProperty("deviceAppVersionCode", hint)); } }
Source:
public Bucket getOrCreateBucket(String bucketName) { try { Bucket bucket = storage.get(bucketName); if (bucket == null) { log.debug(String.format("Creating a new bucket %s", bucketName)); return storage.create(BucketInfo.of(bucketName)); } return bucket; } catch (StorageException e) { throw new NuxeoException(e); } }

Target:
public Bucket getOrCreateBucket(String bucketName) { Bucket bucket = storage.get(bucketName); if (bucket == null) { log.debug(String.format("Creating a new bucket %s", bucketName)); return storage.create(BucketInfo.of(bucketName)); } return bucket; }
Source:
private static Instance buildOafEntityResultInstance(Patent patent, String patentEpoUrlRoot) { Instance instance = new Instance(); instance.setInstancetype(buildOafEntityResultInstanceInstancetype()); instance.setHostedby(buildOafEntityPatentKeyValue()); instance.setCollectedfrom(buildOafEntityPatentKeyValue()); instance.setUrl(Arrays.asList(buildOafEntityResultInstanceUrl(patent, patentEpoUrlRoot))); return instance; }

Target:
private static Instance buildOafEntityResultInstance(Patent patent, String patentEpoUrlRoot) { Instance instance = new Instance(); instance.setInstancetype(buildOafEntityResultInstanceInstancetype()); instance.setHostedby(buildOafEntityPatentKeyValue()); instance.setCollectedfrom(buildOafEntityPatentKeyValue()); instance.setUrl(Collections.singletonList(buildOafEntityResultInstanceUrl(patent, patentEpoUrlRoot))); return instance; }
Source:
public void setMetaData(int x, int z, int y, int metaData) { if (metaData < 0 || metaData >= 16) throw new IllegalArgumentException("Metadata out of range: " + metaData); ChunkSection section = getSection(y); if (section == null) return; int index = section.index(x, y, z); if ((section.types[index] << 4) == 0) return; section.types[index] |= metaData; }

Target:
public void setMetaData(int x, int z, int y, int metaData) { if (metaData < 0 || metaData >= 16) throw new IllegalArgumentException("Metadata out of range: " + metaData); ChunkSection section = getSection(y); if (section == null) return; int index = section.index(x, y, z); if (section.types[index] == 0) return; section.types[index] &= 0xfff0; section.types[index] |= metaData; }
Source:
protected boolean checkStorageDomainStatusNotEqual(StorageDomainStatus status) { if (getStorageDomainStatus() != null && getStorageDomainStatus() != status) { addStorageDomainStatusIllegalMessage(); return true; } return false; }

Target:
protected boolean checkStorageDomainStatusNotEqual(StorageDomainStatus status) { boolean returnValue = false; if (getStorageDomainStatus() != null && getStorageDomainStatus() != null) { returnValue = (getStorageDomainStatus() != status); if (!returnValue) { addStorageDomainStatusIllegalMessage(); } } return returnValue; }
Source:
public void run(StreamApplication app) { try { ProcessorGraph processorGraph = getExecutionPlan(app); List<StreamSpec> streams = processorGraph.getIntermediateStreams().stream() .map(streamEdge -> streamEdge.getStreamSpec()) .collect(Collectors.toList()); StreamManager streamManager = new StreamManager(new JavaSystemConfig(config).getSystemAdmins()); streamManager.createStreams(streams); processorGraph.getProcessorNodes().forEach(processor -> { Config processorConfig = processor.generateConfig(); log.info("Starting processor with config {}", processor.getId(), processorConfig); JobRunner runner = new JobRunner(processorConfig); runner.run(true); }); } catch (Throwable t) { throw new SamzaException("Failed to run application", t); } }

Target:
public void run(StreamApplication app) { try { ProcessorGraph processorGraph = getExecutionPlan(app); List<StreamSpec> streams = processorGraph.getIntermediateStreams().stream() .map(streamEdge -> streamEdge.getStreamSpec()) .collect(Collectors.toList()); streamManager.createStreams(streams); processorGraph.getProcessorNodes().forEach(processor -> { Config processorConfig = processor.generateConfig(); log.info("Starting processor with config {}", processor.getId(), processorConfig); JobRunner runner = new JobRunner(processorConfig); runner.run(true); }); } catch (Throwable t) { throw new SamzaException("Failed to run application", t); } }
Source:
public String humanReadablePath() { String path = super.humanReadablePath(); if(order == null || type == Type.SAVED || type == Type.UPVOTED || type == Type.DOWNVOTED || type == Type.HIDDEN) { return path; } switch(order) { case TOP_HOUR: case TOP_DAY: case TOP_WEEK: case TOP_MONTH: case TOP_YEAR: case TOP_ALL: return path + "?t=" + General.asciiLowercase(order.name().split("_")[1]); default: return path + "?sort=" + General.asciiLowercase(order.name()); } }

Target:
public String humanReadablePath() { String path = super.humanReadablePath(); if(order == null || type != Type.SUBMITTED) { return path; } switch(order) { case TOP_HOUR: case TOP_DAY: case TOP_WEEK: case TOP_MONTH: case TOP_YEAR: case TOP_ALL: return path + "?t=" + General.asciiLowercase(order.name().split("_")[1]); default: return path + "?sort=" + General.asciiLowercase(order.name()); } }
Source:
public void stop() throws Exception { applicationContext.close(); super.stop(); Thread stopThread = new Thread(() -> { try { Thread.sleep(Duration.ofSeconds(20).toMillis()); } catch (InterruptedException e) { } Thread.getAllStackTraces() .entrySet() .stream() .filter(e -> !e.getKey().isDaemon()) .forEach(e -> { log.info("Non daemon Thread \"{}\" (id: {}) still active in state: {}", e.getKey().getName(), e.getKey().getId(), e.getKey().getState()); log.info("Stacktrace of thread {}:\n{}", e.getKey().getName(), Arrays.stream(e.getValue()).map(Object::toString).collect(Collectors.joining("\n"))); }); try { Thread.sleep(Duration.ofSeconds(1).toMillis()); } catch (InterruptedException e) { } System.exit(-1); }); stopThread.setDaemon(true); stopThread.start(); }

Target:
public void stop() throws Exception { applicationContext.close(); super.stop(); Thread timeoutThread = new Thread(() -> { try { Thread.sleep(Duration.ofSeconds(30).toMillis()); } catch (InterruptedException e) { } Set<Entry<Thread, StackTraceElement[]>> threads = Thread.getAllStackTraces().entrySet(); if (threads.stream().allMatch(t -> t.getKey().isDaemon())) { return; } threads.stream() .filter(e -> !e.getKey().isDaemon()) .forEach(e -> { log.error("Non daemon Thread \"{}\" (id: {}) still active in state: {}", e.getKey().getName(), e.getKey().getId(), e.getKey().getState()); log.error("Stacktrace of thread {}:\n{}", e.getKey().getName(), Arrays.stream(e.getValue()).map(Object::toString).collect(Collectors.joining("\n"))); }); try { Thread.sleep(Duration.ofSeconds(1).toMillis()); } catch (InterruptedException e) { } System.exit(-1); }); timeoutThread.setDaemon(true); timeoutThread.start(); }
Source:
public static String getNestedHtml(String raw_html){ String html = raw_html.replace("\\",""); Document doc = Jsoup.parse(html); Elements scripts = doc.getElementsByTag("script"); Pattern pttrn = Pattern.compile("\"html\":\""); String nested_html = ""; for (Element script:scripts){ Matcher m = pttrn.matcher(html = script.html()); if(m.find()){ nested_html += html.substring(m.end(), html.length() -3); } } return nested_html; }

Target:
private static String getNestedHtml(String raw_html){ String html = raw_html.replace("\\",""); Document doc = Jsoup.parse(html); Elements scripts = doc.getElementsByTag("script"); Pattern pttrn = Pattern.compile("\"html\":\""); String nested_html = ""; for (Element script:scripts){ Matcher m = pttrn.matcher(html = script.html()); if(m.find()){ nested_html += html.substring(m.end(), html.length() -3); } } return nested_html; }
Source:
public Boolean getNoZooKeeperRegistration() { return fromNullable(options.getBoolean(noZooKeeperRegistrationArg.getDest())).or(true); }

Target:
public Boolean getNoZooKeeperRegistration() { return fromNullable(options.getBoolean(noZooKeeperRegistrationArg.getDest())).or(false); }
Source:
public CertificateClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy, "Http pipeline policy cannot be null."); policies.add(policy); return this; }

Target:
public CertificateClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy, "'policy' cannot be null."); policies.add(policy); return this; }