auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void handleNewDatastream() { List<Datastream> newDatastreams = _adapter.getAllDatastreams().stream() .filter(ds -> ds.getTarget() == null) .map(ds -> setDatastreamTarget(ds)) .filter(ds -> ds.getTarget() != null) .collect(Collectors.toList()); if (newDatastreams.size() == 0) { return; } boolean succeeded = newDatastreams.stream().allMatch(ds -> _adapter.updateDatastream(ds)); if (succeeded) { _eventQueue.put(CoordinatorEvent.createLeaderDoAssignmentEvent()); return; } if (!leaderDoAssignmentScheduled.get()) { LOG.warn("Schedule retry for handling new datastream"); leaderDoAssignmentScheduled.set(true); _executor.schedule(() -> { _eventQueue.put(CoordinatorEvent.createHandleNewDatastreamEvent()); leaderDoAssignmentScheduled.set(false); }, _config.getRetryIntervalMS(), TimeUnit.MILLISECONDS); } }

Target:
private void handleNewDatastream() { List<Datastream> newDatastreams = _adapter.getAllDatastreams().stream() .filter(ds -> ds.getTarget() == null) .map(ds -> setDatastreamTarget(ds)) .filter(ds -> ds.getTarget() != null) .collect(Collectors.toList()); if (newDatastreams.size() == 0) { return; } boolean succeeded = newDatastreams.stream().allMatch(ds -> { boolean updated = _adapter.updateDatastream(ds); if (!updated) { LOG.warn("failed to update datastream target for " + ds.getName()); } return updated; }); if (succeeded) { _eventQueue.put(CoordinatorEvent.createLeaderDoAssignmentEvent()); return; } if (leaderDoAssignmentScheduled.compareAndSet(false, true)){ LOG.warn("Schedule retry for handling new datastream"); _executor.schedule(() -> { _eventQueue.put(CoordinatorEvent.createHandleNewDatastreamEvent()); leaderDoAssignmentScheduled.set(false); }, _config.getRetryIntervalMS(), TimeUnit.MILLISECONDS); } }
Source:
private DeserializationRuntimeConverter createDecimalConverter(DecimalType decimalType) { return avroObject -> { final byte[] bytes; if (avroObject instanceof GenericFixed) { bytes = ((GenericFixed) avroObject).bytes(); } else if (avroObject instanceof ByteBuffer) { ByteBuffer byteBuffer = (ByteBuffer) avroObject; bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); } else { bytes = (byte[]) avroObject; } return DecimalData.fromUnscaledBytes(bytes, decimalType.getPrecision(), decimalType.getScale()); }; }

Target:
private DeserializationRuntimeConverter createDecimalConverter(DecimalType decimalType) { final int precision = decimalType.getPrecision(); final int scale = decimalType.getScale(); return avroObject -> { final byte[] bytes; if (avroObject instanceof GenericFixed) { bytes = ((GenericFixed) avroObject).bytes(); } else if (avroObject instanceof ByteBuffer) { ByteBuffer byteBuffer = (ByteBuffer) avroObject; bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); } else { bytes = (byte[]) avroObject; } return DecimalData.fromUnscaledBytes(bytes, precision, scale); }; }
Source:
StatementClient startQuery(String sql, Map<String, String> sessionPropertiesOverride) { String source = firstNonNull(clientInfo.get("ApplicationName"), "presto-jdbc"); String traceToken = clientInfo.get("TraceToken"); Iterable<String> clientTags = Splitter.on(',').trimResults().omitEmptyStrings() .split(nullToEmpty(clientInfo.get("ClientTags"))); Map<String, String> allProperties = new HashMap<>(sessionProperties); allProperties.putAll(sessionPropertiesOverride); int millis = networkTimeoutMillis.get(); Duration timeout = (millis > 0) ? new Duration(millis, MILLISECONDS) : new Duration(999, DAYS); ClientSession session = new ClientSession( httpUri, user, source, Optional.ofNullable(traceToken), ImmutableSet.copyOf(clientTags), clientInfo.get("ClientInfo"), catalog.get(), schema.get(), timeZoneId.get(), locale.get(), ImmutableMap.of(), ImmutableMap.copyOf(allProperties), ImmutableMap.copyOf(preparedStatements), transactionId.get(), timeout); return queryExecutor.startQuery(session, sql); }

Target:
StatementClient startQuery(String sql, Map<String, String> sessionPropertiesOverride) { String source = firstNonNull(clientInfo.get("ApplicationName"), "presto-jdbc"); Optional<String> traceToken = Optional.ofNullable(clientInfo.get("TraceToken")); Iterable<String> clientTags = Splitter.on(',').trimResults().omitEmptyStrings() .split(nullToEmpty(clientInfo.get("ClientTags"))); Map<String, String> allProperties = new HashMap<>(sessionProperties); allProperties.putAll(sessionPropertiesOverride); int millis = networkTimeoutMillis.get(); Duration timeout = (millis > 0) ? new Duration(millis, MILLISECONDS) : new Duration(999, DAYS); ClientSession session = new ClientSession( httpUri, user, source, traceToken, ImmutableSet.copyOf(clientTags), clientInfo.get("ClientInfo"), catalog.get(), schema.get(), timeZoneId.get(), locale.get(), ImmutableMap.of(), ImmutableMap.copyOf(allProperties), ImmutableMap.copyOf(preparedStatements), transactionId.get(), timeout); return queryExecutor.startQuery(session, sql); }
Source:
public boolean runOnceOnly(R resource) { try { lock.lock(); if (!shutdownSignal) { init(resource); return true; } } catch (Throwable e) { cleanup(resource, e); } finally { lock.unlock(); } return false; }

Target:
public synchronized boolean runOnceOnly(R resource) { try { if (!shutdownSignal) { init(resource); return true; } } catch (Throwable e) { cleanup(resource, e); } return false; }
Source:
public static void publishCatalog(ZooKeeper zk, int version) throws KeeperException, InterruptedException { String path = VoltZK.catalogbytes + "/" + version; hostLog.info("***publish " + path); Stat stat = new Stat(); byte[] data = zk.getData(path, false, stat); ByteBuffer buffer = ByteBuffer.wrap(data); byte status = buffer.get(); assert (status == (byte)ZKCatalogStatus.PENDING.ordinal()); int expectedNodeCount = buffer.getInt(); buffer.position(0); buffer.put((byte)ZKCatalogStatus.COMPLETE.ordinal()); buffer.putInt(expectedNodeCount); zk.setData(path, buffer.array(), stat.getVersion()); List<String> children = zk.getChildren(VoltZK.catalogbytes, false); for (String child : children) { int priorVersion = Integer.parseInt(child); if (priorVersion < version) { hostLog.info("***deleting " + ZKUtil.joinZKPath(VoltZK.catalogbytes, child)); ZKUtil.deleteRecursively(zk, ZKUtil.joinZKPath(VoltZK.catalogbytes, child)); } } }

