auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void performRename(String newName) { RenameSettings settings = dtoFactory.createDto(RenameSettings.class); RenameParams renameParams = dtoFactory.createDto(RenameParams.class); renameParams.setNewName(newName); VirtualFile file = textEditor.getEditorInput().getFile(); TextDocumentIdentifier textDocumentIdentifier = dtoBuildHelper.createTDI(file); renameParams.setTextDocument(textDocumentIdentifier); org.eclipse.lsp4j.Position position = dtoFactory.createDto(org.eclipse.lsp4j.Position.class); position.setCharacter(cursorPosition.getCharacter()); position.setLine(cursorPosition.getLine()); renameParams.setPosition(position); settings.setUpdateReferences(true); settings.setRenameParams(renameParams); settings.setRenameKind(RenameKind.JAVA_ELEMENT); extensionServiceClient .rename(settings) .then( result -> { enableAutoSave(); undoChanges(); RefactoringStatus refactoringStatus = result.getRefactoringStatus(); if (!FATAL.equals(refactoringStatus.getRefactoringSeverity())) { applyWorkspaceEditAction.applyWorkspaceEdit(result.getCheWorkspaceEdit()); } clientServerEventService.sendFileTrackingResumeEvent(); sendOpenEvent(); }) .catchError( error -> { undoChanges(); enableAutoSave(); clientServerEventService.sendFileTrackingResumeEvent(); notificationManager.notify( locale.failedToRename(), error.getMessage(), FAIL, FLOAT_MODE); }); }

Target:
private void performRename(String newName) { RenameSettings settings = dtoFactory.createDto(RenameSettings.class); RenameParams renameParams = dtoFactory.createDto(RenameParams.class); renameParams.setNewName(newName); VirtualFile file = textEditor.getEditorInput().getFile(); TextDocumentIdentifier textDocumentIdentifier = dtoBuildHelper.createTDI(file); renameParams.setTextDocument(textDocumentIdentifier); org.eclipse.lsp4j.Position position = dtoFactory.createDto(org.eclipse.lsp4j.Position.class); position.setCharacter(cursorPosition.getCharacter()); position.setLine(cursorPosition.getLine()); renameParams.setPosition(position); settings.setUpdateReferences(true); settings.setRenameParams(renameParams); settings.setRenameKind(RenameKind.JAVA_ELEMENT); extensionServiceClient .rename(settings) .then( result -> { enableAutoSave(); undoChanges(); RefactoringStatus refactoringStatus = result.getRefactoringStatus(); if (!FATAL.equals(refactoringStatus.getRefactoringSeverity())) { applyWorkspaceEditAction.applyWorkspaceEdit(result.getCheWorkspaceEdit()); clientServerEventService.sendFileTrackingResumeEvent(); sendOpenEvent(); } else { notificationManager.notify( locale.failedToRename(), getErrorMessage(refactoringStatus.getRefactoringStatusEntries()), FAIL, FLOAT_MODE); } }) .catchError( error -> { undoChanges(); enableAutoSave(); clientServerEventService.sendFileTrackingResumeEvent(); notificationManager.notify( locale.failedToRename(), error.getMessage(), FAIL, FLOAT_MODE); }); }
Source:
public Integer getNumChanges() { if (numChanges == null) { Integer numCount = null; for (final Leg leg : legs){ if (!(leg instanceof Individual)) { if (numCount == null) { numCount = 0; } else { numCount++; } } } return numCount; } else { return numChanges; } }

Target:
public Integer getNumChanges() { if (numChanges == null) { Integer numCount = null; for (final Leg leg : legs){ if (leg instanceof Public) { if (numCount == null) { numCount = 0; } else { numCount++; } } } return numCount; } else { return numChanges; } }
Source:
public static <T> T open(DBI dbi, Class<T> sqlObjectType) { try { check(OPEN); return (T) OPEN.invoke(dbi, sqlObjectType); } catch (Throwable t) { throw new RuntimeException("Error during `SqlObjectBuilder.open` invocation", t); } }

Target:
public static <T> T open(DBI dbi, Class<T> sqlObjectType) { try { check(OPEN); return (T) OPEN.invoke(dbi, sqlObjectType); } catch (RuntimeException e) { throw e; } catch (Throwable t) { throw new RuntimeException("Error during `SqlObjectBuilder.open` invocation", t); } }
Source:
public Optional<Timeline> getTimeline(final UUID id) { final List<Timeline> timelines = jdbcTemplate.query( BASE_TIMELINE_QUERY + " WHERE t.t_id=?", new Object[]{id}, timelineRowMapper); return Optional.ofNullable(timelines.isEmpty() ? null : timelines.get(0)); }

Target:
public Optional<Timeline> getTimeline(final UUID id) { final List<Timeline> timelines = jdbcTemplate.query( BASE_TIMELINE_QUERY + " WHERE t.tl_id=?", timelineRowMapper, id); return Optional.ofNullable(timelines.isEmpty() ? null : timelines.get(0)); }
Source:
void insert(GroupInfo info) { Comparator<GroupInfo> c = new Comparator<GroupInfo>() { @Override public int compare(GroupInfo a, GroupInfo b) { int cmp = Strings.nullToEmpty(a.name()).compareTo( Strings.nullToEmpty(b.name())); if (cmp != 0) { return cmp; } return a.getGroupUUID().compareTo(b.getGroupUUID()); } }; int insertPosition = table.getRowCount(); int left = 1; int right = table.getRowCount() - 1; while (left <= right) { int middle = (left + right) >>> 1; GroupInfo i = getRowItem(middle); int cmp = c.compare(i, info); if (cmp < 0) { left = middle + 1; } else if (cmp > 0) { right = middle - 1; } else { return; } } insertPosition = left; table.insertRow(insertPosition); applyDataRowStyle(insertPosition); populate(insertPosition, info); }

