auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private AllowUpdate isUpdateFromClientAllowedByFilter(StateNode node, String key, boolean log) { if (node.hasFeature(ElementPropertyMap.class)) { ElementPropertyMap propertyMap = node .getFeature(ElementPropertyMap.class); if (propertyMap.updateFromClientFilter != null) { boolean allow = propertyMap.updateFromClientFilter.test(key); if (!allow && log) { getLogger().warn("Ignoring model update for {}. " + "For security reasons, the property must have a " + "two-way binding in the template, be annotated with @{} in the model, or be defined as synchronized.", <START> key, ALLOW_CLIENT_UPDATES_POLYMER); <END> } return allow ? AllowUpdate.EXPLICITLY_ALLOW : AllowUpdate.EXPLICITLY_DISALLOW; } } StateNode parent = node.getParent(); if (parent == null) { return AllowUpdate.NO_EXPLICIT_STATUS; } if (parent.hasFeature(ElementPropertyMap.class)) { ElementPropertyMap parentMap = parent .getFeature(ElementPropertyMap.class); Optional<String> parentProperty = parentMap.getPropertyNames() .filter(property -> node.equals(parentMap.get(property))) .findFirst(); if (parentProperty.isPresent()) { String property = new StringBuilder(parentProperty.get()) .append('.').append(key).toString(); return isUpdateFromClientAllowedByFilter(parent, property, log); } } if (parent.hasFeature(ModelList.class)) { ModelList list = parent.getFeature(ModelList.class); if (list.contains(node)) { return isUpdateFromClientAllowedByFilter(parent, key, log); } } return AllowUpdate.NO_EXPLICIT_STATUS; }</code><technical_language>I add message instead of static final variable is</technical_language>

Target:
private AllowUpdate isUpdateFromClientAllowedByFilter(StateNode node, String key, boolean log) { if (node.hasFeature(ElementPropertyMap.class)) { ElementPropertyMap propertyMap = node .getFeature(ElementPropertyMap.class); if (propertyMap.updateFromClientFilter != null) { boolean allow = propertyMap.updateFromClientFilter.test(key); if (!allow && log) { getLogger().warn("Ignoring model update for {}. " + "For security reasons, the property must have a " + "two-way binding in the template, be annotated" + " with @AllowClientUpdates in the model, or be defined as synchronized.", key); } return allow ? AllowUpdate.EXPLICITLY_ALLOW : AllowUpdate.EXPLICITLY_DISALLOW; } } StateNode parent = node.getParent(); if (parent == null) { return AllowUpdate.NO_EXPLICIT_STATUS; } if (parent.hasFeature(ElementPropertyMap.class)) { ElementPropertyMap parentMap = parent .getFeature(ElementPropertyMap.class); Optional<String> parentProperty = parentMap.getPropertyNames() .filter(property -> node.equals(parentMap.get(property))) .findFirst(); if (parentProperty.isPresent()) { String property = new StringBuilder(parentProperty.get()) .append('.').append(key).toString(); return isUpdateFromClientAllowedByFilter(parent, property, log); } } if (parent.hasFeature(ModelList.class)) { ModelList list = parent.getFeature(ModelList.class); if (list.contains(node)) { return isUpdateFromClientAllowedByFilter(parent, key, log); } } return AllowUpdate.NO_EXPLICIT_STATUS; }
Source:
<code>private Object createLogMessage(Message<?> message) { <START> Assert.notNull(this.expression, "'expression' must not be null"); <END> Assert.notNull(this.evaluationContext, "'evaluationContext' must not be null"); Object logMessage = this.expression.getValue(this.evaluationContext, message); return logMessage instanceof Throwable ? createLogMessage((Throwable) logMessage) : logMessage; }</code><technical_language>This is fine initialization, sounds strange runtime. notNull() throws IllegalArgumentException reflect reality for current message. Assert.state(), is IllegalStateException handling message. OTOH I changed mind decided this code more review: private volatile Expression expression = EXPRESSION_PARSER.parseExpression("payload"); ... private volatile EvaluationContext evaluationContext = ExpressionUtils.createStandardEvaluationContext(); This Spring Context aware, lets do asserts all. a change reinstates previous behavior. next 4.3.5 upgrade issue :smile:</technical_language>

