auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public RequestItemRest fromModel(RequestItem requestItem) { RequestItemRest requestItemRest = new RequestItemRest(); requestItemRest.setAccept_request(requestItem.isAccept_request()); requestItemRest.setAllfiles(requestItem.isAllfiles()); requestItemRest.setBitstream(bitstreamConverter.fromModel(requestItem.getBitstream())); requestItemRest.setDecision_date(requestItem.getDecision_date()); requestItemRest.setExpires(requestItem.getExpires()); requestItemRest.setId(requestItem.getID()); requestItemRest.setItem(itemConverter.fromModel(requestItem.getItem())); requestItemRest.setReq_email(requestItem.getReqEmail()); requestItemRest.setReq_message(requestItem.getReqMessage()); requestItemRest.setReq_name(requestItem.getReqName()); requestItemRest.setRequest_date(requestItem.getRequest_date()); requestItemRest.setToken(requestItem.getToken()); return requestItemRest; }

Target:
public RequestItemRest fromModel(RequestItem requestItem) { RequestItemRest requestItemRest = new RequestItemRest(); requestItemRest.setAccept_request(requestItem.isAccept_request()); requestItemRest.setAllfiles(requestItem.isAllfiles()); requestItemRest.setBitstream_id(requestItem.getBitstream().getID().toString()); requestItemRest.setDecision_date(requestItem.getDecision_date()); requestItemRest.setExpires(requestItem.getExpires()); requestItemRest.setId(requestItem.getID()); requestItemRest.setItem_id(requestItem.getItem().getID().toString()); requestItemRest.setRequest_email(requestItem.getReqEmail()); requestItemRest.setRequest_message(requestItem.getReqMessage()); requestItemRest.setRequest_name(requestItem.getReqName()); requestItemRest.setRequest_date(requestItem.getRequest_date()); requestItemRest.setToken(requestItem.getToken()); return requestItemRest; }
Source:
public void onFavoriteButtonClicked(View favorite) { displayKissBar(false); Pojo pojo = KissApplication.getDataHandler(MainActivity.this).getFavorites(tryToRetrieve) .get(Integer.parseInt((String) favorite.getTag())); final Result result = Result.fromPojo(MainActivity.this, pojo); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { result.fastLaunch(MainActivity.this); } }, KissApplication.TOUCH_DELAY_FAVORITE); }