Target:
void insert(GroupInfo info) { Comparator<GroupInfo> c = new Comparator<GroupInfo>() { @Override public int compare(GroupInfo a, GroupInfo b) { int cmp = nullToEmpty(a.name()).compareTo(nullToEmpty(b.name())); if (cmp != 0) { return cmp; } return a.getGroupUUID().compareTo(b.getGroupUUID()); } private String nullToEmpty(@Nullable String str) { return (str == null) ? "" : str; } }; int insertPosition = table.getRowCount(); int left = 1; int right = table.getRowCount() - 1; while (left <= right) { int middle = (left + right) >>> 1; GroupInfo i = getRowItem(middle); int cmp = c.compare(i, info); if (cmp < 0) { left = middle + 1; } else if (cmp > 0) { right = middle - 1; } else { return; } } insertPosition = left; table.insertRow(insertPosition); applyDataRowStyle(insertPosition); populate(insertPosition, info); }
Source:
public void logRetry(Logger log, String message) { long now = System.currentTimeMillis(); if (lastRetryLog < 0) { log.debug(getMessage(message)); lastRetryLog = now; } else if ((now - lastRetryLog) > logInterval) { log.warn(getMessage(message)); lastRetryLog = now; } }

Target:
public void logRetry(Logger log, String message) { long now = System.nanoTime(); if (lastRetryLog < 0) { if (log.isDebugEnabled()) { log.debug(getMessage(message)); } lastRetryLog = now; } else if ((now - lastRetryLog) > logIntervalNanoSec) { log.warn(getMessage(message)); lastRetryLog = now; } else { if (log.isTraceEnabled()) { log.trace(getMessage(message)); } } }
Source:
public static void eToast(Context context, int resId) { Log.e(Thread.currentThread().getStackTrace()[methodDepth].toString(), context.getString(resId)); toastWorker(context, context.getString(resId)); }

Target:
public static void eToast(Context context, int resId) { eToast(context, context.getString(resId)); }
Source:
public void testEmptyFeatures() { Map<String, Map<String, Long>> emptyMap = new HashMap<>(); Features<VersionLevelRange> emptyFinalizedFeatures = Features.emptyFinalizedFeatures(); assertEquals(new HashMap<>(), emptyFinalizedFeatures.all()); assertEquals(emptyMap, emptyFinalizedFeatures.serialize()); assertEquals(emptyFinalizedFeatures, Features.deserializeFinalizedFeatures(emptyMap)); Features<VersionRange> emptySupportedFeatures = Features.emptySupportedFeatures(); assertEquals(new HashMap<>(), emptySupportedFeatures.all()); assertEquals( new HashMap<String, HashMap<String, Long>>(), emptySupportedFeatures.serialize()); assertEquals(emptySupportedFeatures, Features.deserializeSupportedFeatures(emptyMap)); }

Target:
public void testEmptyFeatures() { Map<String, Map<String, Short>> emptyMap = new HashMap<>(); Features<FinalizedVersionRange> emptyFinalizedFeatures = Features.emptyFinalizedFeatures(); assertTrue(emptyFinalizedFeatures.features().isEmpty()); assertTrue(emptyFinalizedFeatures.toMap().isEmpty()); assertEquals(emptyFinalizedFeatures, Features.fromFinalizedFeaturesMap(emptyMap)); Features<SupportedVersionRange> emptySupportedFeatures = Features.emptySupportedFeatures(); assertTrue(emptySupportedFeatures.features().isEmpty()); assertTrue(emptySupportedFeatures.toMap().isEmpty()); assertEquals(emptySupportedFeatures, Features.fromSupportedFeaturesMap(emptyMap)); }
Source:
private void setLabelScores(LabelType type, LabelInfo label, short score, Account.Id accountId) throws OrmException { if (label.approved != null || label.rejected != null) { return; } if (type.getMin() == null || type.getMax() == null) { return; } if (score != 0) { if (score == type.getMin().getValue() && type.isBlock()) { label.rejected = accountLoader.get(accountId); } else if (score == type.getMax().getValue()) { label.approved = accountLoader.get(accountId); } else if (score < 0) { label.disliked = accountLoader.get(accountId); label.value = score; } else if (score > 0 && label.disliked == null) { label.recommended = accountLoader.get(accountId); label.value = score; } } return; }

Target:
private void setLabelScores(LabelType type, LabelInfo label, short score, Account.Id accountId) throws OrmException { if (label.approved != null || label.rejected != null) { return; } if (type.getMin() == null || type.getMax() == null) { return; } if (score < 0) { label.disliked = accountLoader.get(accountId); label.value = score; } else if (score > 0 && label.disliked == null) { label.recommended = accountLoader.get(accountId); label.value = score; } }
Source:
private void initializeSnapshotsLeasesParams() { if (isRestoreLease()) { Guid activeSnapshotLeaseDomainId = getVm().getStaticData().getLeaseStorageDomainId(); Guid selectedLeaseDomainId = getParameters().getDstLeaseDomainId(); if (selectedLeaseDomainId == null && getDstSnapshot().getVmConfiguration() != null) { Guid dstLeaseDomainId = OvfUtils.fetchLeaseDomainId(getDstSnapshot().getVmConfiguration()); if (dstLeaseDomainId != null && activeSnapshotLeaseDomainId != null && !dstLeaseDomainId.equals( activeSnapshotLeaseDomainId)) { getParameters().setDstLeaseDomainId(activeSnapshotLeaseDomainId); getParameters().setLeaseAction(LeaseAction.UPDATE_LEASE_INFO_AND_LEASE_DOMAIN_ID); return; } else { getParameters().setDstLeaseDomainId(dstLeaseDomainId); } } getParameters().setLeaseAction(determineLeaseAction(activeSnapshotLeaseDomainId, getParameters().getDstLeaseDomainId())); } }

