auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean isDeleteProtectionEnabled(AuthenticatedContext ac, DatabaseStack dbStack) { AwsCredentialView credentialView = new AwsCredentialView(ac.getCloudCredential()); String regionName = ac.getCloudContext().getLocation().getRegion().value(); AmazonRDS rdsClient = awsClient.createRdsClient(credentialView, regionName); String dbInstanceIdentifier = dbStack.getDatabaseServer().getServerId(); DescribeDBInstancesRequest describeDBInstancesRequest = new DescribeDBInstancesRequest().withDBInstanceIdentifier(dbInstanceIdentifier); DescribeDBInstancesResult describeDBInstancesResult; try { LOGGER.debug("RDS Checking if delete protection is enabled"); describeDBInstancesResult = rdsClient.describeDBInstances(describeDBInstancesRequest); } catch (DBInstanceNotFoundException ex) { LOGGER.debug("DB Instance does not exists! Therefor termination protection check is not relevant anymore: {}", ex.getMessage()); return false; } catch (RuntimeException ex) { throw new CloudConnectorException(ex.getMessage(), ex); } return describeDBInstancesResult.getDBInstances() .stream() .findFirst() .get().getDeletionProtection(); }

Target:
public boolean isDeleteProtectionEnabled(AuthenticatedContext ac, DatabaseStack dbStack) { AwsCredentialView credentialView = new AwsCredentialView(ac.getCloudCredential()); String regionName = ac.getCloudContext().getLocation().getRegion().value(); AmazonRDS rdsClient = awsClient.createRdsClient(credentialView, regionName); String dbInstanceIdentifier = dbStack.getDatabaseServer().getServerId(); DescribeDBInstancesRequest describeDBInstancesRequest = new DescribeDBInstancesRequest().withDBInstanceIdentifier(dbInstanceIdentifier); DescribeDBInstancesResult describeDBInstancesResult; try { LOGGER.debug("RDS Checking if delete protection is enabled"); describeDBInstancesResult = rdsClient.describeDBInstances(describeDBInstancesRequest); } catch (DBInstanceNotFoundException ex) { LOGGER.debug("DB Instance does not exist! Therefore termination protection check is not relevant anymore: {}", ex.getMessage()); return false; } catch (RuntimeException ex) { throw new CloudConnectorException(ex.getMessage(), ex); } return describeDBInstancesResult.getDBInstances() .stream() .findFirst() .get().getDeletionProtection(); }
Source:
protected boolean areReferencedEnvelopesEuqal(ReferencedEnvelope e1, ReferencedEnvelope e2) { if (e1==null && e2 ==null) { return true; } if (e1==null || e2 == null) { return false; } boolean equal = Math.round(e1.getMinX())==Math.round(e2.getMinX()) && Math.round(e1.getMinY())==Math.round(e2.getMinY()) && Math.round(e1.getMaxX())==Math.round(e2.getMaxX()) && Math.round(e1.getMaxY())==Math.round(e2.getMaxY()); if (!equal) { return false; } return areCRSEqual(e1.getCoordinateReferenceSystem(), e2.getCoordinateReferenceSystem()); }

Target:
protected boolean areReferencedEnvelopesEuqal(ReferencedEnvelope e1, ReferencedEnvelope e2) { if (e1==null && e2 ==null) return true; if (e1==null || e2 == null) return false; boolean equal = Math.round(e1.getMinX())==Math.round(e2.getMinX()) && Math.round(e1.getMinY())==Math.round(e2.getMinY()) && Math.round(e1.getMaxX())==Math.round(e2.getMaxX()) && Math.round(e1.getMaxY())==Math.round(e2.getMaxY()); if (!equal) return false; return areCRSEqual(e1.getCoordinateReferenceSystem(), e2.getCoordinateReferenceSystem()); }
Source:
private static final int parse2_1Stroke(final String string) { final StringTokenizer stringTokenizer = new StringTokenizer(string, KeyStroke.KEY_DELIMITER, true); final int size = stringTokenizer.countTokens(); final String[] tokens = new String[size]; for (int i = 0; stringTokenizer.hasMoreTokens(); i++) { tokens[i] = stringTokenizer.nextToken(); } int value = 0; if (size % 2 == 1) { String token = tokens[size - 1]; final Integer integer = (Integer) r2_1KeysByName.get(token .toUpperCase(Locale.ENGLISH)); if (integer != null) { value = integer.intValue(); } else if (token.length() == 1) { value = token.toUpperCase(Locale.ENGLISH).charAt(0); } if (value != 0) { for (int i = 0; i < size - 1; i++) { token = tokens[i]; if (i % 2 == 0) { if (token.equalsIgnoreCase(IKeyLookup.CTRL_NAME)) { if ((value & SWT.CTRL) != 0) { return 0; } value |= SWT.CTRL; } else if (token.equalsIgnoreCase(IKeyLookup.ALT_NAME)) { if ((value & SWT.ALT) != 0) { return 0; } value |= SWT.ALT; } else if (token .equalsIgnoreCase(IKeyLookup.SHIFT_NAME)) { if ((value & SWT.SHIFT) != 0) { return 0; } value |= SWT.SHIFT; } else if (token .equalsIgnoreCase(IKeyLookup.COMMAND_NAME)) { if ((value & SWT.COMMAND) != 0) { return 0; } value |= SWT.COMMAND; } else { return 0; } } else if (!KeyStroke.KEY_DELIMITER.equals(token)) { return 0; } } } } return value; }