Target:
public static void publishCatalog(ZooKeeper zk, int version) throws KeeperException, InterruptedException { String path = VoltZK.catalogbytes + "/" + version; Stat stat = new Stat(); byte[] data = zk.getData(path, false, stat); ByteBuffer buffer = ByteBuffer.wrap(data); byte status = buffer.get(); assert (status == (byte)ZKCatalogStatus.PENDING.ordinal()); int catalogSegmentCount = buffer.getInt(); buffer.position(0); buffer.put((byte)ZKCatalogStatus.COMPLETE.ordinal()); buffer.putInt(catalogSegmentCount); zk.setData(path, buffer.array(), stat.getVersion()); List<String> children = zk.getChildren(VoltZK.catalogbytes, false); for (String child : children) { int priorVersion = Integer.parseInt(child); if (priorVersion < version) { ZKUtil.deleteRecursively(zk, ZKUtil.joinZKPath(VoltZK.catalogbytes, child)); } } }
Source:
public void testSemiJoinMemoryReservationYield(Type type) { List<Page> input = createPages(type, 5_000, 500, false); RowPagesBuilder rowPagesBuilder = rowPagesBuilder(false, Ints.asList(0), type); SetBuilderOperatorFactory setBuilderOperatorFactory = new SetBuilderOperatorFactory( 1, new PlanNodeId("test"), type, 0, rowPagesBuilder.getHashChannel(), 10, new JoinCompiler()); GroupByHashYieldAssertion.GroupByHashYieldResult result = finishOperatorWithYieldingGroupByHash( input, type, setBuilderOperatorFactory, operator -> ((SetBuilderOperator) operator).getCapacity(), 170_000); assertGreaterThanOrEqual(result.getYieldCount(), 7); assertGreaterThan(result.getMaxReservedBytes(), 20L << 20); assertEquals(result.getOutput().stream().mapToInt(Page::getPositionCount).sum(), 0); }

Target:
public void testSemiJoinMemoryReservationYield(Type type) { List<Page> input = createPagesWithDistinctHashKeys(type, 5_000, 500); SetBuilderOperatorFactory setBuilderOperatorFactory = new SetBuilderOperatorFactory( 1, new PlanNodeId("test"), type, 0, Optional.of(1), 10, new JoinCompiler()); GroupByHashYieldAssertion.GroupByHashYieldResult result = finishOperatorWithYieldingGroupByHash( input, type, setBuilderOperatorFactory, operator -> ((SetBuilderOperator) operator).getCapacity(), 170_000); assertGreaterThanOrEqual(result.getYieldCount(), 7); assertGreaterThan(result.getMaxReservedBytes(), 20L << 20); assertEquals(result.getOutput().stream().mapToInt(Page::getPositionCount).sum(), 0); }
Source:
private void readEscapedString(){ int chr; while (true) { chr = sr.read(); if (chr == BACKSLASH) { sr.read(); continue; } else if (chr == QUOTATION_MARK) { break; } else if (chr == -1) { throw new IllegalArgumentException("EOF reached while reading JSON field name"); } } }

Target:
private void readEscapedString(){ int chr; while (true) { chr = sr.read(); if (chr == BACKSLASH) { chr = sr.read(); } else if (chr == QUOTATION_MARK) { break; } if (chr == -1) { throw new IllegalArgumentException("EOF reached while reading JSON field name"); } } }
Source:
public StructuredRecord merge(StructuredRecord joinKey, Iterable<JoinElement<StructuredRecord>> joinRow) { StructuredRecord.Builder outRecordBuilder; outRecordBuilder = StructuredRecord.builder(outputSchema); for (JoinElement<StructuredRecord> joinElement : joinRow) { String stageName = joinElement.getStageName(); StructuredRecord record = joinElement.getInputRecord(); Map<String, String> fieldsToRename = perStageFieldsToRename.row(stageName); for (Schema.Field field : record.getSchema().getFields()) { String inputFieldName = field.getName(); if (!fieldsToRename.containsKey(inputFieldName)) { continue; } String outputFieldName = fieldsToRename.get(inputFieldName); outRecordBuilder.set(outputFieldName, record.get(inputFieldName)); } } return outRecordBuilder.build(); }

Target:
public StructuredRecord merge(StructuredRecord joinKey, Iterable<JoinElement<StructuredRecord>> joinRow) { StructuredRecord.Builder outRecordBuilder = StructuredRecord.builder(outputSchema); for (JoinElement<StructuredRecord> joinElement : joinRow) { String stageName = joinElement.getStageName(); StructuredRecord record = joinElement.getInputRecord(); Map<String, String> selectedFields = perStageSelectedFields.row(stageName); for (Schema.Field field : record.getSchema().getFields()) { String inputFieldName = field.getName(); if (!selectedFields.containsKey(inputFieldName)) { continue; } String outputFieldName = selectedFields.get(inputFieldName); outRecordBuilder.set(outputFieldName, record.get(inputFieldName)); } } return outRecordBuilder.build(); }
Source:
public static List<InetSocketAddress> toSocketAddresses(String commaSeparatedAddressesWithPorts) { final String servers[] = commaSeparatedAddressesWithPorts.split(","); return Arrays.stream(servers) .map(s -> { String parts[] = s.split(":"); if (parts.length > 1) { return SocketUtils.socketAddress(parts[0].trim(), Integer.parseInt(parts[1].trim())); } else { return SocketUtils.socketAddress(parts[0].trim(),53); } }) .collect(Collectors.toList()); }

