auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String genomicToEnsemblRestRegion(GenomicLocation genomicLocation) { if (genomicLocation == null) { return null; } String chr = this.chromosomeNormalizer(genomicLocation.getChromosome().trim()); Integer start = genomicLocation.getStart(); Integer end = genomicLocation.getEnd(); String ref = genomicLocation.getReferenceAllele().trim(); String var = genomicLocation.getVariantAllele().trim(); String prefix = ""; if(!ref.equals(var)) { prefix = longestCommonPrefix(ref, var); } if (prefix.length() > 0) { ref = ref.substring(prefix.length()); var = var.substring(prefix.length()); int nStart = start; int nEnd = end; nStart += prefix.length(); if (ref.length() == 0) { nStart -= 1; } start = nStart; } String region; if (start < 1) { region = null; } else if(ref.equals("-") || ref.length() == 0) { try { region = chr + ":" + String.valueOf(start + 1) + "-" + start + ":1/" + var; } catch (NumberFormatException e) { return null; } } else if(var.equals("-") || var.length() == 0) { region = chr + ":" + start + "-" + end + ":1/-"; } else if (ref.length() > 1 || var.length() > 1) { region = chr + ":" + start + "-" + end + ":1/" + var; } else { region = chr + ":" + start + "-" + start + ":1/" + var; } return region; }