Target:
private static final int parse2_1Stroke(final String string) { final StringTokenizer stringTokenizer = new StringTokenizer(string, KeyStroke.KEY_DELIMITER, true); final int size = stringTokenizer.countTokens(); final String[] tokens = new String[size]; for (int i = 0; stringTokenizer.hasMoreTokens(); i++) { tokens[i] = stringTokenizer.nextToken(); } int value = 0; if (size % 2 == 1) { String token = tokens[size - 1]; final Integer integer = (Integer) r2_1KeysByName.get(token .toUpperCase(Locale.ENGLISH)); if (integer != null) { value = integer.intValue(); } else if (token.length() == 1) { value = token.toUpperCase().charAt(0); } if (value != 0) { for (int i = 0; i < size - 1; i++) { token = tokens[i]; if (i % 2 == 0) { if (token.equalsIgnoreCase(IKeyLookup.CTRL_NAME)) { if ((value & SWT.CTRL) != 0) { return 0; } value |= SWT.CTRL; } else if (token.equalsIgnoreCase(IKeyLookup.ALT_NAME)) { if ((value & SWT.ALT) != 0) { return 0; } value |= SWT.ALT; } else if (token .equalsIgnoreCase(IKeyLookup.SHIFT_NAME)) { if ((value & SWT.SHIFT) != 0) { return 0; } value |= SWT.SHIFT; } else if (token .equalsIgnoreCase(IKeyLookup.COMMAND_NAME)) { if ((value & SWT.COMMAND) != 0) { return 0; } value |= SWT.COMMAND; } else { return 0; } } else if (!KeyStroke.KEY_DELIMITER.equals(token)) { return 0; } } } } return value; }
Source:
public static AppConfig parseAppConfig(String appConfigString) { AppConfig appConfig = new AppConfig(); try { JSONObject parentObj = new JSONObject(appConfigString); appConfig.setAppFormatVersion(parentObj.getLong("appFormatVersion")); JSONArray menuParentArray = null; if(appConfig.appFormatVersion >= 6) { JSONObject rootPage = parentObj.getJSONObject("rootPage"); appConfig.mRootPageArgs = rootPage.getJSONObject("args"); appConfig.mRootPageName = rootPage.getString("page"); appConfig.mAppConfigString = appConfig.mRootPageArgs.toString(); appConfig.mNotifications = parentObj.optBoolean("notifications"); } else { throw new RuntimeException("Not Supported appFormatVersion"); } JSONArray majorMenu = null; JSONArray minorMenu = null; if(menuParentArray != null) { majorMenu = menuParentArray.optJSONArray(0); minorMenu = menuParentArray.optJSONArray(1); } if (majorMenu != null) { appConfig.setMajorMenuItems(createMenuItems(majorMenu, true)); } if (minorMenu != null) { appConfig.setMinorMenuItems(createMenuItems(minorMenu, false)); } } catch (JSONException e) { throw new RuntimeException("Invalid app.json!", e); } return appConfig; }

Target:
public static AppConfig parseAppConfig(String appConfigString) { AppConfig appConfig = new AppConfig(); try { JSONObject parentObj = new JSONObject(appConfigString); appConfig.setAppFormatVersion(parentObj.getLong("appFormatVersion")); if(appConfig.appFormatVersion >= 6) { JSONObject rootPage = parentObj.getJSONObject("rootPage"); appConfig.mRootPageArgs = rootPage.getJSONObject("args"); appConfig.mRootPageName = rootPage.getString("page"); appConfig.mAppConfigString = appConfig.mRootPageArgs.toString(); appConfig.mNotifications = parentObj.optBoolean("notifications"); } else { throw new RuntimeException("Not Supported appFormatVersion"); } } catch (JSONException e) { throw new RuntimeException("Invalid app.json!", e); } return appConfig; }
Source:
private void generateNetwork() { this.reportCsvContent = new StringBuilder().append("NODE,TIME,MEASUREMENT\n"); ClusterTimeSeriesReport timeReport = new ClusterTimeSeriesReport(); timeReport.init("Time(sec)", "Network(bytes)", "Network traffic", ""); String[] sortedKeys = sysMonitors.keySet().toArray(new String[0]); Arrays.sort(sortedKeys); for (String s : sortedKeys) { NetworkBytesInMonitor netInMonitor = sysMonitors.get(s).getNetworkBytesInMonitor(); populateGraph(timeReport, "network-inbound-" + s, netInMonitor); } for (String s : sortedKeys) { NetworkBytesOutMonitor netOutMonitor = sysMonitors.get(s).getNetworkBytesOutMonitor(); populateGraph(timeReport, "network-outbound-" + s, netOutMonitor); } generateReport(timeReport, "network_usage"); }

Target:
private void generateNetwork() { reportHeader = new StringBuilder("Second"); reportStrings = null; ClusterTimeSeriesReport timeReport = new ClusterTimeSeriesReport(); timeReport.init("Time(sec)", "Network(bytes)", "Network traffic", ""); for (String s : sysMonitors.keySet()) { reportHeader.append(", network-inbound-" + s + ", network-outbound-" + s); NetworkBytesMonitor netInMonitor = sysMonitors.get(s).getNetworkBytesInMonitor(); populateGraph(timeReport, "network-inbound-" + s, netInMonitor); NetworkBytesMonitor netOutMonitor = sysMonitors.get(s).getNetworkBytesOutMonitor(); populateGraph(timeReport, "network-outbound-" + s, netOutMonitor); } generateReport(timeReport, "network_usage"); }
Source:
private int checkOutOrNot(String branchName) { Preferences prefs = ConfigurationScope.INSTANCE.getNode("org.eclipse.egerrit.prefs"); Preferences editorPrefs = prefs.node("checkout"); int choice = editorPrefs.getInt("doCheckout", 0); if (choice != 0) { return choice; } String title = "Review previously checked-out"; String message = "Change \"" + fChangeInfo.getSubject() + "\"" + " has previously been checked out in branch " + "\"" + branchName + "\"" + ".\n\n" + "Do you want to switch to it or create a new branch?"; MessageDialogWithToggle dialog = new MessageDialogWithToggle(fDraftPublishDelete.getParent().getShell(), title, null, message, MessageDialog.NONE, new String[] { "Cancel", "New Branch", "Switch" }, 0, "Always perform this action", false); dialog.open(); int result = dialog.getReturnCode(); if (dialog.getToggleState()) { editorPrefs.putInt("doCheckout", result); try { editorPrefs.flush(); } catch (BackingStoreException e) { } } return result; }

Target:
private int checkOutOrNot(String branchName) { Preferences prefs = ConfigurationScope.INSTANCE.getNode("org.eclipse.egerrit.prefs"); Preferences editorPrefs = prefs.node("checkout"); int choice = editorPrefs.getInt("doCheckout", 0); if (choice != 0) { return choice; } String title = "Review previously checked-out"; String message = "Change \"" + fChangeInfo.getSubject() + "\"" + " has previously been checked out in branch " + "\"" + branchName + "\"" + ".\n\n" + "Do you want to switch to it or create a new branch?"; MessageDialogWithToggle dialog = new MessageDialogWithToggle(fDraftPublishDelete.getParent().getShell(), title, null, message, MessageDialog.NONE, new String[] { "Cancel", "New Branch", "Switch" }, 0, "Always perform this action", false); dialog.open(); int result = dialog.getReturnCode(); if (result != Window.CANCEL && dialog.getToggleState()) { editorPrefs.putInt("doCheckout", result); try { editorPrefs.flush(); } catch (BackingStoreException e) { } } return result; }
Source:
public Schema generateSchema(final Schema inputSchema) { Schema stateSchema = generateStateSchema(inputSchema); ImmutableList.Builder<Type> typesBuilder = ImmutableList.builder(); ImmutableList.Builder<String> namesBuilder = ImmutableList.builder(); for (Expression expr : emitters) { typesBuilder.add( expr.getOutputType(new ExpressionOperatorParameter(inputSchema, stateSchema))); namesBuilder.add(expr.getOutputName()); } return new Schema(typesBuilder.build(), namesBuilder.build()); }