Target:
private Object createLogMessage(Message<?> message) { Object logMessage = this.expression.getValue(this.evaluationContext, message); return logMessage instanceof Throwable ? createLogMessage((Throwable) logMessage) : logMessage; }
Source:
<code>public void setRouteOverlay(int lineOverlayColor, ObaShape[] shapes, boolean clear) { if (mMap != null) { <START> if (clear) <END> mLineOverlay.clear(); PolylineOptions lineOptions; int totalPoints = 0; for (ObaShape s : shapes) { lineOptions = new PolylineOptions(); lineOptions.color(lineOverlayColor); for (Location l : s.getPoints()) { lineOptions.add(MapHelpV2.makeLatLng(l)); } mLineOverlay.add(mMap.addPolyline(lineOptions)); totalPoints += lineOptions.getPoints().size(); } Log.d(TAG, "Total points for route polylines = " + totalPoints); } }</code><technical_language>Please brackets { for IF statements, if a one-liner</technical_language>

Target:
public void setRouteOverlay(int lineOverlayColor, ObaShape[] shapes, boolean clear) { if (mMap != null) { if (clear) { mLineOverlay.clear(); } PolylineOptions lineOptions; int totalPoints = 0; for (ObaShape s : shapes) { lineOptions = new PolylineOptions(); lineOptions.color(lineOverlayColor); for (Location l : s.getPoints()) { lineOptions.add(MapHelpV2.makeLatLng(l)); } mLineOverlay.add(mMap.addPolyline(lineOptions)); totalPoints += lineOptions.getPoints().size(); } Log.d(TAG, "Total points for route polylines = " + totalPoints); } }
Source:
<code><START> private static String toString(InputStream inputStream) throws IOException { <END> final int bufferSize = 1024; final char[] buffer = new char[bufferSize]; final StringBuilder out = new StringBuilder(); Reader in = new InputStreamReader(inputStream, "UTF-8"); for (; ; ) { int rsz = in.read(buffer, 0, buffer.length); if (rsz < 0){ break; } out.append(buffer, 0, rsz); } return out.toString(); }</code><technical_language>baffled a useful method is in JDK I/O API</technical_language>

Target:
private static String toString(InputStream inputStream) throws IOException { char[] buffer = new char[1024]; StringBuilder out = new StringBuilder(); Reader in = new InputStreamReader(inputStream, UTF_8); for (int rsz; (rsz = in.read(buffer, 0, buffer.length)) >= 0;) { out.append(buffer, 0, rsz); } return out.toString(); }
Source:
<code>public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((LVER == null) ? 0 : LVER.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((comment == null) ? 0 : comment.hashCode()); result = prime * result + ((compatibilityVersion == null) ? 0 : compatibilityVersion.hashCode()); result = prime * result + masterDomainVersion; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((recovery_mode == null) ? 0 : recovery_mode.hashCode()); result = prime * result + ((spmVdsId == null) ? 0 : spmVdsId.hashCode()); <START> result = prime * result + ((status == null) ? 0 : status.hashCode()); <END> result = prime * result + ((storagePoolFormatType == null) ? 0 : storagePoolFormatType.hashCode()); result = prime * result + ((quotaEnforcementType == null) ? 0 : quotaEnforcementType.hashCode()); return result; }</code><technical_language>consider isLocal property too</technical_language>

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((LVER == null) ? 0 : LVER.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((comment == null) ? 0 : comment.hashCode()); result = prime * result + ((compatibilityVersion == null) ? 0 : compatibilityVersion.hashCode()); result = prime * result + masterDomainVersion; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((recovery_mode == null) ? 0 : recovery_mode.hashCode()); result = prime * result + ((spmVdsId == null) ? 0 : spmVdsId.hashCode()); result = prime * result + ((status == null) ? 0 : status.hashCode()); result = prime * result + (isLocal ? 1231 : 1237); result = prime * result + ((storagePoolFormatType == null) ? 0 : storagePoolFormatType.hashCode()); result = prime * result + ((quotaEnforcementType == null) ? 0 : quotaEnforcementType.hashCode()); return result; }
Source:
<code>public Color getBackground(Object element, int columnIndex) { String legendItemText = (String) element; if (legendItemText.equals("Population > 1,000,000")) { <START> return Display.getCurrent().getSystemColor(SWT.COLOR_RED); <END> } else if (legendItemText.equals("Population > 500,000")) { return Display.getCurrent().getSystemColor(SWT.COLOR_GRAY); } else if (legendItemText.equals("Population > 250,000")) { return Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW); } else if (legendItemText.equals("Population > 50,000")) { return Display.getCurrent().getSystemColor(SWT.COLOR_BLUE); } else if (legendItemText.equals("Population > 25,000")) { return Display.getCurrent().getSystemColor(SWT.COLOR_GREEN); } else if (legendItemText.equals("Population > 5000")) { return Display.getCurrent().getSystemColor(SWT.COLOR_CYAN); } else if (legendItemText.equals("Population <= 5000")) { return Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); } return null; }</code><technical_language>I this reads better, if extract Display.getCurrent() a local variable this block</technical_language>

Target:
public Color getBackground(Object element, int columnIndex) { String legendItemText = (String) element; Display display = Display.getCurrent(); if (legendItemText.equals("Population > 1,000,000")) { return display.getSystemColor(SWT.COLOR_RED); } else if (legendItemText.equals("Population > 500,000")) { return display.getSystemColor(SWT.COLOR_GRAY); } else if (legendItemText.equals("Population > 250,000")) { return display.getSystemColor(SWT.COLOR_YELLOW); } else if (legendItemText.equals("Population > 50,000")) { return display.getSystemColor(SWT.COLOR_BLUE); } else if (legendItemText.equals("Population > 25,000")) { return display.getSystemColor(SWT.COLOR_GREEN); } else if (legendItemText.equals("Population > 5000")) { return display.getSystemColor(SWT.COLOR_CYAN); } else if (legendItemText.equals("Population <= 5000")) { return display.getSystemColor(SWT.COLOR_WHITE); } return null; }
Source:
<code>public <E> CacheQuery<E> buildLuceneQuery(IckleParsingResult<TypeMetadata> ickleParsingResult, Map<String, Object> namedParameters, long startOffset, int maxResults, IndexedQueryMode queryMode) { CacheQuery<E> cacheQuery = (CacheQuery<E>) makeCacheQuery(ickleParsingResult, queryMode, namedParameters); if (startOffset >= 0) { cacheQuery = cacheQuery.firstResult((int) startOffset); } if (maxResults > 0) { cacheQuery = cacheQuery.maxResults(maxResults); <START> } <END> return cacheQuery; }</code><technical_language>This do HSEARCH-3896. SearchQuery instances concurrently, put in a cache. I need restore intermediary object similar LuceneQueryParsingResult, hold a SearchPredicate/SearchSort/SearchProjection/etc. safely reused concurrently cached. include SearchScope object in parsing result, scope safely concurrently. finally need create search query</technical_language>

Target:
public <E> IndexedQuery<E> buildLuceneQuery(IckleParsingResult<TypeMetadata> ickleParsingResult, Map<String, Object> namedParameters, long startOffset, int maxResults, IndexedQueryMode queryMode) { if (log.isDebugEnabled()) { log.debugf("Building Lucene query for : %s", ickleParsingResult.getQueryString()); } if (!isIndexed) { throw CONTAINER.cannotRunLuceneQueriesIfNotIndexed(cache.getName()); } SearchQueryBuilder searchQuery = transformParsingResult(ickleParsingResult, namedParameters); if (queryMode == null) queryMode = detectQueryMode(); IndexedQuery<?> cacheQuery = makeCacheQuery(ickleParsingResult, searchQuery, queryMode, namedParameters); if (startOffset >= 0) { cacheQuery = (IndexedQuery<?>) cacheQuery.firstResult((int) startOffset); } if (maxResults > 0) { cacheQuery = (IndexedQuery<?>) cacheQuery.maxResults(maxResults); } return (IndexedQuery<E>) cacheQuery; }
Source:
<code>public void notifyAllLifespansFinishedExecution() { checkState(groupedExecution); state = State.FINISHED; splitSource.close(); <START> whenFinishedOrNewLifespanAdded.set(null); <END> }</code><technical_language>"finished" in whenFinishedOrNewLifespanAdded? scheduling finished for ungrouped execution execution finished for grouped execution</technical_language>