Target:
public void onFavoriteButtonClicked(View favorite) { Pojo pojo = KissApplication.getDataHandler(MainActivity.this).getFavorites(tryToRetrieve) .get(Integer.parseInt((String) favorite.getTag())); final Result result = Result.fromPojo(MainActivity.this, pojo); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { result.fastLaunch(MainActivity.this); } }, KissApplication.TOUCH_DELAY); }
Source:
public ApiResponse handleApiView(String name, JSONObject params) throws ApiException { ApiResponse result = null; if (VIEW_STATS.equals(name)) { Map<String, String> map = new HashMap<>(); for (Entry<String, Long> stat : InMemoryStats.getStats(this.getParam(params, PARAM_KEY_PREFIX, "")).entrySet()) { map.put(stat.getKey(), stat.getValue().toString()); } result = new ApiResponseSet(name, map); } else if (VIEW_ALL_SITES_STATS.equals(name)) { result = new ApiResponseList(name); for (Entry<String, Map<String, Long>> stats : InMemoryStats.getAllSiteStats(this.getParam(params, PARAM_KEY_PREFIX, "")).entrySet()) { ((ApiResponseList)result).addItem(new SiteStatsApiResponse(stats.getKey(), stats.getValue())); } } else if (VIEW_SITE_STATS.equals(name)) { String site = this.getParam(params, PARAM_SITE, null); URI siteURI; try { siteURI = new URI(site, true); site = SessionStructure.getHostName(siteURI); } catch (Exception e) { throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_SITE); } String scheme = siteURI.getScheme(); if (scheme == null || (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https"))) { throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_SITE); } result = new SiteStatsApiResponse(site, InMemoryStats.getSiteStats(site, this.getParam(params, PARAM_KEY_PREFIX, ""))); } else { throw new ApiException(ApiException.Type.BAD_VIEW); } return result; }

Target:
public ApiResponse handleApiView(String name, JSONObject params) throws ApiException { ApiResponse result = null; InMemoryStats memStats = extension.getInMemoryStats(); if (memStats == null) { throw new ApiException(ApiException.Type.DOES_NOT_EXIST); } if (VIEW_STATS.equals(name)) { Map<String, String> map = new HashMap<>(); for (Entry<String, Long> stat : memStats.getStats(this.getParam(params, PARAM_KEY_PREFIX, "")).entrySet()) { map.put(stat.getKey(), stat.getValue().toString()); } result = new ApiResponseSet(name, map); } else if (VIEW_ALL_SITES_STATS.equals(name)) { result = new ApiResponseList(name); for (Entry<String, Map<String, Long>> stats : memStats.getAllSiteStats(this.getParam(params, PARAM_KEY_PREFIX, "")).entrySet()) { ((ApiResponseList)result).addItem(new SiteStatsApiResponse(stats.getKey(), stats.getValue())); } } else if (VIEW_SITE_STATS.equals(name)) { String site = params.getString(PARAM_SITE); URI siteURI; try { siteURI = new URI(site, true); site = SessionStructure.getHostName(siteURI); } catch (Exception e) { throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_SITE); } String scheme = siteURI.getScheme(); if (scheme == null || (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https"))) { throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_SITE); } result = new SiteStatsApiResponse(site, memStats.getSiteStats(site, this.getParam(params, PARAM_KEY_PREFIX, ""))); } else { throw new ApiException(ApiException.Type.BAD_VIEW); } return result; }
Source:
public Response waitForResponse(long timeoutInMs) throws InterruptedException { Response r; synchronized (lock) { if (currentResponse != null) r = currentResponse; else { lock.wait(timeoutInMs); r = currentResponse; } currentResponse = null; } System.out.println("waitForResponse " + i + " " + r); return r; }

Target:
public Response waitForResponse(long timeoutInMs) throws InterruptedException { Response r; synchronized (lock) { if (currentResponse != null) r = currentResponse; else { lock.wait(timeoutInMs); r = currentResponse; } currentResponse = null; } return r; }
Source:
protected void testAddStereotypedElementMergeRToL(Resource left, Resource right) throws IOException { final Comparison comparison = compare(left, right); EList<Diff> differences = comparison.getDifferences(); final StereotypedElementChange stereotypedElementChange = getStereotypedElementChange(differences, DifferenceKind.ADD, 2); assertAddedBaseElementDiff(differences, "model.Class0", stereotypedElementChange); mergeRightToLeft(stereotypedElementChange); for (Diff diff : differences) { assertSame(DifferenceState.MERGED, diff.getState()); } assertEqualsB4Right(right); }

Target:
protected void testAddStereotypedElementMergeRToL(Resource left, Resource right) throws IOException { final Comparison comparison = compare(left, right); EList<Diff> differences = comparison.getDifferences(); final StereotypedElementChange stereotypedElementChange = getStereotypedElementChange(differences, DifferenceKind.ADD, 2); assertAddedBaseElementDiff(differences, "model.Class0", stereotypedElementChange); mergeRightToLeft(stereotypedElementChange); for (Diff diff : differences) { assertSame(DifferenceState.MERGED, diff.getState()); } assertEqualsM2(right); assertEqualsM2(left); }
Source:
public Response perform(Context context) throws Exception { kafkaConfig = kafkaConfigProvider.getProperties(); int timeout = Math.toIntExact(context.getTimeout()); kafkaConfig.put("request.timeout.ms", timeout); try (AdminClient client = Utils.runWithNullContextClassLoader(() -> AdminClient.create(kafkaConfig))) { ListTopicsResult listTopicsResult = client.listTopics(); listTopicsResult.names().get(); return new Response(Status.Success); } catch (Exception e) { return new Response(e); } }

Target:
public Response perform(Context context) throws Exception { Properties kafkaConfig = kafkaConfigProvider.getProperties(); int timeout = Math.toIntExact(context.getTimeout()); kafkaConfig.put("request.timeout.ms", timeout); try (AdminClient client = Utils.runWithNullContextClassLoader(() -> AdminClient.create(kafkaConfig))) { ListTopicsResult listTopicsResult = client.listTopics(); listTopicsResult.names().get(); return new Response(Status.Success); } catch (Exception e) { return new Response(e); } }
Source:
private void formatInternal(String pattern, ZoneInfo.WallTime wallTime, ZoneInfo zoneInfo) { char[] chars = pattern.toCharArray(); if (chars.length == 0) { return; } CharBuffer formatBuffer = CharBuffer.wrap(chars); while (formatBuffer.remaining() > 0) { boolean outputCurrentChar = true; char currentChar = formatBuffer.get(formatBuffer.position()); if (currentChar == '%') { outputCurrentChar = handleToken(formatBuffer, wallTime, zoneInfo); } if (outputCurrentChar) { outputBuilder.append(formatBuffer.get(formatBuffer.position())); } formatBuffer.position(formatBuffer.position() + 1); } }

Target:
private void formatInternal(String pattern, ZoneInfo.WallTime wallTime, ZoneInfo zoneInfo) { if (pattern.length() == 0) { return; } CharBuffer formatBuffer = CharBuffer.wrap(pattern); while (formatBuffer.remaining() > 0) { boolean outputCurrentChar = true; char currentChar = formatBuffer.get(formatBuffer.position()); if (currentChar == '%') { outputCurrentChar = handleToken(formatBuffer, wallTime, zoneInfo); } if (outputCurrentChar) { outputBuilder.append(formatBuffer.get(formatBuffer.position())); } formatBuffer.position(formatBuffer.position() + 1); } }
Source:
public void testInterleavingNoPause() throws InterruptedException { ExecutorService executorService = PTExecutors.newFixedThreadPool(3); accumulator = new LeaderElectionDurationAccumulator(mockConsumer, 300); executorService.submit(() -> leaderElectionResultsWithDurationInRandomOrder(LEADER_1, LEADER_2, 300, 1)); executorService.submit(() -> leaderElectionResultsWithDurationInRandomOrder(LEADER_2, LEADER_3, 300, 17)); executorService.submit(() -> leaderElectionResultsWithDurationInRandomOrder(LEADER_1, LEADER_3, 300, 76)); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); verify(mockConsumer).accept(1L); verify(mockConsumer).accept(17L); verify(mockConsumer).accept(76L); verifyNoMoreInteractions(mockConsumer); }

Target:
public void testInterleavingNoPause() throws InterruptedException { ExecutorService executorService = PTExecutors.newFixedThreadPool(3); accumulator = new LeaderElectionDurationAccumulator(mockConsumer, 300); executorService.submit(() -> leaderElectionResultsWithDurationInRandomOrder(LEADER_1, LEADER_2, 300, 1)); executorService.submit(() -> leaderElectionResultsWithDurationInRandomOrder(LEADER_2, LEADER_3, 300, 1017)); executorService.submit(() -> leaderElectionResultsWithDurationInRandomOrder(LEADER_1, LEADER_3, 300, 2076)); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); verify(mockConsumer).accept(1L); verify(mockConsumer).accept(1017L); verify(mockConsumer).accept(2076L); verifyNoMoreInteractions(mockConsumer); }
Source:
private void initInterpreterSetting(InterpreterSetting interpreterSetting) { interpreterSetting.setConf(conf) .setInterpreterSettingManager(this) .setAngularObjectRegistryListener(angularObjectRegistryListener) .setRemoteInterpreterProcessListener(remoteInterpreterProcessListener) .setAppEventListener(appEventListener) .setDependencyResolver(dependencyResolver) .setLifecycleManager(lifecycleManager) .setRecoveryStorage(recoveryStorage) .setInterpreterEventServer(interpreterEventServer) .postProcessing(); if (conf.isClusterMode()) { try { String pluginName = interpreterSetting.getLauncherPlugin(); PluginManager.get().loadInterpreterLauncher(pluginName, recoveryStorage); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } }

Target:
private void initInterpreterSetting(InterpreterSetting interpreterSetting) { interpreterSetting.setConf(conf) .setInterpreterSettingManager(this) .setAngularObjectRegistryListener(angularObjectRegistryListener) .setRemoteInterpreterProcessListener(remoteInterpreterProcessListener) .setAppEventListener(appEventListener) .setDependencyResolver(dependencyResolver) .setLifecycleManager(lifecycleManager) .setRecoveryStorage(recoveryStorage) .setInterpreterEventServer(interpreterEventServer) .postProcessing(); }
Source:
private void dispatch() { if (isDbInBadState()) { return; } if (CommCareApplication._().isConsumerApp() && !alreadyCheckedForAppFilesChange) { checkForChangedCCZ(); } CommCareApp currentApp = CommCareApplication._().getCurrentApp(); if (currentApp == null) { if (CommCareApplication._().usableAppsPresent()) { CommCareApplication._().initFirstUsableAppRecord(); dispatch(); } else { Intent i = new Intent(getApplicationContext(), CommCareSetupActivity.class); this.startActivityForResult(i, INIT_APP); } } else { try { CommCareApplication._().getSession(); } catch (SessionUnavailableException sue) { launchLoginScreen(); } ApplicationRecord currentRecord = currentApp.getAppRecord(); if (currentApp.getAppResourceState() == CommCareApplication.STATE_CORRUPTED) { handleDamagedApp(); } else if (!currentRecord.isUsable()) { boolean unseated = handleUnusableApp(currentRecord); if (unseated) { dispatch(); } } else if (this.getIntent().hasExtra(SESSION_REQUEST)) { handleExternalLaunch(); } else if (this.getIntent().hasExtra(AndroidShortcuts.EXTRA_KEY_SHORTCUT) && !shortcutExtraWasConsumed) { handleShortcutLaunch(); } else { launchHomeScreen(); } } }

Target:
private void dispatch() { if (isDbInBadState()) { return; } if (CommCareApplication._().isConsumerApp() && !alreadyCheckedForAppFilesChange) { checkForChangedCCZ(); } CommCareApp currentApp = CommCareApplication._().getCurrentApp(); if (currentApp == null) { if (CommCareApplication._().usableAppsPresent()) { CommCareApplication._().initFirstUsableAppRecord(); dispatch(); } else { Intent i = new Intent(getApplicationContext(), CommCareSetupActivity.class); this.startActivityForResult(i, INIT_APP); } } else { ApplicationRecord currentRecord = currentApp.getAppRecord(); try { if (currentApp.getAppResourceState() == CommCareApplication.STATE_CORRUPTED) { handleDamagedApp(); } else if (!currentRecord.isUsable()) { boolean unseated = handleUnusableApp(currentRecord); if (unseated) { dispatch(); } } else if (!CommCareApplication._().getSession().isActive()) { launchLoginScreen(); } else if (this.getIntent().hasExtra(SESSION_REQUEST)) { handleExternalLaunch(); } else if (this.getIntent().hasExtra(AndroidShortcuts.EXTRA_KEY_SHORTCUT) && !shortcutExtraWasConsumed) { handleShortcutLaunch(); } else { launchHomeScreen(); } } catch (SessionUnavailableException sue) { launchLoginScreen(); } } }
Source:
private static boolean isValidRefExpression(final String s) { if (RefSpec.isWildcard(s)) { return isValidRefExpression(s.replace('*', 'X')); } else return Repository.isValidRefName(s) || Repository.isValidRefName(Constants.R_HEADS + s) || Repository.isValidRefName(Constants.R_TAGS + s); }

Target:
private static boolean isValidRefExpression(final String s) { if (RefSpec.isWildcard(s)) { if (s.indexOf('*', s.indexOf('*') + 1) >= 0) { return false; } return isValidRefExpression(s.replace('*', 'X')); } else return Repository.isValidRefName(s) || Repository.isValidRefName(Constants.R_HEADS + s) || Repository.isValidRefName(Constants.R_TAGS + s); }
Source:
public void controlResized(@Nullable ControlEvent e) { refreshDisplayTitles(); refreshDisplayLabels(); fCloseButton.setLocation(fChart.getSize().x - fCloseButton.getSize().x - 5, 5); }

Target:
public void controlResized(@Nullable ControlEvent e) { refreshDisplayTitles(); refreshDisplayLabels(); fCloseButton.setLocation(fChart.getSize().x - fCloseButton.getSize().x - CLOSE_BUTTON_MARGIN, CLOSE_BUTTON_MARGIN); }
Source:
public static <T extends Collection<E>,E> T deepMerge(final Iterable<? extends Iterable<?>> iterableOfIterables, final T collectionToFill) { Iterator<? extends Iterable<?>> iterator = iterableOfIterables.iterator(); if (!iterator.hasNext()) { return collectionToFill; } while (iterator.hasNext()) { deepMergeRecursion(iterator.next(), collectionToFill); } return collectionToFill; }

Target:
public static <T extends Collection<E>,E> T deepMerge(final Iterable<? extends Iterable<?>> iterableOfIterables, final T collectionToFill) { Iterator<? extends Iterable<?>> iterator = iterableOfIterables.iterator(); while (iterator.hasNext()) { deepMergeRecursion(iterator.next(), collectionToFill); } return collectionToFill; }
Source:
private String concatenateList(final List<String> values) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < values.size(); i++) { String value = values.get(i); builder.append(value); if (i < values.size() - 1) { builder.append(","); } } return builder.toString(); }

Target:
private String concatenateList(final List<String> values) { StringBuilder builder = new StringBuilder(); for (String value : values) { builder.append(value); builder.append(","); } builder.setLength(Math.max(builder.length() - 1, 0)); return builder.toString(); }
Source:
public static List<Field> getFields(final Class<?> sourceType) throws IllegalAccessException { return Stream.of(sourceType.getDeclaredFields()).collect(Collectors.toList()); }

Target:
public static List<Field> getFields(final Class<?> sourceType) throws SecurityException { return Stream.of(sourceType.getDeclaredFields()).collect(Collectors.toList()); }
Source:
private static int calculateValue(JavaContext context, Expression expression) { if (expression instanceof IntegralLiteral) { return ((IntegralLiteral) expression).astIntValue(); } JavaParser.ResolvedNode resolvedNode = context.resolve(expression); if (resolvedNode instanceof JavaParser.ResolvedField) { Object value = ((JavaParser.ResolvedField) resolvedNode).getValue(); if (value instanceof Integer) { return (Integer) value; } } if (expression instanceof BinaryExpression) { BinaryExpression binaryExpression = (BinaryExpression) expression; String operator = binaryExpression.astOperator().getSymbol(); int leftValue = calculateValue(context, binaryExpression.astLeft()); int rightValue = calculateValue(context, binaryExpression.astRight()); if (operator.equals("|")) { return leftValue | rightValue; } if (operator.equals("&")) { return leftValue & rightValue; } if (operator.equals("^")) { return leftValue ^ rightValue; } } return 0; }

Target:
private static int calculateValue(JavaContext context, Expression expression) { if (expression instanceof IntegralLiteral) { return ((IntegralLiteral) expression).astIntValue(); } ResolvedNode resolvedNode = context.resolve(expression); if (resolvedNode instanceof ResolvedField) { Object value = ((ResolvedField) resolvedNode).getValue(); if (value instanceof Integer) { return (Integer) value; } } if (expression instanceof BinaryExpression) { BinaryExpression binaryExpression = (BinaryExpression) expression; BinaryOperator operator = binaryExpression.astOperator(); int leftValue = calculateValue(context, binaryExpression.astLeft()); int rightValue = calculateValue(context, binaryExpression.astRight()); if (operator == BinaryOperator.BITWISE_OR) { return leftValue | rightValue; } if (operator == BinaryOperator.BITWISE_AND) { return leftValue & rightValue; } if (operator == BinaryOperator.BITWISE_XOR) { return leftValue ^ rightValue; } } return 0; }
Source:
private void readVector(ColumnReader reader, ColumnVector vector, long current, long total) { ColumnDescriptor column = reader.getDescriptor(); int maxDefinitionLevel = column.getMaxDefinitionLevel(); int index = 0; int fixedLenByteArrayPosition = 0; for ( ; index < ColumnVector.DEFAULT_VECTOR_LENGTH; index++, current++) { if (current >= total) { vector.setNumberOfValues(index); return; } if (reader.getCurrentDefinitionLevel() == maxDefinitionLevel) { switch (column.getType()) { case BOOLEAN: BooleanColumnVector booleanColumnVector = (BooleanColumnVector) vector; booleanColumnVector.values[index] = reader.getBoolean(); break; case DOUBLE: DoubleColumnVector doubleColumnVector = (DoubleColumnVector) vector; doubleColumnVector.values[index] = reader.getDouble(); break; case FLOAT: FloatColumnVector floatColumnVector = (FloatColumnVector) vector; floatColumnVector.values[index] = reader.getFloat(); break; case INT32: IntColumnVector intColumnVector = (IntColumnVector) vector; intColumnVector.values[index] = reader.getInteger(); break; case INT64: LongColumnVector longColumnVector = (LongColumnVector) vector; longColumnVector.values[index] = reader.getLong(); break; case INT96: case FIXED_LEN_BYTE_ARRAY: ByteColumnVector fixedLenVector = (ByteColumnVector) vector; byte[] fixedLenBinary = reader.getBinary().getBytes(); System.arraycopy(fixedLenBinary, 0, fixedLenVector.values, fixedLenByteArrayPosition, fixedLenBinary.length); fixedLenByteArrayPosition += fixedLenBinary.length; break; default: throw new IllegalArgumentException("Unhandled column type " + column.getType()); } vector.isNull[index] = false; } else { vector.isNull[index] = true; } reader.consume(); } vector.setNumberOfValues(index); }

Target:
private void readVector(ColumnReader reader, ColumnVector vector, long current, long total) { ColumnDescriptor column = reader.getDescriptor(); int maxDefinitionLevel = column.getMaxDefinitionLevel(); int index = 0; for ( ; index < ColumnVector.MAX_VECTOR_LENGTH && current < total; index++, current++) { if (reader.getCurrentDefinitionLevel() == maxDefinitionLevel) { vector.readFrom(reader, index); vector.isNull[index] = false; } else { vector.isNull[index] = true; } reader.consume(); } vector.setNumberOfValues(index); }
Source:
public RawQuery build() { Checks.checkNotEmpty(query, "Please specify query string"); return new RawQuery( query, args, tables ); }

Target:
public RawQuery build() { checkNotEmpty(query, "Please specify query string"); return new RawQuery( query, args, tables ); }
Source:
private static <T> T nonNullOrEqual(@Nullable T a, @Nullable T b, String errorMessageTemplate) throws ValidationException { if (a == null) { return b; } else { if (b == null || a.equals(b)) { return a; } else { throw new ValidationException(String.format(errorMessageTemplate, a, b)); } } }

Target:
private static <T> T nonNullOrEqual(@Nullable T a, @Nullable T b, String errorMessageTemplate) throws ValidationException { if (a == null) { return b; } else if (b == null || a.equals(b)) { return a; } else { throw new ValidationException(String.format(errorMessageTemplate, a, b)); } }
Source:
public String description() { return "Will collect information about the system and package everything in an archive. If you specify 'all', " + "everything will be included. You can also fine tune the selection by passing classifiers to the tool, " + "e.g 'logs tx threads'. For a complete list of all available classifiers call the tool with " + "the '--list' flag. If no classifiers are passed, the default list of `logs configs` will be used." ; }

Target:
public String description() { return "Will collect information about the system and package everything in an archive. If you specify 'all', " + "everything will be included. You can also fine tune the selection by passing classifiers to the tool, " + "e.g 'logs tx threads'. For a complete list of all available classifiers call the tool with " + "the '--list' flag. If no classifiers are passed, the default list of `" + String.join( " ", DEFAULT_CLASSIFIERS ) + "` will be used." ; }
Source:
public void testMultithreadAddGetDisjointRanges() throws InterruptedException { final int numAddThreads = 8; final int numGetThreads = 8; final int addsPerThread = 100000; final int getsPerThread = 100; final int totalNumberOfAdds = numAddThreads * addsPerThread; final CountDownLatch countDownLatch = new CountDownLatch(numAddThreads + numGetThreads); final Runnable[] threads = new Runnable[numAddThreads + numGetThreads]; for (int index = 0; index < numAddThreads; index++) { threads[index] =new AddThread(countDownLatch, partitionManager, index, numAddThreads, addsPerThread, IndexParity.ALL_INDEX); } for (int index = 0; index < numGetThreads; index++) { threads[index + numAddThreads] = new GetThread(countDownLatch, partitionManager, getsPerThread); } TestUtils.runConcurrently(threads); final boolean allThreadsFinished = countDownLatch.await(60, TimeUnit.SECONDS); assertTrue(MSG_THREADS_NOT_FINISHED, allThreadsFinished); assertEquals(MSG_SIZE_ASSERTION_FAIL, totalNumberOfAdds, partitionManager.getRangeSet(EVAL_ID, KEY).size()); }

Target:
public void testMultithreadAddGetDisjointRanges() throws InterruptedException { final int numThreadsPerOperation = 8; final int addsPerThread = 100000; final int getsPerThread = 100; final int totalNumberOfAdds = numThreadsPerOperation * addsPerThread; final CountDownLatch countDownLatch = new CountDownLatch(2 * numThreadsPerOperation); final Runnable[] threads = new Runnable[2 * numThreadsPerOperation]; for (int index = 0; index < numThreadsPerOperation; index++) { threads[2 * index] = new RegisterThread(countDownLatch, partitionManager, index, numThreadsPerOperation, addsPerThread, IndexParity.ALL_INDEX); threads[2 * index + 1] = new GetThread(countDownLatch, partitionManager, getsPerThread); } TestUtils.runConcurrently(threads); final boolean allThreadsFinished = countDownLatch.await(60, TimeUnit.SECONDS); assertTrue(MSG_THREADS_NOT_FINISHED, allThreadsFinished); assertEquals(MSG_SIZE_ASSERTION, totalNumberOfAdds, partitionManager.getRangeSet(EVAL_ID, DATA_TYPE).size()); }
Source:
public void testLineBreak() { builder.beginDocument(); builder.beginBlock(BlockType.PARAGRAPH, new Attributes()); builder.characters("line"); builder.lineBreak(); builder.characters("break"); builder.endBlock(); builder.endDocument(); String markup = out.toString(); TestUtil.println(markup); assertEquals("line \nbreak\n\n", markup); }

Target:
public void testLineBreak() { builder.beginDocument(); builder.beginBlock(BlockType.PARAGRAPH, new Attributes()); builder.characters("line"); builder.lineBreak(); builder.characters("break"); builder.endBlock(); builder.endDocument(); assertMarkup("line \nbreak\n\n"); }
Source:
default <R> Task<R> map(final Function1<? super T, ? extends R> func) { return map("map: " + func.getClass().getName(), func); }

Target:
default <R> Task<R> map(final Function1<? super T, ? extends R> func) { return map("map: " + _taskDescriptor.getDescription(func.getClass().getName()), func); }
Source:
public Sequence<Object[]> runQuery(final DruidQuery druidQuery) { final Query query = druidQuery.getQuery(); final Query innerMostQuery = findInnerMostQuery(query); if (plannerContext.getPlannerConfig().isForceTimeCondition() && innerMostQuery.getIntervals().equals(Intervals.ONLY_ETERNITY)) { throw new CannotBuildQueryException("Missing __time filter"); } if (query instanceof TimeseriesQuery) { return executeTimeseries(druidQuery, (TimeseriesQuery) query); } else if (query instanceof TopNQuery) { return executeTopN(druidQuery, (TopNQuery) query); } else if (query instanceof GroupByQuery) { return executeGroupBy(druidQuery, (GroupByQuery) query); } else if (query instanceof ScanQuery) { return executeScan(druidQuery, (ScanQuery) query); } else if (query instanceof SelectQuery) { return executeSelect(druidQuery, (SelectQuery) query); } else { throw new ISE("Cannot run query of class[%s]", query.getClass().getName()); } }

Target:
public Sequence<Object[]> runQuery(final DruidQuery druidQuery) { final Query query = druidQuery.getQuery(); final Query innerMostQuery = findInnerMostQuery(query); if (plannerContext.getPlannerConfig().isRequireTimeCondition() && innerMostQuery.getIntervals().equals(Intervals.ONLY_ETERNITY)) { throw new CannotBuildQueryException( "requireTimeCondition is enabled, all queries must include a filter condition on the __time column" ); } if (query instanceof TimeseriesQuery) { return executeTimeseries(druidQuery, (TimeseriesQuery) query); } else if (query instanceof TopNQuery) { return executeTopN(druidQuery, (TopNQuery) query); } else if (query instanceof GroupByQuery) { return executeGroupBy(druidQuery, (GroupByQuery) query); } else if (query instanceof ScanQuery) { return executeScan(druidQuery, (ScanQuery) query); } else if (query instanceof SelectQuery) { return executeSelect(druidQuery, (SelectQuery) query); } else { throw new ISE("Cannot run query of class[%s]", query.getClass().getName()); } }
Source:
private HttpEntity<UserResource> getUser(UUID requestingUserId, String requestingDeviceIdStr, UUID userId, boolean isCreatedOnBuddyRequest, Optional<String> password) { try (CryptoSession cryptoSession = CryptoSession.start(password, () -> userService.canAccessPrivateData(requestingUserId))) { if (requestingUserId.equals(userId)) { return getOwnUser(requestingUserId, requestingDeviceIdStr, userId, isCreatedOnBuddyRequest); } return getBuddyUser(userId, requestingUserId); } }

Target:
private HttpEntity<UserResource> getUser(UUID requestingUserId, String requestingDeviceIdStr, UUID userId, boolean isCreatedOnBuddyRequest, Optional<String> password) { try (CryptoSession cryptoSession = CryptoSession.start(password, () -> userService.canAccessPrivateData(requestingUserId))) { if (requestingUserId.equals(userId)) { return getOwnUser(requestingUserId, requestingDeviceIdStr, isCreatedOnBuddyRequest); } return getBuddyUser(userId, requestingUserId); } }
Source:
public void testBackgroundCallWaitingWithTimeouts() throws Exception { final Object sync = new Object(); Task<Integer> task = Task.callInBackground(new Callable<Integer>() { public Integer call() throws Exception { synchronized (sync) { sync.wait(); } return 5; } }); assertFalse(task.waitForCompletion(100, TimeUnit.MILLISECONDS)); synchronized (sync) { sync.notify(); } task.waitForCompletion(); assertTrue(task.waitForCompletion(100, TimeUnit.MILLISECONDS)); assertEquals(5, task.getResult().intValue()); }

Target:
public void testBackgroundCallWaitingWithTimeouts() throws Exception { final Object sync = new Object(); Task<Integer> task = Task.callInBackground(new Callable<Integer>() { public Integer call() throws Exception { synchronized (sync) { sync.wait(); Thread.sleep(100); } return 5; } }); assertFalse(task.waitForCompletion(100, TimeUnit.MILLISECONDS)); synchronized (sync) { sync.notify(); } assertTrue(task.waitForCompletion(1000, TimeUnit.MILLISECONDS)); assertTrue(task.waitForCompletion(100, TimeUnit.MILLISECONDS)); assertEquals(5, task.getResult().intValue()); }
Source:
public String getKey() { return remote + " " + directory; }

Target:
private String getKey() { return Subscriber.getKey(remote, directory); }
Source:
public void run() { final String prefKey = UIPreferences.RESOURCEHISTORY_SHOW_FIRST_PARENT_ONLY_DEFAULT; Repository repo = historyPage.getCurrentRepo(); if (repo != null) { String repoSepcificKey = getRepoSpecificKey(repo, prefKey); boolean newBoolean = isChecked(); if (newBoolean == historyPage.store.getBoolean(prefKey)) { historyPage.store.setToDefault(repoSepcificKey); } else { String newValue = newBoolean ? IPreferenceStore.TRUE : IPreferenceStore.FALSE; historyPage.store.putValue(repoSepcificKey, newValue); } historyPage.saveStoreIfNeeded(); } historyPage.refresh(); }

Target:
public void run() { final String prefKey = UIPreferences.RESOURCEHISTORY_SHOW_FIRST_PARENT_ONLY_DEFAULT; Repository repo = historyPage.getCurrentRepo(); if (repo != null) { String repoSpecificKey = getRepoSpecificKey(repo, prefKey); boolean newBoolean = isChecked(); if (newBoolean == historyPage.store.getBoolean(prefKey)) { historyPage.store.setToDefault(repoSpecificKey); } else { String newValue = newBoolean ? IPreferenceStore.TRUE : IPreferenceStore.FALSE; historyPage.store.putValue(repoSpecificKey, newValue); } historyPage.saveStoreIfNeeded(); } historyPage.refresh(); }
Source:
private BiFunction<ITimeEvent, Long, Map<String, String>> getTooltipResolver(ITimeGraphDataProvider<? extends TimeGraphEntryModel> provider) { return (event, time) -> { Long entryId = null; synchronized (fEntries) { entryId = fEntryIds.get(event.getEntry(), provider); } if (entryId == null) { return Collections.emptyMap(); } Builder<@NonNull String, @NonNull Object> builder = ImmutableMap.builder(); builder.put(DataProviderParameterUtils.REQUESTED_TIME_KEY, Collections.singletonList(time)); builder.put(DataProviderParameterUtils.REQUESTED_ITEMS_KEY, Collections.singletonList(entryId)); if (event instanceof TimeEvent) { IOutputElement model = ((TimeEvent) event).getModel(); if (model != null) { builder.put(DataProviderParameterUtils.REQUESTED_ELEMENT_KEY, model); } } TmfModelResponse<Map<String, String>> response = provider.fetchTooltip(builder.build(), new NullProgressMonitor()); Map<String, String> tooltip = response.getModel(); return (tooltip == null) ? Collections.emptyMap() : tooltip; }; }

Target:
private BiFunction<ITimeEvent, Long, Map<String, String>> getTooltipResolver(ITimeGraphDataProvider<? extends TimeGraphEntryModel> provider) { return (event, time) -> { Long entryId = null; synchronized (fEntries) { entryId = fEntryIds.get(event.getEntry(), provider); } if (entryId == null) { return Collections.emptyMap(); } IOutputElement element = null; if (event instanceof TimeEvent) { element = ((TimeEvent) event).getModel(); } Map<@NonNull String, @NonNull Object> parameters = getFetchTooltipParameters(time, entryId, element); TmfModelResponse<Map<String, String>> response = provider.fetchTooltip(parameters, new NullProgressMonitor()); Map<String, String> tooltip = response.getModel(); return (tooltip == null) ? Collections.emptyMap() : tooltip; }; }
Source:
public static <T> byte[] encode(AtomicCoder<T> coder, T original) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); coder.encode(original, bos, null); bos.flush(); return bos.toByteArray(); }

Target:
public static <T> byte[] encode(AtomicCoder<T> coder, T original) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); coder.encode(original, bos, null); return bos.toByteArray(); }
Source:
public synchronized void sendStatus() { byte protocolVersion = getVersion().getCode(); int networkId = config.networkId(); final BigInteger totalDifficulty; final byte[] bestHash; if (syncManager.isFastSyncRunning()) { bestHash = blockstore.getBlockHashByNumber(0); Block genesis = blockstore.getBlockByHash(bestHash); totalDifficulty = genesis.getDifficultyBI(); } else { bestHash = blockstore.getBestBlock().getHash(); totalDifficulty = blockchain.getTotalDifficulty(); } StatusMessage msg = new StatusMessage(protocolVersion, networkId, ByteUtil.bigIntegerToBytes(totalDifficulty), bestHash, blockstore.getBlockHashByNumber(0)); sendMessage(msg); ethState = EthState.STATUS_SENT; sendNextHeaderRequest(); }