Target:
public Schema generateSchema(final Schema inputSchema) { Schema stateSchema = generateStateSchema(inputSchema); ImmutableList.Builder<Type> typesBuilder = ImmutableList.builder(); ImmutableList.Builder<String> namesBuilder = ImmutableList.builder(); for (Expression expr : emitters) { typesBuilder.add( expr.getOutputType(new ExpressionOperatorParameter(inputSchema, stateSchema))); namesBuilder.add(expr.getOutputName()); } return Schema.of(typesBuilder.build(), namesBuilder.build()); }
Source:
private boolean containsTimerEvent(String type, Object event) { if (!type.equals("timerTriggered") || !(event instanceof TimerInstance)) { return false; } TimerInstance timerInstance = (TimerInstance) event; return getTimerInstances().contains(timerInstance.getId()); }

Target:
private boolean containsTimerEvent(String type, Object event) { if (!type.equals("timerTriggered") || !(event instanceof TimerInstance)) { return false; } TimerInstance timerInstance = (TimerInstance) event; List<Long> timersRegisteredInNodeInstance = getTimerInstances(); return timersRegisteredInNodeInstance != null && timersRegisteredInNodeInstance.contains(timerInstance.getId()); }
Source:
public GroupType(Repetition repetition, String name, LogicalTypeAnnotation logicalTypeAnnotation, Type... fields) { this(repetition, name, logicalTypeAnnotation, Arrays.asList(fields)); }

Target:
GroupType(Repetition repetition, String name, LogicalTypeAnnotation logicalTypeAnnotation, Type... fields) { this(repetition, name, logicalTypeAnnotation, Arrays.asList(fields)); }
Source:
public ITmfContext seekEvent(double ratio) { CtfTmfLightweightContext context = new CtfTmfLightweightContext(this); final long end = this.getEndTime().getValue(); final long start = this.getStartTime().getValue(); final long diff = end - start; final CtfTmfTimestamp ratioTs = new CtfTmfTimestamp((long) (diff * ratio) + start); context.seek( ratioTs.getValue() ); context.setRank(ITmfContext.UNKNOWN_RANK); return context; }

Target:
public ITmfContext seekEvent(double ratio) { CtfTmfLightweightContext context = new CtfTmfLightweightContext(this); final long end = this.getEndTime().getValue(); final long start = this.getStartTime().getValue(); final long diff = end - start; final long ratioTs = (long) (diff * ratio) + start; context.seek(ratioTs); context.setRank(ITmfContext.UNKNOWN_RANK); return context; }
Source:
protected Schema generateSchema() { Operator child = getChild(); if (child == null) { return null; } Schema inputSchema = child.getSchema(); if (inputSchema == null) { return null; } groupSchema = inputSchema.getSubSchema(gFields); final ImmutableList.Builder<Type> aggTypes = ImmutableList.<Type> builder(); final ImmutableList.Builder<String> aggNames = ImmutableList.<String> builder(); try { for (Aggregator agg : AggUtils.allocateAggs(factories, inputSchema)) { Schema curAggSchema = agg.getResultSchema(); aggTypes.addAll(curAggSchema.getColumnTypes()); aggNames.addAll(curAggSchema.getColumnNames()); } } catch (DbException e) { throw new RuntimeException("unable to allocate aggregators to determine output schema", e); } aggSchema = new Schema(aggTypes, aggNames); return Schema.merge(groupSchema, aggSchema); }

Target:
protected Schema generateSchema() { Operator child = getChild(); if (child == null) { return null; } Schema inputSchema = child.getSchema(); if (inputSchema == null) { return null; } groupSchema = inputSchema.getSubSchema(gFields); resultSchema = Schema.of(groupSchema.getColumnTypes(), groupSchema.getColumnNames()); try { for (Aggregator agg : AggUtils.allocateAggs(factories, inputSchema)) { Schema curAggSchema = agg.getResultSchema(); resultSchema = Schema.merge(resultSchema, curAggSchema); } } catch (DbException e) { throw new RuntimeException("unable to allocate aggregators to determine output schema", e); } return resultSchema; }
Source:
protected void setupEncodedValueWriter() throws IOException { final CompressedObjectStrategy.CompressionStrategy compressionStrategy = indexSpec.getDimensionCompression(); String filenameBase = StringUtils.safeFormat("%s.forward_dim", dimensionName); if (capabilities.hasMultipleValues()) { encodedValueWriter = (compressionStrategy != CompressedObjectStrategy.CompressionStrategy.UNCOMPRESSED) ? CompressedVSizeIndexedV3Writer.create( ioPeon, filenameBase, cardinality, compressionStrategy ) : new VSizeIndexedWriter(ioPeon, filenameBase, cardinality); } else { encodedValueWriter = (compressionStrategy != CompressedObjectStrategy.CompressionStrategy.UNCOMPRESSED) ? CompressedVSizeIntsIndexedWriter.create( ioPeon, filenameBase, cardinality, compressionStrategy ) : new VSizeIndexedIntsWriter(ioPeon, filenameBase, cardinality); } encodedValueWriter.open(); }

Target:
protected void setupEncodedValueWriter() throws IOException { final CompressedObjectStrategy.CompressionStrategy compressionStrategy = indexSpec.getDimensionCompression(); String filenameBase = StringUtils.format("%s.forward_dim", dimensionName); if (capabilities.hasMultipleValues()) { encodedValueWriter = (compressionStrategy != CompressedObjectStrategy.CompressionStrategy.UNCOMPRESSED) ? CompressedVSizeIndexedV3Writer.create( ioPeon, filenameBase, cardinality, compressionStrategy ) : new VSizeIndexedWriter(ioPeon, filenameBase, cardinality); } else { encodedValueWriter = (compressionStrategy != CompressedObjectStrategy.CompressionStrategy.UNCOMPRESSED) ? CompressedVSizeIntsIndexedWriter.create( ioPeon, filenameBase, cardinality, compressionStrategy ) : new VSizeIndexedIntsWriter(ioPeon, filenameBase, cardinality); } encodedValueWriter.open(); }
Source:
public FluentInitializer init(Collection<Date> datesCollection, Locale locale) { if (datesCollection.isEmpty()){ throw new IllegalArgumentException( "daysCollection is empty."); } Date minDate = datesCollection.iterator().next(); Date maxDate = datesCollection.iterator().next(); for (Date date : datesCollection) { Calendar cal = Calendar.getInstance(locale); cal.setTime(date); setMidnight(cal); selectableCals.add(cal); if (date.after(maxDate)) maxDate = date; else if (date.before(minDate)) minDate = date; } Calendar cal = Calendar.getInstance(locale); cal.setTime(maxDate); cal.add(DATE, 1); maxDate = cal.getTime(); isCheckDayInSelectableCals = true; return init(minDate, maxDate, locale); }

