auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static <O> KeyVaultLongRunningOperation transformToLongRunningOperation(O operation) { if (operation instanceof RestoreOperation) { RestoreOperation restoreOperation = (RestoreOperation) operation; return new KeyVaultRestoreOperation(restoreOperation.getStatus(), restoreOperation.getStatusDetails(), createKeyVaultErrorFromError(restoreOperation.getError()), restoreOperation.getJobId(), restoreOperation.getStartTime(), restoreOperation.getEndTime()); } else if (operation instanceof SelectiveKeyRestoreOperation) { SelectiveKeyRestoreOperation selectiveKeyRestoreOperation = (SelectiveKeyRestoreOperation) operation; return new KeyVaultRestoreOperation(selectiveKeyRestoreOperation.getStatus(), selectiveKeyRestoreOperation.getStatusDetails(), createKeyVaultErrorFromError(selectiveKeyRestoreOperation.getError()), selectiveKeyRestoreOperation.getJobId(), selectiveKeyRestoreOperation.getStartTime(), selectiveKeyRestoreOperation.getEndTime()); } else if (operation instanceof FullBackupOperation) { FullBackupOperation fullBackupOperation = (FullBackupOperation) operation; return new KeyVaultBackupOperation(fullBackupOperation.getStatus(), fullBackupOperation.getStatusDetails(), createKeyVaultErrorFromError(fullBackupOperation.getError()), fullBackupOperation.getJobId(), fullBackupOperation.getStartTime(), fullBackupOperation.getEndTime(), fullBackupOperation.getAzureStorageBlobContainerUri()); } else { throw new UnsupportedOperationException("Operation type not supported"); } }

Target:
private static <O> KeyVaultLongRunningOperation transformToLongRunningOperation(O operation) { if (operation instanceof RestoreOperation) { RestoreOperation restoreOperation = (RestoreOperation) operation; return new KeyVaultRestoreOperation(restoreOperation.getStatus(), restoreOperation.getStatusDetails(), createKeyVaultErrorFromError(restoreOperation.getError()), restoreOperation.getJobId(), restoreOperation.getStartTime(), restoreOperation.getEndTime()); } else if (operation instanceof SelectiveKeyRestoreOperation) { SelectiveKeyRestoreOperation selectiveKeyRestoreOperation = (SelectiveKeyRestoreOperation) operation; return new KeyVaultRestoreOperation(selectiveKeyRestoreOperation.getStatus(), selectiveKeyRestoreOperation.getStatusDetails(), createKeyVaultErrorFromError(selectiveKeyRestoreOperation.getError()), selectiveKeyRestoreOperation.getJobId(), selectiveKeyRestoreOperation.getStartTime(), selectiveKeyRestoreOperation.getEndTime()); } else if (operation instanceof FullBackupOperation) { FullBackupOperation fullBackupOperation = (FullBackupOperation) operation; return new KeyVaultBackupOperation(fullBackupOperation.getStatus(), fullBackupOperation.getStatusDetails(), createKeyVaultErrorFromError(fullBackupOperation.getError()), fullBackupOperation.getJobId(), fullBackupOperation.getStartTime(), fullBackupOperation.getEndTime(), fullBackupOperation.getAzureStorageBlobContainerUri()); } else { throw new UnsupportedOperationException(); } }
Source:
List<DirectoryCleaner.DeletionMeta> perWorkerDirCleanup(long size) { return workerLogs.getAllWorkerDirs().stream() .map(Unchecked.function(dir -> directoryCleaner.deleteOldestWhileTooLarge(Collections.singletonList(dir), size, true, null))) .collect(toList()); }

Target:
List<DeletionMeta> perWorkerDirCleanup(long size) { return workerLogs.getAllWorkerDirs().stream() .map(Unchecked.function(dir -> directoryCleaner.deleteOldestWhileTooLarge(Collections.singletonList(dir), size, true, null))) .collect(toList()); }
Source:
private static CompletableFuture<Exception> publishItem( final Producer<String, String> producer, final String topicId, final BatchItem item, final HystrixKafkaCircuitBreaker circuitBreaker) throws EventPublishingException { try { final CompletableFuture<Exception> result = new CompletableFuture<>(); final ProducerRecord<String, String> kafkaRecord = new ProducerRecord<>( topicId, toKafkaPartition(item.getPartition()), item.getPartition(), item.getEvent().toString()); circuitBreaker.markStart(); producer.send(kafkaRecord, ((metadata, exception) -> { if (null != exception) { LOG.warn("Failed to publish to kafka topic {}", topicId, exception); item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); if (hasKafkaConnectionException(exception)) { circuitBreaker.markFailure(); } else { circuitBreaker.markSuccessfully(); } result.complete(exception); } else { item.updateStatusAndDetail(EventPublishingStatus.SUBMITTED, ""); circuitBreaker.markSuccessfully(); result.complete(null); } })); return result; } catch (final RuntimeException e) { circuitBreaker.markSuccessfully(); item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); throw new EventPublishingException("Error publishing message to kafka", e); } }

Target:
private static CompletableFuture<Exception> publishItem( final Producer<String, String> producer, final String topicId, final BatchItem item, final HystrixKafkaCircuitBreaker circuitBreaker) throws EventPublishingException { try { final CompletableFuture<Exception> result = new CompletableFuture<>(); final ProducerRecord<String, String> kafkaRecord = new ProducerRecord<>( topicId, KafkaCursor.toKafkaPartition(item.getPartition()), item.getPartition(), item.getEvent().toString()); circuitBreaker.markStart(); producer.send(kafkaRecord, ((metadata, exception) -> { if (null != exception) { LOG.warn("Failed to publish to kafka topic {}", topicId, exception); item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); if (hasKafkaConnectionException(exception)) { circuitBreaker.markFailure(); } else { circuitBreaker.markSuccessfully(); } result.complete(exception); } else { item.updateStatusAndDetail(EventPublishingStatus.SUBMITTED, ""); circuitBreaker.markSuccessfully(); result.complete(null); } })); return result; } catch (final InterruptException e) { Thread.currentThread().interrupt(); circuitBreaker.markSuccessfully(); item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); throw new EventPublishingException("Error publishing message to kafka", e); } catch (final RuntimeException e) { circuitBreaker.markSuccessfully(); item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); throw new EventPublishingException("Error publishing message to kafka", e); } }
Source:
public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException { return null; }