Target:
public synchronized void sendStatus() { byte protocolVersion = getVersion().getCode(); int networkId = config.networkId(); final BigInteger totalDifficulty; final byte[] bestHash; if (syncManager.isFastSyncRunning()) { bestHash = blockstore.getBlockHashByNumber(0); Block genesis = blockstore.getBlockByHash(bestHash); totalDifficulty = genesis.getDifficultyBI(); } else { bestHash = blockstore.getBestBlock().getHash(); totalDifficulty = blockchain.getTotalDifficulty(); } StatusMessage msg = new StatusMessage(protocolVersion, networkId, ByteUtil.bigIntegerToBytes(totalDifficulty), bestHash, config.getGenesis().getHash()); sendMessage(msg); ethState = EthState.STATUS_SENT; sendNextHeaderRequest(); }
Source:
private ItemsToPush missingRevisionsToJsonDocs( Map<String, DocumentRevisionTree> allTrees, Map<String, Set<String>> revisions) { ItemsToPush itemsToPush = new ItemsToPush(); for(Map.Entry<String, Set<String>> e : revisions.entrySet()) { String docId = e.getKey(); Set<String> missingRevisions = e.getValue(); DocumentRevisionTree tree = allTrees.get(docId); for(String rev : missingRevisions) { long sequence = tree.lookup(docId, rev).getSequence(); List<DocumentRevision> path = tree.getPathForNode(sequence); DocumentRevision dr = path.get(0); List<? extends Attachment> atts = this.sourceDb.getDbCore().attachmentsForRevision(dr); Map<String, Object> json = RevisionHistoryHelper.revisionHistoryToJson(path, atts); MultipartAttachmentWriter mpw = RevisionHistoryHelper.addMultiparts(path, atts); if (mpw == null) { itemsToPush.serializedDocs.add(sJsonHelper.toJson(json)); } else { itemsToPush.multiparts.add(mpw); } } } return itemsToPush; }