Target:
public FluentInitializer init(Collection<Date> datesCollection, Locale locale) { if (datesCollection.isEmpty()) { throw new IllegalArgumentException( "daysCollection is empty."); } Date minDate = datesCollection.iterator().next(); Date maxDate = datesCollection.iterator().next(); for (Date date : datesCollection) { Calendar cal = Calendar.getInstance(locale); cal.setTime(date); setMidnight(cal); selectableCals.add(cal); if (date.after(maxDate)) { maxDate = date; } else if (date.before(minDate)) { minDate = date; } } Calendar cal = Calendar.getInstance(locale); cal.setTime(maxDate); cal.add(DATE, 1); maxDate = cal.getTime(); isCheckDayInSelectableCals = true; return init(minDate, maxDate, locale); }
Source:
public IssueOutputView(Issue issue) { this(issue, null, null); }

Target:
public IssueOutputView(Issue issue) { this(issue, null); }
Source:
public String getURL(XWikiDocument document) throws Exception { XWikiContext xcontext = this.xcontextProvider.get(); Map<String, String> parameters = new LinkedHashMap<>(); parameters.put(XWiki.CACHE_VERSION, document.getVersion()); XWikiURLFactory urlf = xcontext.getURLFactory(); URL url = urlf.createSkinURL(this.reference.getName(), document.getSpace(), document.getName(), document.getDatabase(), xcontext, parameters); return urlf.getURL(url, xcontext); }

Target:
public String getURL(XWikiDocument document) throws Exception { XWikiContext xcontext = this.xcontextProvider.get(); Map<String, Object> parameters = new LinkedHashMap<>(); parameters.put(XWiki.CACHE_VERSION, document.getVersion()); XWikiURLFactory urlf = xcontext.getURLFactory(); URL url = urlf.createSkinURL(this.reference.getName(), document.getSpace(), document.getName(), document.getDatabase(), xcontext, parameters); return urlf.getURL(url, xcontext); }
Source:
private SortedSet<String> getUniqueAttributes(List<Issue> issues) { SortedSet<String> uniqAttributes = new TreeSet<>(); issues.stream() .forEach(issue -> { for (Entry<String, JsonElement> entry : issue.getFlatten().entrySet()) { uniqAttributes.add(entry.getKey()); } }); return uniqAttributes; }

Target:
private SortedSet<String> getUniqueAttributes(List<Issue> issues) { SortedSet<String> uniqueAttributes = new TreeSet<>(); for (Issue issue : issues) { for (Entry<String, JsonElement> entry : issue.getFlatten().entrySet()) { uniqueAttributes.add(entry.getKey()); } } return uniqueAttributes; }
Source:
public void testCreateUserVariableInFormulaEditor() { String userVariableName = "testVariable1"; onBrickAtPosition(1).onChildView(withId(R.id.brick_set_variable_edit_text)).perform(click()); onView(withId(R.id.formula_editor_keyboard_data)).perform(click()); onView(withId(R.id.button_add)).perform(click()); onView(withId(R.id.dialog_formula_editor_data_name_edit_text)).perform(typeText(userVariableName)); onView(withText(R.string.ok)).perform(click()); onView(allOf(withChild(withText(userVariableName)), withChild(withText("0.0")))).check(matches(isDisplayed())); pressBack(); onView(allOf(withParent(withId(R.id.set_variable_spinner)), withText(userVariableName))).check(matches (isDisplayed())); pressBack(); onBrickAtPosition(1).onVariableSpinner(R.id.set_variable_spinner).onChildView(withText(userVariableName)) .check(matches(isDisplayed())); onBrickAtPosition(1).checkShowsText(userVariableName); }

Target:
public void testCreateUserVariableInFormulaEditor() { String userVariableName = "testVariable1"; addNewVariableViaFormulaEditor(1, userVariableName); onView(allOf(withParent(withId(R.id.set_variable_spinner)), withText(userVariableName))) .check(matches(isDisplayed())); pressBack(); onBrickAtPosition(1).onVariableSpinner(R.id.set_variable_spinner).onChildView(withText(userVariableName)) .check(matches(isDisplayed())); onBrickAtPosition(1) .checkShowsText(userVariableName); }
Source:
public void testTernaryFunctionsParsingUnsuccessful() throws Exception { for (String function : ternaryFunctions) { testFunctionParsingUnsuccessful(function, failingTernaryFunctionExpressions); } }

Target:
public void testTernaryFunctionsParsingUnsuccessful() { for (String function : ternaryFunctions) { testFunctionParsingUnsuccessful(function, failingTernaryFunctionExpressions); } }
Source:
private void endTrace(BuildData buildData){ if(buildData == null){ return; } Tracer tracer = GlobalTracer.get(); DatadogUtilities.severe(logger, null, "endTrace - Cache key: " + buildData.getBuildId(null)); Span span = DatadogTraceCache.cache.get(buildData.getBuildId(null)); if (span != null) { Scope scope = tracer.scopeManager().activate(span, false); span.finish(); scope.close(); DatadogTraceCache.cache.remove(buildData.getBuildId(null)); } else { } }