Target:
public synchronized void notifyAllLifespansFinishedExecution() { checkState(groupedExecution); state = State.FINISHED; splitSource.close(); whenFinishedOrNewLifespanAdded.set(null); }
Source:
<code><START> public Object getEvent(){ <END> return event; }</code><technical_language>typed</technical_language>

Target:
public SCMEvent getEvent(){ return event; }
Source:
<code>public final long doLong(final long receiver, final long right) { assert right >= 0; if (Long.SIZE - Long.numberOfLeadingZeros(receiver) + right > Long.SIZE - 1) { <START> CompilerDirectives.transferToInterpreter(); <END> throw new ArithmeticException("shift overflows long"); } return receiver << right; }</code><technical_language>this need this?: suggestion CompilerDirectives.transferToInterpreterAndInvalidate(); understanding is code properly invalidated done compiled code interpreter. If I remember correctly, @chumer mentioned a long time ago</technical_language>

Target:
public final long doLong(final long receiver, final long right) { assert right >= 0; if (Long.SIZE - Long.numberOfLeadingZeros(receiver) + right > Long.SIZE - 1) { CompilerDirectives.transferToInterpreterAndInvalidate(); throw new ArithmeticException("shift overflows long"); } return receiver << right; }
Source:
<code>private void addMarkers() { Icon lightningBoltIcon = IconFactory.getInstance(MatrixApiActivity.this) .fromResource(R.drawable.lightning_bolt); <START> for (com.mapbox.geojson.Feature feature : featureCollection.features()) { <END> mapboxMap.addMarker(new MarkerOptions() .position(new LatLng(feature.getProperty("Latitude").getAsDouble(), feature.getProperty("Longitude").getAsDouble())) .snippet(feature.getStringProperty("Station_Name")) .icon(lightningBoltIcon)); } }</code><technical_language>reason this is full namespace here</technical_language>

Target:
private void addMarkers() { Icon lightningBoltIcon = IconFactory.getInstance(MatrixApiActivity.this) .fromResource(R.drawable.lightning_bolt); for (Feature feature : featureCollection.features()) { mapboxMap.addMarker(new MarkerOptions() .position(new LatLng(feature.getProperty("Latitude").getAsDouble(), feature.getProperty("Longitude").getAsDouble())) .snippet(feature.getStringProperty("Station_Name")) .icon(lightningBoltIcon)); } }
Source:
<code>private List<SimpleInterval> prepareTargetSegments(final Genome genome, final List<ModeledSegment> targetSegmentsWithCalls) { <START> final List<SimpleInterval> targetSegmentsUnfixed; <END> if (!useAllCopyRatioSegments) { logger.info("Merging copy-neutral and uncalled target-coverage segments..."); targetSegmentsUnfixed = SegmentMergeUtils.mergeNeutralSegments(targetSegmentsWithCalls); logger.info("Number of segments after copy-neutral merging: " + targetSegmentsUnfixed.size()); } else { targetSegmentsUnfixed = targetSegmentsWithCalls.stream().map(ModeledSegment::getSimpleInterval) .collect(Collectors.toList()); } return SegmentUtils.fixTargetSegmentStarts(targetSegmentsUnfixed, genome.getTargets()); }</code><technical_language>If do long a variable name, try capture needs fixed targetSegmentsWithUnfixedBreakpoints</technical_language>

Target:
private List<SimpleInterval> prepareTargetSegments(final Genome genome, final List<ModeledSegment> targetSegmentsWithCalls) { final List<SimpleInterval> targetSegmentsWithUnfixedStarts; if (!useAllCopyRatioSegments) { logger.info("Merging copy-neutral and uncalled target-coverage segments..."); targetSegmentsWithUnfixedStarts = SegmentMergeUtils.mergeNeutralSegments(targetSegmentsWithCalls); logger.info("Number of segments after copy-neutral merging: " + targetSegmentsWithUnfixedStarts.size()); } else { targetSegmentsWithUnfixedStarts = targetSegmentsWithCalls.stream().map(ModeledSegment::getSimpleInterval) .collect(Collectors.toList()); } return SegmentUtils.fixTargetSegmentStarts(targetSegmentsWithUnfixedStarts, genome.getTargets()); }
Source:
<code>private void turnTheRadioOn(Thing radioThing) { radioHandler.handleCommand(radioThing.getChannel(FSInternetRadioBindingConstants.CHANNEL_POWER).getUID(), OnOffType.ON); FrontierSiliconRadio radio; try { Field f = radioHandler.getClass().getDeclaredField("radio"); f.setAccessible(true); <START> radio = (FrontierSiliconRadio) f.get(radioHandler); <END> } catch (IllegalStateException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) { throw new IllegalStateException("Cannot access radio per reflection.", ex); } waitForAssert(() -> { try { assertThat("The radio was not turned on successfully", radio.getPower(), is(true)); } catch (IOException ex) { throw new AssertionError("I/O error", ex); } }); }</code><technical_language>here, of - this is more meant a mental note for us: hassle-free private field access is worth a utility method in base class</technical_language>

Target:
private void turnTheRadioOn(Thing radioThing) { radioHandler.handleCommand(radioThing.getChannel(FSInternetRadioBindingConstants.CHANNEL_POWER).getUID(), OnOffType.ON); final FrontierSiliconRadio radio = HandlerUtils.getRadio(radioHandler); waitForAssert(() -> { try { assertTrue(radio.getPower()); } catch (IOException ex) { throw new AssertionError("I/O error", ex); } }); }
Source:
<code>@Override public void changeKey(@Nullable State outgoingState, State incomingState, Flow.Direction direction, Context incomingStateContext, Flow.TraversalCallback callback) { if (textView == null) { textView = new TextView(activity); textView.setGravity(Gravity.CENTER); } textView.setText(incomingState.getKey().toString()); <START> activity.setContentView(textView); <END> callback.onTraversalCompleted(); }</code><technical_language>Weird calling setContentView again</technical_language>

Target:
@Override public void changeKey(@Nullable State outgoingState, State incomingState, Flow.Direction direction, Context incomingStateContext, Flow.TraversalCallback callback) { if (textView == null) { textView = new TextView(activity); textView.setGravity(Gravity.CENTER); activity.setContentView(textView); } textView.setText(incomingState.getKey().toString()); callback.onTraversalCompleted(); }
Source:
<code>public void testIsComplexNestedExpression() { <START> assertTrue(!isComplexTemplate("${a:${b:c}}")); <END> }</code><technical_language>assertFalse</technical_language>