Target:
public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException { throw new NotImplementedException(); }
Source:
private void initFragments() { if (null == contributionsListFragment) { contributionsListFragment = new ContributionsListFragment(); } contributionsListFragment.setCallback(new Callback() { @Override public void retryUpload(Contribution contribution) { ContributionsFragment.this.retryUpload(contribution); } @Override public void deleteUpload(Contribution contribution) { contributionsPresenter.deleteUpload(contribution); } @Override public void openMediaDetail(int position) { showDetail(position); } @Override public int getNumberOfContributions() { return numberOfContributions; } @Override public Contribution getContributionForPosition(int position) { Contribution contribution = (Contribution) contributionsPresenter.getItemAtPosition(position); return contribution; } @Override public int findItemPositionWithId(String id) { return contributionsPresenter.getChildPositionWithId(id); } }); if(null==mediaDetailPagerFragment){ mediaDetailPagerFragment=new MediaDetailPagerFragment(); } }

Target:
private void initFragments() { if (null == contributionsListFragment) { contributionsListFragment = new ContributionsListFragment(); } contributionsListFragment.setCallback(new Callback() { @Override public void retryUpload(Contribution contribution) { ContributionsFragment.this.retryUpload(contribution); } @Override public void deleteUpload(Contribution contribution) { contributionsPresenter.deleteUpload(contribution); } @Override public void openMediaDetail(int position) { showDetail(position); } @Override public int getNumberOfContributions() { return numberOfContributions; } @Override public Contribution getContributionForPosition(int position) { return (Contribution) contributionsPresenter.getItemAtPosition(position); } @Override public int findItemPositionWithId(String id) { return contributionsPresenter.getChildPositionWithId(id); } }); if(null==mediaDetailPagerFragment){ mediaDetailPagerFragment=new MediaDetailPagerFragment(); } }
Source:
void send(ControlMessage message, SystemStream systemStream, MessageCollector collector) { Integer partitionCount = partitions.get(systemStream); if (partitionCount == null) { SystemStreamMetadata metadata = metadataCache.getSystemStreamMetadata(systemStream, true); partitionCount = metadata.getSystemStreamPartitionMetadata().size(); partitions.put(systemStream, partitionCount); } LOG.debug(String.format("Broadcast %s message from task %s to %s with %s partition", MessageType.of(message).name(), message.getTaskName(), systemStream, partitionCount)); for (int i = 0; i < partitionCount; i++) { OutgoingMessageEnvelope envelopeOut = new OutgoingMessageEnvelope(systemStream, i, null, message); collector.send(envelopeOut); } }

Target:
void send(ControlMessage message, SystemStream systemStream, MessageCollector collector) { Integer partitionCount = PARTITION_COUNT_CACHE.computeIfAbsent(systemStream, ss -> { SystemStreamMetadata metadata = metadataCache.getSystemStreamMetadata(ss, true); if (metadata == null) { throw new SamzaException("Unable to find metadata for stream " + systemStream); } return metadata.getSystemStreamPartitionMetadata().size(); }); LOG.debug(String.format("Broadcast %s message from task %s to %s with %s partition", MessageType.of(message).name(), message.getTaskName(), systemStream, partitionCount)); for (int i = 0; i < partitionCount; i++) { OutgoingMessageEnvelope envelopeOut = new OutgoingMessageEnvelope(systemStream, i, null, message); collector.send(envelopeOut); } }
Source:
private boolean validateImagesAvailability() { for (DiskImage image : new ArrayList<>(getImages())) { Guid imageGroupId = image.getId() != null ? image.getId() : Guid.Empty; if (!validateImageAvailability(image, imageGroupId)) { if (getParameters().isAllowPartialImport()) { log.warn("Disk image '{}/{}' doesn't exist on any of its storage domains. " + "Ignoring since the force flag in on", imageGroupId, image.getImageId()); getImages().remove(image); failedDisksToImportForAuditLog.putIfAbsent(image.getId(), image.getDiskAlias()); } else { return failValidation(EngineMessage.TEMPLATE_IMAGE_NOT_EXIST); } } } return true; }

Target:
private boolean validateImagesAvailability() { for (DiskImage image : new ArrayList<>(getImages())) { Guid imageGroupId = image.getId() != null ? image.getId() : Guid.Empty; if (!validateImageAvailability(image, imageGroupId)) { if (!getParameters().isAllowPartialImport()) { return failValidation(EngineMessage.TEMPLATE_IMAGE_NOT_EXIST); } log.warn("Disk image '{}/{}' doesn't exist on any of its storage domains. " + "Ignoring since the 'Allow Partial' flag in on", imageGroupId, image.getImageId()); getImages().remove(image); failedDisksToImportForAuditLog.putIfAbsent(image.getId(), image.getDiskAlias()); } } return true; }
Source:
public Subscriber<? super T> call(final Subscriber<? super Boolean> child) { final SingleDelayedProducer<Boolean> producer = new SingleDelayedProducer<Boolean>(child); Subscriber<T> s = new Subscriber<T>() { boolean hasElements; boolean done; @Override public void onNext(T t) { hasElements = true; boolean result; try { result = predicate.call(t); } catch (Throwable e) { Exceptions.throwOrReport(e, this, t); return; } if (result && !done) { done = true; producer.setValue(!returnOnEmpty); unsubscribe(); } } @Override public void onError(Throwable e) { if (!done) { done = true; child.onError(e); } } @Override public void onCompleted() { if (!done) { done = true; if (hasElements) { producer.setValue(false); } else { producer.setValue(returnOnEmpty); } } } }; child.add(s); child.setProducer(producer); return s; }

Target:
public Subscriber<? super T> call(final Subscriber<? super Boolean> child) { final SingleDelayedProducer<Boolean> producer = new SingleDelayedProducer<Boolean>(child); Subscriber<T> s = new Subscriber<T>() { boolean hasElements; boolean done; @Override public void onNext(T t) { if (done) { return; } hasElements = true; boolean result; try { result = predicate.call(t); } catch (Throwable e) { Exceptions.throwOrReport(e, this, t); return; } if (result) { done = true; producer.setValue(!returnOnEmpty); unsubscribe(); } } @Override public void onError(Throwable e) { if (!done) { done = true; child.onError(e); } else { RxJavaHooks.onError(e); } } @Override public void onCompleted() { if (!done) { done = true; if (hasElements) { producer.setValue(false); } else { producer.setValue(returnOnEmpty); } } } }; child.add(s); child.setProducer(producer); return s; }
Source:
public void validate() { if (!containsMacro("port") && port < 0) { throw new IllegalArgumentException("Port cannot be negative"); } }