Target:
private ItemsToPush missingRevisionsToJsonDocs( Map<String, DocumentRevisionTree> allTrees, Map<String, Set<String>> revisions) { ItemsToPush itemsToPush = new ItemsToPush(); for(Map.Entry<String, Set<String>> e : revisions.entrySet()) { String docId = e.getKey(); Set<String> missingRevisions = e.getValue(); DocumentRevisionTree tree = allTrees.get(docId); for(String rev : missingRevisions) { long sequence = tree.lookup(docId, rev).getSequence(); List<DocumentRevision> path = tree.getPathForNode(sequence); DocumentRevision dr = path.get(0); List<? extends Attachment> atts = this.sourceDb.getDbCore().attachmentsForRevision(dr); Map<String, Object> json = RevisionHistoryHelper.revisionHistoryToJson(path, atts, this.config.pushAttachmentsInline); MultipartAttachmentWriter mpw = RevisionHistoryHelper.createMultipartWriter(path, atts, this.config.pushAttachmentsInline); if (mpw == null) { itemsToPush.serializedDocs.add(sJsonHelper.toJson(json)); } else { itemsToPush.multiparts.add(mpw); } } } return itemsToPush; }
Source:
public static long getPropertyAsLong(Properties props, String propertyName, long defaultValue) { String value = props.getProperty(propertyName, "").trim(); if (value.isEmpty()) { return defaultValue; } try { return Long.parseLong(value); } catch (NumberFormatException e) { throw new IllegalArgumentException( "Property " + propertyName + " must be a number in Kinesis importer configuration."); } }