Target:
public void testIsComplexNestedExpression() { assertFalse(isComplexTemplate("${a:${b:c}}")); }
Source:
<code>public void run(@Nonnull JSession session) throws Exception { OutputJackLibrary ojl = session.getJackOutputLibrary(); List<Meta> metas = session.getMetas(); for (Meta meta : metas) { addMetaToOutputJackLib(meta, ojl); } List<InputLibrary> importedLibraries = session.getImportedLibraries(); for (InputLibrary importedLibrary : importedLibraries) { if (importedLibrary.containsFileType(FileType.JPP)) { Iterator<InputVFile> jppIter = importedLibrary.iterator(FileType.JPP); while (jppIter.hasNext()) { InputVFile jppFile = jppIter.next(); Location loc = jppFile.getLocation(); String name; if (loc instanceof ZipLocation) { name = ((ZipLocation) jppFile.getLocation()).getEntryName(); <START> if (importedLibrary.getMajorVersion() != 0) { <END> name = name.substring( FileType.JPP.getVPathPrefix().split().iterator().next().length() + 1); } } else { name = ((FileLocation) jppFile.getLocation()).getPath(); if (importedLibrary.getMajorVersion() != 0) { String prefix = FileType.JPP.getVPathPrefix().split().iterator().next() + '/'; name = name.substring(name.lastIndexOf(prefix) + prefix.length()); } } Meta meta = new Meta(new VPath(name, '/'), jppFile); addMetaToOutputJackLib(meta, ojl); } } } }</code><technical_language>Strange, discuss</technical_language>