Target:
public void validate() { if (port < 0) { throw new IllegalArgumentException("Port cannot be negative"); } }
Source:
private <R> R getUpcallResultInner(long timestamp, Object[] conflictObject) { if (TransactionalContext.isInTransaction()) { try { return (R) TransactionalContext.getCurrentContext() .getUpcallResult(this, timestamp, conflictObject); } catch (Exception e) { log.warn("UpcallResult[{}] Exception: {}", this, e); this.abortTransaction(e); } } if (underlyingObject.getUpcallResults().containsKey(timestamp)) { log.trace("Upcall[{}] Direct", this, timestamp); R ret = (R) underlyingObject.getUpcallResults().get(timestamp); underlyingObject.getUpcallResults().remove(timestamp); return ret == VersionLockedObject.NullValue.NULL_VALUE ? null : ret; } for (int x = 0; x < rt.getParameters().getTrimRetry(); x++) { try { return underlyingObject.update(o -> { o.syncObjectUnsafe(timestamp); if (o.getUpcallResults().containsKey(timestamp)) { log.trace("Upcall[{}] Sync'd", this, timestamp); R ret = (R) o.getUpcallResults().get(timestamp); o.getUpcallResults().remove(timestamp); return ret == VersionLockedObject.NullValue.NULL_VALUE ? null : ret; } throw new RuntimeException("Attempted to get the result " + "of an upcall@" + timestamp + " but we are @" + underlyingObject.getVersionUnsafe() + " and we don't have a copy"); }); } catch (TrimmedException ex) { log.info("accessInner: Encountered trimmed address space " + "while accessing version on attempt {}", timestamp, x); underlyingObject.update(o -> { o.resetUnsafe(); return null; }); } } throw new TrimmedUpcallException(timestamp); }

Target:
private <R> R getUpcallResultInner(long timestamp, Object[] conflictObject) { if (TransactionalContext.isInTransaction()) { try { return (R) TransactionalContext.getCurrentContext() .getUpcallResult(this, timestamp, conflictObject); } catch (Exception e) { log.warn("UpcallResult[{}] Exception: {}", this, e); this.abortTransaction(e); } } if (underlyingObject.getUpcallResults().containsKey(timestamp)) { log.trace("Upcall[{}] Direct", this, timestamp); R ret = (R) underlyingObject.getUpcallResults().get(timestamp); underlyingObject.getUpcallResults().remove(timestamp); return ret == VersionLockedObject.NullValue.NULL_VALUE ? null : ret; } for (int x = 0; x < rt.getParameters().getTrimRetry(); x++) { try { return underlyingObject.update(o -> { o.syncObjectUnsafe(timestamp); if (o.getUpcallResults().containsKey(timestamp)) { log.trace("Upcall[{}] Sync'd", this, timestamp); R ret = (R) o.getUpcallResults().get(timestamp); o.getUpcallResults().remove(timestamp); return ret == VersionLockedObject.NullValue.NULL_VALUE ? null : ret; } throw new RuntimeException("Attempted to get the result " + "of an upcall@" + timestamp + " but we are @" + underlyingObject.getVersionUnsafe() + " and we don't have a copy"); }); } catch (TrimmedException ex) { log.info("getUpcallResultInner: Encountered trimmed address space " + "while accessing version on attempt {}", timestamp, x); underlyingObject.update(o -> { o.resetUnsafe(); return null; }); } } throw new TrimmedUpcallException(timestamp); }
Source:
public void onUnityAdsStart(String placementId) { if (mMediationRewardedAdCallback != null) { mMediationRewardedAdCallback.onVideoStart(); } }

Target:
public void onUnityAdsStart(String placementId) { if (mMediationRewardedAdCallback != null) { mMediationRewardedAdCallback.reportAdImpression(); mMediationRewardedAdCallback.onVideoStart(); } }
Source:
public static boolean isBranchNameValid(String name) { if (name.isEmpty()) { return false; } for (int i = 0; i < ILLEGAL_CHARS.length(); i++) { char illegalChar = ILLEGAL_CHARS.charAt(i); if (name.contains(String.valueOf(illegalChar))) { return false; } } return true; }

Target:
public static boolean isBranchNameValid(String name) { return Repository.isValidRefName(name); }
Source:
public void stop(long timeInNS, long inSize, long outSize, Exchange ex) { Message request = ex.getInMessage(); TimingContext timingContext = TimingContext.get(request); if (timingContext == null) { timingContext = startAndAttachTimingContext(request); } record(timingContext, ex); }

Target:
public void stop(long timeInNS, long inSize, long outSize, Exchange ex) { Message request = ex.getInMessage(); TimingContext timingContext = TimingContext.get(request); if (timingContext == null) { LOG.warning("Unable for record metric for exchange: " + ex); } else { record(timingContext, ex); } }
Source:
public void checkStateChanged(CheckStateChangedEvent event) { CounterChartViewer counterChartViewer = fCounterChartViewer; if (counterChartViewer == null) { return; } if (getTrace() == null) { return; } ICheckable checkboxTree = event.getCheckable(); if (checkboxTree instanceof CheckboxTreeViewer) { @NonNull Set<@NonNull Integer> quarks = new TreeSet<>(); CheckboxTreeViewer checkboxTreeViewer = (CheckboxTreeViewer) checkboxTree; setSubtreeChecked(event.getElement(), event.getChecked()); maintainCheckIntegrity(event.getElement()); for (Object checkedElement : checkboxTreeViewer.getCheckedElements()) { if (checkedElement instanceof CounterTreeViewerEntry) { quarks.add(((CounterTreeViewerEntry) checkedElement).getQuark()); } } counterChartViewer.updateChart(quarks); } }