Target:
private void initializeSnapshotsLeasesParams() { if (isRestoreLease()) { Guid activeSnapshotLeaseDomainId = getVm().getStaticData().getLeaseStorageDomainId(); Guid selectedLeaseDomainId = getParameters().getDstLeaseDomainId(); LeaseAction leaseAction = null; if (selectedLeaseDomainId == null && getDstSnapshot().getVmConfiguration() != null) { Guid dstLeaseDomainId = OvfUtils.fetchLeaseDomainId(getDstSnapshot().getVmConfiguration()); if (dstLeaseDomainId != null && activeSnapshotLeaseDomainId != null && !dstLeaseDomainId.equals( activeSnapshotLeaseDomainId)) { getParameters().setDstLeaseDomainId(activeSnapshotLeaseDomainId); leaseAction = LeaseAction.UPDATE_LEASE_INFO_AND_LEASE_DOMAIN_ID; } else { getParameters().setDstLeaseDomainId(dstLeaseDomainId); } } if (leaseAction == null) { leaseAction = determineLeaseAction(activeSnapshotLeaseDomainId, getParameters().getDstLeaseDomainId()); } getParameters().setLeaseAction(leaseAction); } }
Source:
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; this.request.setLastRetryWithException(lastRetryWithException); long remainingMilliseconds = (this.waitTimeInSeconds * 1000) - this.durationTimer.getTime(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.debug("Received retrywith exception after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); }

Target:
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { Duration backoffTime; Duration timeout; if (!(exception instanceof RetryWithException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); return Mono.just(ShouldRetryResult.noRetry()); } RetryWithException lastRetryWithException = (RetryWithException)exception; GoneAndRetryWithRetryPolicy.this.lastRetryWithException = lastRetryWithException; long remainingMilliseconds = (this.waitTimeInSeconds * 1_000L) - GoneAndRetryWithRetryPolicy.this.getElapsedTime().toMillis(); int currentRetryAttemptCount = this.attemptCount++; if (remainingMilliseconds <= 0) { logger.warn("Received RetryWithException after backoff/retry. Will fail the request.", lastRetryWithException); return Mono.just(ShouldRetryResult.error(lastRetryWithException)); } backoffTime = Duration.ofMillis( Math.min( Math.min(this.currentBackoffMilliseconds, remainingMilliseconds), RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS)); this.currentBackoffMilliseconds *= RetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: ms.", backoffTime.toMillis()); long timeoutInMillSec = remainingMilliseconds - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofMillis(RetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_MS); logger.info("Received RetryWithException, will retry, ", exception); return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(false, true, timeout, currentRetryAttemptCount))); }
Source:
public void testDatasourceRemove() throws Exception { final RemoveDsBeanRemote bean = lookupEJB(MODULE_NAME, RemoveDsBean.class, RemoveDsBeanRemote.class); bean.testDatasource(); remove(datasourceAddress()); }

Target:
public void testDatasourceRemove() throws Exception { final RemoveDsBeanRemote bean = lookupEJB(MODULE_NAME, RemoveDsBean.class, RemoveDsBeanRemote.class); bean.testDatasource(); try { remove(datasourceAddress()); fail("Removal of the datasource should have failed."); } catch (MgmtOperationException expected) { } bean.testDatasource(); }
Source:
private void updateSslVerifyUser(boolean value) { StoredConfig userConfig = GlobalConfigCache.getInstance() .getUserConfig(); try { userConfig.load(); updateSslVerify(userConfig, value); } catch (IOException | ConfigInvalidException e) { LOG.error(MessageFormat.format(JGitText.get().userConfigFileInvalid, userConfig, e)); } }

Target:
private void updateSslVerifyUser(boolean value) { StoredConfig userConfig = null; try { userConfig = GlobalConfigCache.getInstance().getUserConfig(); updateSslVerify(userConfig, value); } catch (IOException | ConfigInvalidException e) { LOG.error(MessageFormat.format(JGitText.get().userConfigFileInvalid, userConfig, e)); } }
Source:
public InterpreterResult internalInterpret(String cmd, InterpreterContext context) { this.intpContext = context; TerminalManager.getInstance().setInterpreterContext(context); if (null == terminalThread) { try { terminalPort = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces(); terminalThread = new TerminalThread(terminalPort); terminalThread.start(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); return new InterpreterResult(Code.ERROR, e.getMessage()); } for (int i = 0; i < 5 && !terminalThread.isRunning(); i++) { try { LOGGER.info("loop = " + i); Thread.sleep(500); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } } } setParagraphConfig(); createTerminalDashboard(context.getNoteId(), context.getParagraphId(), terminalPort); return new InterpreterResult(Code.SUCCESS); }

Target:
public InterpreterResult internalInterpret(String cmd, InterpreterContext context) { this.intpContext = context; TerminalManager.getInstance().setInterpreterContext(context); if (null == terminalThread) { try { terminalPort = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces(); terminalThread = new TerminalThread(terminalPort); terminalThread.start(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); return new InterpreterResult(Code.ERROR, e.getMessage()); } for (int i = 0; i < 10 && !terminalThread.isRunning(); i++) { try { LOGGER.info("loop = " + i); Thread.sleep(500); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } } if (!terminalThread.isRunning()) { LOGGER.error("Terminal interpreter can not running!"); } } setParagraphConfig(); createTerminalDashboard(context.getNoteId(), context.getParagraphId(), terminalPort); return new InterpreterResult(Code.SUCCESS); }
Source:
private void initLayout() { setProgressBarVisible(false); pushToApplicationsManager = new PushToApplicationsManager(dialogService, stateManager); BorderPane head = new BorderPane(); head.setTop(createMenu()); head.setCenter(createToolbar()); setTop(head); SplitPane.setResizableWithParent(sidePane, Boolean.FALSE); splitPane.getItems().addAll(sidePane, tabbedPane); mainStage.showingProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean showing) { if (showing) { setDividerPosition(); EasyBind.subscribe(sidePane.visibleProperty(), visible -> { if (visible) { if (!splitPane.getItems().contains(sidePane)) { splitPane.getItems().add(0, sidePane); setDividerPosition(); } } else { splitPane.getItems().remove(sidePane); } }); mainStage.showingProperty().removeListener(this); observable.removeListener(this); } } }); setCenter(splitPane); }

Target:
private void initLayout() { setProgressBarVisible(false); BorderPane head = new BorderPane(); head.setTop(createMenu()); head.setCenter(createToolbar()); setTop(head); SplitPane.setResizableWithParent(sidePane, Boolean.FALSE); splitPane.getItems().addAll(sidePane, tabbedPane); mainStage.showingProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean showing) { if (showing) { setDividerPosition(); EasyBind.subscribe(sidePane.visibleProperty(), visible -> { if (visible) { if (!splitPane.getItems().contains(sidePane)) { splitPane.getItems().add(0, sidePane); setDividerPosition(); } } else { splitPane.getItems().remove(sidePane); } }); mainStage.showingProperty().removeListener(this); observable.removeListener(this); } } }); setCenter(splitPane); }
Source:
public AbstractBulkLightblueRequest() { this(Collections.<E> emptyList()); }