Target:
public String genomicToEnsemblRestRegion(GenomicLocation genomicLocation) { if (genomicLocation == null) { return null; } GenomicLocation normalizedGenomicLocation = normalizeGenomicLocation(genomicLocation); String chr = normalizedGenomicLocation.getChromosome(); Integer start = normalizedGenomicLocation.getStart(); Integer end = normalizedGenomicLocation.getEnd(); String ref = normalizedGenomicLocation.getReferenceAllele().trim(); String var = normalizedGenomicLocation.getVariantAllele().trim(); String region; if (start < 1) { region = null; } else if(ref.equals("-") || ref.length() == 0) { try { region = chr + ":" + String.valueOf(start + 1) + "-" + start + ":1/" + var; } catch (NumberFormatException e) { return null; } } else if(var.equals("-") || var.length() == 0) { region = chr + ":" + start + "-" + end + ":1/-"; } else if (ref.length() > 1 || var.length() > 1) { region = chr + ":" + start + "-" + end + ":1/" + var; } else { region = chr + ":" + start + "-" + start + ":1/" + var; } return region; }
Source:
public CookieInterceptor(String username, String password, String baseURL) { try { this.sessionURL = new URL(String.format("%s/_session", baseURL)); username = URLEncoder.encode(username, "UTF-8"); password = URLEncoder.encode(password, "UTF-8"); this.sessionRequestBody = String.format("name=%s&password=%s", username, password) .getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (MalformedURLException e) { throw new RuntimeException(e); } }

Target:
public CookieInterceptor(String username, String password, String baseURL) { try { this.sessionURL = new URL(String.format("%s/_session", baseURL)); username = URLEncoder.encode(username, "UTF-8"); password = URLEncoder.encode(password, "UTF-8"); this.sessionRequestBody = String.format("name=%s&password=%s", username, password) .getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (MalformedURLException e) { logger.log(Level.SEVERE, "Failed to create URL for _session endpoint", e); throw new RuntimeException(e); } }
Source:
public void applyState(XSiteState[] chunk) throws Exception { if (trace) { log.tracef("Received state: %s", extractKeys(chunk)); } else if (debug) { log.debugf("Received state: %s keys", chunk.length); } if (transactionManager != null) { applyStateInTransaction(chunk); } else { applyStateInNonTransaction(chunk); } }

Target:
public void applyState(XSiteState[] chunk) throws Exception { if (debug) { log.debugf("Received state: %s keys", chunk.length); } if (transactionManager != null) { applyStateInTransaction(chunk); } else { applyStateInNonTransaction(chunk); } }
Source:
private String getSparkHome(String sparkVersion) { String sparkHome = getSysProps().get("spark." + sparkVersion + ".home"); if (sparkHome == null) { info("Couldn't find spark." + sparkVersion + ".home property."); String sparkDir = getSysProps().get("spark.home.dir"); String sparkHomePrefix = getSysProps().get("spark.home.prefix") != null ? getSysProps().get("spark.home.prefix") : "*"; info(" Looking for spark at " + sparkDir + " directory with " + sparkHomePrefix + " prefix for " + sparkVersion + " version."); DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(sparkDir); scanner.setIncludes( new String[]{sparkHomePrefix + sparkVersion.replace(".", "") + "*", sparkHomePrefix + sparkVersion + "*"}); scanner.scan(); String[] directories = scanner.getIncludedDirectories(); if (directories != null && directories.length > 0) { sparkHome = sparkDir + "/" + directories[directories.length - 1]; } else { scanner.setIncludes(new String[]{sparkHomePrefix + "*"}); scanner.scan(); String[] availableDirectories = scanner.getIncludedDirectories(); if (availableDirectories != null && availableDirectories.length > 0) { Set<String> availableVersions = Sets.newTreeSet(); for (String directory : availableDirectories) { String version = directory.replace(sparkHomePrefix, ""); availableVersions.add(version.contains(".") ? version.substring(0, 5) : Joiner.on(".").join(version.substring(0, 3).split(""))); } throw new RuntimeException( "SPARK version specified by User is not available. Available versions are : " + Joiner.on(",") .join(availableVersions)); } } } return sparkHome; }

Target:
private String getSparkHome(String sparkVersion) { String sparkHome = getSysProps().get("spark." + sparkVersion + ".home"); if (sparkHome == null) { info("Couldn't find spark." + sparkVersion + ".home property."); String sparkDir = getSysProps().get(SPARK_BASE_DIR); String sparkHomePrefix = getSysProps().get(SPARK_HOME_PREFIX) != null ? getSysProps().get(SPARK_HOME_PREFIX) : "*"; String replaceTo = getSysProps().get(SPARK_VERSION_REGEX_TO_REPLACE); String replaceWith = getSysProps().get(SPARK_VERSION_REGEX_TO_REPLACE_WITH) != null ? getSysProps() .get(SPARK_VERSION_REGEX_TO_REPLACE_WITH) : ""; String versionPatterToMatch = sparkHomePrefix + ( replaceTo != null ? sparkVersion .replace(replaceTo, replaceWith) : sparkVersion) + "*"; info("Looking for spark at " + sparkDir + " directory with " + sparkHomePrefix + " prefix for " + sparkVersion + " version."); DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(sparkDir); scanner.setIncludes(new String[]{versionPatterToMatch}); scanner.scan(); String[] directories = scanner.getIncludedDirectories(); if (directories != null && directories.length > 0) { sparkHome = sparkDir + "/" + directories[directories.length - 1]; } else { String sparkReferenceDoc = getSysProps().get(SPARK_REFERENCE_DOCUMENT); String exceptionMessage = sparkReferenceDoc == null ? "SPARK version specified by User is not available." : "SPARK version specified by User is not available. Available versions are mentioned at: " + sparkReferenceDoc; throw new RuntimeException(exceptionMessage); } } return sparkHome; }
Source:
private void peekDrawerInvalidate() { if (mPeekScroller.computeScrollOffset()) { final int oldX = mOffsetPixels; final int x = mPeekScroller.getCurrX(); if (x != oldX) setOffsetPixels(x); if (!mPeekScroller.isFinished()) { ViewCompat.postOnAnimation(this, mPeekRunnable); return; } else if (mPeekDelay > 0) { mPeekStartRunnable = new Runnable() { @Override public void run() { startPeek(); } }; postDelayed(mPeekStartRunnable, mPeekDelay); } } completePeek(); }

Target:
private void peekDrawerInvalidate() { if (mPeekScroller.computeScrollOffset()) { final int oldX = mOffsetPixels; final int x = mPeekScroller.getCurrX(); if (x != oldX) setOffsetPixels(x); if (!mPeekScroller.isFinished()) { postOnAnimation(mPeekRunnable); return; } else if (mPeekDelay > 0) { mPeekStartRunnable = new Runnable() { @Override public void run() { startPeek(); } }; postDelayed(mPeekStartRunnable, mPeekDelay); } } completePeek(); }
Source:
public boolean isAddressValid(String address) { if (address.endsWith("L")) { String address_noL = address.substring(0, address.length() - 1); if (address_noL.length() != 20) { return false; } for (char addressCharacter : address_noL.toCharArray()) { if (!Character.isDigit(addressCharacter)) { return false; } } return true; }else{ return false; } }

Target:
public boolean isAddressValid(String address) { if (address.endsWith("L")) { String addressWithoutL = address.substring(0, address.length() - 1); if (addressWithoutL.length() != 20) { return false; } for (char addressCharacter : addressWithoutL.toCharArray()) { if (!Character.isDigit(addressCharacter)) { return false; } } return true; }else{ return false; } }
Source:
public synchronized Map<String, Optional<MemoryInfo>> getWorkerMemoryInfo() { Map<String, Optional<MemoryInfo>> memoryInfo = new HashMap<>(); AllNodes allNodes = nodeManager.getAllNodes(); Set<Node> workers = union(union(allNodes.getActiveNodes(), allNodes.getInactiveNodes()), allNodes.getShuttingDownNodes()); for (Entry<String, RemoteNodeMemory> entry : nodes.entrySet()) { Optional<Node> worker = workers.stream() .filter(node -> node.getNodeIdentifier().equals(entry.getKey())) .findFirst(); String workerId = entry.getKey(); if (worker.isPresent()) { workerId += " [" + worker.get().getHostAndPort().getHostText() + "]"; } memoryInfo.put(workerId, entry.getValue().getInfo()); } return memoryInfo; }

Target:
public synchronized Map<String, Optional<MemoryInfo>> getWorkerMemoryInfo() { Map<String, Optional<MemoryInfo>> memoryInfo = new HashMap<>(); for (Entry<String, RemoteNodeMemory> entry : nodes.entrySet()) { String workerId = entry.getKey() + " [" + entry.getValue().getNode().getHostAndPort().getHostText() + "]"; memoryInfo.put(workerId, entry.getValue().getInfo()); } return memoryInfo; }
Source:
protected void writeOtherDevices(VmBase vmBase, XmlTextWriter write) { List<VmDevice> devices = vmBase.getUnmanagedDeviceList(); Collection<VmDevice> managedDevices = vmBase.getManagedVmDeviceMap().values(); for (VmDevice device : managedDevices) { if (VmDeviceType.SOUND.getName().equals(device.getType()) || VmDeviceType.USB.getName().equals(device.getDevice()) || VmDeviceType.SPICEVMC.getName().equals(device.getDevice())) { devices.add(device); } } for (VmDevice vmDevice : devices) { _writer.WriteStartElement("Item"); _writer.WriteStartElement("rasd:ResourceType"); _writer.WriteRaw(OvfHardware.OTHER); _writer.WriteEndElement(); _writer.WriteStartElement("rasd:InstanceId"); _writer.WriteRaw((String.valueOf(vmDevice.getId().getDeviceId()))); _writer.WriteEndElement(); writeVmDeviceInfo(vmDevice); _writer.WriteEndElement(); } }

Target:
protected void writeOtherDevices(VmBase vmBase, XmlTextWriter write) { List<VmDevice> devices = vmBase.getUnmanagedDeviceList(); Collection<VmDevice> managedDevices = vmBase.getManagedVmDeviceMap().values(); for (VmDevice device : managedDevices) { if (VmDeviceCommonUtils.isSpecialDevice(device.getDevice(), device.getType())) { devices.add(device); } } for (VmDevice vmDevice : devices) { _writer.WriteStartElement("Item"); _writer.WriteStartElement("rasd:ResourceType"); _writer.WriteRaw(OvfHardware.OTHER); _writer.WriteEndElement(); _writer.WriteStartElement("rasd:InstanceId"); _writer.WriteRaw((String.valueOf(vmDevice.getId().getDeviceId()))); _writer.WriteEndElement(); writeVmDeviceInfo(vmDevice); _writer.WriteEndElement(); } }
Source:
public void enqueueTask(NotificationContext changeContext) throws Exception { if (_batchModeEnabled && changeContext.getType() == NotificationContext.Type.CALLBACK) { logger.debug("Callbackhandler {}, Enqueuing callback", _uid ); if (!isReady()) { logger.info("CallbackHandler is not ready, ignore change callback from path: {}, for " + "listener: {}", _uid, _path, _listener); } else { CallbackProcessor callbackProcessorRef = _batchCallbackProcessor.get(); if (callbackProcessorRef != null) { callbackProcessorRef.queueEvent(changeContext.getType(), changeContext); } else { throw new HelixException( "Failed to process callback in batch mode. Batch Callback Processor does not exist."); } } } else { invoke(changeContext); } if (_monitor != null) { _monitor.increaseCallbackUnbatchedCounters(); } }

Target:
public void enqueueTask(NotificationContext changeContext) throws Exception { if (_batchModeEnabled && changeContext.getType() == NotificationContext.Type.CALLBACK) { logger.debug("Callbackhandler {}, Enqueuing callback", _uid ); if (!isReady()) { logger.info("CallbackHandler is not ready, ignore change callback from path: {}, for " + "listener: {}", _uid, _path, _listener); } else { CallbackProcessor callbackProcessor = _batchCallbackProcessorRef.get(); if (callbackProcessor != null) { callbackProcessor.queueEvent(changeContext.getType(), changeContext); } else { throw new HelixException( "Failed to process callback in batch mode. Batch Callback Processor does not exist."); } } } else { invoke(changeContext); } if (_monitor != null) { _monitor.increaseCallbackUnbatchedCounters(); } }
Source:
public void shouldBeHealthyForOneLeaderElectionPerMinute() { markLeaderElectionsAtSpecifiedInterval(3, 60); assertThat(leaderElectionHealthCheck.leaderElectionRateHealthStatus()) .isEqualTo(LeaderElectionHealthStatus.HEALTHY); }

Target:
public void shouldBeHealthyForOneLeaderElectionPerMinute() { markLeaderElectionsAtSpecifiedInterval(3, Duration.ofSeconds(60)); assertThat(leaderElectionHealthCheck.leaderElectionRateHealthStatus()) .isEqualTo(LeaderElectionHealthStatus.HEALTHY); }
Source:
public void setUp() throws Exception { when(location.toString()).thenReturn("dw-thing.jar"); when(location.getVersion()).thenReturn(Optional.of("1.0.0")); bootstrap.addCommand(command); this.cli = new Cli(location, bootstrap, stdOut, stdErr); }

Target:
public void setUp() throws Exception { final JarLocation location = mock(JarLocation.class); final Bootstrap<Configuration> bootstrap = new Bootstrap<>(app); when(location.toString()).thenReturn("dw-thing.jar"); when(location.getVersion()).thenReturn(Optional.of("1.0.0")); bootstrap.addCommand(command); cli = new Cli(location, bootstrap, stdOut, stdErr); }
Source:
private static String getUri(String rawUrl, String apiUri) { if (StringUtils.isNotBlank(rawUrl)) { return getRawUrlUri(rawUrl); } else if (isBlank(apiUri)) { return "<LINK_0>"; }else { return apiUri; } }

Target:
private static String getUri(String rawUrl, String apiUri) { if (StringUtils.isNotBlank(rawUrl)) { return getRawUrlUri(rawUrl); } else if (isBlank(apiUri)) { return GitHubServerConfig.GITHUB_URL; }else { return apiUri; } }
Source:
public String toString() { StringWriter writer = new StringWriter(); try { new ObjectMapper().writeValue(writer, graph); } catch (Exception e) { log.debug ("Error while constructing new ObjectMapper",e); } return writer.toString(); }

Target:
public String toString() { StringWriter writer = new StringWriter(); try { new ObjectMapper().writeValue(writer, graph); } catch (Exception e) { log.error ("Error while constructing new ObjectMapper", e); } return writer.toString(); }
Source:
private boolean verifyLayout(View target, Set<Integer> rules) { ViewGroup parent = (ViewGroup) target.getParent(); SparseArray<View> idToChild = new SparseArray<View>(); int count = parent.getChildCount(); for (int i = 0; i < count; i++) { View child = parent.getChildAt(i); int childId = child.getId(); if (childId > 0) { idToChild.put(childId, child); } } ArrayMap<View, ArrayList<View>> dependencyGraph = new ArrayMap<View, ArrayList<View>>(); int size = idToChild.size(); for (int i = 0; i < size; i++) { final View child = idToChild.valueAt(i); final RelativeLayout.LayoutParams childLayoutParams = (RelativeLayout.LayoutParams) child.getLayoutParams(); int[] layoutRules = childLayoutParams.getRules(); ArrayList<View> dependencies = new ArrayList<View>(); for (int rule : rules) { int dependencyId = layoutRules[rule]; if (dependencyId > 0 && dependencyId != child.getId()) { dependencies.add(idToChild.get(dependencyId)); } } dependencyGraph.put(child, dependencies); } return hasCycle(dependencyGraph); }

Target:
private boolean verifyLayout(View target, Set<Integer> rules) { ViewGroup parent = (ViewGroup) target.getParent(); SparseArray<View> idToChild = new SparseArray<View>(); int count = parent.getChildCount(); for (int i = 0; i < count; i++) { View child = parent.getChildAt(i); int childId = child.getId(); if (childId > 0) { idToChild.put(childId, child); } } ArrayMap<View, ArrayList<View>> dependencyGraph = new ArrayMap<View, ArrayList<View>>(); int size = idToChild.size(); for (int i = 0; i < size; i++) { final View child = idToChild.valueAt(i); final RelativeLayout.LayoutParams childLayoutParams = (RelativeLayout.LayoutParams) child.getLayoutParams(); int[] layoutRules = childLayoutParams.getRules(); ArrayList<View> dependencies = new ArrayList<View>(); for (int rule : rules) { int dependencyId = layoutRules[rule]; if (dependencyId > 0 && dependencyId != child.getId()) { dependencies.add(idToChild.get(dependencyId)); } } dependencyGraph.put(child, dependencies); } return mCycleDetector.hasCycle(dependencyGraph); }
Source:
public Task update(UpdateTaskPayload updateTaskPayload) { org.activiti.engine.task.Task internalTask = taskService.createTaskQuery().taskId(updateTaskPayload.getTaskId()).singleResult(); if (internalTask == null) { throw new NotFoundException("Unable to find task for the given id: " + updateTaskPayload.getTaskId()); } int updates=0; String oldValue,newValue; if ((newValue = updateTaskPayload.getName()) != null) { oldValue = internalTask.getName(); if (!Objects.equals(oldValue,newValue)) { updates++; internalTask.setName(newValue); } } if ((newValue = updateTaskPayload.getDescription()) != null) { oldValue = internalTask.getDescription(); if (!Objects.equals(oldValue,newValue)) { updates++; internalTask.setDescription(newValue); } } if (updateTaskPayload.getPriority() != null) { if (internalTask.getPriority()!=updateTaskPayload.getPriority()) { updates++; internalTask.setPriority(updateTaskPayload.getPriority()); } } if (updateTaskPayload.getDueDate() != null) { if (!Objects.equals(internalTask.getDueDate(),updateTaskPayload.getDueDate())) { updates++; internalTask.setDueDate(updateTaskPayload.getDueDate()); } } if ((newValue=updateTaskPayload.getParentTaskId()) != null) { oldValue = internalTask.getParentTaskId(); if (!Objects.equals(oldValue,newValue)) { updates++; internalTask.setParentTaskId(newValue); } } if ((newValue=updateTaskPayload.getFormKey()) != null) { oldValue = internalTask.getFormKey(); if (!Objects.equals(oldValue,newValue)) { updates++; internalTask.setFormKey(newValue); } } if (updates > 0) { taskService.saveTask(internalTask); } return taskConverter.from(taskService.createTaskQuery().taskId(updateTaskPayload.getTaskId()).singleResult()); }

Target:
public Task update(UpdateTaskPayload updateTaskPayload) { return taskRuntimeHelper.applyUpdateTaskPayload(true, updateTaskPayload); }
Source:
public FutureCompletionStage<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action, Executor executor) { requireNonNull(action, "action"); return thenCombineAsync(other, (ignoreValue, ignoreError) -> { action.run(); return null; }, executor); }

Target:
public FutureCompletionStage<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action, Executor executor) { requireNonNull(action, "action"); return thenCombineAsync(other, (ignoreOtherValue, ignoreError) -> { action.run(); return null; }, executor); }
Source:
public void addNotEmptyIdConnection() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); newPosixConnection.setId(Guid.newGuid().toString()); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(Guid.Empty); doReturn(newPosixConnection.getId()).when(command).isConnWithSameDetailsExists(newPosixConnection, null); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ID_NOT_EMPTY); }