Target:
public static List<InetSocketAddress> toSocketAddresses(String commaSeparatedAddressesWithPorts) { final String[] servers = commaSeparatedAddressesWithPorts.split(","); return Arrays.stream(servers) .map(s -> { final HostAndPort hp = HostAndPort.fromString(s.trim()) .withDefaultPort(53) .requireBracketsForIPv6(); return SocketUtils.socketAddress(hp.getHostText(), hp.getPort()); }) .collect(Collectors.toList()); }
Source:
protected final void check() { Preconditions.checkArgument(!keyStorePath().isPresent() || keyStorePassword().isPresent(), "keyStorePassword cannot be absent if keyStorePath is present"); }

Target:
protected final void check() { Preconditions.checkArgument( keyStorePath().isPresent() == keyStorePassword().isPresent(), "keyStorePath and keyStorePassword must both be present or both be absent"); Preconditions.checkArgument( !keyStoreKeyAlias().isPresent() || keyStorePath().isPresent(), "keyStorePath must be present if keyStoreKeyAlias is present"); }
Source:
private static <T> List<T> getReversed(Collection<T> collection) { ArrayList<T> result = new ArrayList<>(); result.addAll(collection); Collections.reverse(result); return result; }

Target:
private static <T> List<T> getReversed(Collection<T> collection) { ArrayList<T> result = new ArrayList<>(collection); Collections.reverse(result); return result; }
Source:
public void shouldGetBuiltInExtension() throws OperationException { ContextService contextService = Framework.getService(ContextService.class); Map<String, ContextHelper> contextHelperList = contextService.getHelperFunctions(); assertTrue(contextHelperList.containsKey("Fn")); assertNotNull(contextHelperList.get("Fn")); assertTrue(contextHelperList.get("Fn") instanceof PlatformFunctions); }

Target:
public void shouldGetBuiltInExtension() { ContextService contextService = Framework.getService(ContextService.class); Map<String, ContextHelper> contextHelperList = contextService.getHelperFunctions(); assertTrue(contextHelperList.containsKey("Fn")); assertNotNull(contextHelperList.get("Fn")); assertTrue(contextHelperList.get("Fn") instanceof PlatformFunctions); }
Source:
public void deleteData(String feedName, String cluster) throws FalconException, ParseException, IOException { Entity existingEntity = configStore.get(EntityType.FEED, feedName); if (existingEntity == null) { throw new FalconException("Feed Not Found " + feedName); } Feed feed = (Feed) existingEntity; Storage rawStorage = FeedHelper.createStorage(cluster, feed); String feedPathTemplate = rawStorage.getUriTemplate(LocationType.DATA); Properties vars = new Properties(); vars.put(FeedDataPath.VARS.YEAR.name(), "*"); vars.put(FeedDataPath.VARS.MONTH.name(), "*"); vars.put(FeedDataPath.VARS.DAY.name(), "*"); vars.put(FeedDataPath.VARS.HOUR.name(), "*"); vars.put(FeedDataPath.VARS.MINUTE.name(), "*"); String feedPath = ExpressionHelper.substitute(feedPathTemplate, vars); FileStatus files = fs.globStatus(new Path(feedPath)); for (FileStatus file : files) { fs.delete(file.getPath(), true); } }

Target:
public void deleteData(String feedName, String cluster) throws FalconException, ParseException, IOException { Entity existingEntity = configStore.get(EntityType.FEED, feedName); if (existingEntity == null) { throw new FalconException("Feed Not Found " + feedName); } Feed feed = (Feed) existingEntity; Storage rawStorage = FeedHelper.createStorage(cluster, feed); String feedPathTemplate = rawStorage.getUriTemplate(LocationType.DATA); Path feedBasePath = FeedHelper.getFeedBasePath(feedPathTemplate); fs.delete(feedBasePath, true); }
Source:
public static FirewallType getDefaultFirewallType(Version clusterCompatibilityVersion) { return clusterCompatibilityVersion.less(Version.v4_2) ? FirewallType.IPTABLES : FirewallType.FIREWALLD; }

Target:
public static FirewallType getDefaultFirewallType(Version clusterCompatibilityVersion) { return clusterCompatibilityVersion.greater(Version.v3_6) ? FirewallType.FIREWALLD : FirewallType.IPTABLES; }
Source:
private void showOverlayTutorialOne() { new ShowcaseView.Builder(mActivity) .setContentTitle(R.string.tutorial_one_title) .setContentText(R.string.tutorial_one_summary) .singleShot(TUTORIAL_VERSION) .setShowcaseEventListener(new OnShowcaseEventListener() { @Override public void onShowcaseViewShow(final ShowcaseView scv) { } @Override public void onShowcaseViewHide(final ShowcaseView scv) { scv.setVisibility(View.GONE); showOverlayTutorialTwo(); } @Override public void onShowcaseViewDidHide(final ShowcaseView scv) { } }) .build(); }

Target:
private void showOverlayTutorialOne() { hideText(); new ShowcaseView.Builder(mActivity) .setContentTitle(R.string.tutorial_one_title) .setContentText(R.string.tutorial_one_summary) .singleShot(TUTORIAL_VERSION) .setShowcaseEventListener(new OnShowcaseEventListener() { @Override public void onShowcaseViewShow(final ShowcaseView scv) { scv.setButtonText(mActivity.getResources().getString(R.string.tutorial_next)); } @Override public void onShowcaseViewHide(final ShowcaseView scv) { scv.setVisibility(View.GONE); showOverlayTutorialTwo(); } @Override public void onShowcaseViewDidHide(final ShowcaseView scv) { } }) .build(); }
Source:
protected String elementLabel(GraphicalEditPart editPart) { if (editPart instanceof ActivityPartitionNameEditPart) { editPart = (GraphicalEditPart) editPart.getParent(); } Collection<String> displayValue = DEFAULT_LABEL_DISPLAY; IMaskManagedLabelEditPolicy policy = (IMaskManagedLabelEditPolicy) editPart.getEditPolicy(IMaskManagedLabelEditPolicy.MASK_MANAGED_LABEL_EDIT_POLICY); if (policy != null) { displayValue = policy.getCurrentDisplayValue(); } return getCustomLabel(getUMLElement(editPart), displayValue); }