Target:
private void endTrace(BuildData buildData){ if(buildData == null){ return; } DatadogUtilities.severe(logger, null, "endTrace - Cache key: " + buildData.getBuildId(null)); DatadogTraceCache.AugmentedSpan augmentedSpan = DatadogTraceCache.cache.remove(buildData.getBuildId(null)); if(augmentedSpan != null) { Span span = augmentedSpan.span; if (span != null) { span.finish(); } else { } } else { } }
Source:
public static @Nullable Set<Integer> getThreadsOfCpus(KernelAnalysisModule module, Collection<Long> cpus, long rangeStart, long rangeEnd) { ITmfStateSystem ss = module.getStateSystem(); if (ss == null) { return null; } Set<Long> uniqueCpus = (cpus instanceof Set ? (Set<Long>) cpus : ImmutableSet.copyOf(cpus)); int threadsQuark = ss.optQuarkAbsolute(Attributes.THREADS); if (threadsQuark == ITmfStateSystem.INVALID_ATTRIBUTE) { return null; } List<Integer> threadQuarks = ss.getSubAttributes(threadsQuark, false); return threadQuarks.stream() .filter(threadQuark -> { int threadCurrentCpuQuark = ss.optQuarkRelative(threadQuark, Attributes.CURRENT_CPU_RQ); if (threadCurrentCpuQuark == ITmfStateSystem.INVALID_ATTRIBUTE) { return false; } Iterator<ITmfStateInterval> it = StateSystemUtils.getIteratorOverQuark(ss, threadCurrentCpuQuark, rangeStart, rangeEnd); while (it.hasNext()) { ITmfStateInterval interval = it.next(); ITmfStateValue value = interval.getStateValue(); if (!value.isNull() && uniqueCpus.contains(Long.valueOf(value.unboxLong()))) { return true; } } return false; }) .map(ss::getAttributeName) .filter(attribName -> !attribName.startsWith(Attributes.THREAD_0_PREFIX)) .map(Integer::parseInt) .collect(Collectors.toSet()); }

Target:
public static @Nullable Set<Integer> getThreadsOfCpus(KernelAnalysisModule module, Collection<Long> cpus, long rangeStart, long rangeEnd) { ITmfStateSystem ss = module.getStateSystem(); if (ss == null) { return null; } Set<Long> uniqueCpus = (cpus instanceof Set ? (Set<Long>) cpus : ImmutableSet.copyOf(cpus)); int threadsQuark = ss.optQuarkAbsolute(Attributes.THREADS); if (threadsQuark == ITmfStateSystem.INVALID_ATTRIBUTE) { return null; } List<Integer> threadQuarks = ss.getSubAttributes(threadsQuark, false); return threadQuarks.stream() .filter(threadQuark -> { int threadCurrentCpuQuark = ss.optQuarkRelative(threadQuark, Attributes.CURRENT_CPU_RQ); if (threadCurrentCpuQuark == ITmfStateSystem.INVALID_ATTRIBUTE) { return false; } Iterator<ITmfStateInterval> it = StateSystemUtils.getIteratorOverQuark(ss, threadCurrentCpuQuark, rangeStart, rangeEnd); return StreamUtils.getStream(it) .map(ITmfStateInterval::getStateValue) .filter(value -> !value.isNull()) .map(value -> Long.valueOf(value.unboxLong())) .anyMatch(uniqueCpus::contains); }) .map(ss::getAttributeName) .filter(attribName -> !attribName.startsWith(Attributes.THREAD_0_PREFIX)) .map(Integer::valueOf) .collect(Collectors.toSet()); }
Source:
public void initialize(NumberPattern parameters) { Pattern.Flag[] flags = parameters.flags(); int intFlag = 0; for ( Pattern.Flag flag : flags ) { intFlag = intFlag | flag.getValue(); } try { this.pattern = java.util.regex.Pattern.compile( parameters.regexp(), intFlag ); } catch (PatternSyntaxException e) { throw log.getInvalidRegularExpressionException( e ); } if ( !parameters.numberFormat().trim().isEmpty() ) { try { this.numberFormat = new DecimalFormat( parameters.numberFormat() ); } catch (IllegalArgumentException e) { throw log.getInvalidNumberFormatException(); } } }

Target:
public void initialize(NumberPattern parameters) { NumberPattern.Flag[] flags = parameters.flags(); int intFlag = 0; for ( NumberPattern.Flag flag : flags ) { intFlag = intFlag | flag.getValue(); } try { this.pattern = java.util.regex.Pattern.compile( parameters.regexp(), intFlag ); } catch (PatternSyntaxException e) { throw log.getInvalidRegularExpressionException( e ); } this.numberFormatString = parameters.numberFormat(); if ( !StringHelper.isNullOrEmptyString( numberFormatString ) ) { try { new DecimalFormat( numberFormatString ); } catch (IllegalArgumentException e) { throw log.getInvalidNumberFormatException(); } } }
Source:
public byte[] toBytes(String value) { if (type.equalsIgnoreCase(SetContainerHostMapping.TYPE)) { SetContainerHostMapping hostMapping = new SetContainerHostMapping(SOURCE, "", value, config.get("jmx.tunneling.url"), config.get("jmx.url")); return messageSerde.toBytes(hostMapping.getMessageMap()); } else if (type.equalsIgnoreCase(SetTaskContainerMapping.TYPE)) { SetTaskContainerMapping setTaskContainerMapping = new SetTaskContainerMapping(SOURCE, "", value); return messageSerde.toBytes(setTaskContainerMapping.getMessageMap()); } else if (type.equalsIgnoreCase(SetChangelogMapping.TYPE)) { SetChangelogMapping changelogMapping = new SetChangelogMapping(SOURCE, "", Integer.valueOf(value)); return messageSerde.toBytes(changelogMapping.getMessageMap()); } else { throw new SamzaException(String.format("Unknown coordinator stream message type: %s", type)); } }