Target:
public void addNotEmptyIdConnection() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); newPosixConnection.setId(Guid.newGuid().toString()); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(Guid.Empty); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ID_NOT_EMPTY); }
Source:
public void init(Config.Scope config) { Integer maxDetail = config.getInt("max-detail-length", 0); maxDetailLength = (maxDetail == null) ? 0 : maxDetail; }

Target:
public void init(Config.Scope config) { maxDetailLength = config.getInt("max-detail-length", 0); }
Source:
public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("database", "jdbc://127.0.0.1:8001") .put("suites-table-name", "suite_source") .put("queries-table-name", "query_source") .put("suite-name", "test1") .build(); BenchmarkSuiteConfig expected = new BenchmarkSuiteConfig() .setDatabase("jdbc://127.0.0.1:8001") .setSuitesTableName("suite_source") .setQueriesTableName("query_source") .setSuite("test1"); assertFullMapping(properties, expected); }

Target:
public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("suite", "test1") .put("suites-table-name", "suite_source") .put("queries-table-name", "query_source") .build(); BenchmarkSuiteConfig expected = new BenchmarkSuiteConfig() .setSuite("test1") .setSuitesTableName("suite_source") .setQueriesTableName("query_source"); assertFullMapping(properties, expected); }
Source:
public List<MimeMessage> generateNewInstructorAccountJoinEmail(InstructorAttributes instructor,String shortName, String institute) throws AddressException,MessagingException,UnsupportedEncodingException { MimeMessage messageToUser = getEmptyEmailAddressedToEmail(instructor.email); MimeMessage messageToAdmin = getEmptyEmailAddressedToEmail(Config.SUPPORT_EMAIL); MimeMessage messageWithJoinLinkOnly = getEmptyEmailAddressedToEmail(Config.SUPPORT_EMAIL); List<MimeMessage> messages = new ArrayList<MimeMessage>(); messages.add(messageToUser); messages.add(messageToAdmin); messageToUser.setSubject(String.format(SUBJECT_PREFIX_NEW_INSTRUCTOR_ACCOUNT + " " + shortName)); messageToAdmin.setSubject(String.format(SUBJECT_PREFIX_NEW_INSTRUCTOR_ACCOUNT_COPY + " " + shortName+" "+ "[" + instructor.email + "]")); String joinUrl = ""; if (instructor != null) { String key; key = StringHelper.encrypt(instructor.key); joinUrl = Config.APP_URL + Const.ActionURIs.INSTRUCTOR_COURSE_JOIN; joinUrl = Url.addParamToUrl(joinUrl, Const.ParamsNames.REGKEY, key); joinUrl = Url.addParamToUrl(joinUrl, Const.ParamsNames.INSTRUCTOR_INSTITUTION, institute); } for(MimeMessage message : messages){ String emailBody = EmailTemplates.NEW_INSTRCUTOR_ACCOUNT_WELCOME; emailBody = emailBody.replace("${userName}", shortName); emailBody = emailBody.replace("${joinUrl}",joinUrl); message.setContent(emailBody, "text/html"); } messageWithJoinLinkOnly.setContent(joinUrl, "text/html"); messages.add(messageWithJoinLinkOnly); return messages; }