Target:
public static long getPropertyAsLong(Properties props, String propertyName, long defaultValue) { String value = props.getProperty(propertyName, "").trim(); if (value.isEmpty()) { return defaultValue; } try { long val = Long.parseLong(value); if (val <= 0) { throw new IllegalArgumentException( "Value of " + propertyName + " should be positive, but current value is " + val); } return val; } catch (NumberFormatException e) { throw new IllegalArgumentException( "Property " + propertyName + " must be a number in Kinesis importer configuration."); } }
Source:
public static List<ITmfStateInterval> queryHistoryRange(ITmfStateSystem ss, int attributeQuark, long t1, long t2) throws AttributeNotFoundException, StateSystemDisposedException { List<ITmfStateInterval> intervals; ITmfStateInterval currentInterval; long ts, tEnd; if (t2 < t1) { throw new TimeRangeException("Start:" + t1 + ", End:" + t2); } if (t2 > ss.getCurrentEndTime()) { tEnd = ss.getCurrentEndTime(); } else { tEnd = t2; } intervals = new ArrayList<>(); currentInterval = ss.querySingleState(t1, attributeQuark); intervals.add(currentInterval); ts = currentInterval.getEndTime(); while (ts != -1 && ts < tEnd) { ts++; currentInterval = ss.querySingleState(ts, attributeQuark); intervals.add(currentInterval); ts = currentInterval.getEndTime(); } return intervals; }