Target:
public AbstractBulkLightblueRequest() { this.requests = new ArrayList<E>(); }
Source:
private void assertSorted(int[] input) { if (input.length < 2) { return; } for (int i = 1; i < input.length; i++) { if (input[i-1] > input[i]) { throw new IllegalStateException("Input must be sorted"); } } }

Target:
private void assertSorted(int[] input) { if (input.length <= 1) { return; } for (int i = 1; i < input.length; i++) { if (input[i-1] > input[i]) { throw new IllegalStateException("Input must be sorted"); } } }
Source:
protected void showDialog(Bundle state) { Context context = getContext(); Resources res = context.getResources(); AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.Calypso_AlertDialog); View titleView = View.inflate(getContext(), R.layout.detail_list_preference_title, null); mWhichButtonClicked = DialogInterface.BUTTON_NEGATIVE; builder.setPositiveButton(android.R.string.ok, this); builder.setNegativeButton(res.getString(R.string.cancel).toUpperCase(Locale.getDefault()), this); if (titleView != null) { TextView titleText = (TextView) titleView.findViewById(R.id.title); if (titleText != null) { titleText.setText(getTitle()); } builder.setCustomTitle(titleView); } else { builder.setTitle(getTitle()); } if (mDialogMessage != null) { builder.setMessage(mDialogMessage); } View view = View.inflate(getContext(), getDialogLayoutResource(), null); if (view != null) { onBindDialogView(view); builder.setView(view); } if ((mDialog = builder.create()) == null) return; if (state != null) { mDialog.onRestoreInstanceState(state); } mDialog.setOnDismissListener(this); mDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); mDialog.show(); Button positive = mDialog.getButton(DialogInterface.BUTTON_POSITIVE); Button negative = mDialog.getButton(DialogInterface.BUTTON_NEGATIVE); if (positive != null) WPPrefUtils.layoutAsFlatButton(positive); if (negative != null) WPPrefUtils.layoutAsFlatButton(negative); }

Target:
protected void showDialog(Bundle state) { Context context = getContext(); Resources res = context.getResources(); AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.Calypso_AlertDialog); View titleView = View.inflate(getContext(), R.layout.detail_list_preference_title, null); mWhichButtonClicked = DialogInterface.BUTTON_NEGATIVE; builder.setPositiveButton(android.R.string.ok, this); builder.setNegativeButton(res.getString(android.R.string.cancel).toUpperCase(Locale.getDefault()), this); if (titleView != null) { TextView titleText = (TextView) titleView.findViewById(R.id.title); if (titleText != null) { titleText.setText(getTitle()); } builder.setCustomTitle(titleView); } else { builder.setTitle(getTitle()); } if (mDialogMessage != null) { builder.setMessage(mDialogMessage); } View view = View.inflate(getContext(), getDialogLayoutResource(), null); if (view != null) { onBindDialogView(view); builder.setView(view); } if ((mDialog = builder.create()) == null) return; if (state != null) { mDialog.onRestoreInstanceState(state); } mDialog.setOnDismissListener(this); mDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); mDialog.show(); Button positive = mDialog.getButton(DialogInterface.BUTTON_POSITIVE); Button negative = mDialog.getButton(DialogInterface.BUTTON_NEGATIVE); if (positive != null) WPPrefUtils.layoutAsFlatButton(positive); if (negative != null) WPPrefUtils.layoutAsFlatButton(negative); }
Source:
public void stop() throws Throwable { boltSchedulers.values().forEach( s -> s.stop() ); boltSchedulers.clear(); forkJoinThreadPool.shutdown(); forkJoinThreadPool = null; }

Target:
public void stop() { boltSchedulers.values().forEach( this::stopScheduler ); boltSchedulers.clear(); forkJoinThreadPool.shutdown(); forkJoinThreadPool = null; }
Source:
public DataSet<ExecRow> getDataSet(DataSetProcessor dsp) throws StandardException { if (!isOpen) throw new IllegalStateException("Operation is not open"); if (bypass) { return source.getDataSet(dsp); } final long fetchLimit = getFetchLimit(); long offset = getTotalOffset(); OperationContext operationContext = dsp.createOperationContext(this); dsp.incrementOpDepth(); DataSet<ExecRow> sourceDS = source.getDataSet(dsp); dsp.decrementOpDepth(); DataSet<ExecRow> sourceSet = sourceDS.map(new CloneFunction<>(operationContext)); if (dsp.isSparkExplain()) { DataSet<ExecRow> ds = dsp.createDataSet(Iterators.transform(Collections.emptyIterator(), new Function<String, ExecRow>() { @Nullable @Override public ExecRow apply(@Nullable String n) { try { return getExecRowDefinition().getClone(); } catch (Exception e) { throw new RuntimeException(e); } } } ), this.explainPlan ); handleSparkExplain(ds, sourceDS, dsp); return ds; } else return sourceSet.zipWithIndex(operationContext).mapPartitions(new OffsetFunction<SpliceOperation, ExecRow>(operationContext, offset, fetchLimit)); }

Target:
public DataSet<ExecRow> getDataSet(DataSetProcessor dsp) throws StandardException { if (!isOpen) throw new IllegalStateException("Operation is not open"); if (bypass) { return source.getDataSet(dsp); } final long fetchLimit = getFetchLimit(); long offset = getTotalOffset(); OperationContext operationContext = dsp.createOperationContext(this); dsp.incrementOpDepth(); DataSet<ExecRow> sourceDS = source.getDataSet(dsp); dsp.decrementOpDepth(); DataSet<ExecRow> sourceSet = sourceDS.map(new CloneFunction<>(operationContext)); if (dsp.isSparkExplain()) { DataSet<ExecRow> ds = dsp.getEmpty(); handleSparkExplain(ds, sourceDS, dsp); return ds; } else return sourceSet.zipWithIndex(operationContext).mapPartitions(new OffsetFunction<SpliceOperation, ExecRow>(operationContext, offset, fetchLimit)); }
Source:
public StatementExecution buildPreparedStatement( DbParameterAccessor[] accessors) throws SQLException { DbParameterAccessors paramAccessors = new DbParameterAccessors(accessors); PreparedStatement ps = environment.getConnection().prepareCall(toSqlString(paramAccessors)); StatementExecution cs; if (paramAccessors.containsReturnValue()) { cs = environment.createFunctionStatementExecution(ps); } else { cs = environment.createStatementExecution(ps); } bindParametersTo(paramAccessors, cs); return cs; }