Target:
public void checkStateChanged(CheckStateChangedEvent event) { CounterChartViewer counterChartViewer = fCounterChartViewer; if (counterChartViewer == null) { return; } if (getTrace() == null) { return; } ICheckable checkboxTree = event.getCheckable(); if (checkboxTree instanceof CheckboxTreeViewer) { @NonNull Set<@NonNull Integer> quarks = new TreeSet<>(); fFilteredCheckboxTree.setSubtreeChecked(event.getElement(), event.getChecked()); for (Object checkedElement : fFilteredCheckboxTree.getCheckedElements()) { fFilteredCheckboxTree.maintainCheckIntegrity(checkedElement); if (checkedElement instanceof CounterTreeViewerEntry) { quarks.add(((CounterTreeViewerEntry) checkedElement).getQuark()); } } counterChartViewer.updateChart(quarks); } }
Source:
public ConstructQueryMetadata readConstructQueryMetadata(SnapshotBase tx, String nodeId) { Optional<NodeType> type = NodeType.fromNodeId(nodeId); try { checkArgument(type.isPresent() && type.get() == NodeType.CONSTRUCT); LOG.debug("Retrieving Metadata from Cache: {}", nodeId); return (ConstructQueryMetadata) commonNodeMetadataCache.get(nodeId, new Callable<CommonNodeMetadata>() { @Override public CommonNodeMetadata call() throws Exception { LOG.debug("Seeking Metadata from Fluo Table: {}.", nodeId); return dao.readConstructQueryMetadata(tx, nodeId); } }); } catch (Exception e) { throw new RuntimeException("Unable to access ConstructQueryMetadata for nodeId: " + nodeId, e); } }

Target:
public ConstructQueryMetadata readConstructQueryMetadata(SnapshotBase tx, String nodeId) { checkNotNull(nodeId); checkNotNull(tx); Optional<NodeType> type = NodeType.fromNodeId(nodeId); checkArgument(type.isPresent() && type.get() == NodeType.CONSTRUCT); try { LOG.debug("Retrieving Metadata from Cache: {}", nodeId); return (ConstructQueryMetadata) commonNodeMetadataCache.get(nodeId, () -> { LOG.debug("Seeking Metadata from Fluo Table: {}.", nodeId); return dao.readConstructQueryMetadata(tx, nodeId); }); } catch (Exception e) { throw new RuntimeException("Unable to access ConstructQueryMetadata for nodeId: " + nodeId, e); } }
Source:
NaiEntity(String name, String encoding ,List<EapEntity> eaps) { this.name = name; this.encoding = encoding; this.eaps = eaps; }

Target:
NaiEntity(String name, String encoding, List<EapEntity> eaps) { this.name = name; this.encoding = encoding; this.eaps = ImmutableList.copyOf(eaps); }
Source:
static Immutable of(Iterable<? extends Value<?>> values) { return Sponge.getRegistry().requireFactory(Factory.class).of(values); }

Target:
static Mutable of(Iterable<? extends Value<?>> values) { return Sponge.getRegistry().requireFactory(Mutable.Factory.class).of(values); }
Source:
private void addNewTemplate(JSONObject model) { JSONObject newTemplate; int oldPosition = getArguments().getInt("position"); JSONArray templates = model.getJSONArray("tmpls"); JSONObject oldTemplate = templates.getJSONObject(oldPosition); newTemplate = Models.newTemplate(newCardName(templates)); newTemplate.put("qfmt", oldTemplate.get("qfmt")); newTemplate.put("afmt", oldTemplate.get("afmt")); if (templates.length() == 1) { flipQA(newTemplate); } int lastExistingOrd = templates.getJSONObject(templates.length() - 1).getInt("ord"); Timber.d("addNewTemplate() lastExistingOrd was %s", lastExistingOrd); newTemplate.put("ord", lastExistingOrd + 1); templates.put(newTemplate); mTemplateEditor.getTempModel().addNewTemplate(newTemplate); mTemplateEditor.selectTemplate(templates.length() - 1); }

Target:
private void addNewTemplate(JSONObject model) { JSONObject newTemplate; int oldPosition = getArguments().getInt("position"); JSONArray templates = model.getJSONArray("tmpls"); JSONObject oldTemplate = templates.getJSONObject(oldPosition); newTemplate = Models.newTemplate(newCardName(templates)); newTemplate.put("qfmt", oldTemplate.get("qfmt")); newTemplate.put("afmt", oldTemplate.get("afmt")); if (templates.length() == 1) { flipQA(newTemplate); } int lastExistingOrd = templates.getJSONObject(templates.length() - 1).getInt("ord"); Timber.d("addNewTemplate() lastExistingOrd was %s", lastExistingOrd); newTemplate.put("ord", lastExistingOrd + 1); templates.put(newTemplate); mTemplateEditor.getTempModel().addNewTemplate(newTemplate); mTemplateEditor.mViewPager.getAdapter().notifyDataSetChanged(); mTemplateEditor.mViewPager.setCurrentItem(templates.length() - 1, mTemplateEditor.animationDisabled()); }
Source:
public String validateFields() { if (Control.Mode.safe == Control.getSingleton().getMode()) { return Constant.messages.getString("ascan.custom.notSafe.error"); } if (this.filterPanel != null) { String fail = this.filterPanel.validateFields(); if (fail != null) { return fail; } } if (this.customPanels != null) { for (CustomScanPanel customPanel : this.customPanels) { String fail = customPanel.validateFields(); if (fail != null) { return fail; } } for (CustomScanPanel customPanel : this.customPanels) { Target target = customPanel.getTarget(); if (target != null && target.isValid()) { return null; } } } if (this.target == null || !this.target.isValid()) { return Constant.messages.getString("ascan.custom.nostart.error"); } switch (Control.getSingleton().getMode()) { case protect: List<StructuralNode> nodes = target.getStartNodes(); if (nodes != null) { for (StructuralNode node : nodes) { if (node instanceof StructuralSiteNode) { SiteNode siteNode = ((StructuralSiteNode) node).getSiteNode(); if (!siteNode.isIncludedInScope()) { return Constant.messages.getString( "ascan.custom.targetNotInScope.error", siteNode.getHierarchicNodeName()); } } } } break; default: } return null; }