Target:
protected String elementLabel(GraphicalEditPart editPart) { GraphicalEditPart graphicalEditPart = editPart; if (editPart instanceof ActivityPartitionNameEditPart) { graphicalEditPart = (GraphicalEditPart) editPart.getParent(); } Collection<String> displayValue = DEFAULT_LABEL_DISPLAY; IMaskManagedLabelEditPolicy policy = (IMaskManagedLabelEditPolicy) editPart.getEditPolicy(IMaskManagedLabelEditPolicy.MASK_MANAGED_LABEL_EDIT_POLICY); if (policy != null) { displayValue = policy.getCurrentDisplayValue(); } return getCustomLabel(getUMLElement(graphicalEditPart), displayValue); }
Source:
public void invalidCaCertificateWithKubernetesApiMode() { Map<String, Comparable> properties = new HashMap<String, Comparable>(); properties.put(SERVICE_DNS.key(), null); new KubernetesConfig(properties); }

Target:
public void invalidCaCertificateWithKubernetesApiMode() { Map<String, Comparable> properties = new HashMap<String, Comparable>(); new KubernetesConfig(properties); }
Source:
public String computeHmac256(final String stringToSign) { try { Mac hmacSha256 = Mac.getInstance("HmacSHA256"); hmacSha256.init(new SecretKeySpec(this.accountKey, "HmacSHA256")); byte[] utf8Bytes = stringToSign.getBytes(StandardCharsets.UTF_8); return Base64.getEncoder().encodeToString(hmacSha256.doFinal(utf8Bytes)); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeyException e) { throw new RuntimeException("Please double check the account key. Error details: " + e.getMessage()); } }

Target:
public String computeHmac256(final String stringToSign) { try { Mac hmacSha256 = Mac.getInstance("HmacSHA256"); hmacSha256.init(new SecretKeySpec(this.accountKey, "HmacSHA256")); byte[] utf8Bytes = stringToSign.getBytes(StandardCharsets.UTF_8); return Base64.getEncoder().encodeToString(hmacSha256.doFinal(utf8Bytes)); } catch (final NoSuchAlgorithmException e) { LOGGER.asError().log(e.getMessage()); throw new RuntimeException(e); } catch (InvalidKeyException e) { LOGGER.asError().log("Please double check the account key. Error details: " + e.getMessage()); throw new RuntimeException("Please double check the account key. Error details: " + e.getMessage()); } }
Source:
private void compileProlog(ObjectId prolog, File tempDir) throws IOException, CompileException { File tempRules = File.createTempFile("rules", ".pl", tempDir); Compiler comp = new Compiler(); OutputStream out = new FileOutputStream(tempRules); try { git.open(prolog).copyTo(out); comp.prologToJavaSource(tempRules.getPath(), tempDir.getPath()); } finally { out.close(); tempRules.delete(); } }

Target:
private void compileProlog(ObjectId prolog, File tempDir) throws IOException, CompileException { File tempRules = File.createTempFile("rules", ".pl", tempDir); Compiler comp = new Compiler(); OutputStream out = new FileOutputStream(tempRules); try { git.open(prolog).copyTo(out); } finally { out.flush(); out.close(); } try { comp.prologToJavaSource(tempRules.getPath(), tempDir.getPath()); } finally { tempRules.delete(); } }
Source:
public static void assertFilesEqual(final File f1, final File f2) { try { if (f1.length() != f2.length()) { throw new SAMException("Files " + f1 + " and " + f2 + " are different lengths."); } final FileInputStream s1 = new FileInputStream(f1); final FileInputStream s2 = new FileInputStream(f2); final byte[] buf1 = new byte[1024 * 1024]; final byte[] buf2 = new byte[1024 * 1024]; int len1; while ((len1 = s1.read(buf1)) != -1) { final int len2 = s2.read(buf2); if (len1 != len2) { s1.close(); s2.close(); throw new SAMException("Unexpected EOF comparing files that are supposed to be the same length."); } if (!Arrays.equals(buf1, buf2)) { s1.close(); s2.close(); throw new SAMException("Files " + f1 + " and " + f2 + " differ."); } } s1.close(); s2.close(); } catch (IOException e) { throw new SAMException("Exception comparing files " + f1 + " and " + f2, e); } }

Target:
public static void assertFilesEqual(final File f1, final File f2) { if (f1.length() != f2.length()) { throw new SAMException("File " + f1 + " is " + f1.length() + " bytes but file " + f2 + " is " + f2.length() + " bytes."); } try ( final FileInputStream s1 = new FileInputStream(f1); final FileInputStream s2 = new FileInputStream(f2); ) { final byte[] buf1 = new byte[1024 * 1024]; final byte[] buf2 = new byte[1024 * 1024]; int len1; while ((len1 = s1.read(buf1)) != -1) { final int len2 = s2.read(buf2); if (len1 != len2) { throw new SAMException("Unexpected EOF comparing files that are supposed to be the same length."); } if (!Arrays.equals(buf1, buf2)) { throw new SAMException("Files " + f1 + " and " + f2 + " differ."); } } } catch (final IOException e) { throw new SAMException("Exception comparing files " + f1 + " and " + f2, e); } }
Source:
protected void executeQueryCommand() { List<GlusterVolumeEntity> eligibleVolumeList = new ArrayList<GlusterVolumeEntity>(); Guid masterVolumeId = getParameters().getVolumeId(); GlusterVolumeEntity masterVolume = getGlusterVolumeDao().getById(masterVolumeId); List<VDSGroup> vdsGroups = getDbFacade().getVdsGroupDao().getAll(); for (VDSGroup vdsGroup : vdsGroups) { if (vdsGroup.getId() != masterVolume.getClusterId() && vdsGroup.getcompatibility_version().equals(getDbFacade().getVdsGroupDao().get(masterVolume.getClusterId()).getcompatibility_version()) && vdsGroup.supportsGlusterService()) { List<GlusterVolumeEntity> volumes = getGlusterVolumeDao().getByClusterId(vdsGroup.getId()); for (GlusterVolumeEntity volume : volumes) { if (volume.getStatus() == GlusterStatus.UP && volume.getAdvancedDetails().getCapacityInfo().getUsedSize().equals(0L) && volume.getAdvancedDetails().getCapacityInfo().getFreeSize() >= masterVolume.getAdvancedDetails().getCapacityInfo().getUsedSize()) { eligibleVolumeList.add(volume); } } } } getQueryReturnValue().setReturnValue(eligibleVolumeList); }