Target:
public StatementExecution buildPreparedStatement( DbParameterAccessor[] accessors) throws SQLException { DbParameterAccessors paramAccessors = new DbParameterAccessors(accessors); PreparedStatement ps = environment.getConnection().prepareCall(toSqlString(paramAccessors)); StatementExecution cs; if (paramAccessors.containsReturnValue()) { cs = environment.createFunctionStatementExecution(ps); } else { cs = environment.createStatementExecution(ps); } paramAccessors.bindParameters(cs); return cs; }
Source:
public VaultContainer(String dockerImageName) { super(dockerImageName); setWaitStrategy(Wait.forHttp("/v1/secret/is_alive").forStatusCode(400)); }

Target:
public VaultContainer(String dockerImageName) { super(dockerImageName); setWaitStrategy(Wait.forHttp("/v1/sys/health").forStatusCode(200)); withCreateContainerCmdModifier(cmd -> cmd.withCapAdd(IPC_LOCK)); withEnv("VAULT_ADDR", "<LINK_1>" + port); withExposedPorts(port); }
Source:
public static String getRandomString(int length) { Random r = new Random(); StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { sb.append((char) r.nextInt(25) + 'A'); } return sb.toString(); }

Target:
public static String getRandomString(int length) { Random r = new Random(); StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { sb.append((char) r.nextInt(26) + 'A'); } return sb.toString(); }
Source:
public void testRemoveWithinBounds(){ ArrayListOfIntsWritable a = new ArrayListOfIntsWritable(); a.add(one).add(three).add(five).add(seven); assertTrue(one == a.remove(0)); assertTrue(three == a.get(0)); assertTrue(five == a.get(1)); assertTrue(five == a.remove(1)); assertTrue(seven == a.get(2)); }

Target:
public void testRemoveWithinBounds(){ ArrayListOfInts a = new ArrayListOfInts(); a.add(one).add(three).add(five).add(seven); assertTrue(one == a.remove(0)); assertTrue(three == a.get(0)); assertTrue(five == a.get(1)); assertTrue(five == a.remove(1)); assertTrue(seven == a.get(2)); }
Source:
public void testSimpleBehavior() { PolymerClassDefinition def = parseAndExtractClassDefFromCall( LINE_JOINER.join( " ", "var FunBehavior = {", " properties: {", " ", " isFun: {", " type: Boolean,", " value: true,", " }", " },", " listeners: {", " click: 'doSomethingFun',", " },", " ", " foo: 'hooray',", "", " ", " doSomethingFun: function(funAmount) { alert('Something ' + funAmount + ' fun!'); },", " ", " created: function() {}", "};", "var A = Polymer({", " is: 'x-element',", " properties: {", " pets: {", " type: Array,", " notify: true,", " },", " name: String,", " },", " behaviors: [ FunBehavior ],", "});")); assertNotNull(def); assertEquals(1, def.version); assertTrue(def.target.isName()); assertEquals("A", def.target.getString()); assertNull(def.nativeBaseElement); assertThat(def.behaviors).hasSize(1); assertThat(def.props).hasSize(3); }

Target:
public void testSimpleBehavior() { PolymerClassDefinition def = parseAndExtractClassDefFromCall( LINE_JOINER.join( " ", "var FunBehavior = {", " properties: {", " ", " isFun: {", " type: Boolean,", " value: true,", " }", " },", " listeners: {", " click: 'doSomethingFun',", " },", " ", " foo: 'hooray',", "", " ", " doSomethingFun: function(funAmount) { alert('Something ' + funAmount + ' fun!'); },", " ", " created: function() {}", "};", "var A = Polymer({", " is: 'x-element',", " properties: {", " pets: {", " type: Array,", " notify: true,", " },", " name: String,", " },", " behaviors: [ FunBehavior ],", "});")); assertNotNull(def); assertEquals(PolymerClassDefinition.DefinitionType.ObjectLiteral, def.defType); NodeSubject.assertNode(def.target).hasType(Token.NAME); assertEquals("A", def.target.getString()); assertNull(def.nativeBaseElement); assertThat(def.behaviors).hasSize(1); assertThat(def.props).hasSize(3); }
Source:
public void manageMods() { ModManagerController modManagerController = uiService.loadFxml("theme/mod_manager.fxml"); List<Action> actions = Arrays.asList(new Action(i18n.get("modVault.modManager.cancel"), Type.OK_DONE, Event::consume), new Action(i18n.get("modVault.modManager.save"), event -> modManagerController.apply())); notificationService.addNotification(new ImmediateNotification(i18n.get("modVault.modManager"), i18n.get("modVault.modManager.description"), Severity.INFO, actions, modManagerController.getRoot() )); }

Target:
public void manageMods() { ModManagerController modManagerController = uiService.loadFxml("theme/mod_manager.fxml"); JFXDialog jfxDialog = uiService.showInDialog(modVaultRoot, modManagerController.getRoot(), i18n.get("modVault.modManager")); jfxDialog.setOnDialogClosed(event -> modManagerController.apply()); }
Source:
public static void main(String[] args) { CliWrapper cliWrapper = new CliWrapper(); CommandLine commandLine = null; try { commandLine = cliWrapper.parse(args); } catch (ParseException e) { printUsage(cliWrapper); System.out.println(e.getMessage()); System.exit(1); } Configuration.instance().setConfigurationFilename(commandLine.getOptionValue(CliWrapper.CONF)); Configuration.instance().init(); Configuration.instance().updateWithCliOptions(commandLine); ConnectorFacade facade = ConnectorFacadeFactory.INSTANCE.build(Configuration.instance().getProperty("cli.connector")); new Engine(facade).run(); }