Target:
public void run(@Nonnull JSession session) throws Exception { OutputJackLibrary ojl = session.getJackOutputLibrary(); List<Meta> metas = session.getMetas(); for (Meta meta : metas) { addMetaToOutputJackLib(meta, ojl); } List<InputLibrary> importedLibraries = session.getImportedLibraries(); for (InputLibrary importedLibrary : importedLibraries) { if (importedLibrary.containsFileType(FileType.JPP)) { Iterator<InputVFile> jppIter = importedLibrary.iterator(FileType.JPP); while (jppIter.hasNext()) { InputVFile jppFile = jppIter.next(); String name = getNameFromInputVFile(importedLibrary, jppFile); Meta meta = new Meta(new VPath(name, '/'), jppFile); addMetaToOutputJackLib(meta, ojl); } } } }
Source:
<code>static public String updateScriptFile(String line) { String newFile = ""; newFile += "# newFile += "csarRoot=$(find ~ -maxdepth 1 -path \"*.csar\");"; newFile += "\n"; newFile += "IFS=';' read -ra NAMES <<< \"$DAs\";"; newFile += "\n"; newFile += "for i in \"${NAMES[@]}\"; do"; newFile += "\n"; newFile += " IFS=',' read -ra PATH <<< \"$i\"; "; newFile += "\n"; newFile += " dirName=$(/usr/bin/sudo /usr/bin/dirname $csarRoot${PATH[1]})"; newFile += "\n"; newFile += " baseName=$(/usr/bin/sudo /usr/bin/basename $csarRoot${PATH[1]})"; <START> newFile += "\n"; <END> newFile += " filename=\"${baseName%.*}\""; newFile += "\n"; newFile += " if [[ \"${PATH[1]}\" == *.tar ]];"; newFile += "\n"; newFile += " then"; newFile += "\n"; newFile += " cd $dirName"; newFile += "\n"; newFile += " /usr/bin/sudo mkdir -p $filename"; newFile += "\n"; newFile += " /bin/tar -xvzf $baseName -C $filename"; newFile += "\n"; newFile += " fi"; newFile += "\n"; newFile += "done"; newFile += "\n"; newFile += "export DEBIAN_FRONTEND=noninteractive"; newFile += "\n"; newFile += "/usr/bin/sudo -E /usr/bin/dpkg -i -R -E -B $filename"; newFile += "\n"; return newFile; }</code><technical_language>remove "\n"s 211, 213, 215, 217, 221,223, 225, 227, 229, 231, 237</technical_language>

Target:
static public String updateScriptFile(String line) { return "# "csarRoot=$(find ~ -maxdepth 1 -path \"*.csar\");" + "\n" + "IFS=';' read -ra NAMES <<< \"$DAs\";" + "\n" + "for i in \"${NAMES[@]}\"; do" + "\n" + " IFS=',' read -ra PATH <<< \"$i\"; " + "\n" + " dirName=$(/usr/bin/sudo /usr/bin/dirname $csarRoot${PATH[1]})" + "\n" + " baseName=$(/usr/bin/sudo /usr/bin/basename $csarRoot${PATH[1]})" + "\n" + " filename=\"${baseName%.*}\"" + "\n" + " if [[ \"${PATH[1]}\" == *.tar ]];" + "\n" + " then" + "\n" + " cd $dirName" + "\n" + " /usr/bin/sudo mkdir -p $filename" + "\n" + " /bin/tar -xvzf $baseName -C $filename" + "\n" + " fi" + "\n" + "done" + "\n" + "export DEBIAN_FRONTEND=noninteractive" + "\n" + "/usr/bin/sudo -E /usr/bin/dpkg -i -R -E -B $filename"; }
Source:
<code>public void responseListener() throws Exception { HTTP2Client http2Client = new HTTP2Client(); http2Client.start(); SocketAddress serverAddress = new InetSocketAddress("localhost", 8080); CompletableFuture<Session> sessionCF = http2Client.connect(serverAddress, new Session.Listener.Adapter()); Session session = sessionCF.get(); <START> HttpFields.Mutable requestHeaders = HttpFields.build() <END> .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {version}"); MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); HeadersFrame headersFrame = new HeadersFrame(request, null, true); session.newStream(headersFrame, new Stream.Listener.Adapter() { @Override public void onHeaders(Stream stream, HeadersFrame frame) { MetaData metaData = frame.getMetaData(); if (metaData.isResponse()) { MetaData.Response response = (MetaData.Response)metaData; System.getLogger("http2").log(INFO, "Received response {0}", response); } else { System.getLogger("http2").log(INFO, "Received trailers {0}", metaData.getFields()); } } @Override public void onData(Stream stream, DataFrame frame, Callback callback) { ByteBuffer buffer = frame.getData(); System.getLogger("http2").log(INFO, "Consuming buffer {0}", buffer); callback.succeeded(); } }); }</code><technical_language>Remove .Mutable</technical_language>

Target:
public void responseListener() throws Exception { HTTP2Client http2Client = new HTTP2Client(); http2Client.start(); SocketAddress serverAddress = new InetSocketAddress("localhost", 8080); CompletableFuture<Session> sessionCF = http2Client.connect(serverAddress, new Session.Listener.Adapter()); Session session = sessionCF.get(); HttpFields requestHeaders = HttpFields.build() .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {version}"); MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); HeadersFrame headersFrame = new HeadersFrame(request, null, true); session.newStream(headersFrame, new Stream.Listener.Adapter() { @Override public void onHeaders(Stream stream, HeadersFrame frame) { MetaData metaData = frame.getMetaData(); if (metaData.isResponse()) { MetaData.Response response = (MetaData.Response)metaData; System.getLogger("http2").log(INFO, "Received response {0}", response); } else { System.getLogger("http2").log(INFO, "Received trailers {0}", metaData.getFields()); } } @Override public void onData(Stream stream, DataFrame frame, Callback callback) { ByteBuffer buffer = frame.getData(); System.getLogger("http2").log(INFO, "Consuming buffer {0}", buffer); callback.succeeded(); } }); }
Source:
<code>private void probeCallBack(Probe probe, boolean success) { LOG.debug("Probe datanode: result: {}, type: {}", probe.getDatanodeInfo(), success, probe.getType()); probeInProg.remove(probe.getDatanodeInfo().getDatanodeUuid()); if (success) { if (probe.getType() == ProbeType.CHECK_DEAD) { LOG.info("Remove the node out from dead node list: {}.", probe.getDatanodeInfo()); removeDeadNode(probe.getDatanodeInfo()); } else if (probe.getType() == ProbeType.CHECK_SUSPECT) { <START> LOG.info("Remove the node out from suspect node list: {}.", <END> probe.getDatanodeInfo()); removeNodeFromDeadNodeDetector(probe.getDatanodeInfo()); } } else { if (probe.getType() == ProbeType.CHECK_SUSPECT) { LOG.warn("Probe failed, add suspect node to dead node list: {}.", probe.getDatanodeInfo()); addToDead(probe.getDatanodeInfo()); } } }</code><technical_language>a lot of stale relicas, supsect nodes dead nodes. nodes print this log. is purpose of printing this log? client access suspect node</technical_language>

Target:
private void probeCallBack(Probe probe, boolean success) { LOG.debug("Probe datanode: result: {}, type: {}", probe.getDatanodeInfo(), success, probe.getType()); probeInProg.remove(probe.getDatanodeInfo().getDatanodeUuid()); if (success) { if (probe.getType() == ProbeType.CHECK_DEAD) { LOG.info("Remove the node out from dead node list: {}.", probe.getDatanodeInfo()); removeDeadNode(probe.getDatanodeInfo()); } else if (probe.getType() == ProbeType.CHECK_SUSPECT) { LOG.debug("Remove the node out from suspect node list: {}.", probe.getDatanodeInfo()); removeNodeFromDeadNodeDetector(probe.getDatanodeInfo()); } } else { if (probe.getType() == ProbeType.CHECK_SUSPECT) { LOG.warn("Probe failed, add suspect node to dead node list: {}.", probe.getDatanodeInfo()); addToDead(probe.getDatanodeInfo()); } } }
Source:
<code>public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof HttpHost) { <START> final HttpHost that = (HttpHost) obj; <END> final String thisAddressValue = this.address==null ? this.lcHostname : this.address.getHostAddress().toLowerCase(Locale.ENGLISH); final String thatAddressValue = that.address==null ? that.lcHostname : that.address.getHostAddress().toLowerCase(Locale.ENGLISH); return this.lcHostname.equals(that.lcHostname) && this.port == that.port && this.schemeName.equals(that.schemeName) && thisAddressValue.equals(thatAddressValue); } else { return false; } }</code><technical_language>I fine adding another constructor, I prefer #hashCode #equals do a simple comparison instead of comparing some derived values. Oleg</technical_language>

Target:
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof HttpHost) { final HttpHost that = (HttpHost) obj; return this.lcHostname.equals(that.lcHostname) && this.port == that.port && this.schemeName.equals(that.schemeName) && (this.address==null ? that.address== null : this.address.equals(that.address)); } else { return false; } }
Source:
<code>public void getLatestDisplay_CurrentIsNull_DisplayUnchanged() { DisplaySafe safe = new DisplaySafe(null); DisplaySafe safeSpy = spy(safe); when(safeSpy.getCurrent()).thenReturn(null); <START> boolean nullDisplayExceptionThrown = false; <END> try { safeSpy.getLatestDisplay(); } catch (DisplaySafe.NullDisplayException nde) { nullDisplayExceptionThrown = true; } assertTrue(nullDisplayExceptionThrown); }</code><technical_language>Instead of a boolean, @Test(expected = DisplaySafe.NullDisplayException.class) a more universally accepted of testing exception is thrown</technical_language>

Target:
public void getLatestDisplay_CurrentIsNull_DisplayUnchanged() throws DisplaySafe.NullDisplayException { DisplaySafe safe = new DisplaySafe(null); DisplaySafe safeSpy = spy(safe); when(safeSpy.getCurrent()).thenReturn(null); safeSpy.getLatestDisplay(); }
Source:
<code>public static Bbox getBoundingBoxFromFgdcMetadata(String inMetadata) throws JAXBException, UnsupportedEncodingException{ Bbox bbox = new Bbox(); Metadata metadata = null; try { JAXBContext jaxbContext = JAXBContext.newInstance(Metadata.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); metadata = (Metadata) jaxbUnmarshaller.unmarshal(new ByteArrayInputStream(inMetadata.getBytes("UTF-8"))); } catch (JAXBException e) { <START> log.error("Unable to parse xml file. Has the schema changed? https:www.fgdc.gov/schemas/metadata/fgdc-std-001-1998-sect01.xsd :" + e.getMessage()); <END> throw e; } Idinfo idinfo = metadata.getIdinfo(); Spdom spdom = idinfo.getSpdom(); Bounding bounding = spdom.getBounding(); double minx = bounding.getWestbc(); double miny = bounding.getSouthbc(); double maxx = bounding.getEastbc(); double maxy = bounding.getNorthbc(); Bbox result = new Bbox(); result.setBbox(minx, miny, maxx, maxy); bbox.setBbox(minx, miny, maxx, maxy); return bbox; }</code><technical_language>https:www -> https://www</technical_language>