Target:
public List<MimeMessage> generateNewInstructorAccountJoinEmail(InstructorAttributes instructor,String shortName, String institute) throws AddressException,MessagingException,UnsupportedEncodingException { MimeMessage messageToUser = getEmptyEmailAddressedToEmail(instructor.email); MimeMessage messageToAdmin = getEmptyEmailAddressedToEmail(Config.SUPPORT_EMAIL); MimeMessage messageWithJoinLinkOnly = getEmptyEmailAddressedToEmail(Config.SUPPORT_EMAIL); List<MimeMessage> messages = new ArrayList<MimeMessage>(); messages.add(messageToUser); messages.add(messageToAdmin); messageToUser.setSubject(String.format(SUBJECT_PREFIX_NEW_INSTRUCTOR_ACCOUNT + " " + shortName)); messageToAdmin.setSubject(String.format(SUBJECT_PREFIX_NEW_INSTRUCTOR_ACCOUNT_COPY + " " + shortName+" "+ "[" + instructor.email + "]")); String joinUrl = generateNewInstructorAccountJoinLink(instructor, institute); for(MimeMessage message : messages){ String emailBody = EmailTemplates.NEW_INSTRCUTOR_ACCOUNT_WELCOME; emailBody = emailBody.replace("${userName}", shortName); emailBody = emailBody.replace("${joinUrl}",joinUrl); message.setContent(emailBody, "text/html"); } messageWithJoinLinkOnly.setContent(joinUrl, "text/html"); messages.add(messageWithJoinLinkOnly); return messages; }
Source:
public void testCleanUpExceptionSuppressing() throws Exception { OneInputStreamTaskTestHarness<String, String> testHarness = new OneInputStreamTaskTestHarness<>( OneInputStreamTask::new, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO); testHarness.setupOutputForSingletonOperatorChain(); StreamConfig streamConfig = testHarness.getStreamConfig(); streamConfig.setStreamOperator(new FailingTwiceOperator()); streamConfig.setOperatorID(new OperatorID()); testHarness.invoke(); testHarness.waitForTaskRunning(); testHarness.processElement(new StreamRecord<>("Doesn't matter", 0)); try { testHarness.waitForTaskCompletion(); } catch (Exception ex) { Assert.assertTrue(ex.getCause() instanceof ExpectedTestException); Assert.assertTrue( ex.getCause() .getSuppressed()[0] .getMessage() .equals("Dispose Exception. This exception should be suppressed")); } }