Target:
public static void main(String[] args) { CliWrapper cliWrapper = new CliWrapper(); CommandLine commandLine = null; try { commandLine = cliWrapper.parse(args); } catch (ParseException e) { printUsage(cliWrapper); System.out.println(e.getMessage()); System.exit(1); } ConfigurationHolder.initFromFile(commandLine.getOptionValue(CliWrapper.CONF)); ConfigurationHolder.instance().updateWithCliOptions(commandLine); ConnectorFacade facade = ConnectorFacadeFactory.INSTANCE.build(ConfigurationHolder.instance().getProperty("cli.connector")); new Engine(facade).run(); }
Source:
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (args.length == 1 && (args[0].equals("?") || args[0].equals("-h"))) { sender.sendMessage(new TextComponentString(getHelp())); return; } if (sender.getEntityWorld().isRemote) return; EntityPlayerMP player = args.length < 2 ? getCommandSenderAsPlayer(sender) : getPlayer(server, sender, args[0]); ItemStack held = player.getHeldItemMainhand(); boolean bind = true; if (held.getItem() instanceof IBindable) { Binding binding = ((IBindable) held.getItem()).getBinding(held); if (binding != null) bind = false; if (args.length < 2) if (args.length == 1) if (isBoolean(args[0])) bind = Boolean.parseBoolean(args[0]); else player = getPlayer(server, sender, args[0]); if (bind) { if (binding != null && binding.getOwnerName().equals(player.getName())) { sender.sendMessage(new TextComponentTranslation("commands.bloodmagic.bind.error.ownerEqualsTarget")); return; } binding = new Binding(player.getGameProfile().getId(), player.getGameProfile().getName()); BindableHelper.applyBinding(held, binding); this.player = player; sender.sendMessage(new TextComponentTranslation("commands.bloodmagic.bind.success", getInfo())); } else { if (binding == null) { sender.sendMessage(new TextComponentTranslation("commands.bloodmagic.bind.error.notBound")); } held.getTagCompound().removeTag("binding"); sender.sendMessage(new TextComponentTranslation("commands.bloodmagic.bind.remove.success")); } } else sender.sendMessage(new TextComponentTranslation("commands.bloodmagic.bind.error.notBindable")); }

Target:
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (args.length == 1 && (args[0].equals("?") || args[0].equals("help"))) { sender.sendMessage(new TextComponentTranslation(getHelp())); return; } if (sender.getEntityWorld().isRemote) return; EntityPlayerMP player = args.length < 2 ? getCommandSenderAsPlayer(sender) : getPlayer(server, sender, args[0]); ItemStack held = player.getHeldItemMainhand(); boolean bind = true; if (held.getItem() instanceof IBindable) { Binding binding = ((IBindable) held.getItem()).getBinding(held); if (binding != null) bind = false; if (args.length < 2) if (args.length == 1) if (isBoolean(args[0])) bind = Boolean.parseBoolean(args[0]); else player = getPlayer(server, sender, args[0]); if (bind) { if (binding.getOwnerName().equals(player.getName())) { sender.sendMessage(new TextComponentTranslation("commands.bloodmagic.bind.error.ownerEqualsTarget")); return; } binding = new Binding(player.getGameProfile().getId(), player.getGameProfile().getName()); BindableHelper.applyBinding(held, binding); this.player = player; sender.sendMessage(new TextComponentTranslation("commands.bloodmagic.bind.success", getInfo())); } else { if (binding == null) { sender.sendMessage(new TextComponentTranslation("commands.bloodmagic.bind.error.notBound")); } held.getTagCompound().removeTag("binding"); sender.sendMessage(new TextComponentTranslation("commands.bloodmagic.bind.remove.success")); } } else sender.sendMessage(new TextComponentTranslation("commands.bloodmagic.bind.error.notBindable")); }
Source:
public void configure(Binder binder) { if (binder != null) { SqlBindings.addOperatorConversion(binder, BloomFilterOperatorConversion.class); } }

Target:
public void configure(Binder binder) { SqlBindings.addOperatorConversion(binder, BloomFilterOperatorConversion.class); ExpressionModule.addExprMacro(binder, BloomFilterExprMacro.class); }
Source:
public void checkTime() throws Exception { m_out.print("- checking if time of database \"" + getDatabaseName() + "\" is matching system time... "); try (Statement st = getConnection().createStatement()) { try (ResultSet rs = st.executeQuery("SELECT NOW()")) { if (rs.next()) { final Timestamp currentDatabaseTime = rs.getTimestamp(1); final long currentSystemTime = System.currentTimeMillis(); final long diff = currentDatabaseTime.getTime() - currentSystemTime; if (Math.abs(diff) > 1000) { m_out.println("NOT OK"); throw new Exception("Database time and system time differ. Please update either the database time or the system time"); } m_out.println("OK"); } } } }

Target:
public void checkTime() throws Exception { m_out.print("- checking if time of database \"" + getDatabaseName() + "\" is matching system time... "); try (Statement st = getConnection().createStatement()) { final long beforeQueryTime = System.currentTimeMillis(); try (ResultSet rs = st.executeQuery("SELECT NOW()")) { if (rs.next()) { final Timestamp currentDatabaseTime = rs.getTimestamp(1); final long currentSystemTime = System.currentTimeMillis(); final long diff = currentDatabaseTime.getTime() - currentSystemTime; final long queryExecuteDelta = Math.abs(currentSystemTime - beforeQueryTime); if (Math.abs(diff) > 1000 + queryExecuteDelta) { m_out.println("NOT OK"); final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(); final String databaseDateString = simpleDateFormat.format(new Date(currentDatabaseTime.getTime())); final String systemTimeDateString = simpleDateFormat.format(new Date(currentSystemTime)); throw new Exception("Database time and system time differ." + "System time: " + systemTimeDateString + ", database time: " + databaseDateString + ", diff: " + Math.abs(diff) + "ms. The maximum allowed difference is 1000ms." + " Please update either the database time or system time"); } m_out.println("OK"); } } } }
Source:
public void OnPnoNetworkFound() { Log.d(TAG, "Pno scan result event"); mWifiMonitor.broadcastSchedScanResultEvent(mClientInterfaceName); }