Target:
public String validateFields() { if (Control.Mode.safe == Control.getSingleton().getMode()) { return Constant.messages.getString("ascan.custom.notSafe.error"); } String errorMessage = this.filterPanel.validateFields(); if (errorMessage != null) { return errorMessage; } if (this.customPanels != null) { for (CustomScanPanel customPanel : this.customPanels) { errorMessage = customPanel.validateFields(); if (errorMessage != null) { return errorMessage; } } for (CustomScanPanel customPanel : this.customPanels) { Target target = customPanel.getTarget(); if (target != null && target.isValid()) { return null; } } } if (this.target == null || !this.target.isValid()) { return Constant.messages.getString("ascan.custom.nostart.error"); } switch (Control.getSingleton().getMode()) { case protect: List<StructuralNode> nodes = target.getStartNodes(); if (nodes != null) { for (StructuralNode node : nodes) { if (node instanceof StructuralSiteNode) { SiteNode siteNode = ((StructuralSiteNode) node).getSiteNode(); if (!siteNode.isIncludedInScope()) { return Constant.messages.getString( "ascan.custom.targetNotInScope.error", siteNode.getHierarchicNodeName()); } } } } break; default: } return null; }
Source:
public OSFileStore[] getFileStores() { Map<String, String> fstype = new HashMap<>(); try { List<String> mounts = FileUtil.readFile("/proc/self/mounts"); for (String mount : mounts) { String[] split = mount.split(" "); if (split.length < 6) { continue; } fstype.put(split[1].replaceAll("\\\\040", " "), split[2]); } } catch (IOException e) { LOG.error("Error reading /proc/self/mounts. Can't detect filetypes."); } List<OSFileStore> fsList = new ArrayList<>(); for (FileStore store : FileSystems.getDefault().getFileStores()) { String path = store.toString().replace(" (" + store.name() + ")", ""); if (path.startsWith("/proc") || path.startsWith("/sys") || path.startsWith("/run") || path.startsWith("/dev")) continue; String name = store.name(); if (path.equals("/")) name = "/"; String description = "Mount Point"; if (store.name().startsWith("/dev")) description = "Local Disk"; String type = "unknown"; if (fstype.containsKey(path)) { type = fstype.get(path); } try { fsList.add(new OSFileStore(name, description, type, store.getUsableSpace(), store.getTotalSpace())); } catch (IOException e) { LOG.trace("", e); continue; } } return fsList.toArray(new OSFileStore[fsList.size()]); }

Target:
public OSFileStore[] getFileStores() { Map<String, String> fstype = new HashMap<>(); List<String> mounts = FileUtil.readFile("/proc/self/mounts"); for (String mount : mounts) { String[] split = mount.split(" "); if (split.length < 6) { continue; } fstype.put(split[1].replaceAll("\\\\040", " "), split[2]); } List<OSFileStore> fsList = new ArrayList<>(); for (FileStore store : FileSystems.getDefault().getFileStores()) { String path = store.toString().replace(" (" + store.name() + ")", ""); if (this.pseudofs.contains(store.name())) { if (store.name().equals("tmpfs")) { if (listElementStarts(this.tmpfsPaths, path)) { continue; } } else { continue; } } String name = store.name(); if (path.equals("/")) name = "/"; String description = "Mount Point"; if (store.name().startsWith("/dev")) description = "Local Disk"; String type = "unknown"; if (fstype.containsKey(path)) { type = fstype.get(path); } try { fsList.add(new OSFileStore(name, path, description, type, store.getUsableSpace(), store.getTotalSpace())); } catch (IOException e) { LOG.trace("", e); continue; } } return fsList.toArray(new OSFileStore[fsList.size()]); }
Source:
private void saveHeartBeat(final List<WriteRequest> lastSeenWriteRequests) { final BatchWriteItemRequest batchWriteItemRequest = new BatchWriteItemRequest(); int i = 0; for (final List<WriteRequest> partition : Lists.partition(lastSeenWriteRequests, 25)) { i++; final Map<String, List<WriteRequest>> map = Maps.newHashMap(); map.put(tableName, partition); batchWriteItemRequest.withRequestItems(map); try { final BatchWriteItemResult result = dynamoDBClient.batchWriteItem(batchWriteItemRequest); final Map<String, List<WriteRequest>> unprocessed = result.getUnprocessedItems(); if (unprocessed == null || unprocessed.isEmpty()) { continue; } final float ratio = unprocessed.size() / (float) partition.size() * 100.0f; LOGGER.info("Table : {}% ({} attempted, unprocessed)", tableName, Math.round(ratio), partition.size(), unprocessed.size()); }catch (AmazonClientException e) { LOGGER.error("Error persisting last seen device data: {}", e.getMessage()); } } LOGGER.error("Iterations: {}", i); }

Target:
private void saveHeartBeat(final List<WriteRequest> lastSeenWriteRequests) { final BatchWriteItemRequest batchWriteItemRequest = new BatchWriteItemRequest(); int i = 0; for (final List<WriteRequest> partition : Lists.partition(lastSeenWriteRequests, DYNAMO_BATCH_WRITE_LIMIT)) { i++; final Map<String, List<WriteRequest>> map = Maps.newHashMap(); map.put(tableName, partition); batchWriteItemRequest.withRequestItems(map); try { final BatchWriteItemResult result = dynamoDBClient.batchWriteItem(batchWriteItemRequest); final Map<String, List<WriteRequest>> unprocessed = result.getUnprocessedItems(); if (unprocessed == null || unprocessed.isEmpty()) { continue; } final float ratio = unprocessed.size() / (float) partition.size() * 100.0f; LOGGER.info("Table : {}% ({} attempted, unprocessed)", tableName, Math.round(ratio), partition.size(), unprocessed.size()); }catch (AmazonClientException e) { LOGGER.error("Error persisting last seen device data: {}", e.getMessage()); } } LOGGER.error("Iterations: {}", i); }
Source:
private BrokerResponse processLiteralOnlyBrokerRequest(BrokerRequest brokerRequest, long compilationStartTimeNs, RequestStatistics requestStatistics) throws IllegalStateException { System.out.println("brokerRequest = " + brokerRequest.toString()); BrokerResponseNative brokerResponse = new BrokerResponseNative(); List<String> columnNames = new ArrayList<>(); List<DataSchema.ColumnDataType> columnTypes = new ArrayList<>(); List<Object> row = new ArrayList<>(); for (Expression e : brokerRequest.getPinotQuery().getSelectList()) { computeResultsForExpression(e, columnNames, columnTypes, row); } DataSchema dataSchema = new DataSchema(columnNames.toArray(new String[0]), columnTypes.toArray(new DataSchema.ColumnDataType[0])); List<Object[]> rows = new ArrayList<>(); rows.add(row.toArray()); ResultTable resultTable = new ResultTable(dataSchema, rows); brokerResponse.setResultTable(resultTable); long totalTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - compilationStartTimeNs); brokerResponse.setTimeUsedMs(totalTimeMs); requestStatistics.setQueryProcessingTime(totalTimeMs); requestStatistics.setStatistics(brokerResponse); return brokerResponse; }