Target:
public static List<ITmfStateInterval> queryHistoryRange(ITmfStateSystem ss, int attributeQuark, long t1, long t2) throws AttributeNotFoundException, StateSystemDisposedException { List<ITmfStateInterval> intervals; ITmfStateInterval currentInterval; long ts, tEnd; if (t2 < t1) { throw new TimeRangeException(ss.getSSID() + " Start:" + t1 + ", End:" + t2); } if (t2 > ss.getCurrentEndTime()) { tEnd = ss.getCurrentEndTime(); } else { tEnd = t2; } intervals = new ArrayList<>(); currentInterval = ss.querySingleState(t1, attributeQuark); intervals.add(currentInterval); ts = currentInterval.getEndTime(); while (ts != -1 && ts < tEnd) { ts++; currentInterval = ss.querySingleState(ts, attributeQuark); intervals.add(currentInterval); ts = currentInterval.getEndTime(); } return intervals; }
Source:
public int getSegmentCount(long periodDurationUs) { if( endNumber != C.INDEX_UNSET) { return endNumber; } else if (segmentTimeline != null) { return segmentTimeline.size(); } else if (periodDurationUs != C.TIME_UNSET) { long durationUs = (duration * C.MICROS_PER_SECOND) / timescale; return (int) Util.ceilDivide(periodDurationUs, durationUs); } else { return DashSegmentIndex.INDEX_UNBOUNDED; } }