Target:
public void OnPnoNetworkFound() { Log.d(TAG, "Pno scan result event"); mWifiMonitor.broadcastPnoScanResultEvent(mClientInterfaceName); }
Source:
int getSwapSegmentsInUse() throws StoreException { String[] tempSegments = dataDir.list(TEMP_LOG_SEGMENTS_FILTER); if (tempSegments == null) { throw new StoreException("Error occurred while listing files in data dir:" + dataDir.getAbsolutePath(), StoreErrorCodes.Unknown_Error); } return tempSegments.length; }

Target:
int getSwapSegmentsInUse() throws StoreException { String[] tempSegments = dataDir.list(TEMP_LOG_SEGMENTS_FILTER); if (tempSegments == null) { throw new StoreException("Error occurred while listing files in data dir:" + dataDir.getAbsolutePath(), StoreErrorCodes.IOError); } return tempSegments.length; }
Source:
private void lsRefsV2() throws IOException { PacketLineOutRefAdvertiser adv = new PacketLineOutRefAdvertiser(pckOut); Map<String, Ref> refs = getAdvertisedOrDefaultRefs(); String line; String refPrefix = null; adv.setUseProtocolV2(true); line = pckIn.readString(); END if not. if (line == PacketLineIn.DELIM) { while ((line = pckIn.readString()) != PacketLineIn.END) { if (line.equals("peel")) { adv.setDerefTags(true); } else if (line.equals("symrefs")) { findSymrefs(adv, refs); } else if (line.startsWith("ref-prefix ")) { refPrefix = line.substring("ref-prefix ".length()); } else { throw new PackProtocolException("unexpected " + line); } } } else if (line != PacketLineIn.END) { throw new PackProtocolException("unexpected " + line); } if (refPrefix != null) { HashMap<String, Ref> refsToSend = new HashMap<>(); for (Map.Entry<String, Ref> entry : refs.entrySet()) { if (!entry.getKey().startsWith(refPrefix)) { continue; } refsToSend.put(entry.getKey(), entry.getValue()); } refs = refsToSend; } adv.send(refs); adv.end(); }

Target:
private void lsRefsV2() throws IOException { PacketLineOutRefAdvertiser adv = new PacketLineOutRefAdvertiser(pckOut); Map<String, Ref> refs = getAdvertisedOrDefaultRefs(); String line; ArrayList<String> refPrefixes = new ArrayList<>(); adv.setUseProtocolV2(true); line = pckIn.readString(); END if not. if (line == PacketLineIn.DELIM) { while ((line = pckIn.readString()) != PacketLineIn.END) { if (line.equals("peel")) { adv.setDerefTags(true); } else if (line.equals("symrefs")) { findSymrefs(adv, refs); } else if (line.startsWith("ref-prefix ")) { refPrefixes.add(line.substring("ref-prefix ".length())); } else { throw new PackProtocolException("unexpected " + line); } } } else if (line != PacketLineIn.END) { throw new PackProtocolException("unexpected " + line); } if (!refPrefixes.isEmpty()) { HashMap<String, Ref> refsToSend = new HashMap<>(); for (Map.Entry<String, Ref> entry : refs.entrySet()) { for (String refPrefix : refPrefixes) { if (entry.getKey().startsWith(refPrefix)) { refsToSend.put(entry.getKey(), entry.getValue()); continue; } } } refs = refsToSend; } adv.send(refs); adv.end(); }
Source:
public void removeClientListener(byte[] listenerId) { EventDispatcher dispatcher = clientListeners.get(listenerId); dispatcher.transport.release(); clientListeners.remove(listenerId); if (log.isTraceEnabled()) log.tracef("Remove client listener with id %s", Util.printArray(listenerId)); }

Target:
public void removeClientListener(byte[] listenerId) { EventDispatcher dispatcher = clientListeners.remove(listenerId); dispatcher.transport.release(); if (log.isTraceEnabled()) log.tracef("Remove client listener with id %s", Util.printArray(listenerId)); }
Source:
public void testCast() throws Exception { final DefaultConfiguration configurationForTestCast = createCheckConfig(WhitespaceAfterCheck.class); configurationForTestCast.addAttribute("tokens", "TYPECAST"); final String[] expected = { "88:21: " + getCheckMessage(MSG_WS_TYPECAST), }; verify(configurationForTestCast, getPath("InputWhitespace.java"), expected); }

Target:
public void testCast() throws Exception { final DefaultConfiguration configurationTestCast = createCheckConfig(WhitespaceAfterCheck.class); configurationTestCast.addAttribute("tokens", "TYPECAST"); final String[] expected = { "88:21: " + getCheckMessage(MSG_WS_TYPECAST), }; verify(configurationTestCast, getPath("InputWhitespace.java"), expected); }
Source:
public void runForPPC64() { VmDevice dbSpaprVscsiController = devices.stream().filter(d -> d.getType().equals(VmDeviceGeneralType.CONTROLLER)) .filter(d -> d.getDevice().equals(VdsProperties.Scsi)) .filter(d -> { Map<String, String> addressMap = StringMapUtils.string2Map(d.getAddress()); if (!addressMap.isEmpty() && addressMap.get("type").equals(VdsProperties.spapr_vio)) { return true; } return false; }).findFirst() .orElse(null); if (dbSpaprVscsiController != null) { return; } Map<String, Object> specParams = new HashMap<>(); Map<String, String> spaprAddress = new HashMap<>(); specParams.put(VdsProperties.Index, "0"); spaprAddress.put(VdsProperties.Type, VdsProperties.spapr_vio); dbSpaprVscsiController = new VmDevice( null, VmDeviceGeneralType.CONTROLLER, VdsProperties.Scsi, spaprAddress.toString(), specParams, false, true, false, "", null, null, null); devices.add(dbSpaprVscsiController); }