Target:
public static Bbox getBoundingBoxFromFgdcMetadata(String inMetadata) throws JAXBException, UnsupportedEncodingException{ Bbox bbox = new Bbox(); Metadata metadata = null; try { JAXBContext jaxbContext = JAXBContext.newInstance(Metadata.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); metadata = (Metadata) jaxbUnmarshaller.unmarshal(new ByteArrayInputStream(inMetadata.getBytes("UTF-8"))); } catch (JAXBException e) { log.error("Unable to parse xml file. Has the schema changed? <LINK_0> :" + e.getMessage()); throw e; } Idinfo idinfo = metadata.getIdinfo(); Spdom spdom = idinfo.getSpdom(); Bounding bounding = spdom.getBounding(); double minx = bounding.getWestbc(); double miny = bounding.getSouthbc(); double maxx = bounding.getEastbc(); double maxy = bounding.getNorthbc(); Bbox result = new Bbox(); result.setBbox(minx, miny, maxx, maxy); bbox.setBbox(minx, miny, maxx, maxy); return bbox; }
Source:
<code>public boolean apply(Game game, Ability source) { Player targetPlayer = game.getPlayer(source.getFirstTarget()); Player you = game.getPlayer(source.getControllerId()); if (targetPlayer == null || you == null) { return false; } int amountToDiscard = source.getManaCostsToPay().getX(); <START> TargetCard target = new TargetCardInHand(amountToDiscard, StaticFilters.FILTER_CARD_CARDS); <END> targetPlayer.discard(new CardsImpl(target.getTargets()), source, game); return true; }</code><technical_language>Missing notTarget choose call Outcome.Discard</technical_language>

Target:
public boolean apply(Game game, Ability source) { Player targetPlayer = game.getPlayer(source.getFirstTarget()); Player you = game.getPlayer(source.getControllerId()); if (targetPlayer == null || you == null) { return false; } int amountToDiscard = source.getManaCostsToPay().getX(); TargetCard target = new TargetCardInHand(amountToDiscard, StaticFilters.FILTER_CARD_CARDS); you.choose(outcome, targetPlayer.getHand(), target, game); targetPlayer.discard(new CardsImpl(target.getTargets()), source, game); return true; }
Source:
<code>protected ServiceIndex createServiceIndex() { Stack stack = context.objectManager.loadResource(Stack.class, service.getStackId()); String serviceIndex = ServiceDiscoveryUtil.getGeneratedServiceIndex(stack, service, launchConfigName, instanceName); ServiceIndex serviceIndexObj = context.serviceDao.createServiceIndex(service, launchConfigName, serviceIndex); if (DataAccessor.fieldBool(service, ServiceConstants.FIELD_SERVICE_RETAIN_IP)) { Object requestedIpObj = ServiceDiscoveryUtil.getLaunchConfigObject(service, launchConfigName, InstanceConstants.FIELD_REQUESTED_IP_ADDRESS); String requestedIp = null; if (requestedIpObj != null) { List<String> availableIPs = new ArrayList<>(); if (requestedIpObj instanceof List<?>) { for (Object item : (List<?>) requestedIpObj) { availableIPs.add(ObjectUtils.toString(item, null)); } } <START> List<String> usedIPs = context.serviceDao.getUsedIPsFromServiceIndexByServiceID(service); <END> for (String candidateIP: availableIPs) { if (usedIPs.isEmpty() || !usedIPs.contains(candidateIP)) { requestedIp = candidateIP; break; } } } else { Object labels = ServiceDiscoveryUtil.getLaunchConfigObject(service, launchConfigName, InstanceConstants.FIELD_LABELS); if (labels != null) { requestedIp = ((Map<String, String>) labels).get(SystemLabels.LABEL_REQUESTED_IP); } } context.sdService.allocateIpToServiceIndex(service, serviceIndexObj, requestedIp); } return serviceIndexObj; }</code><technical_language>reason validating IPs service? services of account? enough requested ip address standalone container. I recall, in ip allocation code below, pool manager return if ip address is allocated in subnet: <LINK_0> if prove pool manager validates duplicates for service requested ips, omit adding extra layer of validation in services code</technical_language>

Target:
protected ServiceIndex createServiceIndex() { Stack stack = context.objectManager.loadResource(Stack.class, service.getStackId()); String serviceIndex = ServiceDiscoveryUtil.getGeneratedServiceIndex(stack, service, launchConfigName, instanceName); ServiceIndex serviceIndexObj = context.serviceDao.createServiceIndex(service, launchConfigName, serviceIndex); if (DataAccessor.fieldBool(service, ServiceConstants.FIELD_SERVICE_RETAIN_IP)) { List<String> requestedIps = new ArrayList<>(); Object requestedIpObj = ServiceDiscoveryUtil .getLaunchConfigObject(service, launchConfigName, InstanceConstants.FIELD_REQUESTED_IP_ADDRESS); if (requestedIpObj != null && !StringUtils.isEmpty(requestedIpObj.toString())) { requestedIps.addAll(Arrays.asList(StringUtils.stripAll(StringUtils.split(requestedIpObj.toString(), ",")))); } else { Object labels = ServiceDiscoveryUtil.getLaunchConfigObject( service, launchConfigName, InstanceConstants.FIELD_LABELS); if (labels != null) { String requestedIp = ((Map<String, String>) labels) .get(SystemLabels.LABEL_REQUESTED_IP); if (!StringUtils.isEmpty(requestedIp)) { requestedIps.addAll(Arrays.asList(StringUtils.stripAll(StringUtils.split(requestedIp, ",")))); } } } context.sdService.allocateIpToServiceIndex(service, serviceIndexObj, requestedIps); } return serviceIndexObj; }
Source:
<code>public static List<Rule> compose(Collection<ExternalDependency> dependencies) { return dependencies .stream() <START> .sorted(ExternalDependency.compareByName) <END> .map( dependency -> { Rule rule = new HttpFile() .mavenCoords(dependency.getMavenCoords()) .sha256(DependencyUtils.sha256(dependency.getRealDependencyFile())) .name(dependency.getTargetName()); rule.name(dependency.getTargetName()); return rule; }) .collect(Collectors.toList()); }</code><technical_language>Is this sorting needed? I thought buck sorted internally templates sort cc @romanoid</technical_language>