Target:
protected void executeQueryCommand() { Guid masterVolumeId = getParameters().getVolumeId(); GlusterVolumeEntity masterVolume = getGlusterVolumeDao().getById(masterVolumeId); getQueryReturnValue().setReturnValue(getEligibleVolumesList(getUpVolumesWithSuggestedCapacityAndNotInMasterCluster(masterVolume), getExistingSessionSlaveVolumes())); }
Source:
public QueueAsyncClient createQueue(String queueName, Map<String, String> metadata) { QueueAsyncClient queueAsyncClient = new QueueAsyncClient(client, queueName); try { queueAsyncClient.create(metadata).block(); } catch (StorageErrorException ex) { if (!StorageErrorCode.QUEUE_ALREADY_EXISTS.toString().equals(ex.value().message())) { throw ex; } } return queueAsyncClient; }

Target:
public Mono<Response<QueueAsyncClient>> createQueue(String queueName, Map<String, String> metadata) { QueueAsyncClient queueAsyncClient = new QueueAsyncClient(client, queueName); return queueAsyncClient.create(metadata) .map(response -> new SimpleResponse<>(response, queueAsyncClient)); }
Source:
public void render(BaseViewHolder tag, Caption model) { ViewHolder viewHolder = (ViewHolder) tag; String captionText = model.content; if (captionText.endsWith("<br />")) { captionText = captionText.substring(0, captionText.length() - 6); } viewHolder.transcriptTv.setText(captionText); final int position = getPosition(model); viewHolder.transcriptTv.setTextColor(isSelected(position) ? edx_brand_gray_base : edx_brand_primary_base); }

Target:
public void render(BaseViewHolder tag, Caption model) { final ViewHolder viewHolder = (ViewHolder) tag; String captionText = model.content; if (captionText.endsWith("<br />")) { captionText = captionText.substring(0, captionText.length() - 6); } viewHolder.transcriptTv.setText(captionText); final int position = getPosition(model); if (isSelected(position)) { viewHolder.transcriptTv.setTextColor(SELECTED_TRANSCRIPT_COLOR); viewHolder.transcriptTv.setTypeface(Typeface.DEFAULT_BOLD); } else { viewHolder.transcriptTv.setTextColor(UNSELECTED_TRANSCRIPT_COLOR); viewHolder.transcriptTv.setTypeface(Typeface.DEFAULT); } }
Source:
public void testWrite() throws Exception { OpenFalconWriter openFalconWriter = new OpenFalconWriter(new JsonFactory(), ImmutableList.<String>of(), "localhost", "project=falcon,module=judge"); StringWriter writer = new StringWriter(); openFalconWriter.write(writer, dummyServer(), dummyQuery(), dummyResults()); String json = writer.toString(); assertThatJson(json).isArray().ofLength(1); }

Target:
public void testWrite() throws Exception { OpenFalconWriter openFalconWriter = new OpenFalconWriter(new JsonFactory(), ImmutableList.<String>of(), "localhost", "project=falcon,module=judge"); StringWriter writer = new StringWriter(); openFalconWriter.write(writer, dummyServer(), dummyQuery(), dummyResults()); String json = writer.toString(); assertThatJson(json) .isArray().ofLength(1); assertThatJson(json) .node("[0].metric").isEqualTo("MemoryAlias.ObjectPendingFinalizationCount") .node("[0].endpoint").isEqualTo("localhost") .node("[0].counterType").isEqualTo("GAUGE") .node("[0].step").isEqualTo(60) .node("[0].value").isEqualTo(10); }
Source:
public String getSupportEndPoint() throws OpenStackException { String msnError = "It is not possible to obtain the Support endpoint"; List<String> regions = getRegionsForService("support") ; if (regions == null || regions.size() == 0) { String msn = msnError + " : " + "No support endpoits in any region"; log.error(msn); throw new OpenStackException(msn); } log.debug("Get url for Support server in region " + regions.get(0)); String url; try { url = getEndPointByNameAndRegionName("support", regions.get(0)); } catch (OpenStackException e) { String msn = msnError + " : " + e.getMessage(); log.error(msn); throw new OpenStackException(msn); } return url; }

Target:
public String getSupportEndPoint() throws OpenStackException { String msnError = "It is not possible to obtain the Security endpoint"; List<String> regions = getRegionsForService("security") ; if (regions == null || regions.size() == 0) { String msn = msnError + " : " + "No security endpoint in any region"; log.error(msn); throw new OpenStackException(msn); } log.debug("Get url for security server in region " + regions.get(0)); String url; try { url = getEndPointByNameAndRegionName("security", regions.get(0)); } catch (OpenStackException e) { String msn = msnError + " : " + e.getMessage(); log.error(msn); throw new OpenStackException(msn); } return url; }
Source:
public void concealsMembers() throws IOException { final MkContainer container = new MkGrizzlyContainer() .next(new MkAnswer.Simple(HttpURLConnection.HTTP_NO_CONTENT)) .next(new MkAnswer.Simple(HttpURLConnection.HTTP_INTERNAL_ERROR)) .start(); final RtPublicMembers members = new RtPublicMembers( new ApacheRequest(container.home()), organization() ); members.conceal(user()); final MkQuery req = container.take(); MatcherAssert.assertThat( req.method(), Matchers.equalTo(Request.DELETE) ); MatcherAssert.assertThat( req.body(), Matchers.isEmptyOrNullString() ); MatcherAssert.assertThat( req.uri().toString(), Matchers.endsWith(MEMBER_URL) ); this.thrown.expect(AssertionError.class); members.conceal(user()); container.stop(); }

Target:
public void concealsMembers() throws IOException { final MkContainer container = new MkGrizzlyContainer() .next(new MkAnswer.Simple(HttpURLConnection.HTTP_NO_CONTENT)) .next(new MkAnswer.Simple(HttpURLConnection.HTTP_INTERNAL_ERROR)) .start(); try { final RtPublicMembers members = new RtPublicMembers( new ApacheRequest(container.home()), organization() ); members.conceal(user()); final MkQuery req = container.take(); MatcherAssert.assertThat( req.method(), Matchers.equalTo(Request.DELETE) ); MatcherAssert.assertThat( req.body(), Matchers.isEmptyOrNullString() ); MatcherAssert.assertThat( req.uri().toString(), Matchers.endsWith(MEMBER_URL) ); this.thrown.expect(AssertionError.class); members.conceal(user()); } finally { container.stop(); } }
Source:
public static <T> int indexOf(T[] array, T o) { checkArgument(array != null, "Input array is null"); for (int index = 0; index < array.length; index++) { if (array[index] == o) { return index; } else if (o != null && o.equals(array[index])) { return index; } } return -1; }