Target:
public byte[] toBytes(String value) { if (type.equalsIgnoreCase(SetContainerHostMapping.TYPE)) { SetContainerHostMapping hostMapping = new SetContainerHostMapping(SOURCE, "", value, "", ""); return messageSerde.toBytes(hostMapping.getMessageMap()); } else if (type.equalsIgnoreCase(SetTaskContainerMapping.TYPE)) { SetTaskContainerMapping setTaskContainerMapping = new SetTaskContainerMapping(SOURCE, "", value); return messageSerde.toBytes(setTaskContainerMapping.getMessageMap()); } else if (type.equalsIgnoreCase(SetChangelogMapping.TYPE)) { SetChangelogMapping changelogMapping = new SetChangelogMapping(SOURCE, "", Integer.valueOf(value)); return messageSerde.toBytes(changelogMapping.getMessageMap()); } else { throw new SamzaException(String.format("Unknown coordinator stream message type: %s", type)); } }
Source:
protected void convertVm(int defaultOsId, DisplayType defaultDisplayType, long fetchTime, Map<String, Object> vmInfo) { Guid vmId = Guid.createGuidFromString((String) vmInfo.get(VdsProperties.vm_guid)); String vmNameOnHost = (String) vmInfo.get(VdsProperties.vm_name); if (isHostedEngineVm(vmId, vmNameOnHost)) { importHostedEngineVm(vmInfo); return; } VmStatic vmStatic = new VmStatic(); vmStatic.setId(vmId); vmStatic.setCreationDate(new Date()); vmStatic.setClusterId(getClusterId()); vmStatic.setName(String.format(EXTERNAL_VM_NAME_FORMAT, vmNameOnHost)); vmStatic.setOrigin(OriginType.EXTERNAL); vmStatic.setNumOfSockets(VdsBrokerObjectsBuilder.parseIntVdsProperty(vmInfo.get(VdsProperties.num_of_cpus))); vmStatic.setMemSizeMb(VdsBrokerObjectsBuilder.parseIntVdsProperty(vmInfo.get(VdsProperties.mem_size_mb))); vmStatic.setMaxMemorySizeMb(VdsBrokerObjectsBuilder.parseIntVdsProperty(vmInfo.get(VdsProperties.maxMemSize))); vmStatic.setSingleQxlPci(false); setOsId(vmStatic, (String) vmInfo.get(VdsProperties.guest_os), defaultOsId); setDisplayType(vmStatic, (String) vmInfo.get(VdsProperties.displayType), defaultDisplayType); addExternallyManagedVm(vmStatic); addDevices(vmInfo, fetchTime); log.info("Importing VM '{}' as '{}', as it is running on the on Host, but does not exist in the engine.", vmNameOnHost, vmStatic.getName()); }

Target:
protected void convertVm(int defaultOsId, DisplayType defaultDisplayType, long fetchTime, Map<String, Object> vmInfo) { Guid vmId = Guid.createGuidFromString((String) vmInfo.get(VdsProperties.vm_guid)); String vmNameOnHost = (String) vmInfo.get(VdsProperties.vm_name); if (isHostedEngineVm(vmId, vmNameOnHost)) { importHostedEngineVm(vmInfo); return; } VmStatic vmStatic = new VmStatic(); vmStatic.setId(vmId); vmStatic.setCreationDate(new Date()); vmStatic.setClusterId(getClusterId()); vmStatic.setName(String.format(EXTERNAL_VM_NAME_FORMAT, vmNameOnHost)); vmStatic.setOrigin(OriginType.EXTERNAL); vmStatic.setNumOfSockets(VdsBrokerObjectsBuilder.parseIntVdsProperty(vmInfo.get(VdsProperties.num_of_cpus))); vmStatic.setMemSizeMb(VdsBrokerObjectsBuilder.parseIntVdsProperty(vmInfo.get(VdsProperties.mem_size_mb))); final int maxMemorySize = vmInfo.get(VdsProperties.maxMemSize) != null ? VdsBrokerObjectsBuilder.parseIntVdsProperty(vmInfo.get(VdsProperties.maxMemSize)) : vmStatic.getMemSizeMb(); vmStatic.setMaxMemorySizeMb(maxMemorySize); vmStatic.setSingleQxlPci(false); setOsId(vmStatic, (String) vmInfo.get(VdsProperties.guest_os), defaultOsId); setDisplayType(vmStatic, (String) vmInfo.get(VdsProperties.displayType), defaultDisplayType); addExternallyManagedVm(vmStatic); addDevices(vmInfo, fetchTime); log.info("Importing VM '{}' as '{}', as it is running on the on Host, but does not exist in the engine.", vmNameOnHost, vmStatic.getName()); }
Source:
public Answer execute(final ResizeVolumeCommand command, final CitrixResourceBase citrixResourceBase) { Connection conn = citrixResourceBase.getConnection(); String volId = command.getPath(); long newSize = command.getNewSize(); try { if(command.getCurrentSize() <= newSize) { s_logger.info("No need to resize volume: " + volId +", current size " + command.getCurrentSize() + " is same as new size " + newSize); return new ResizeVolumeAnswer(command, true, "success", newSize); } if (command.isManaged()) { resizeSr(conn, command); } VDI vdi = citrixResourceBase.getVDIbyUuid(conn, volId); vdi.resize(conn, newSize); return new ResizeVolumeAnswer(command, true, "success", newSize); } catch (Exception ex) { s_logger.warn("Unable to resize volume", ex); String error = "Failed to resize volume: " + ex; return new ResizeVolumeAnswer(command, false, error); } }

Target:
public Answer execute(final ResizeVolumeCommand command, final CitrixResourceBase citrixResourceBase) { Connection conn = citrixResourceBase.getConnection(); String volId = command.getPath(); long newSize = command.getNewSize(); try { if (command.getCurrentSize() >= newSize) { s_logger.info("No need to resize volume: " + volId +", current size " + command.getCurrentSize() + " is same as new size " + newSize); return new ResizeVolumeAnswer(command, true, "success", newSize); } if (command.isManaged()) { resizeSr(conn, command); } VDI vdi = citrixResourceBase.getVDIbyUuid(conn, volId); vdi.resize(conn, newSize); return new ResizeVolumeAnswer(command, true, "success", newSize); } catch (Exception ex) { s_logger.warn("Unable to resize volume", ex); String error = "Failed to resize volume: " + ex; return new ResizeVolumeAnswer(command, false, error); } }
Source:
private static void formatInlineCodeTag(StringBuilder builder, DetailNode inlineTag) throws CheckstyleException { boolean isCodeTag = false; for (DetailNode node : inlineTag.getChildren()) { switch (node.getType()) { case JavadocTokenTypes.JAVADOC_INLINE_TAG_START: case JavadocTokenTypes.JAVADOC_INLINE_TAG_END: case JavadocTokenTypes.WS: break; case JavadocTokenTypes.TEXT: if (isCodeTag) { builder.append("<code>").append(node.getText()).append("</code>"); } else { builder.append(node.getText()); } break; case JavadocTokenTypes.LITERAL_LITERAL: break; case JavadocTokenTypes.CODE_LITERAL: isCodeTag = true; break; default: throw new CheckstyleException("Inline tag " + JavadocUtils.getTokenName(node.getType()) + " is not supported"); } } }