Target:
public static List<Rule> compose(Collection<ExternalDependency> dependencies) { return dependencies .stream() .sorted(ExternalDependency.compareByName) .map( dependency -> { Rule rule = new HttpFile() .mavenCoords(dependency.getMavenCoords()) .sha256(DependencyUtils.shaSum256(dependency.getRealDependencyFile())) .name(dependency.getTargetName()); rule.name(dependency.getTargetName()); return rule; }) .collect(Collectors.toList()); }
Source:
<code>public void onFailedResponse(ReplicaId replicaId) { failedRequests.add(replicaId); <START> onReplicaResponse(replicaId); <END> }</code><technical_language>this base. is this copied</technical_language>

Target:
public void onFailedResponse(ReplicaId replicaId) { super.onFailedResponse(replicaId); onReplicaResponse(replicaId); }
Source:
<code>public void selectionChanged(SelectionChangedEvent event) { CounterChartViewer counterChartViewer = fCounterChartViewer; if (counterChartViewer == null) { return; } if (counterChartViewer.getTrace() == null) { return; } ISelection selection = event.getSelection(); if (selection instanceof IStructuredSelection) { Object entry = ((IStructuredSelection) selection).getFirstElement(); if (entry instanceof CounterTreeViewerEntry) { @NonNull Set<@NonNull Integer> quark = new TreeSet<>(); quark.add(((CounterTreeViewerEntry) entry).getQuark()); <START> TmfQuarkSignal <END> signal = new TmfQuarkSignal(this, quark); broadcast(signal); } } }</code><technical_language>tab</technical_language>

Target:
public void selectionChanged(SelectionChangedEvent event) { CounterChartViewer counterChartViewer = fCounterChartViewer; if (counterChartViewer == null) { return; } if (getTrace() == null) { return; } ISelection selection = event.getSelection(); if (selection instanceof IStructuredSelection) { Object entry = ((IStructuredSelection) selection).getFirstElement(); if (entry instanceof CounterTreeViewerEntry) { @NonNull Set<@NonNull Integer> quark = new TreeSet<>(); quark.add(((CounterTreeViewerEntry) entry).getQuark()); counterChartViewer.updateChart(quark); } } }
Source:
<code>public Integer parse(CharSequence text) throws ParseException { MatchResult match = RegExp.compile("^(\\d+)\\s*(\\w*)$").exec(text.toString().trim()); <START> MatchResult match_megabytes = <END> RegExp.compile("^(\\d+)\\s*(\\w*)$").exec(messages.megabytes("0")); if (match == null) { return 0; } String prefix = match.getGroup(1); String suffix = match.getGroup(2); String suffix_megabytes = match_megabytes != null ? match_megabytes.getGroup(2) : null; Integer size = null; try { size = Integer.parseInt(prefix); } catch (NumberFormatException e) { return 0; } if (suffix.equalsIgnoreCase("TB") || suffix.equalsIgnoreCase("T")) { return size * 1024 * 1024; } else if (suffix.equalsIgnoreCase("GB") || suffix.equalsIgnoreCase("G")) { return size * 1024; } else if (suffix.equalsIgnoreCase("MB") || suffix.equalsIgnoreCase("M") || suffix.equalsIgnoreCase(suffix_megabytes)) { return size; } else if (StringHelper.isNullOrEmpty(suffix)) { return size; } else { return 0; } }</code><technical_language>simpler add 'MB' constants CommonApplicationConstants.properties files, compare (instead of parsing message...)</technical_language>

Target:
public Integer parse(CharSequence text) throws ParseException { MatchResult match = RegExp.compile("^(\\d+)\\s*(\\w*)$").exec(text.toString().trim()); if (match == null) { return 0; } String prefix = match.getGroup(1); String suffix = match.getGroup(2); Integer size = null; try { size = Integer.parseInt(prefix); } catch (NumberFormatException e) { return 0; } if (suffix.equalsIgnoreCase("TB") || suffix.equalsIgnoreCase("T")) { return size * 1024 * 1024; } else if (suffix.equalsIgnoreCase("GB") || suffix.equalsIgnoreCase("G")) { return size * 1024; } else if (suffix.equalsIgnoreCase("MB") || suffix.equalsIgnoreCase("M") || suffix.equalsIgnoreCase(constant.mb())) { return size; } else if (StringHelper.isNullOrEmpty(suffix)) { return size; } else { return 0; } }
Source:
<code>public void sliceLengthIsToolarge() { expectedException.expect(IllegalArgumentException.class); <START> Series series = new Series("12345"); <END> List<List<Integer>> actual = series.slices(6); }</code><technical_language>check exception message if want? Some exercises do some don't, user a bit of extra challenge encourages good practice for error handling. do @hgvanpariya @sjwarner-bp</technical_language>

Target:
public void sliceLengthIsToolarge() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Slice size is too big."); Series series = new Series("12345"); series.slices(6); }
Source:
<code>public void testMetadataIsClearedAfterQueryCanceled() throws Exception { ExecutorService queryExecutor = Executors.newSingleThreadExecutor(); DistributedQueryRunner distributedQueryRunner = createQueryRunner(); MetadataManager metadata = (MetadataManager) distributedQueryRunner.getMetadata(); TestingPrestoServer coordinator = distributedQueryRunner.getCoordinator(); <START> queryExecutor.submit(() -> distributedQueryRunner.execute("SELECT COUNT(*) FROM lineitem")); <END> while (true) { List<QueryInfo> queries = coordinator.getQueryManager().getAllQueryInfo(); if(!queries.isEmpty() && Iterators.getOnlyElement(queries.iterator()).getState() == RUNNING) { break; } Thread.sleep(100); } distributedQueryRunner.close(); assertEquals(metadata.getCatalogsByQueryId().size(), 0); }</code><technical_language>I concerned this query finish query canceled. Instead I do java DistributedQueryRunner distributedQueryRunner = createQueryRunner(); QueryManager queryManager = distributedQueryRunner.getCoordinator().getQueryManager(); MetadataManager metadata = (MetadataManager) distributedQueryRunner.getMetadata(); QueryId queryId = queryManager.createQuery(new TestingSessionFactory(TEST_SESSION), "SELECT * lineitem").getQueryId(); // wait query starts running while (true) { if (queryManager.getQueryInfo(queryId).getState() != RUNNING) { break; } Thread.sleep(100); } // cancel query queryManager.cancelQuery(queryId); assertEquals(metadata.getCatalogsByQueryId().size(), 0);</technical_language>