Target:
public static <T> int indexOf(T[] array, T o) { checkArgument(array != null, "Input array is null"); for (int index = 0; index < array.length; index++) { if (Objects.equal(o, array[index])) { return index; } } return -1; }
Source:
public <T> T createInstance(StoreConfiguration cfg) { if (cfg instanceof DeployedStoreConfiguration) { DeployedStoreConfiguration deployedConfiguration = (DeployedStoreConfiguration) cfg; DeployedCacheStoreMetadata deployedCacheStoreMetadata = null; try { InfinispanLogger.ROOT_LOGGER.info(String.format("Waiting for deployment of Custom Cache Store (%s).", deployedConfiguration.getCustomStoreClassName())); deployedCacheStoreMetadata = getPromise(deployedConfiguration.getCustomStoreClassName()).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); return (T) deployedCacheStoreMetadata.getLoaderWriterRawInstance(); } catch (InterruptedException | ExecutionException e) { throw new IllegalStateException("An error occurred while processing the deployment", e); } catch (TimeoutException e) { InfinispanLogger.ROOT_LOGGER.error(String.format("Waiting for deployment of Custom Cache Store (%s) timed out. Please check if this cache store is really present.", deployedConfiguration.getCustomStoreClassName())); } } return null; }

Target:
public <T> T createInstance(StoreConfiguration cfg) { if (cfg instanceof DeployedStoreConfiguration) { DeployedStoreConfiguration deployedConfiguration = (DeployedStoreConfiguration) cfg; DeployedCacheStoreMetadata deployedCacheStoreMetadata = null; try { InfinispanLogger.ROOT_LOGGER.debug(String.format("Waiting for deployment of Custom Cache Store (%s).", deployedConfiguration.getCustomStoreClassName())); deployedCacheStoreMetadata = getPromise(deployedConfiguration.getCustomStoreClassName()).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); return (T) deployedCacheStoreMetadata.getLoaderWriterRawInstance(); } catch (InterruptedException | ExecutionException e) { throw new IllegalStateException("An error occurred while processing the deployment", e); } catch (TimeoutException e) { InfinispanLogger.ROOT_LOGGER.loadingCustomCacheStoreTimeout(deployedConfiguration.getCustomStoreClassName()); } } return null; }
Source:
public void start() { final int concurrencyLevel = configuration.locking().concurrencyLevel(); localTransactions = CollectionFactory.makeConcurrentMap(concurrencyLevel, 0.75f, concurrencyLevel); globalToLocalTransactions = CollectionFactory.makeConcurrentMap(concurrencyLevel, 0.75f, concurrencyLevel); if (configuration.clustering().cacheMode().isClustered()) { minTopologyRecalculationLock = new ReentrantLock(); remoteTransactions = CollectionFactory.makeConcurrentMap(concurrencyLevel, 0.75f, concurrencyLevel); notifier.addListener(this); clustered = true; } boolean totalOrder = configuration.transaction().transactionProtocol().isTotalOrder(); if (clustered && !totalOrder) { completedTransactionsInfo = new CompletedTransactionsInfo(); ThreadFactory tf = new ThreadFactory() { @Override public Thread newThread(Runnable r) { String address = rpcManager != null ? rpcManager.getTransport().getAddress().toString() : "local"; Thread th = new Thread(r, "TxCleanupService," + cacheName + "," + address); th.setDaemon(true); return th; } }; executorService = Executors.newScheduledThreadPool(2, tf); long interval = configuration.transaction().reaperWakeUpInterval(); executorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { completedTransactionsInfo.cleanupCompletedTransactions(); } }, interval, interval, TimeUnit.MILLISECONDS); executorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { cleanupOrphanedTransactions(); } }, interval, interval, TimeUnit.MILLISECONDS); } }

Target:
public void start() { final int concurrencyLevel = configuration.locking().concurrencyLevel(); localTransactions = CollectionFactory.makeConcurrentMap(concurrencyLevel, 0.75f, concurrencyLevel); globalToLocalTransactions = CollectionFactory.makeConcurrentMap(concurrencyLevel, 0.75f, concurrencyLevel); if (configuration.clustering().cacheMode().isClustered()) { minTopologyRecalculationLock = new ReentrantLock(); remoteTransactions = CollectionFactory.makeConcurrentMap(concurrencyLevel, 0.75f, concurrencyLevel); notifier.addListener(this); clustered = true; } boolean totalOrder = configuration.transaction().transactionProtocol().isTotalOrder(); if (clustered && !totalOrder) { completedTransactionsInfo = new CompletedTransactionsInfo(); ThreadFactory tf = new ThreadFactory() { @Override public Thread newThread(Runnable r) { String address = rpcManager != null ? rpcManager.getTransport().getAddress().toString() : "local"; Thread th = new Thread(r, "TxCleanupService," + cacheName + "," + address); th.setDaemon(true); return th; } }; executorService = Executors.newSingleThreadScheduledExecutor(tf); long interval = configuration.transaction().reaperWakeUpInterval(); executorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { completedTransactionsInfo.cleanupCompletedTransactions(); } }, interval, interval, TimeUnit.MILLISECONDS); executorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { cleanupOrphanedTransactions(); } }, interval, interval, TimeUnit.MILLISECONDS); } }
Source:
public ValidatingOutputFormat getValidatingOutputFormat(PipelineConfigurer pipelineConfigurer) { FileFormat format = config.getFormat(); return pipelineConfigurer.usePlugin(ValidatingOutputFormat.PLUGIN_TYPE, format.name().toLowerCase(), format.name().toLowerCase(), config.getRawProperties()); }