Target:
public int getSegmentCount(long periodDurationUs) { if (segmentTimeline != null) { return segmentTimeline.size(); } else if (endNumber != C.INDEX_UNSET) { return (int) (endNumber - startNumber + 1); } else if (periodDurationUs != C.TIME_UNSET) { long durationUs = (duration * C.MICROS_PER_SECOND) / timescale; return (int) Util.ceilDivide(periodDurationUs, durationUs); } else { return DashSegmentIndex.INDEX_UNBOUNDED; } }
Source:
public Option getOrAddStaticOption(String optionKey, String value) { Option option = options.get(optionKey); if (option == null) { option = new Option(optionKey, value, null); options.put(optionKey, option); } return option; }

Target:
Option getOrAddStaticOption(String optionKey, String value) { Option option = options.get(optionKey); if (option == null) { option = new Option(optionKey, value, null); options.put(optionKey, option); } return option; }
Source:
for (int i = 0; i < n; i++) { RelDataType type = opBinding.getOperandType(i); if (SqlTypeUtil.isString(type) || SqlTypeUtil.isCharacter(type)) { return type; } else if (SqlTypeUtil.isDouble(type)) { hasDouble = true; } }

Target:
for (int i = 0; i < n; i++) { RelDataType type = opBinding.getOperandType(i); SqlTypeName sqlTypeName = type.getSqlTypeName(); ValueType valueType = Calcites.getValueTypeForSqlTypeName(sqlTypeName); if (valueType == ValueType.STRING) { returnSqlTypeName = sqlTypeName; break; } else if (valueType == ValueType.DOUBLE || valueType == ValueType.FLOAT) { returnSqlTypeName = SqlTypeName.DOUBLE; hasDouble = true; } else if (valueType == ValueType.LONG && !hasDouble) { returnSqlTypeName = SqlTypeName.BIGINT; } else if (sqlTypeName != SqlTypeName.NULL) { throw new IAE("Argument %d has invalid type: %s", i, sqlTypeName); } }
Source:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { String fullPath = request.getParameter("fullPath"); String action = request.getParameter("sakai_action"); String overwrite = request.getParameter("overwrite"); logger.debug("Received action: "+action+" for file: "+fullPath); checkRunData(request); if(fullPath != null) { String uploadMax = ServerConfigurationService.getString("content.upload.max"); String siteQuota = ServerConfigurationService.getString("siteQuota@org.sakaiproject.content.api.ContentHostingService"); Long fileSize = Long.parseLong(request.getHeader("content-length")); if((uploadMax != null && !"".equals(uploadMax)) && (fileSize /1024L / 1024L) > Long.parseLong(uploadMax)){ addAlert(getState(request), rb.getFormattedMessage("alert.over-per-upload-quota", new Object[]{uploadMax})); } else if ((siteQuota != null && !"".equals(siteQuota)) && (fileSize /1024L / 1024L) > Long.parseLong(siteQuota)) { addAlert(getState(request), rb.getFormattedMessage("alert.over-site-upload-quota", new Object[]{siteQuota})); } else { JetspeedRunData rundata = (JetspeedRunData) request.getAttribute(ATTR_RUNDATA); if (checkCSRFToken(request,rundata,action)) { doDragDropUpload(request, response, fullPath, overwrite); } } } else { if (action!=null) { JetspeedRunData rundata = (JetspeedRunData) request.getAttribute(ATTR_RUNDATA); if (checkCSRFToken(request,rundata,action)) { super.doPost(request, response); } } else { logger.warn("Action null and file null in ResourcesHelperAction"); } } }