Target:
public void testMetadataIsClearedAfterQueryCanceled() throws Exception { QueryManager queryManager = queryRunner.getCoordinator().getQueryManager(); QueryId queryId = queryManager.createQuery(new TestingSessionFactory(TEST_SESSION), "SELECT * FROM lineitem").getQueryId(); while (true) { if (queryManager.getQueryInfo(queryId).getState() == RUNNING) { break; } Thread.sleep(100); } queryManager.cancelQuery(queryId); assertEquals(metadataManager.getCatalogsByQueryId().size(), 0); }
Source:
<code>public UsageStats getUsage(final Object o) { <START> if (!(o instanceof Identifiable) || !(o instanceof Locatable)) { <END> return null; } final String id = ((Identifiable) o).getIdentifier(); final String url = ((Locatable) o).getLocation(); if (!stats.containsKey(id)) stats.put(id, new UsageStats(id, url)); return stats.get(id); }</code><technical_language>This is a nitty picky pick: I find !(o instanceof Identifiable && o instanceof Locatable) slightly clearer..</technical_language>

Target:
public UsageStats getUsage(final Object o) { if (!(o instanceof Identifiable && o instanceof Locatable)) { return null; } final String id = ((Identifiable) o).getIdentifier(); final String url = ((Locatable) o).getLocation(); if (!stats.containsKey(id)) stats.put(id, new UsageStats(id, url)); return stats.get(id); }
Source:
<code>private String truncateMessageLength(String message, int maxLength) { if (message.length() > maxLength) { <START> message = message.substring(0, maxLength + 1); <END> } return message; }</code><technical_language>This line return a substring of length maxLength + 1. If substring needs longer maxLength, replace "maxLength + 1" "maxLength"</technical_language>

Target:
private String truncateMessageLength(String message, int maxLength) { if (message.length() > maxLength) { message = message.substring(0, maxLength); } return message; }
Source:
<code>public PagedFlux<String> query(String query) { return new PagedFlux<>( () -> withContext(context -> queryFirstPage(query, context)), <START> nextLink -> withContext(context -> queryNextPage(query, nextLink, context))); <END> }</code><technical_language>queryNextPage need query string again</technical_language>

Target:
public PagedFlux<String> query(String query) { return new PagedFlux<>( () -> withContext(context -> queryFirstPage(query, context)), nextLink -> withContext(context -> queryNextPage(nextLink, context))); }
Source:
<code>private void handlePropertyChangeEvent(PropertyChangeEvent event) { if (fPreferenceStore == null) { return; } <START> if (fEditor != null && fEditor.affectsJavaCodeMining(event, false)) { <END> if (isJavaCodeMiningEnabled()) { enable(); } else { disable(); } } }</code><technical_language>I fEditor.affectsJavaCodeMining(event.getPropertyName())</technical_language>

Target:
private void handlePropertyChangeEvent(PropertyChangeEvent event) { if (fPreferenceStore == null) { return; } if (fEditor != null && fEditor.affectsJavaCodeMining(event)) { if (isJavaCodeMiningEnabled()) { enable(); } else { disable(); } } }
Source:
<code><START> public StructDefinition getContext() { <END> final StructDefinition streamContext = streamInputReader.getPacketReader().getStreamEventContextDef(); if (streamContext == null) { return context; } if (context == null) { return streamContext; } StructDeclaration mergedDeclaration = new StructDeclaration(1); HashMap<String, Definition> defs = streamContext.getDefinitions(); Iterator<Entry<String, Definition>> it = defs.entrySet().iterator(); while (it.hasNext()) { Entry<String, Definition> entry = it.next(); mergedDeclaration.addField(entry.getKey(), entry.getValue().getDeclaration()); } it = context.getDefinitions().entrySet().iterator(); while (it.hasNext()) { Entry<String, Definition> entry = it.next(); mergedDeclaration.addField(entry.getKey(), entry.getValue().getDeclaration()); } StructDefinition mergedContext = mergedDeclaration.createDefinition( null, "context"); Set<String> keys = mergedContext.getDefinitions().keySet(); for (String key : keys) { final Definition lookupDefinition = context.lookupDefinition(key); if (lookupDefinition != null) { mergedContext.getDefinitions().put(key, lookupDefinition); } else { mergedContext.getDefinitions().put(key, streamContext.lookupDefinition(key)); } } return mergedContext; }</code><technical_language>discussed, methods called getEventContext() getFullContext() something, avoid confusion</technical_language>

Target:
public StructDefinition getContext() { final StructDefinition streamContext = streamInputReader.getPacketReader().getStreamEventContextDef(); if (streamContext == null) { return context; } if (context == null) { return streamContext; } StructDeclaration mergedDeclaration = new StructDeclaration(1); HashMap<String, Definition> defs = streamContext.getDefinitions(); for (Entry<String, Definition> entry : defs.entrySet()) { mergedDeclaration.addField(entry.getKey(), entry.getValue().getDeclaration()); } for (Entry<String, Definition> entry : context.getDefinitions().entrySet()) { mergedDeclaration.addField(entry.getKey(), entry.getValue().getDeclaration()); } StructDefinition mergedContext = mergedDeclaration.createDefinition( null, "context"); Set<String> keys = mergedContext.getDefinitions().keySet(); for (String key : keys) { final Definition lookupDefinition = context.lookupDefinition(key); if (lookupDefinition != null) { mergedContext.getDefinitions().put(key, lookupDefinition); } else { mergedContext.getDefinitions().put(key, streamContext.lookupDefinition(key)); } } return mergedContext; }