Target:
public void testCleanUpExceptionSuppressing() throws Exception { OneInputStreamTaskTestHarness<String, String> testHarness = new OneInputStreamTaskTestHarness<>( OneInputStreamTask::new, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO); testHarness.setupOutputForSingletonOperatorChain(); StreamConfig streamConfig = testHarness.getStreamConfig(); streamConfig.setStreamOperator(new FailingTwiceOperator()); streamConfig.setOperatorID(new OperatorID()); testHarness.invoke(); testHarness.waitForTaskRunning(); testHarness.processElement(new StreamRecord<>("Doesn't matter", 0)); try { testHarness.waitForTaskCompletion(); } catch (Exception ex) { if (!(ex.getCause() instanceof ExpectedTestException)) { throw ex; } if (!(Iterables.getOnlyElement(asList(ex.getCause().getSuppressed())) instanceof FailingTwiceOperator.DisposeException)) { throw ex; } } }
Source:
public void startup() throws Exception { super.startup(); try { clientId = generateClientId(); } catch (Exception e) { LOGGER.log(Level.WARNING, "[" + getName() + "] could not generate client ID. Is this machine connected to the internet?"); throw e; } StreamingConnectionFactory factory = new StreamingConnectionFactory(clusterId,clientId); factory.setNatsUrl("nats://" + this.serverHost + ":" + this.serverPort); stanConnection = factory.createConnection(); }

Target:
public void startup() throws Exception { super.startup(); client.startup(); }
Source:
private void createIndexToolOutputTable(Connection connection) throws Exception { ConnectionQueryServices queryServices = connection.unwrap(PhoenixConnection.class).getQueryServices(); Admin admin = queryServices.getAdmin(); if (admin.tableExists(TableName.valueOf(OUTPUT_TABLE_NAME))) { return; } HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(OUTPUT_TABLE_NAME)); tableDescriptor.setValue("DISABLE_TABLE_SOR", "true"); tableDescriptor.setValue(ColumnFamilyDescriptorBuilder.TTL, String.valueOf(MetaDataProtocol.DEFAULT_LOG_TTL)); HColumnDescriptor columnDescriptor = new HColumnDescriptor(QueryConstants.DEFAULT_COLUMN_FAMILY); tableDescriptor.addFamily(columnDescriptor); admin.createTable(tableDescriptor); }

Target:
private void createIndexToolOutputTable(Connection connection) throws Exception { ConnectionQueryServices queryServices = connection.unwrap(PhoenixConnection.class).getQueryServices(); Admin admin = queryServices.getAdmin(); if (admin.tableExists(TableName.valueOf(OUTPUT_TABLE_NAME))) { return; } HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(OUTPUT_TABLE_NAME)); tableDescriptor.setValue(ColumnFamilyDescriptorBuilder.TTL, String.valueOf(MetaDataProtocol.DEFAULT_LOG_TTL)); HColumnDescriptor columnDescriptor = new HColumnDescriptor(QueryConstants.DEFAULT_COLUMN_FAMILY); tableDescriptor.addFamily(columnDescriptor); admin.createTable(tableDescriptor); }
Source:
public boolean bind(final ClientEndpoint endpoint) { if (!clientSelector.select(endpoint)) { return false; } if (endpointManager.registerEndpoint(endpoint)) { Connection conn = endpoint.getConnection(); if (conn instanceof TcpIpConnection) { InetSocketAddress socketAddress = conn.getRemoteSocketAddress(); if (socketAddress != null) { Address address = new Address(socketAddress); ((TcpIpConnection) conn).setEndPoint(address); } } } else { return true; } if (!clientSelector.select(endpoint)) { endpointManager.removeEndpoint(endpoint); return false; } return true; }