Target:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { String fullPath = request.getParameter("fullPath"); String action = request.getParameter("sakai_action"); logger.debug("Received action: "+action+" for file: "+fullPath); checkRunData(request); if(fullPath != null) { String uploadMax = ServerConfigurationService.getString("content.upload.max"); String siteQuota = ServerConfigurationService.getString("siteQuota@org.sakaiproject.content.api.ContentHostingService"); Long fileSize = Long.parseLong(request.getHeader("content-length")); if((uploadMax != null && !"".equals(uploadMax)) && (fileSize /1024L / 1024L) > Long.parseLong(uploadMax)){ addAlert(getState(request), rb.getFormattedMessage("alert.over-per-upload-quota", new Object[]{uploadMax})); } else if ((siteQuota != null && !"".equals(siteQuota)) && (fileSize /1024L / 1024L) > Long.parseLong(siteQuota)) { addAlert(getState(request), rb.getFormattedMessage("alert.over-site-upload-quota", new Object[]{siteQuota})); } else { JetspeedRunData rundata = (JetspeedRunData) request.getAttribute(ATTR_RUNDATA); if (checkCSRFToken(request,rundata,action)) { doDragDropUpload(request, response, fullPath); } } } else { if (action!=null) { JetspeedRunData rundata = (JetspeedRunData) request.getAttribute(ATTR_RUNDATA); if (checkCSRFToken(request,rundata,action)) { super.doPost(request, response); } } else { logger.warn("Action null and file null in ResourcesHelperAction"); } } }
Source:
private String loadExistingUUID() { File eclipseUUIDFile = new File(System.getProperty("user.home") + UUID_PATH); if (!eclipseUUIDFile.exists()) return null; InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(eclipseUUIDFile)); Properties prop = new Properties(); prop.load(in); return (String) prop.get(PROP_UUID); } catch (IOException e) { return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }

Target:
private String loadExistingUUID() { File eclipseUUIDFile = new File(System.getProperty("user.home") + UUID_PATH); if (!eclipseUUIDFile.exists()) return null; try(InputStream in = new BufferedInputStream(new FileInputStream(eclipseUUIDFile))) { Properties prop = new Properties(); prop.load(in); return (String) prop.get(PROP_UUID); } catch (IOException e) { return null; } }
Source:
private void updateDeploymentConfigurationWithEncryptedKeys(Map<String, String> encryptedKeyMap) throws ConfigParserException { try { List<String> lines = Files.readAllLines(Paths.get(deploymentConfigurationPath)); try (BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(deploymentConfigurationPath), StandardCharsets.UTF_8))) { boolean found = false; for (String line : lines) { if (found) { if (StringUtils.isNotEmpty(StringUtils.substringBetween(line.trim(), ConfigConstants.SECTION_PREFIX, ConfigConstants.SECTION_SUFIX))) { found = false; } else { StringTokenizer stringTokenizer = new StringTokenizer(line, ConfigConstants.KEY_VALUE_SEPERATOR); if (stringTokenizer.hasMoreTokens()) { String key = stringTokenizer.nextToken(); String value = encryptedKeyMap.get(key.trim()); line = key.concat(" = \"").concat(value).concat("\""); } } } else { if (ConfigConstants.SECRETS_SECTION.equals(line.trim())) { found = true; } } bufferedWriter.write(line); bufferedWriter.newLine(); } bufferedWriter.flush(); } } catch (IOException e) { throw new ConfigParserException("Error while writing encrypted values into deployment file", e); } }

Target:
private void updateDeploymentConfigurationWithEncryptedKeys(Map<String, String> encryptedKeyMap) throws ConfigParserException { try { List<String> lines = Files.readAllLines(Paths.get(deploymentConfigurationPath)); try (BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(deploymentConfigurationPath), StandardCharsets.UTF_8))) { boolean found = false; for (String line : lines) { if (found) { if (line.matches("[.+]")) { found = false; } else { StringTokenizer stringTokenizer = new StringTokenizer(line, ConfigConstants.KEY_VALUE_SEPERATOR); if (stringTokenizer.hasMoreTokens()) { String key = stringTokenizer.nextToken(); String value = encryptedKeyMap.get(key.trim()); line = key.concat(" = \"").concat(value).concat("\""); } } } else { if (ConfigConstants.SECRETS_SECTION.equals(line.trim())) { found = true; } } bufferedWriter.write(line); bufferedWriter.newLine(); } bufferedWriter.flush(); } } catch (IOException e) { throw new ConfigParserException("Error while writing encrypted values into deployment file", e); } }