Target:
private BrokerResponse processLiteralOnlyBrokerRequest(BrokerRequest brokerRequest, long compilationStartTimeNs, RequestStatistics requestStatistics) throws IllegalStateException { BrokerResponseNative brokerResponse = new BrokerResponseNative(); List<String> columnNames = new ArrayList<>(); List<DataSchema.ColumnDataType> columnTypes = new ArrayList<>(); List<Object> row = new ArrayList<>(); for (Expression e : brokerRequest.getPinotQuery().getSelectList()) { computeResultsForExpression(e, columnNames, columnTypes, row); } DataSchema dataSchema = new DataSchema(columnNames.toArray(new String[0]), columnTypes.toArray(new DataSchema.ColumnDataType[0])); List<Object[]> rows = new ArrayList<>(); rows.add(row.toArray()); ResultTable resultTable = new ResultTable(dataSchema, rows); brokerResponse.setResultTable(resultTable); long totalTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - compilationStartTimeNs); brokerResponse.setTimeUsedMs(totalTimeMs); requestStatistics.setQueryProcessingTime(totalTimeMs); requestStatistics.setStatistics(brokerResponse); return brokerResponse; }
Source:
public LocationAware makeIndexableSourceFromStream(final InputStream inputStream) { if (inputStream instanceof BlockCompressedInputStream) { return new AsciiLineReaderIterator(new BlockCompressedAsciiLineReader((BlockCompressedInputStream) inputStream)); } else if (inputStream instanceof PositionalBufferedStream) { return new AsciiLineReaderIterator(new AsciiLineReader((PositionalBufferedStream)inputStream)); } else { return new AsciiLineReaderIterator(new AsciiLineReader(inputStream)); } }

Target:
public LocationAware makeIndexableSourceFromStream(final InputStream inputStream) { return new AsciiLineReaderIterator(AsciiLineReader.from(inputStream)); }
Source:
public boolean stop(Duration timeout) { log.debug("Stopping ..."); if (pools == null) { return true; } long failures = pools.parallelStream().filter(comp -> !comp.stop(timeout)).count(); log.debug(String.format("Stopped %d failure", failures)); return failures == 0L; }

Target:
public boolean stop(Duration timeout) { log.debug("Stopping ..."); if (pools == null) { return true; } long failures = pools.parallelStream().filter(comp -> !comp.stop(timeout)).count(); log.debug(String.format("Stopped %d failure", failures)); return failures == 0; }
Source:
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException { if (!args.hasNext()) { if (this.returnSource) { return tryReturnSource(source, args); } if (this.returnTarget) { return tryReturnTarget(source, args, this.type == null ? Entity.class : this.type); } } Object state = args.getState(); try { Entity entity = (Entity) super.parseValue(source, args); if (!type.isAssignableFrom(entity.getClass())) { Text name = Sponge.getRegistry().getAllOf(EntityType.class).stream() .filter(t -> t.getEntityClass().equals(this.type)).findFirst() .map(EntityType::getTranslation).<Text>map(Text::of) .orElse(Text.of(this.type.getSimpleName())); throw args.createError(Text.of("The entity is not of the required type! (", name, ")")); } return entity; } catch (ArgumentParseException ex) { if (this.returnSource) { args.setState(state); return tryReturnSource(source, args); } throw ex; } }

Target:
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException { if (!args.hasNext()) { if (this.returnSource) { return tryReturnSource(source, args, true); } if (this.returnTarget) { return tryReturnTarget(source, args); } } Object state = args.getState(); try { Iterable<Entity> entities = (Iterable<Entity>) super.parseValue(source, args); for (Entity entity : entities) { if (!this.checkEntity(entity)) { Text name; if (this.type == null) { name = Sponge.getRegistry().getAllOf(EntityType.class).stream() .filter(t -> t.getEntityClass().equals(this.clazz)).findFirst() .map(EntityType::getTranslation).<Text>map(Text::of) .orElse(Text.of(this.clazz.getSimpleName())); } else { name = Text.of(this.type); } throw args.createError(Text.of("The entity is not of the required type! (", name, ")")); } } return entities; } catch (ArgumentParseException ex) { if (this.returnSource) { args.setState(state); return tryReturnSource(source, args, true); } throw ex; } }
Source:
protected String toJSONPlan(String sql, PlannerType plannerType) { CompiledPlan compiledPlan = (plannerType == PlannerType.CALCITE) ? compileAdHocCalcitePlan(sql, true, true, DeterminismMode.SAFER) : compileAdHocPlan(sql, true, true); assert (compiledPlan.rootPlanGraph != null); PlanNodeTree planTree = new PlanNodeTree(compiledPlan.rootPlanGraph); String planTreeJSON = planTree.toJSONString(); if (compiledPlan.subPlanGraph != null) { PlanNodeTree subPlanTree = new PlanNodeTree(compiledPlan.subPlanGraph); String subPlanTreeJSON = subPlanTree.toJSONString(); planTreeJSON += subPlanTreeJSON; } return planTreeJSON; }

Target:
protected String toJSONPlan(String sql, PlannerType plannerType) { CompiledPlan compiledPlan = (plannerType == PlannerType.CALCITE) ? compileAdHocCalcitePlan(sql, true, true, DeterminismMode.SAFER) : compileAdHocPlan(sql, true, true); assertNotNull("Root plan graph is null", compiledPlan.rootPlanGraph); PlanNodeTree planTree = new PlanNodeTree(compiledPlan.rootPlanGraph); String planTreeJSON = planTree.toJSONString(); if (compiledPlan.subPlanGraph != null) { PlanNodeTree subPlanTree = new PlanNodeTree(compiledPlan.subPlanGraph); String subPlanTreeJSON = subPlanTree.toJSONString(); planTreeJSON += subPlanTreeJSON; } return planTreeJSON; }
Source:
private List<Permission> getPermission(final List<Integer> permissions) { final List<Permission> permissionList = new ArrayList<>(); for (final Integer permissionId : permissions) { final Permission permission = this.workbenchDataManager.getPermission(permissionId); permissionList.add(permission); } final Collection result = CollectionUtils.collect(permissionList, new Transformer() { @Override public Integer transform(final Object input) { final Permission permission = (Permission) input; return Integer.valueOf(permission.getPermissionId()); } }); for (final Iterator<Permission> it = permissionList.iterator(); it.hasNext();) { final Permission permission = it.next(); if (result.contains(permission.getParent().getPermissionId())) { it.remove(); } } return permissionList; }