Target:
public boolean bind(final ClientEndpoint endpoint) { if (!clientSelector.select(endpoint)) { return false; } if (!endpointManager.registerEndpoint(endpoint)) { return true; } Connection conn = endpoint.getConnection(); if (conn instanceof TcpIpConnection) { InetSocketAddress socketAddress = conn.getRemoteSocketAddress(); if (socketAddress != null) { Address address = new Address(socketAddress); ((TcpIpConnection) conn).setEndPoint(address); } } if (!clientSelector.select(endpoint)) { endpointManager.removeEndpoint(endpoint); return false; } return true; }
Source:
public void update(Observable o, Object arg) { clear(); createProfiles(); }

Target:
public void update(Observable o, Object arg) { profiles = createProfiles(); }
Source:
public boolean equals(Object o) { if (o instanceof WorkItemDefinition) { WorkItemDefinition other = (WorkItemDefinition) o; return super.equals(other) && name.equals(other.name) && ((null != category) ? category.equals(other.category) : null == other.category) && ((null != description) ? description.equals(other.description) : null == other.description) && ((null != displayName) ? displayName.equals(other.displayName) : null == other.displayName) && ((null != documentation) ? documentation.equals(other.documentation) : null == other.documentation) && ((null != iconDefinition) ? iconDefinition.equals(other.iconDefinition) : null == other.iconDefinition) && ((null != defaultHandler) ? defaultHandler.equals(other.defaultHandler) : null == other.defaultHandler) && ((null != parameters) ? parameters.equals(other.parameters) : null == other.parameters) && ((null != results) ? results.equals(other.results) : null == other.results) && ((null != dependencies) ? dependencies.equals(other.dependencies) : null == other.dependencies); } return false; }

Target:
public boolean equals(Object o) { if (o instanceof WorkItemDefinition) { WorkItemDefinition other = (WorkItemDefinition) o; return super.equals(other) && name.equals(other.name) && Objects.equals(category, other.category) && Objects.equals(description, other.description) && Objects.equals(displayName, other.displayName) && Objects.equals(documentation, other.documentation) && Objects.equals(iconDefinition, other.iconDefinition) && Objects.equals(defaultHandler, other.defaultHandler) && Objects.equals(parameters, other.parameters) && Objects.equals(results, other.results) && Objects.equals(dependencies, other.dependencies); } return false; }
Source:
public void start() { onPingRequestSubscriber = Subscribers.create(new OnPingRequestAction()); transport.listen().observeOn(scheduler) .filter(PING_FILTER) .filter(targetFilter()) .subscribe(onPingRequestSubscriber); onAskToPingRequestSubscriber = Subscribers.create(new OnAskToPingRequestAction()); transport.listen().observeOn(scheduler) .filter(PING_REQ_FILTER) .subscribe(onAskToPingRequestSubscriber); onTransitAckRequestSubscriber = Subscribers.create(new OnTransitAckRequestAction()); transport.listen().observeOn(scheduler) .filter(ACK_FILTER) .filter(ORIGINAL_ISSUER_FILTER) .subscribe(onTransitAckRequestSubscriber); int pingTime = config.getPingTime(); pingTask = executor.scheduleWithFixedDelay(new PingTask(), pingTime, pingTime, TimeUnit.MILLISECONDS); }

Target:
public void start() { onPingRequestSubscriber = Subscribers.create(new OnPingRequestAction()); transport.listen().observeOn(scheduler) .filter(PING_FILTER) .filter(targetFilter()) .subscribe(onPingRequestSubscriber); onAskToPingRequestSubscriber = Subscribers.create(new OnAskToPingRequestAction()); transport.listen().observeOn(scheduler) .filter(PING_REQ_FILTER) .subscribe(onAskToPingRequestSubscriber); onTransitAckRequestSubscriber = Subscribers.create(new OnTransitAckRequestAction()); transport.listen().observeOn(scheduler) .filter(ACK_FILTER) .filter(ORIGINAL_ISSUER_FILTER) .subscribe(onTransitAckRequestSubscriber); int pingTime = config.getPingTime(); pingTask = executor.scheduleWithFixedDelay(this::doPing, pingTime, pingTime, TimeUnit.MILLISECONDS); }
Source:
public ContainerSpec(ContainerSpec other) { super(other.getId(), other.getContainerName(), other.getServerTemplateKey()); this.releasedId = other.releasedId; this.status = other.status; this.configs = other.getConfigs().isEmpty() ? Collections.emptyMap() : new EnumMap<>(other.getConfigs()); }

Target:
public ContainerSpec(ContainerSpec other) { super(other.getId(), other.getContainerName(), other.getServerTemplateKey()); this.releasedId = other.releasedId; this.status = other.status; this.configs = other.getConfigs().isEmpty() ? new EnumMap<>(Capability.class) : new EnumMap<>(other.getConfigs()); }
Source:
private void waitForQueryToBeKilled(DistributedQueryRunner queryRunner) throws InterruptedException { boolean queryDone = false; while (!queryDone) { for (BasicQueryInfo info : queryRunner.getCoordinator().getQueryManager().getQueries()) { if (info.getState().isDone()) { assertNotNull(info.getErrorCode()); assertEquals(info.getErrorCode().getCode(), CLUSTER_OUT_OF_MEMORY.toErrorCode().getCode()); queryDone = true; break; } } MILLISECONDS.sleep(10); } }

Target:
private void waitForQueryToBeKilled(DistributedQueryRunner queryRunner) throws InterruptedException { while (true) { for (BasicQueryInfo info : queryRunner.getCoordinator().getQueryManager().getQueries()) { if (info.getState().isDone()) { assertNotNull(info.getErrorCode()); assertEquals(info.getErrorCode().getCode(), CLUSTER_OUT_OF_MEMORY.toErrorCode().getCode()); return; } } MILLISECONDS.sleep(10); } }
Source:
public PageInfo evict() { PageId victim = mEvictor.evict(); if (victim == null) { return null; } return mPageMap.get(victim); }