Target:
private static void formatInlineCodeTag(StringBuilder builder, DetailNode inlineTag) throws CheckstyleException { boolean wrapWithCodeTag = false; for (DetailNode node : inlineTag.getChildren()) { switch (node.getType()) { case JavadocTokenTypes.CODE_LITERAL: wrapWithCodeTag = true; break; case JavadocTokenTypes.TEXT: if (wrapWithCodeTag) { builder.append("<code>").append(node.getText()).append("</code>"); } else { builder.append(node.getText()); } break; case JavadocTokenTypes.LITERAL_LITERAL: case JavadocTokenTypes.JAVADOC_INLINE_TAG_START: case JavadocTokenTypes.JAVADOC_INLINE_TAG_END: case JavadocTokenTypes.WS: break; default: throw new CheckstyleException("Unsupported inline tag " + JavadocUtils.getTokenName(node.getType())); } } }
Source:
public static String getContentCharSet(final HttpEntity entity) throws ParseException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } String charSet = null; if (entity.getContentType() != null) { HeaderElement values[] = entity.getContentType().getElements(); if (values.length > 0) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charSet = param.getValue(); } } } return charSet; }

Target:
public static String getContentCharSet(final HttpEntity entity) throws ParseException { String charSet = null; if (entity.getContentType() != null) { HeaderElement values[] = entity.getContentType().getElements(); if (values.length > 0) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charSet = param.getValue(); } } } return charSet; }
Source:
protected IStatus run(IProgressMonitor monitor) { schedule(6 * 60 * 60 * 1000L); if (enabled) { try { TelemetryClientConfig clientConfig = getTelemetryClientConfig(); telemetryEngine.getClient().tryUpload(clientConfig, isAnyProjectConnected()); } catch (Exception e) { SonarLintLogger.get().debug("Unable to send usage statistics", e); } } return Status.OK_STATUS; }

Target:
protected IStatus run(IProgressMonitor monitor) { schedule(TimeUnit.HOURS.toMillis(6)); if (enabled) { try { TelemetryClientConfig clientConfig = getTelemetryClientConfig(); telemetryEngine.getClient().tryUpload(clientConfig, isAnyProjectConnected()); } catch (Exception e) { } } return Status.OK_STATUS; }
Source:
public void stepCreateConsole(final RequestMonitor rm) { IGDBBackend backend = fTracker.getService(IGDBBackend.class); String defaultPathName = backend.getProgramPath().lastSegment(); if (defaultPathName == null) { defaultPathName = ""; } String progPathName = CDebugUtils.getAttribute(getAttributes(), ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, defaultPathName); final String pathLabel = new Path(progPathName).lastSegment(); final Process inferiorProcess = new MIInferiorProcess(getContainerContext(), backend.getMIOutputStream()); final ILaunch launch = (ILaunch) getContainerContext().getAdapter( ILaunch.class); final String groupId = ((IMIContainerDMContext) getContainerContext()) .getGroupId(); DebugPlugin.getDefault().asyncExec(new Runnable() { @Override public void run() { Map<String, String> attributes = new HashMap<String, String>(); attributes.put(IGdbDebugConstants.PROCESS_TYPE_CREATION_ATTR, IGdbDebugConstants.INFERIOR_PROCESS_CREATION_VALUE); IProcess runtimeInferior = DebugPlugin.newProcess(launch, inferiorProcess, pathLabel, attributes); runtimeInferior.setAttribute( IGdbDebugConstants.INFERIOR_GROUPID_ATTR, groupId); rm.done(); } }); return; }

Target:
public void stepCreateConsole(final RequestMonitor rm) { IGDBBackend backend = fTracker.getService(IGDBBackend.class); String defaultPathName = backend.getProgramPath().lastSegment(); if (defaultPathName == null) { defaultPathName = ""; } String progPathName = CDebugUtils.getAttribute(getAttributes(), ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, defaultPathName); final String pathLabel = new Path(progPathName).lastSegment(); final Process inferiorProcess = new MIInferiorProcess(getContainerContext(), backend.getMIOutputStream()); final ILaunch launch = (ILaunch) getContainerContext().getAdapter( ILaunch.class); final String groupId = ((IMIContainerDMContext) getContainerContext()) .getGroupId(); DebugPlugin.getDefault().asyncExec(new Runnable() { @Override public void run() { try { Map<String, String> attributes = new HashMap<String, String>(); attributes.put(IGdbDebugConstants.PROCESS_TYPE_CREATION_ATTR, IGdbDebugConstants.INFERIOR_PROCESS_CREATION_VALUE); IProcess runtimeInferior = DebugPlugin.newProcess(launch, inferiorProcess, pathLabel, attributes); runtimeInferior.setAttribute( IGdbDebugConstants.INFERIOR_GROUPID_ATTR, groupId); } finally { rm.done(); } } }); return; }
Source:
public static String restoreLocale(String username) { String currentLocale = null; if (StringUtils.isNotBlank(username)) { PreparedStatement statement = null; Connection connection = null; ResultSet results = null; try { connection = DatabaseUpdater.getConnection(); Integer userId = getUserIdByName(username, connection); if (userId != null) { String select = "select property_value from user_property where user_id = ? and property = ?"; statement = connection.prepareStatement(select); statement.setInt(1, userId); statement.setString(2, OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE); if (statement.execute()) { results = statement.getResultSet(); if (results.next()) { currentLocale = results.getString(1); } } } if (currentLocale == null) { currentLocale = readSystemDefaultLocale(connection); } } catch (Exception e) { log.error("Error while retriving locale property", e); } finally { try { if (statement != null) { statement.close(); } } catch (SQLException e) { log.warn("Error while closing statement"); } if (connection != null) { try { connection.close(); } catch (SQLException e) { log.debug(DATABASE_CLOSING_ERROR, e); } } if (results != null) { try { results.close(); } catch (SQLException e) { log.warn("Error while closing ResultSet"); } } } } if (currentLocale == null) { currentLocale = OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE; } return currentLocale; }

Target:
public static String restoreLocale(String username) { String currentLocale = null; if (StringUtils.isNotBlank(username)) { PreparedStatement statement = null; Connection connection = null; ResultSet results = null; try { connection = DatabaseUpdater.getConnection(); Integer userId = getUserIdByName(username, connection); if (userId != null) { String select = "select property_value from user_property where user_id = ? and property = ?"; statement = connection.prepareStatement(select); statement.setInt(1, userId); statement.setString(2, OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE); if (statement.execute()) { results = statement.getResultSet(); if (results.next()) { currentLocale = results.getString(1); } } } if (currentLocale == null) { currentLocale = readSystemDefaultLocale(connection); } } catch (Exception e) { log.error("Error while retriving locale property", e); } finally { try { if (statement != null) { statement.close(); } } catch (SQLException e) { log.warn("Error while closing statement"); } if (connection != null) { try { connection.close(); } catch (SQLException e) { log.debug(DATABASE_CLOSING_ERROR, e); } } if (results != null) { try { results.close(); } catch (SQLException e) { log.warn("Error while closing ResultSet", e); } } } } if (currentLocale == null) { currentLocale = OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE; } return currentLocale; }
Source:
private static PrintStream createOutputStream(String testScenarioName) { try { String reportName = "report-" + testScenarioName + "-" + DateFormatUtils.format( new Date(), "yyyy-MM-dd-HH:mm" ) + ".txt"; final OutputStream std = System.out; final OutputStream file = new PrintStream( reportName ); final OutputStream stream = new OutputStream() { @Override public void write(int b) throws IOException { std.write( b ); file.write( b ); } @Override public void flush() throws IOException { std.flush(); file.flush(); } @Override public void close() throws IOException { file.close(); } }; PrintStream ps = new PrintStream( stream ); return ps; } catch (FileNotFoundException e) { throw new RuntimeException( e ); } }