Target:
private List<Permission> getPermission(final List<Integer> permissions) { final List<Permission> permissionList = this.permissionService.getPermissionsByIds(new HashSet<>(permissions)); for (final Iterator<Permission> it = permissionList.iterator(); it.hasNext(); ) { final Permission permission = it.next(); if (permission.getParent() != null && permissions.contains(permission.getParent().getPermissionId())) { it.remove(); } } return permissionList; }
Source:
public void disconnect(final BaseComponent... reason) { if ( thisState != State.STATUS && thisState != State.PING && thisState != State.HANDSHAKE ) { ch.getHandle().eventLoop().schedule( new Runnable() { @Override public void run() { ch.close( new Kick( ComponentSerializer.toString( reason ) ) ); } }, 250, TimeUnit.MILLISECONDS ); } else { ch.close(); } }

Target:
public void disconnect(final BaseComponent... reason) { if ( canSendKickMessage() ) { ch.delayedClose( new Kick( ComponentSerializer.toString( reason ) ) ); } else { ch.close(); } }
Source:
void deliver() { int frameSize = protonSession.session.getConnection().getTransport().getOutboundFrameSizeLimit() - 50 - (delivery.getTag() != null ? delivery.getTag().length : 0); DeliveryAnnotations deliveryAnnotationsToEncode; if (reference.getProtocolData() != null && reference.getProtocolData() instanceof DeliveryAnnotations) { deliveryAnnotationsToEncode = (DeliveryAnnotations)reference.getProtocolData(); } else { deliveryAnnotationsToEncode = null; } LargeBodyReader context = message.getLargeBodyReader(); try { context.open(); try { context.position(position); long bodySize = context.getSize(); ByteBuffer buf = ByteBuffer.allocate(frameSize); for (; position < bodySize; ) { if (!connection.flowControl(this::resume)) { context.close(); return; } buf.clear(); if (position == 0) { writeHeaderAndAnnotations(context, buf, deliveryAnnotationsToEncode); } int size = context.readInto(buf); sender.send(new ReadableBuffer.ByteBufferReader(buf)); position += size; if (position < bodySize) { connection.instantFlush(); } } } finally { context.close(); } if (preSettle) { try { sessionSPI.ack(null, brokerConsumer, reference.getMessage()); } catch (Exception e) { log.debug(e.getMessage(), e); } delivery.settle(); } else { sender.advance(); } connection.instantFlush(); synchronized (creditsLock) { pending.decrementAndGet(); } finishLargeMessage(); } catch (Exception e) { log.warn(e.getMessage(), e); brokerConsumer.errorProcessing(e, reference); } }

Target:
void deliver() { int frameSize = protonSession.session.getConnection().getTransport().getOutboundFrameSizeLimit() - 50 - (delivery.getTag() != null ? delivery.getTag().length : 0); DeliveryAnnotations deliveryAnnotationsToEncode; message.checkReference(reference); if (reference.getProtocolData() != null && reference.getProtocolData() instanceof DeliveryAnnotations) { deliveryAnnotationsToEncode = (DeliveryAnnotations)reference.getProtocolData(); } else { deliveryAnnotationsToEncode = null; } LargeBodyReader context = message.getLargeBodyReader(); try { context.open(); try { context.position(position); long bodySize = context.getSize(); ByteBuffer buf = ByteBuffer.allocate(frameSize); for (; position < bodySize; ) { if (!connection.flowControl(this::resume)) { context.close(); return; } buf.clear(); if (position == 0) { writeHeaderAndAnnotations(context, buf, deliveryAnnotationsToEncode); } int size = context.readInto(buf); sender.send(new ReadableBuffer.ByteBufferReader(buf)); position += size; if (position < bodySize) { connection.instantFlush(); } } } finally { context.close(); } if (preSettle) { try { sessionSPI.ack(null, brokerConsumer, reference.getMessage()); } catch (Exception e) { log.debug(e.getMessage(), e); } delivery.settle(); } else { sender.advance(); } connection.instantFlush(); synchronized (creditsLock) { pending.decrementAndGet(); } finishLargeMessage(); } catch (Exception e) { log.warn(e.getMessage(), e); brokerConsumer.errorProcessing(e, reference); } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_task_detail); if (getResources().getBoolean(R.bool.has_two_panes)) { Intent taskListIntent = new Intent(this, TaskListActivity.class); taskListIntent.putExtra(TaskListActivity.EXTRA_FORCE_LIST_SELECTION, getIntent().getBooleanExtra(TaskListActivity.EXTRA_FORCE_LIST_SELECTION, false)); taskListIntent.putExtra(TaskListActivity.EXTRA_DISPLAY_TASK, true); taskListIntent.setData(getIntent().getData()); startActivity(taskListIntent); finish(); return; } if (savedInstanceState == null) { ViewTaskFragment fragment = ViewTaskFragment.newInstance(getIntent().getData(), new PrimaryColor(this)); getSupportFragmentManager().beginTransaction().add(R.id.task_detail_container, fragment).commit(); } }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_task_detail); if (getResources().getBoolean(R.bool.has_two_panes)) { Intent taskListIntent = new Intent(this, TaskListActivity.class); taskListIntent.putExtra(TaskListActivity.EXTRA_FORCE_LIST_SELECTION, getIntent().getBooleanExtra(TaskListActivity.EXTRA_FORCE_LIST_SELECTION, false)); taskListIntent.putExtra(TaskListActivity.EXTRA_DISPLAY_TASK, true); taskListIntent.setData(getIntent().getData()); startActivity(taskListIntent); finish(); return; } if (savedInstanceState == null) { int color = getIntent().getIntExtra(EXTRA_COLOR, 0); ViewTaskFragment fragment = ViewTaskFragment.newInstance( getIntent().getData(), color != 0 ? new ValueColor(color) : new PrimaryColor(this)); getSupportFragmentManager().beginTransaction().add(R.id.task_detail_container, fragment).commit(); } }
Source:
public Image apply(final VMImage image) { FluentIterable.from(locations.get()).firstMatch(LocationPredicates.idEquals(image.location)).orNull(); final ImageBuilder builder = new ImageBuilder() .name(image.offer) .description(image.sku) .status(Image.Status.AVAILABLE) .version(image.sku) .id(encodeFieldsToUniqueId(image)) .providerId(image.publisher) .location(image.globallyAvailable ? null : FluentIterable.from(locations.get()) .firstMatch(LocationPredicates.idEquals(image.location)) .orNull()); final OperatingSystem.Builder osBuilder = osFamily().apply(image); return builder.operatingSystem(osBuilder.build()).build(); }