Target:
public PageInfo evict() { PageId victim = mEvictor.evict(); if (victim == null) { return null; } PageInfo victimInfo = mPageMap.get(victim); if (victimInfo == null) { LOG.error("Invalid result returned by evictor: page not available", victim); mEvictor.updateOnDelete(victim); return null; } return victimInfo; }
Source:
public ActivityImpl parseReceiveTask(Element receiveTaskElement, ScopeImpl scope) { ActivityImpl activity = createActivityOnScope(receiveTaskElement, scope); activity.setActivityBehavior(new ReceiveTaskActivityBehavior()); parseAsynchronousContinuationForActivity(receiveTaskElement, activity); parseExecutionListenersOnScope(receiveTaskElement, activity); if (receiveTaskElement.attribute("messageRef") != null) { activity.setScope(true); activity.setEventScope(activity); EventSubscriptionDeclaration declaration = parseMessageEventDefinition(receiveTaskElement, null); declaration.setActivityId(activity.getActivityId()); declaration.setEventScopeActivityId(activity.getActivityId()); addEventSubscriptionDeclaration(declaration, activity, receiveTaskElement); } for (BpmnParseListener parseListener : parseListeners) { parseListener.parseReceiveTask(receiveTaskElement, scope, activity); } return activity; }

Target:
public ActivityImpl parseReceiveTask(Element receiveTaskElement, ScopeImpl scope) { ActivityImpl activity = createActivityOnScope(receiveTaskElement, scope); activity.setActivityBehavior(new ReceiveTaskActivityBehavior()); parseAsynchronousContinuationForActivity(receiveTaskElement, activity); parseExecutionListenersOnScope(receiveTaskElement, activity); if (receiveTaskElement.attribute("messageRef") != null) { activity.setScope(true); activity.setEventScope(activity); EventSubscriptionDeclaration declaration = parseMessageEventDefinition(receiveTaskElement, activity.getId()); declaration.setActivityId(activity.getActivityId()); declaration.setEventScopeActivityId(activity.getActivityId()); addEventSubscriptionDeclaration(declaration, activity, receiveTaskElement); } for (BpmnParseListener parseListener : parseListeners) { parseListener.parseReceiveTask(receiveTaskElement, scope, activity); } return activity; }
Source:
public DataRecord getRecord(DataIdentifier identifier) throws DataStoreException { return null; }

Target:
public DataRecord getRecord(DataIdentifier identifier) throws DataStoreException { DataRecord result = getRecordIfStored(identifier); if (null == result) { throw new DataStoreException(String.format("No matching record for identifier %s", identifier.toString())); } return result; }
Source:
public DataSet< V> intersect(DataSet< V> dataSet, String name, OperationContext context, boolean pushScope, String scopeDetail) { pushScopeIfNeeded(context, pushScope, scopeDetail); try { Dataset<Row> that = SpliceSpark.getSession() .createDataFrame( rdd.map( new LocatedRowToRowFunction()), context.getOperation() .getExecRowDefinition() .schema()); Dataset<Row> other = SpliceSpark.getSession() .createDataFrame( ((SparkDataSet)dataSet).rdd .map(new LocatedRowToRowFunction()), context.getOperation() .getExecRowDefinition() .schema()); Dataset<Row> result = that.intersect(other); return new SparkDataSet( result.javaRDD() .map(new RowToLocatedRowFunction(context))); } catch (Exception se){ throw new RuntimeException(se); }finally { if (pushScope) context.popScope(); } }

Target:
public DataSet< V> intersect(DataSet< V> dataSet, String name, OperationContext context, boolean pushScope, String scopeDetail) { pushScopeIfNeeded(context, pushScope, scopeDetail); try { Dataset<Row> left = SpliceSpark.getSession() .createDataFrame( rdd.map( new LocatedRowToRowFunction()), context.getOperation() .getExecRowDefinition() .schema()); Dataset<Row> right = SpliceSpark.getSession() .createDataFrame( ((SparkDataSet)dataSet).rdd .map(new LocatedRowToRowFunction()), context.getOperation() .getExecRowDefinition() .schema()); Dataset<Row> result = left.intersect(right); return toSpliceLocatedRow(result,context); } catch (Exception se){ throw new RuntimeException(se); }finally { if (pushScope) context.popScope(); } }
Source:
public ChemComp getChemComp(String recordName) { String name = recordName.toUpperCase().trim(); try { try(InputStream inStream = this.getClass().getResourceAsStream("/chemcomp/"+name + ".cif.gz")) { logger.debug("Reading chemcomp/"+name+".cif.gz"); if ( inStream == null){ logger.debug("Getting empty chem comp for {}",name); ChemComp cc = ChemComp.getEmptyChemComp(); cc.setId(name); return cc; } MMcifParser parser = new SimpleMMcifParser(); ChemCompConsumer consumer = new ChemCompConsumer(); parser.addMMcifConsumer(consumer); parser.parse(new BufferedReader(new InputStreamReader(new GZIPInputStream(inStream)))); ChemicalComponentDictionary dict = consumer.getDictionary(); ChemComp chemComp = dict.getChemComp(name); return chemComp; } } catch (IOException e){ logger.error("IOException caught while reading chem comp {}.",name,e); } logger.warn("Problem when loading chem comp {}, will use an empty chem comp for it", name); ChemComp cc = ChemComp.getEmptyChemComp(); cc.setId(name); return cc; }

Target:
public ChemComp getChemComp(String recordName) { String name = recordName.toUpperCase().trim(); try(InputStream inStream = this.getClass().getResourceAsStream("/chemcomp/"+name + ".cif.gz")) { logger.debug("Reading chemcomp/"+name+".cif.gz"); if ( inStream == null){ logger.debug("Getting empty chem comp for {}",name); ChemComp cc = ChemComp.getEmptyChemComp(); cc.setId(name); return cc; } MMcifParser parser = new SimpleMMcifParser(); ChemCompConsumer consumer = new ChemCompConsumer(); parser.addMMcifConsumer(consumer); parser.parse(new BufferedReader(new InputStreamReader(new GZIPInputStream(inStream)))); ChemicalComponentDictionary dict = consumer.getDictionary(); ChemComp chemComp = dict.getChemComp(name); return chemComp; } catch (IOException e){ logger.error("IOException caught while reading chem comp {}.",name,e); } logger.warn("Problem when loading chem comp {}, will use an empty chem comp for it", name); ChemComp cc = ChemComp.getEmptyChemComp(); cc.setId(name); return cc; }
Source:
private void registerAbnormalStopHandler() throws InfrastructureException { project .pods() .watch( (action, pod) -> { if (pod.getStatus() != null && "Failed".equals(pod.getStatus().getPhase())) { try { internalStop(emptyMap()); final String podName = pod.getMetadata().getName(); eventService.publish( DtoFactory.newDto(RuntimeStatusEvent.class) .withIdentity(DtoConverter.asDto(getContext().getIdentity())) .withStatus("STOPPED") .withPrevStatus("RUNNING") .withFailed(true) .withError(format("Pod '%s' was abnormally stopped", podName))); } catch (InfrastructureException ex) { LOG.error("OpenShift environment stop failed cause '{}'", ex.getMessage()); } } }); }