Target:
private static PrintStream createOutputStream(String testScenarioName) { try { File targetDir = getTargetDir(); File reportFile = new File( targetDir, "report-" + testScenarioName + "-" + DateFormatUtils.format( new Date(), "yyyy-MM-dd-HH'h'mm'm'" ) + ".txt" ); final OutputStream std = System.out; final OutputStream file = new PrintStream( reportFile ); final OutputStream stream = new OutputStream() { @Override public void write(int b) throws IOException { std.write( b ); file.write( b ); } @Override public void flush() throws IOException { std.flush(); file.flush(); } @Override public void close() throws IOException { file.close(); } }; PrintStream ps = new PrintStream( stream ); return ps; } catch (FileNotFoundException e) { throw new RuntimeException( e ); } }
Source:
private Partition selectPreferredPartition(List<Partition> partitions) { Partition preferredPartition = null; for (Partition p : partitions) { if (preferredPartition == null) { preferredPartition = p; } else if (preferredPartition.senders.size() < p.senders.size()) { preferredPartition = p; } else if (preferredPartition.senders.size() == p.senders.size() && preferredPartition.actualMembers.size() < p.actualMembers.size()) { preferredPartition = p; } else if (preferredPartition.topology.getTopologyId() < p.topology.getTopologyId()) { preferredPartition = p; } } assert preferredPartition != null; return preferredPartition; }

Target:
private Partition selectPreferredPartition(List<Partition> partitions) { Partition preferredPartition = null; for (Partition p : partitions) { if (p.isPreferable(preferredPartition)) { preferredPartition = p; } } assert preferredPartition != null; return preferredPartition; }
Source:
private void updateCase(Case caseForBlock, String caseId) throws InvalidStructureException, IOException, XmlPullParserException { while (nextTagInBlock("update")) { String key = parser.getName(); String value = parser.nextText().trim(); switch (key) { case "case_type": caseForBlock.setTypeId(value); break; case "case_name": caseForBlock.setName(value); break; case "date_opened": caseForBlock.setDateOpened(DateUtils.parseDate(value)); break; case "owner_id": String oldUserId = caseForBlock.getUserId(); if (oldUserId == null) { throw InvalidStructureException.readableInvalidStructureException("The case_id field of a <case> was found null", parser); } if (!oldUserId.equals(value)) { onIndexDisrupted(caseId); } caseForBlock.setUserId(value); break; case "external_id": caseForBlock.setExternalId(value); break; default: caseForBlock.setProperty(key, value); break; } } }

Target:
private void updateCase(Case caseForBlock, String caseId) throws InvalidStructureException, IOException, XmlPullParserException { while (nextTagInBlock("update")) { String key = parser.getName(); String value = parser.nextText().trim(); switch (key) { case "case_type": caseForBlock.setTypeId(value); break; case "case_name": caseForBlock.setName(value); break; case "date_opened": caseForBlock.setDateOpened(DateUtils.parseDate(value)); break; case "owner_id": String oldUserId = caseForBlock.getUserId(); if (!oldUserId.equals(value)) { onIndexDisrupted(caseId); } caseForBlock.setUserId(value); break; case "external_id": caseForBlock.setExternalId(value); break; default: caseForBlock.setProperty(key, value); break; } } }
Source:
private String processDatastreamPositionRequest(URI request) { _logger.debug("Processing datastream position request: {}", request); boolean hasParams = request.getQuery() != null; DatastreamPositionResponse response = _runningTasks.values() .stream() .map(AbstractKafkaBasedConnectorTask::getPositionResponse) .reduce(DatastreamPositionResponse::merge) .orElse(new DatastreamPositionResponse()); _logger.debug("Unfiltered datastream position response: {}", response); if (hasParams) { Optional<String> datastreamName = URLEncodedUtils.parse(request.getQuery(), Charset.defaultCharset()) .stream() .filter(pair -> DATASTREAM_KEY.equalsIgnoreCase(pair.getName())) .map(NameValuePair::getValue) .findFirst(); datastreamName.ifPresent(name -> response.retainAll(Collections.singleton(name))); Optional<String> topicName = URLEncodedUtils.parse(request.getQuery(), Charset.defaultCharset()) .stream() .filter(pair -> TOPIC_KEY.equalsIgnoreCase(pair.getName())) .map(NameValuePair::getValue) .findFirst(); if (topicName.isPresent()) { for (PhysicalSources sources : response.getDatastreamToPhysicalSources().values()) { Map<String, PhysicalSourcePosition> positions = sources.getPhysicalSourceToPosition(); for (String position : positions.keySet()) { if (!position.matches("^" + topicName.get() + "-\\d+$")) { positions.remove(position); } } } } } _logger.debug("Filtered datastream position response: {}", response); return DatastreamPositionResponse.toJson(response); }

Target:
private String processDatastreamPositionRequest(URI request) { _logger.debug("Processing datastream position request: {}", request); DatastreamPositionResponse response = _runningTasks.values() .stream() .map(AbstractKafkaBasedConnectorTask::getPositionResponse) .reduce(DatastreamPositionResponse::merge) .orElse(new DatastreamPositionResponse()); _logger.debug("Unfiltered datastream position response: {}", response); extractQueryParam(request, DATASTREAM_KEY).ifPresent(name -> response.retainAll(Collections.singleton(name))); extractQueryParam(request, TOPIC_KEY).ifPresent(topic -> { for (PhysicalSources sources : response.getDatastreamToPhysicalSources().values()) { Map<String, PhysicalSourcePosition> positions = sources.getPhysicalSourceToPosition(); for (String position : positions.keySet()) { if (!position.matches("^" + topic + "-\\d+$")) { positions.remove(position); } } } }); _logger.debug("Filtered datastream position response: {}", response); return DatastreamPositionResponse.toJson(response); }