Target:
public Image apply(final VMImage image) { final ImageBuilder builder = new ImageBuilder() .name(image.offer) .description(image.sku) .status(Image.Status.AVAILABLE) .version(image.sku) .id(encodeFieldsToUniqueId(image)) .providerId(image.publisher) .location(image.globallyAvailable ? null : FluentIterable.from(locations.get()) .firstMatch(LocationPredicates.idEquals(image.location)) .get()); final OperatingSystem.Builder osBuilder = osFamily().apply(image); return builder.operatingSystem(osBuilder.build()).build(); }
Source:
public String toString() { return "DeviceMessageMetadata [deviceIdentification=" + this.deviceIdentification + ", organisationIdentification=" + this.organisationIdentification + ", correlationUid=" + this.correlationUid + ", messageType=" + this.messageType + ", messagePriority=" + this.messagePriority + ", scheduleTime=" + this.scheduleTime + "]"; }

Target:
public String toString() { return "DeviceMessageMetadata [deviceIdentification=" + this.deviceIdentification + ", organisationIdentification=" + this.organisationIdentification + ", correlationUid=" + this.correlationUid + ", messageType=" + this.messageType + ", messagePriority=" + this.messagePriority + ", scheduleTime=" + this.scheduleTime + ", bypassRetry=" + this.bypassRetry + "]"; }
Source:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.put(POLL_INITIAL_PERIOD, 5000); properties.put(POLL_MAX_PERIOD, 20000); properties.put(TIMEOUT_NODE_RUNNING, 300000); properties.put(TIMEOUT_NODE_SUSPENDED, 300000); properties.put(TIMEOUT_NODE_TERMINATED, 300000); return properties; }

Target:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); return properties; }
Source:
public void updateDebugConfig(IDeploymentConfig deploymentConfig, DebuggingContext debugContext, IProgressMonitor monitor) throws CoreException { monitor.subTask("Updating Deployment Configuration"); if (deploymentConfig == null || deploymentConfig.getEnvironmentVariables() == null) { return; } updateDeploymentConfigValues(deploymentConfig, debugContext); IClient client = getClient(deploymentConfig); DeploymentConfigListenerJob connectionListenerJob = new DeploymentConfigListenerJob(deploymentConfig); connectionListenerJob.addJobChangeListener(new JobChangeAdapter() { public void done(IJobChangeEvent event) { ConnectionsRegistrySingleton.getInstance().removeListener(connectionListenerJob); debugContext.setPod(connectionListenerJob.getPod()); if (event.getResult().isOK() && debugContext.getDebugListener() != null) { try { debugContext.getDebugListener().onPodRestart(debugContext, monitor); } catch (CoreException e) { throw new OpenShiftCoreException(e); } } }; }); ConnectionsRegistrySingleton.getInstance().addListener(connectionListenerJob); connectionListenerJob.schedule(); client.update(deploymentConfig); try { connectionListenerJob.join(DeploymentConfigListenerJob.TIMEOUT, monitor); } catch (OperationCanceledException | InterruptedException e) { e.printStackTrace(); } }

Target:
public void updateDebugConfig(IDeploymentConfig deploymentConfig, DebuggingContext debugContext, IProgressMonitor monitor) throws CoreException { monitor.subTask("Updating Deployment Configuration"); if (deploymentConfig == null || deploymentConfig.getEnvironmentVariables() == null) { return; } updateDeploymentConfigValues(deploymentConfig, debugContext); IClient client = getClient(deploymentConfig); DeploymentConfigListenerJob deploymentListenerJob = new DeploymentConfigListenerJob(deploymentConfig); deploymentListenerJob.addJobChangeListener(new JobChangeAdapter() { public void done(IJobChangeEvent event) { ConnectionsRegistrySingleton.getInstance().removeListener(deploymentListenerJob.getConnectionsRegistryListener()); debugContext.setPod(deploymentListenerJob.getPod()); if (event.getResult().isOK() && debugContext.getDebugListener() != null) { try { debugContext.getDebugListener().onPodRestart(debugContext, monitor); } catch (CoreException e) { throw new OpenShiftCoreException(e); } } }; }); ConnectionsRegistrySingleton.getInstance().addListener(deploymentListenerJob.getConnectionsRegistryListener()); deploymentListenerJob.schedule(); client.update(deploymentConfig); try { deploymentListenerJob.join(DeploymentConfigListenerJob.TIMEOUT, monitor); } catch (OperationCanceledException | InterruptedException e) { e.printStackTrace(); } IStatus result = deploymentListenerJob.getResult(); if (result == null) { throw new CoreException(deploymentListenerJob.getTimeOutStatus()); } else if (!result.isOK()) { throw new CoreException(result); } }
Source:
void sync(boolean force) throws IOException { if (force) { for (FileChannel ch : channelsToSync) { ch.force(true); channelsToSync.remove(ch); } } log.trace("Sync'd channels", channelsToSync.size()); }

Target:
void sync(boolean force) throws IOException { Optional<IOException> err = Optional.empty(); if (force) { for (FileChannel ch : channelsToSync) { try { ch.force(true); } catch (IOException ex) { log.warn("Error - can't sync a file channel"); err = Optional.of(ex); } finally { channelsToSync.remove(ch); } } } log.trace("Sync'd channels", channelsToSync.size()); if (err.isPresent()) { throw err.get(); } }