Target:
private void registerAbnormalStopHandler() throws InfrastructureException { project .pods() .watch( (action, pod) -> { if (pod.getStatus() != null && POD_FAILED_STATUS.equals(pod.getStatus().getPhase())) { try { internalStop(emptyMap()); } catch (InfrastructureException ex) { LOG.error("OpenShift environment stop failed cause '{}'", ex.getMessage()); } finally { sendRuntimeStoppedEvent( format("Pod '%s' was abnormally stopped", pod.getMetadata().getName())); } } }); }
Source:
public static final HTInterval readFrom(ByteBuffer buffer) throws IOException { HTInterval interval; long intervalStart, intervalEnd; int attribute; TmfStateValue value; byte valueType; byte array[]; int posStart = buffer.position(); intervalStart = buffer.getLong(); intervalEnd = buffer.getLong() + intervalStart; attribute = buffer.getInt(); valueType = buffer.get(); switch (valueType) { case TYPE_NULL: value = TmfStateValue.nullValue(); break; case TYPE_INTEGER: value = TmfStateValue.newValueInt(buffer.getInt()); break; case TYPE_STRING: int valueSize = buffer.get(); array = new byte[valueSize]; buffer.get(array); value = TmfStateValue.newValueString(new String(array)); byte res = buffer.get(); if (res != 0) { throw new IOException(errMsg); } break; case TYPE_LONG: value = TmfStateValue.newValueLong(buffer.getLong()); break; case TYPE_DOUBLE: value = TmfStateValue.newValueDouble(buffer.getDouble()); break; default: throw new IOException(errMsg); } try { interval = new HTInterval(intervalStart, intervalEnd, attribute, value, buffer.position() - posStart); } catch (TimeRangeException e) { throw new IOException(errMsg); } return interval; }

Target:
public static final HTInterval readFrom(ByteBuffer buffer) throws IOException { HTInterval interval; long intervalStart, intervalEnd; int attribute; TmfStateValue value; byte valueType; byte array[]; int posStart = buffer.position(); intervalStart = buffer.getLong(); intervalEnd = buffer.getLong(); attribute = buffer.getInt(); valueType = buffer.get(); switch (valueType) { case TYPE_NULL: value = TmfStateValue.nullValue(); break; case TYPE_INTEGER: value = TmfStateValue.newValueInt(buffer.getInt()); break; case TYPE_STRING: int valueSize = buffer.get(); array = new byte[valueSize]; buffer.get(array); value = TmfStateValue.newValueString(new String(array)); byte res = buffer.get(); if (res != 0) { throw new IOException(errMsg); } break; case TYPE_LONG: value = TmfStateValue.newValueLong(buffer.getLong()); break; case TYPE_DOUBLE: value = TmfStateValue.newValueDouble(buffer.getDouble()); break; default: throw new IOException(errMsg); } try { interval = new HTInterval(intervalStart, intervalEnd, attribute, value, buffer.position() - posStart); } catch (TimeRangeException e) { throw new IOException(errMsg); } return interval; }
Source:
public Rule JsonObject() { return FirstOf( Sequence( ZeroOrMore( WhiteSpace() ).skipNode(), "{ ", FirstOf( Sequence( Pair(), ZeroOrMore( Sequence( ", ", Pair() ) ) ), Optional( Pair() ) ).suppressNode(), "} " ), Sequence( ZeroOrMore( ANY ), builder.setInvalidJsonInPrefix( match() ), ACTION( false ) ) ); }

Target:
public Rule JsonObject() { return Sequence( ZeroOrMore( WhiteSpace() ).skipNode(), "{ ", FirstOf( Sequence( Pair(), ZeroOrMore( Sequence( ", ", Pair() ) ) ), Optional( Pair() ) ).suppressNode(), "} " ); }
Source:
public static void request(final String host, final int port, final FullHttpRequest request, final Consumer<FullHttpResponse> consumer, final Long timeoutSeconds) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(1); EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); Channel channel = new Bootstrap() .group(eventLoopGroup) .channel(NioSocketChannel.class) .remoteAddress(host, port) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel ch) throws Exception { ch.pipeline() .addLast(new HttpClientCodec()) .addLast(new HttpObjectAggregator(1024 * 1024)) .addLast(new SimpleChannelInboundHandler<FullHttpResponse>() { @Override protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpResponse httpResponse) throws Exception { try { consumer.accept(httpResponse); } finally { countDownLatch.countDown(); } } }); } }).connect() .sync().channel(); channel.writeAndFlush(request); countDownLatch.await(timeoutSeconds, TimeUnit.SECONDS); channel.close().sync(); }

Target:
public static void request(final String host, final int port, final FullHttpRequest request, final Consumer<FullHttpResponse> consumer, final Long timeoutSeconds) { CountDownLatch countDownLatch = new CountDownLatch(1); EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); Channel channel = new Bootstrap() .group(eventLoopGroup) .channel(NioSocketChannel.class) .remoteAddress(host, port) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel ch) throws Exception { ch.pipeline() .addLast(new HttpClientCodec()) .addLast(new HttpObjectAggregator(1024 * 1024)) .addLast(new SimpleChannelInboundHandler<FullHttpResponse>() { @Override protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpResponse httpResponse) throws Exception { try { consumer.accept(httpResponse); } finally { countDownLatch.countDown(); } } }); } }).connect() .sync().channel(); channel.writeAndFlush(request); countDownLatch.await(timeoutSeconds, TimeUnit.SECONDS); channel.close().sync(); }