Target:
protected ValidatingOutputFormat getValidatingOutputFormat(PipelineConfigurer pipelineConfigurer) { FileFormat format = config.getFormat(); return pipelineConfigurer.usePlugin(ValidatingOutputFormat.PLUGIN_TYPE, format.name().toLowerCase(), format.name().toLowerCase(), config.getRawProperties()); }
Source:
public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) { if (!ctx.isOriginLocal()) { return invokeNext(ctx, command); } final Map<Object, Object> map = command.getMap(); FileDescriptorSource source = new FileDescriptorSource(); for (Object key : map.keySet()) { final Object value = map.get(key); if (!(key instanceof String)) { throw log.keyMustBeString(key.getClass()); } if (!(value instanceof String)) { throw log.valueMustBeString(value.getClass()); } if (shouldIntercept(key)) { if (!((String) key).endsWith(PROTO_KEY_SUFFIX)) { throw log.keyMustBeStringEndingWithProto(key); } source.addProtoFile((String) key, (String) value); } } VisitableCommand cmd = commandsFactory.buildLockControlCommand(ERRORS_KEY_SUFFIX, command.getFlagsBitSet(), null); invoker.running().invoke(ctx, cmd); return invokeNextThenAccept(ctx, command, (rCtx, rCommand, rv) -> { long flagsBitSet = copyFlags((rCommand)); ProgressCallback progressCallback = null; if (rCtx.isOriginLocal()) { progressCallback = new ProgressCallback(rCtx, flagsBitSet); source.withProgressCallback(progressCallback); } else { source.withProgressCallback(EMPTY_CALLBACK); } try { serializationContext.registerProtoFiles(source); } catch (DescriptorParserException e) { throw log.failedToParseProtoFile(e); } if (progressCallback != null) { updateGlobalErrors(rCtx, progressCallback.getErrorFiles(), flagsBitSet); } }); }

Target:
public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) { if (!ctx.isOriginLocal()) { return invokeNext(ctx, command); } final Map<Object, Object> map = command.getMap(); FileDescriptorSource source = new FileDescriptorSource(); for (Object key : map.keySet()) { final Object value = map.get(key); if (!(key instanceof String)) { throw log.keyMustBeString(key.getClass()); } if (!(value instanceof String)) { throw log.valueMustBeString(value.getClass()); } if (shouldIntercept(key)) { if (!((String) key).endsWith(PROTO_KEY_SUFFIX)) { throw log.keyMustBeStringEndingWithProto(key); } source.addProtoFile((String) key, (String) value); } } VisitableCommand cmd = commandsFactory.buildLockControlCommand(ERRORS_KEY_SUFFIX, command.getFlagsBitSet(), null); invoker.running().invoke(ctx, cmd); return invokeNextThenAccept(ctx, command, (rCtx, rCommand, rv) -> { long flagsBitSet = copyFlags(rCommand); ProgressCallback progressCallback = null; if (rCtx.isOriginLocal()) { progressCallback = new ProgressCallback(rCtx, flagsBitSet); source.withProgressCallback(progressCallback); } else { source.withProgressCallback(EMPTY_CALLBACK); } try { serializationContext.registerProtoFiles(source); } catch (DescriptorParserException e) { throw log.failedToParseProtoFile(e); } if (progressCallback != null) { updateGlobalErrors(rCtx, progressCallback.getErrorFiles(), flagsBitSet); } }); }
Source:
public LegalEntitySurvivalProbabilities survivalProbabilities(StandardId legalEntityId, Currency currency) { CreditDiscountFactors survivalProbabilities = creditCurves.get(Pair.of(legalEntityId, currency)); if (survivalProbabilities == null) { throw new IllegalArgumentException("Unable to find credit curve: " + legalEntityId + ", " + currency); } return LegalEntitySurvivalProbabilities.of(survivalProbabilities, legalEntityId); }

Target:
public LegalEntitySurvivalProbabilities survivalProbabilities(StandardId legalEntityId, Currency currency) { LegalEntitySurvivalProbabilities survivalProbabilities = creditCurves.get(Pair.of(legalEntityId, currency)); if (survivalProbabilities == null) { throw new IllegalArgumentException("Unable to find credit curve: " + legalEntityId + ", " + currency); } return survivalProbabilities; }
Source:
private void runOn(final String account, final String region) { try { log.info("Scanning EC2 instances to fetch AMIs {}/{}", account, region); final AmazonEC2Client ec2Client = clientProvider.getClient( AmazonEC2Client.class, account, getRegion(fromName(region))); Optional<String> nextToken = empty(); do { final DescribeInstancesRequest request = new DescribeInstancesRequest(); if (nextToken.isPresent()) { request.withNextToken(nextToken.get()); } else { request.withFilters(new Filter("instance-state-name").withValues("running")); } nextToken.ifPresent(request::setNextToken); final DescribeInstancesResult result = ec2Client.describeInstances(request); nextToken = Optional.ofNullable(result.getNextToken()); for (final Reservation reservation : result.getReservations()) { for (final Instance instance : reservation.getInstances()) { processInstance(ec2Client, account, region, instance); } } } while (nextToken.isPresent()); } catch (final AmazonServiceException a) { log.error(a.getMessage(), a); } }

Target:
private void runOn(final String account, final String region) { try { log.info("Scanning EC2 instances to fetch AMIs {}/{}", account, region); final AmazonEC2Client ec2Client = clientProvider.getClient( AmazonEC2Client.class, account, getRegion(fromName(region))); Optional<String> nextToken = empty(); do { final DescribeInstancesRequest request = new DescribeInstancesRequest(); if (nextToken.isPresent()) { request.withNextToken(nextToken.get()); } else { request.withFilters(new Filter("instance-state-name").withValues("running")); } final DescribeInstancesResult result = ec2Client.describeInstances(request); nextToken = Optional.ofNullable(trimToNull(result.getNextToken())); for (final Reservation reservation : result.getReservations()) { for (final Instance instance : reservation.getInstances()) { processInstance(ec2Client, account, region, instance); } } } while (nextToken.isPresent()); } catch (final AmazonServiceException a) { log.error(a.getMessage(), a); } }
Source:
public List<String> getUntrackedFolders() { LinkedList<String> untracked = new LinkedList<String>(untrackedFolders); if (!untrackedParentFolders.isEmpty()) { String toBeAdded = untrackedParentFolders.getLast(); while (!untracked.isEmpty() && untracked.getLast().startsWith(toBeAdded)) untracked.removeLast(); untracked.addLast(toBeAdded); } LinkedList<String> ret = new LinkedList<String>(); for (String p: untracked) { boolean ignored = false; for (String i: ignoredPaths) { if (p.startsWith(i)) { ignored = true; break; } } if (!ignored) ret.add(p); } return ret; }