Target:
public void runForPPC64() { boolean dbSpaprVscsiControllerExist = devices.stream().filter(d -> d.getType().equals(VmDeviceGeneralType.CONTROLLER)) .filter(d -> d.getDevice().equals(VdsProperties.Scsi)) .anyMatch(d -> { Map<String, String> addressMap = StringMapUtils.string2Map(d.getAddress()); return VdsProperties.spapr_vio.equals(addressMap.get("type")); }); if (dbSpaprVscsiControllerExist) { return; } Map<String, Object> specParams = new HashMap<>(); Map<String, String> spaprAddress = new HashMap<>(); specParams.put(VdsProperties.Index, "0"); spaprAddress.put(VdsProperties.Type, VdsProperties.spapr_vio); VmDevice dbSpaprVscsiController = new VmDevice( null, VmDeviceGeneralType.CONTROLLER, VdsProperties.Scsi, spaprAddress.toString(), specParams, false, true, false, "", null, null, null); devices.add(dbSpaprVscsiController); }
Source:
private synchronized void display() { try { token.acquire(); if ((searchFilteredList.size() > 0) && (pageIndex <= searchFilteredList.size())) { builder.append(org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4( buildString(searchFilteredList.get(pageIndex-1).getMessages()))); }else{ builder.replace(0, builder.length(), ""); builder.append("<b>") .append(Res.getString("message.no.history.found")) .append("</b>"); } window.setText(builder.toString()); builder.replace(0, builder.length(), ""); if (window.getText().length() > 0) window.setCaretPosition(0); pageCounter.setText(pageIndex + " / " + maxPages); token.release(); } catch (InterruptedException e) { Log.error(e); e.printStackTrace(); } }

Target:
private synchronized void display() { try { token.acquire(); if ((searchFilteredList.size() > 0) && (pageIndex <= searchFilteredList.size())) { builder.append(unescapeHtml4(buildString(searchFilteredList.get(pageIndex-1).getMessages()))); }else{ builder.replace(0, builder.length(), ""); builder.append("<b>") .append(Res.getString("message.no.history.found")) .append("</b>"); } window.setText(builder.toString()); builder.replace(0, builder.length(), ""); if (window.getText().length() > 0) window.setCaretPosition(0); pageCounter.setText(pageIndex + " / " + maxPages); token.release(); } catch (InterruptedException e) { Log.error(e); e.printStackTrace(); } }
Source:
private UUID mapId(FIELD col, int val) throws SQLException { if (col == FIELD.owningComm) { Community comm = communityService.findByLegacyId(context, val); return comm == null ? null : comm.getID(); } if (col == FIELD.owningColl) { org.dspace.content.Collection coll = collectionService.findByLegacyId(context, val); return coll == null ? null : coll.getID(); } if (col == FIELD.owningItem) { Item item = itemService.findByLegacyId(context, val); return item == null ? null : item.getID(); } return null; }

Target:
private UUID mapId(FIELD col, int val) throws SQLException { if (col == FIELD.owningComm) { Community comm = communityService.findByLegacyId(context, val); return comm == null ? null : comm.getID(); } if (col == FIELD.owningColl) { org.dspace.content.Collection coll = collectionService.findByLegacyId(context, val); return coll == null ? null : coll.getID(); } if (col == FIELD.owningItem) { Item item = itemService.findByLegacyId(context, val); checkLastItem(item); return item == null ? null : item.getID(); } if (col == FIELD.epersonid) { EPerson per = epersonService.findByLegacyId(context, val); return per == null ? null : per.getID(); } return null; }
Source:
private void addCategories(final Contentlet contentlet, final Map<String, Object> map, final Set<TransformOptions> options, final User user) { final boolean allCategoriesInfo = options.contains(CATEGORIES_INFO); final boolean includeCategoryName = options.contains(CATEGORIES_NAME); if (includeCategoryName || allCategoriesInfo) { try { final List<Category> cats = toolBox.categoryAPI.getParents(contentlet, user, true); final List<CategoryField> categoryFields = contentlet.getContentType() .fields(CategoryField.class).stream().filter(Objects::nonNull) .map(CategoryField.class::cast).collect(Collectors.toList()); for (final CategoryField categoryField : categoryFields) { final Category parentCategory = toolBox.categoryAPI .find(categoryField.values(), user, true); final List<Category> childCategories = new ArrayList<>(); if (parentCategory != null) { for (final Category category : cats) { if (toolBox.categoryAPI .isParent(category, parentCategory, user, true)) { childCategories.add(category); } } } if (!childCategories.isEmpty()) { final List categoriesValue; if (allCategoriesInfo) { categoriesValue = childCategories.stream() .map(Category::getMap) .collect(Collectors.toList()); } else { categoriesValue = childCategories.stream().map(category -> ImmutableMap .of(category.getKey(), category.getCategoryName())) .collect(Collectors.toList()); } map.put(categoryField.variable(), categoriesValue); } } } catch (DotDataException | DotSecurityException e) { Logger.warn(DefaultTransformStrategy.class, "Unable to get categories from content with id "); } } }

Target:
private void addCategories(final Contentlet contentlet, final Map<String, Object> map, final Set<TransformOptions> options, final User user) { final boolean allCategoriesInfo = options.contains(CATEGORIES_INFO); final boolean includeCategoryName = options.contains(CATEGORIES_NAME); if (includeCategoryName || allCategoriesInfo) { try { final List<Category> categories = toolBox.categoryAPI.getParents(contentlet, user, true); final List<CategoryField> categoryFields = contentlet.getContentType() .fields(CategoryField.class).stream().filter(Objects::nonNull) .map(CategoryField.class::cast).collect(Collectors.toList()); for (final CategoryField categoryField : categoryFields) { final Category parentCategory = toolBox.categoryAPI .find(categoryField.values(), user, true); final List<Category> childCategories = new ArrayList<>(); if (parentCategory != null) { for (final Category category : categories) { if (toolBox.categoryAPI .isParent(category, parentCategory, user, true)) { childCategories.add(category); } } } if (!childCategories.isEmpty()) { final List categoriesValue; if (allCategoriesInfo) { categoriesValue = childCategories.stream() .map(Category::getMap) .collect(Collectors.toList()); } else { categoriesValue = childCategories.stream().map(category -> ImmutableMap .of(category.getKey(), category.getCategoryName())) .collect(Collectors.toList()); } map.put(categoryField.variable(), categoriesValue); } } } catch (DotDataException | DotSecurityException e) { Logger.warn(DefaultTransformStrategy.class, "Unable to get categories from content with id "); } } }