Target:
public List<String> getUntrackedFolders() { LinkedList<String> ret = new LinkedList<String>(untrackedFolders); if (!untrackedParentFolders.isEmpty()) { String toBeAdded = untrackedParentFolders.getLast(); while (!ret.isEmpty() && ret.getLast().startsWith(toBeAdded)) ret.removeLast(); ret.addLast(toBeAdded); } return ret; }
Source:
public RepositoryObjectDataLoader loadModel(RepositoryObject obj) throws FedoraException { PID pid = obj.getPid(); try (FcrepoResponse response = getClient().get(pid.getRepositoryUri()) .accept("text/turtle") .perform()) { Model model = ModelFactory.createDefaultModel(); model.read(response.getBody(), null, Lang.TURTLE.getName()); obj.setModel(model); } catch (IOException e) { throw new FedoraException("Failed to read model for " + pid.getRepositoryUri(), e); } catch (FcrepoOperationFailedException e) { throw ClientFaultResolver.resolve(e); } return this; }

Target:
public RepositoryObjectDataLoader loadModel(RepositoryObject obj) throws FedoraException { URI metadataUri = obj.getMetadataUri(); try (FcrepoResponse response = getClient().get(metadataUri) .accept(TURTLE_MIMETYPE) .perform()) { Model model = ModelFactory.createDefaultModel(); model.read(response.getBody(), null, Lang.TURTLE.getName()); obj.setModel(model); } catch (IOException e) { throw new FedoraException("Failed to read model for " + metadataUri, e); } catch (FcrepoOperationFailedException e) { throw ClientFaultResolver.resolve(e); } return this; }
Source:
private List<SiriusServerPageDto> getPages(ModelingProject modelingProject, Session session) { return WorkflowHelper.on(session).getPageDescriptions().map(page -> { DAnalysis self = ((DAnalysisSessionImpl) session).getAnalyses().get(0); Map<String, Object> variables = new HashMap<>(); variables.put(SELF, self); IEvaluationResult result = new SiriusBackendInterpreter(session).evaluateExpression(variables, page.getTitleExpression()); String identifier = page.getName(); String name = result.asString(); return new SiriusServerPageDto(identifier, name); }).collect(Collectors.toList()); }

Target:
private List<SiriusServerPageDto> getPages(ModelingProject modelingProject, Session session) { return WorkflowHelper.on(session).getPageDescriptions().map(page -> { DAnalysis self = ((DAnalysisSessionImpl) session).allAnalyses().stream().findFirst().orElse(null); Map<String, Object> variables = new HashMap<>(); variables.put(SELF, self); IEvaluationResult result = new SiriusBackendInterpreter(session).evaluateExpression(variables, page.getTitleExpression()); String identifier = page.getName(); String name = result.asString(); return new SiriusServerPageDto(identifier, name); }).collect(Collectors.toList()); }
Source:
private String getThreadName(LogRecord record) { String cacheKey = "" + record.getThreadID(); if (threadNameCache.containsKey(cacheKey)) { return threadNameCache.get(cacheKey); } long threadId = record.getThreadID(); String threadName = "" + record.getThreadID(); Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); for (Thread thread : threadSet) { if (thread.getId() == threadId) { threadName = thread.getName(); break; } } threadNameCache.put(cacheKey, threadName); return threadName; }

Target:
private String getThreadName(LogRecord record) { if (record.getThreadID() == Thread.currentThread().getId()) { return Thread.currentThread().getName(); } String cacheKey = "" + record.getThreadID(); if (threadNameCache.containsKey(cacheKey)) { return threadNameCache.get(cacheKey); } long threadId = record.getThreadID(); String threadName = "" + record.getThreadID(); Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); for (Thread thread : threadSet) { if (thread.getId() == threadId) { threadName = thread.getName(); break; } } threadNameCache.put(cacheKey, threadName); return threadName; }
Source:
public byte[] call(final byte[] memento) throws Exception { LOG.log(Level.INFO, String.format("%s starting...", taskId)); final TraceInfo taskTraceInfo = memento == null ? null : HTraceUtils.fromAvro(hTraceInfoCodec.decode(memento)); userComputeTask.initialize(); final ExecutorService executor = Executors.newSingleThreadExecutor(); Future<?> result = executor.submit(new Runnable() { @Override public void run() { try (final MetricsCollector collector = metricsCollector) { collector.registerTrackers(metricTrackerSet); while (!isTerminated()) { try (final TraceScope traceScope = Trace.startSpan("iter-" + iteration, taskTraceInfo)) { userTaskTrace.setParentTraceInfo(TraceInfo.fromSpan(traceScope.getSpan())); collector.start(); receiveData(); runUserComputeTask(); sendData(); collector.stop(); sendMetrics(); } iteration++; } userComputeTask.cleanup(); } catch (final Exception e) { throw new RuntimeException(e); } finally { terminated.countDown(); } } }); terminated.await(); executor.shutdownNow(); try { result.get(); } catch (final ExecutionException e) { if (!isClosing.get()) { throw new Exception(e); } else { LOG.log(Level.INFO, "Task closed by EM."); } } return null; }

Target:
public byte[] call(final byte[] memento) throws Exception { LOG.log(Level.INFO, String.format("%s starting...", taskId)); final TraceInfo taskTraceInfo = memento == null ? null : HTraceUtils.fromAvro(hTraceInfoCodec.decode(memento)); userComputeTask.initialize(); final ExecutorService executor = Executors.newSingleThreadExecutor(); final Future<?> result = executor.submit(new Runnable() { @Override public void run() { try (final MetricsCollector collector = metricsCollector) { collector.registerTrackers(metricTrackerSet); while (!isTerminated()) { try (final TraceScope traceScope = Trace.startSpan("iter-" + iteration, taskTraceInfo)) { userTaskTrace.setParentTraceInfo(TraceInfo.fromSpan(traceScope.getSpan())); collector.start(); receiveData(); runUserComputeTask(); sendData(); collector.stop(); sendMetrics(); } iteration++; } userComputeTask.cleanup(); } catch (final Exception e) { throw new RuntimeException(e); } finally { terminated.countDown(); } } }); terminated.await(); executor.shutdownNow(); try { result.get(); } catch (final ExecutionException e) { if (isClosing.get()) { LOG.log(Level.INFO, "Task closed by TaskCloseHandler."); } else { throw new Exception(e); } } return null; }