auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ResolveNodeResponse resolveNode(JsonRpcPeer peer, JSONObject params) throws JsonRpcException { ResolveNodeRequest request = mObjectMapper.convertValue(params, ResolveNodeRequest.class); Object object = mObjectIdMapper.getObjectForId(request.nodeId); int mappedObjectId = Runtime.mapObject(peer, object); Runtime.RemoteObject remoteObject = new Runtime.RemoteObject(); remoteObject.type = Runtime.ObjectType.OBJECT; remoteObject.subtype = Runtime.ObjectSubType.NODE; <START> remoteObject.className = object.getClass().getName(); <END> remoteObject.value = null; remoteObject.description = null; remoteObject.objectId = String.valueOf(mappedObjectId); ResolveNodeResponse response = new ResolveNodeResponse(); response.object = remoteObject; return response; }</code><technical_language>Please fix in a separate diff for clarity</technical_language>

Target:
public ResolveNodeResponse resolveNode(JsonRpcPeer peer, JSONObject params) throws JsonRpcException { ResolveNodeRequest request = mObjectMapper.convertValue(params, ResolveNodeRequest.class); Object object = mObjectIdMapper.getObjectForId(request.nodeId); int mappedObjectId = Runtime.mapObject(peer, object); Runtime.RemoteObject remoteObject = new Runtime.RemoteObject(); remoteObject.type = Runtime.ObjectType.OBJECT; remoteObject.subtype = Runtime.ObjectSubType.NODE; remoteObject.className = remoteObject.getClass().getName(); remoteObject.value = null; remoteObject.description = null; remoteObject.objectId = String.valueOf(mappedObjectId); ResolveNodeResponse response = new ResolveNodeResponse(); response.object = remoteObject; return response; }
Source:
<code>public void doProbeBundle(Launchpad launchpad) { try { URL resource = Launchpad.class.getResource("/probe.jar"); Bundle probeBundle = launchpad.getFramework() .getBundleContext() .installBundle(resource.toString(), resource.openStream()); @SuppressWarnings("unchecked") Class<ProbeImpl> c = (Class<ProbeImpl>) probeBundle.loadClass(ProbeImpl.class.getName()); <START> Probe probe = c.getDeclaredConstructor() <END> .newInstance(); launchpad.setProbe(probe); } catch (Exception e) { e.printStackTrace(); } }</code><technical_language>is this better</technical_language>

Target:
public void doProbeBundle(Launchpad launchpad) { try { URL resource = Launchpad.class.getResource("/probe.jar"); Bundle probeBundle = launchpad.getFramework() .getBundleContext() .installBundle(resource.toString(), resource.openStream()); @SuppressWarnings("unchecked") Class<ProbeImpl> c = (Class<ProbeImpl>) probeBundle.loadClass(ProbeImpl.class.getName()); Probe probe = c.getConstructor() .newInstance(); launchpad.setProbe(probe); } catch (Exception e) { e.printStackTrace(); } }
Source:
<code>public Node<View<?>, Edge> getParent(final double x, final double y) { final Optional<Node<View<?>, Edge>> parent = canvasHandler.getElementAt(x, y); <START> return parent.isPresent() ? parent.get() : null; <END> }</code><technical_language>matters much, idiomatic "unpack" Optional a return in case of empty is [orElse](<LINK_0> this common pattern i bit verbose: return parent.orElse(null) this kind of defeats purpose of Optionals in place (to avoid return nulls). +1 merge</technical_language>

Target:
public Node<View<?>, Edge> getParent(final double x, final double y) { final Optional<Node<View<?>, Edge>> parent = canvasHandler.getElementAt(x, y); return parent.orElse(null); }
Source:
<code>private final void onWatermark(long watermark, MessageCollector collector, TaskCoordinator coordinator) { final long inputWatermarkMin; if (prevOperators.isEmpty()) { inputWatermarkMin = watermark; } else { inputWatermarkMin = prevOperators.stream().map(op -> op.getOutputWatermark()).min(Long::compare).get(); } if (inputWatermark < inputWatermarkMin) { inputWatermark = inputWatermarkMin; LOG.trace("Advance input watermark to in operator {}", inputWatermark, getOperatorName()); final long outputWm; InitableFunction transformFn = getOperatorSpec().getTransformFn(); <START> if (transformFn != null && transformFn instanceof WatermarkFunction) { <END> WatermarkFunction watermarkFn = (WatermarkFunction) transformFn; watermarkFn.processWatermark(inputWatermark); outputWm = watermarkFn.getOutputWatermark(); } else { outputWm = handleWatermark(inputWatermark, collector, coordinator); } if (outputWatermark < outputWm) { outputWatermark = outputWm; LOG.debug("Advance output watermark to in operator {}", outputWatermark, getOperatorName()); this.registeredOperators.forEach(op -> op.onWatermark(outputWatermark, collector, coordinator)); } } }</code><technical_language>condition implies first</technical_language>

Target:
private final void onWatermark(long watermark, MessageCollector collector, TaskCoordinator coordinator) { final long inputWatermarkMin; if (prevOperators.isEmpty()) { inputWatermarkMin = watermark; } else { inputWatermarkMin = prevOperators.stream().map(op -> op.getOutputWatermark()).min(Long::compare).get(); } if (inputWatermark < inputWatermarkMin) { inputWatermark = inputWatermarkMin; LOG.trace("Advance input watermark to in operator {}", inputWatermark, getOperatorName()); final Long outputWm; WatermarkFunction watermarkFn = getOperatorSpec().getWatermarkFn(); if (watermarkFn != null) { watermarkFn.processWatermark(inputWatermark); outputWm = watermarkFn.getOutputWatermark(); } else { outputWm = handleWatermark(inputWatermark, collector, coordinator); } propagateWatermark(outputWm, collector, coordinator); } }
Source:
<code>public static byte[] fileToBytes(File path) throws IOException { FileInputStream fin = null; <START> byte[] buffer = new byte[(int) path.length() + 1000]; <END> int readBytes = 0; int totalBytes = 0; try { fin = new FileInputStream(path); while (readBytes >= 0) { totalBytes += readBytes; readBytes = fin.read(buffer, totalBytes, buffer.length - totalBytes - 1); } } catch(IOException ioe) { throw new IOException("File " + path.getAbsolutePath() + " is empty"); } finally { if (fin != null) { try { fin.close(); } catch (Exception e) } } byte[] bytes = Arrays.copyOf(buffer, totalBytes); return bytes; }</code><technical_language>I recommend original fin.getChannel().size() get file size more efficient. path.length() more IOs. 1000 bytes needed</technical_language>

Target:
public static byte[] fileToBytes(File path) throws IOException { return Files.readAllBytes(path.toPath()); }
Source:
<code>public static ByteRange fromOffsetRange(long startOffset, long endOffset) throws InvalidByteRangeException { <START> if (startOffset < 0 || endOffset < 0 || endOffset < startOffset) { <END> throw new InvalidByteRangeException(startOffset, endOffset); } return new ByteRange(startOffset, endOffset, ByteRangeType.OFFSET_RANGE); }</code><technical_language>I endOffset < 0 check is redundant here</technical_language>

Target:
public static ByteRange fromOffsetRange(long startOffset, long endOffset) { if (startOffset < 0 || endOffset < startOffset) { throw new IllegalArgumentException( "Invalid range offsets provided for ByteRange; startOffset=" + startOffset + ", endOffset=" + endOffset); } return new ByteRange(startOffset, endOffset, ByteRangeType.OFFSET_RANGE); }
Source:
<code>public void testEncodePositionSingle() throws Exception { Tk103ProtocolEncoder encoder = new Tk103ProtocolEncoder(); Command command = new Command(); command.setDeviceId(1); command.setType(Command.TYPE_POSITION_SINGLE); Assert.assertEquals("(123456789012345AP00)", encoder.encodeCommand(command)); IdentityManager old = Context.getIdentityManager(); Context.init(t580wManager); try { Assert.assertEquals("[begin]sms2,*getposl*,[end]", encoder.encodeCommand(command)); <START> } finally { <END> Context.init(old); } }</code><technical_language>This is wrong</technical_language>

Target:
public void testEncodePositionSingle() throws Exception { Tk103ProtocolEncoder encoder = new Tk103ProtocolEncoder(); Command command = new Command(); command.setDeviceId(1); command.setType(Command.TYPE_POSITION_SINGLE); Assert.assertEquals("(123456789012345AP00)", encoder.encodeCommand(command)); }
Source:
<code>private RuleIteratorInternal createIterator() { try { setParameters(stmt); return new RuleIteratorInternal(stmt); } catch (SQLException e) { DatabaseUtils.closeQuietly(stmt); <START> throw new IllegalStateException("Fail to prepare SQL request to select all issues", e); <END> } }</code><technical_language>wrong label "issues"</technical_language>

Target:
private RuleIteratorInternal createIterator() { try { setParameters(stmt); return new RuleIteratorInternal(stmt); } catch (SQLException e) { DatabaseUtils.closeQuietly(stmt); throw new IllegalStateException("Fail to prepare SQL request to select all rules", e); } }
Source:
<code>public boolean equals(final Object o) { if (o instanceof PatchListKey) { final PatchListKey k = (PatchListKey) o; return eq(oldId, k.oldId) && eq(newId, k.newId) && aPatchSetId == k.aPatchSetId <START> && bPatchSetId == k.bPatchSetId <END> && whitespace == k.whitespace; } return false; }</code><technical_language>lines redundant? eq(oldId, k.oldId) implies aPatchSetId == k.aPatchSetId eq(newId, k.newId) implies bPatchsetId == k.bPatchSetId Right</technical_language>

Target:
public boolean equals(final Object o) { if (o instanceof PatchListKey) { final PatchListKey k = (PatchListKey) o; return eq(oldId, k.oldId) && eq(newId, k.newId) && whitespace == k.whitespace; } return false; }
Source:
<code>public List<Location> resolveList(Object l) { if (l==null) l = Collections.emptyList(); if (l instanceof String) l = JavaStringEscapes.unwrapJsonishListIfPossible((String)l); if (l instanceof Iterable) return resolve((Iterable<?>)l); <START> throw new IllegalArgumentException("Location list must be supplied as a collection or a string, not "+l); <END> }</code><technical_language>I prefer ", "+(l == null ? null : l.getClass()));</technical_language>

Target:
public List<Location> resolveList(Object l) { if (l==null) l = Collections.emptyList(); if (l instanceof String) l = JavaStringEscapes.unwrapJsonishListIfPossible((String)l); if (l instanceof Iterable) return resolve((Iterable<?>)l); throw new IllegalArgumentException("Location list must be supplied as a collection or a string, not "+ JavaClassNames.simpleClassName(l)+"/"+l); }
Source:
<code>public Map<String,Object> getDynamicTemplateData() { if(dynamicTemplateData == null) <START> return Collections.<String,Object>emptyMap(); <END> return dynamicTemplateData; }</code><technical_language>Nitpick: generally safer include curly brackets for _all_ if statements. protect a future developer accidentally introducing a bug if another line is added if statement. Alternatively, a more succinct of writing this method be: return (dynamicTemplateData == null) ? Collections.<String, Object>emptyMap() : dynamicTemplateData;</technical_language>

Target:
public Map<String,Object> getDynamicTemplateData() { return dynamicTemplateData == null ? Collections.<String,Object>emptyMap() : dynamicTemplateData; }
Source:
<code>private void buildVmDevicesFromDb(VmDeviceGeneralType generalType, boolean addAddress, Map<String, Object> extraSpecParams) { List<VmDevice> vmDevices = DbFacade.getInstance() .getVmDeviceDao() .getVmDeviceByVmIdAndType(vm.getId(), generalType); for (VmDevice vmDevice : vmDevices) { Map struct = new HashMap(); struct.put(VdsProperties.Type, vmDevice.getType().getValue()); struct.put(VdsProperties.Device, vmDevice.getDevice()); Map<String, Object> specParams = vmDevice.getSpecParams(); <START> if (extraSpecParams != null) { <END> for (Map.Entry<String, Object> entry : extraSpecParams.entrySet()) { specParams.put(entry.getKey(), entry.getValue()); } } struct.put(VdsProperties.SpecParams, specParams); struct.put(VdsProperties.DeviceId, String.valueOf(vmDevice.getId().getDeviceId())); if (addAddress) { addAddress(vmDevice, struct); } devices.add(struct); } }</code><technical_language>i replace loop specParam.putAll(extraSpecParams)</technical_language>

Target:
private void buildVmDevicesFromDb(VmDeviceGeneralType generalType, boolean addAddress, Map<String, Object> extraSpecParams) { List<VmDevice> vmDevices = DbFacade.getInstance() .getVmDeviceDao() .getVmDeviceByVmIdAndType(vm.getId(), generalType); for (VmDevice vmDevice : vmDevices) { Map struct = new HashMap(); struct.put(VdsProperties.Type, vmDevice.getType().getValue()); struct.put(VdsProperties.Device, vmDevice.getDevice()); Map<String, Object> specParams = vmDevice.getSpecParams(); if (extraSpecParams != null) { specParams.putAll(extraSpecParams); } struct.put(VdsProperties.SpecParams, specParams); struct.put(VdsProperties.DeviceId, String.valueOf(vmDevice.getId().getDeviceId())); if (addAddress) { addAddress(vmDevice, struct); } devices.add(struct); } }
Source:
<code>public Menu generatePanelMenu(){ Menu panelMenu = new Menu("Panels"); Menu autoCreatePanelMenu = new Menu("Auto-create"); List<MenuItem> items = new ArrayList<>(); List<MenuItem> autoCreateItems = new ArrayList<>(); items.add(createLeftPanel()); items.add(createRightPanel()); items.add(closePanel()); <START> autoCreateItems.add(createCustomizedPanel(ASSIGNEE_PANEL_NAME, ASSIGNEE_FILTER_NAME)); <END> autoCreateItems.add(createCustomizedPanel(MILESTONE_PANEL_NAME, MILESTONE_FILTER_NAME)); autoCreateItems.add(createCustomizedPanel(UPDATED_PANEL_NAME, UPDATED_FILTER_NAME)); autoCreatePanelMenu.getItems().addAll(autoCreateItems); panelMenu.getItems().addAll(items); panelMenu.getItems().add(autoCreatePanelMenu); return panelMenu; }</code><technical_language>createLeftPanel() etc. trips a bit reading this. Adding _Menu_ _MenuItem_ suffix menu related variables methods clearer</technical_language>

Target:
public Menu generatePanelMenu(){ Menu panelMenu = new Menu("Panels"); Menu autoCreatePanelMenu = new Menu("Auto-create"); List<MenuItem> items = new ArrayList<>(); List<MenuItem> autoCreateItems = new ArrayList<>(); items.add(createLeftPanelMenuItem()); items.add(createRightPanelMenuItem()); items.add(closePanelMenuItem()); autoCreateItems.add(createCustomizedPanelMenuItem(ASSIGNEE_PANEL_NAME, ASSIGNEE_FILTER_NAME)); autoCreateItems.add(createCustomizedPanelMenuItem(MILESTONE_PANEL_NAME, MILESTONE_FILTER_NAME)); autoCreateItems.add(createCustomizedPanelMenuItem(UPDATED_PANEL_NAME, UPDATED_FILTER_NAME)); autoCreatePanelMenu.getItems().addAll(autoCreateItems); panelMenu.getItems().addAll(items); panelMenu.getItems().add(autoCreatePanelMenu); return panelMenu; }
Source:
<code>public Appenderator createRealtimeAppenderatorForTask( String taskId, DataSchema schema, AppenderatorConfig config, FireDepartmentMetrics metrics, DataSegmentPusher dataSegmentPusher, ObjectMapper objectMapper, IndexIO indexIO, IndexMerger indexMerger, QueryRunnerFactoryConglomerate conglomerate, DataSegmentAnnouncer segmentAnnouncer, ServiceEmitter emitter, ExecutorService queryExecutorService, Cache cache, CacheConfig cacheConfig, CachePopulatorStats cachePopulatorStats ) { synchronized (this) { DatasourceBundle datasourceBundle = datasourceBundles.computeIfAbsent( schema.getDataSource(), (datasource) -> { <START> return new DatasourceBundle(datasource); <END> } ); Appenderator appenderator = new AppenderatorImpl( schema, rewriteAppenderatorConfigMemoryLimits(config), metrics, dataSegmentPusher, objectMapper, segmentAnnouncer, datasourceBundle.getWalker(), indexIO, wrapIndexMerger(indexMerger), cache ); datasourceBundle.addAppenderator(taskId, appenderator); return appenderator; } }</code><technical_language>nit: DatasourceBundle::new</technical_language>

Target:
public Appenderator createRealtimeAppenderatorForTask( String taskId, DataSchema schema, AppenderatorConfig config, FireDepartmentMetrics metrics, DataSegmentPusher dataSegmentPusher, ObjectMapper objectMapper, IndexIO indexIO, IndexMerger indexMerger, QueryRunnerFactoryConglomerate conglomerate, DataSegmentAnnouncer segmentAnnouncer, ServiceEmitter emitter, ExecutorService queryExecutorService, Cache cache, CacheConfig cacheConfig, CachePopulatorStats cachePopulatorStats ) { synchronized (this) { DatasourceBundle datasourceBundle = datasourceBundles.computeIfAbsent( schema.getDataSource(), DatasourceBundle::new ); Appenderator appenderator = new AppenderatorImpl( schema, rewriteAppenderatorConfigMemoryLimits(config), metrics, dataSegmentPusher, objectMapper, segmentAnnouncer, datasourceBundle.getWalker(), indexIO, wrapIndexMerger(indexMerger), cache ); datasourceBundle.addAppenderator(taskId, appenderator); return appenderator; } }
Source:
<code>public void goToLastEvent() throws CTFException { long endTime = Long.MIN_VALUE; for (CTFStreamInputReader sir : fPrio) { sir.goToLastEvent(); IEventDefinition currentEvent = sir.getCurrentEvent(); if (currentEvent != null) { endTime = Math.max(currentEvent.getTimestamp(), endTime); } } setEndTime(fTrace.timestampCyclesToNanos(endTime)); <START> seek(endTime - 1); <END> }</code><technical_language>If is event time it, event. seek endTime advance queue is empty</technical_language>

Target:
public void goToLastEvent() throws CTFException { long endTime = Long.MIN_VALUE; for (CTFStreamInputReader sir : fPrio) { sir.goToLastEvent(); IEventDefinition currentEvent = sir.getCurrentEvent(); if (currentEvent != null) { endTime = Math.max(currentEvent.getTimestamp(), endTime); } } setEndTime(fTrace.timestampCyclesToNanos(endTime)); seek(getEndTime()); }
Source:
<code>public Mono<Integer> readMinThroughput() { return this.read().flatMap(cosmosContainerResponse -> database.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" <START> + cosmosContainerResponse.resourceSettings().resourceId() + "'", new FeedOptions()) <END> .single()).flatMap(offerFeedResponse -> { if (offerFeedResponse.results().isEmpty()) { return Mono.error(BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return database.getDocClientWrapper().readOffer(offerFeedResponse.results().get(0).selfLink()) .single(); }).map(cosmosOfferResponse -> Integer.parseInt(cosmosOfferResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.OFFER_MIN_THROUGHPUT))); }</code><technical_language>susceptible SQL injection attack</technical_language>

Target:
public Mono<Integer> readMinThroughput() { return this.read().flatMap(cosmosContainerResponse -> database.getDocClientWrapper() .queryOffers( new SqlQuerySpec("select * from c where c.offerResourceId = @OFFER_RESOURCE_ID", new SqlParameterList(new SqlParameter("@OFFER_RESOURCE_ID", cosmosContainerResponse.resourceSettings().resourceId()))), new FeedOptions()) .single()).flatMap(offerFeedResponse -> { if (offerFeedResponse.results().isEmpty()) { return Mono.error(BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return database.getDocClientWrapper().readOffer(offerFeedResponse.results().get(0).selfLink()) .single(); }).map(cosmosOfferResponse -> Integer.parseInt(cosmosOfferResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.OFFER_MIN_THROUGHPUT))); }
Source:
<code>public void testQueryDocumentExpiration() throws CouchbaseLiteException, Exception { Date dto5 = new Date(System.currentTimeMillis() + 500L); <START> Date dto10 = new Date(System.currentTimeMillis() + 2000L); <END> Date dto20 = new Date(System.currentTimeMillis() + 2000L); Date dto30 = new Date(System.currentTimeMillis() + 3000L); Date dto40 = new Date(System.currentTimeMillis() + 4000L); long dto60InMS = System.currentTimeMillis() + 6000L; MutableDocument doc1 = new MutableDocument("doc"); MutableDocument doc10 = new MutableDocument("doc10"); MutableDocument doc1a = new MutableDocument("doc1"); MutableDocument doc1b = new MutableDocument("doc2"); MutableDocument doc1c = new MutableDocument("doc3"); doc1.setInt("answer", 42); doc1.setString("notHere", "string"); save(doc1); doc10.setInt("answer", 42); doc10.setString("notHere", "string"); save(doc10); db.setDocumentExpiration("doc10", dto10); db.delete(doc10); doc1a.setInt("answer", 42); doc1a.setString("a", "string"); save(doc1a); doc1b.setInt("answer", 42); doc1b.setString("b", "string"); save(doc1b); doc1c.setInt("answer", 42); doc1c.setString("c", "string"); save(doc1c); db.setDocumentExpiration("doc", dto5); db.setDocumentExpiration("doc1", dto20); db.setDocumentExpiration("doc2", dto30); db.setDocumentExpiration("doc3", dto40); Thread.sleep(1000); Query query = QueryBuilder.select(SR_DOCID, SR_EXPIRATION) .from(DataSource.database(db)) .where(Meta.expiration .lessThan(Expression.longValue(dto60InMS))); assertEquals(query.execute().allResults().size(), 3); }</code><technical_language>+1000L</technical_language>

Target:
public void testQueryDocumentExpiration() throws CouchbaseLiteException, Exception { Date dto5 = new Date(System.currentTimeMillis() + 500L); Date dto20 = new Date(System.currentTimeMillis() + 2000L); Date dto30 = new Date(System.currentTimeMillis() + 3000L); Date dto40 = new Date(System.currentTimeMillis() + 4000L); long dto60InMS = System.currentTimeMillis() + 6000L; MutableDocument doc = new MutableDocument("doc"); MutableDocument doc10 = new MutableDocument("doc10"); MutableDocument doc1 = new MutableDocument("doc1"); MutableDocument doc2 = new MutableDocument("doc2"); MutableDocument doc3 = new MutableDocument("doc3"); doc.setInt("answer", 42); doc.setString("notHere", "string"); save(doc); doc10.setInt("answer", 42); doc10.setString("notHere", "string"); save(doc10); db.setDocumentExpiration("doc10", dto20); db.delete(doc20); doc1.setInt("answer", 42); doc1.setString("a", "string"); save(doc1); doc2.setInt("answer", 42); doc2.setString("b", "string"); save(doc2); doc3.setInt("answer", 42); doc3.setString("c", "string"); save(doc3); db.setDocumentExpiration("doc", dto5); db.setDocumentExpiration("doc1", dto20); db.setDocumentExpiration("doc2", dto30); db.setDocumentExpiration("doc3", dto40); Thread.sleep(1000); Query query = QueryBuilder.select(SR_DOCID, SR_EXPIRATION) .from(DataSource.database(db)) .where(Meta.expiration .lessThan(Expression.longValue(dto60InMS))); assertEquals(query.execute().allResults().size(), 3); }
Source:
<code>public Iterable<ConnectorFactory> getConnectorFactories() { <START> return ImmutableList.of(new HiveConnectorFactory(name, getClassLoader(), Optional.of(metastore))); <END> }</code><technical_language>metastore is nullable</technical_language>

Target:
public Iterable<ConnectorFactory> getConnectorFactories() { return ImmutableList.of(new HiveConnectorFactory(name, getClassLoader(), metastore)); }
Source:
<code>public DeclarationsSearchGroup(IWorkbenchSite site, IDLTKLanguageToolkit tk) { fSite = site; this.toolkit = tk; fGroupId = IContextMenuConstants.GROUP_SEARCH; fFindDeclarationsAction = new FindDeclarationsAction(toolkit, site); fFindDeclarationsAction.setActionDefinitionId(IScriptEditorActionDefinitionIds.SEARCH_DECLARATIONS_IN_WORKSPACE); fFindDeclarationsInProjectAction = new FindDeclarationsInProjectAction( toolkit, site); fFindDeclarationsInProjectAction.setActionDefinitionId(IScriptEditorActionDefinitionIds.SEARCH_DECLARATIONS_IN_PROJECTS); fFindDeclarationsInHierarchyAction = new FindDeclarationsInHierarchyAction( toolkit, site); fFindDeclarationsInHierarchyAction.setActionDefinitionId(IScriptEditorActionDefinitionIds.SEARCH_DECLARATIONS_IN_HIERARCHY); fFindDeclarationsInWorkingSetAction = new FindDeclarationsInWorkingSetAction( toolkit, site); fFindDeclarationsInWorkingSetAction.setActionDefinitionId(IScriptEditorActionDefinitionIds.SEARCH_DECLARATIONS_IN_WORKING_SET); <START> fSelectionProvider = fSite.getSelectionProvider(); <END> fRegisterInProvider = true; registerActions(); }</code><technical_language>OK. assert check</technical_language>

Target:
public DeclarationsSearchGroup(IWorkbenchSite site, IDLTKLanguageToolkit tk) { fSite = site; this.toolkit = tk; fGroupId = IContextMenuConstants.GROUP_SEARCH; fFindDeclarationsAction = new FindDeclarationsAction(toolkit, site); fFindDeclarationsAction.setActionDefinitionId(IScriptEditorActionDefinitionIds.SEARCH_DECLARATIONS_IN_WORKSPACE); fFindDeclarationsInProjectAction = new FindDeclarationsInProjectAction( toolkit, site); fFindDeclarationsInProjectAction.setActionDefinitionId(IScriptEditorActionDefinitionIds.SEARCH_DECLARATIONS_IN_PROJECTS); fFindDeclarationsInHierarchyAction = new FindDeclarationsInHierarchyAction( toolkit, site); fFindDeclarationsInHierarchyAction.setActionDefinitionId(IScriptEditorActionDefinitionIds.SEARCH_DECLARATIONS_IN_HIERARCHY); fFindDeclarationsInWorkingSetAction = new FindDeclarationsInWorkingSetAction( toolkit, site); fFindDeclarationsInWorkingSetAction.setActionDefinitionId(IScriptEditorActionDefinitionIds.SEARCH_DECLARATIONS_IN_WORKING_SET); fSelectionProvider = fSite.getSelectionProvider(); assert fSelectionProvider != null; registerActions(); }
Source:
<code>CorfuStreamEntry<K, V, M> fromSMREntry(SMREntry entry, @Nonnull final long epoch, @Nonnull final Class<K> keyClass, @Nonnull final Class<V> payloadClass, @Nullable final Class<M> metadataClass) { long address = entry.getGlobalAddress(); OperationType operationType; log.trace("fromSRMEntry: Table streamer got SMR {}", keyClass.getName(), entry.getSMRMethod()); switch(entry.getSMRMethod()) { case "put": operationType = OperationType.UPDATE; break; case "clear": operationType = OperationType.CLEAR; break; <START> default: <END> operationType = OperationType.DELETE; break; } Object[] args = entry.getSMRArguments(); log.trace("Converting SMREntry at address to CorfuStreamEntry: Operation: Length of arguments: {}. " + "({} -> {}, {})", address, operationType, args.length, keyClass.getCanonicalName(), payloadClass.getCanonicalName(), (metadataClass != null) ? metadataClass.getCanonicalName() : "null"); K key = null; V payload = null; M metadata = null; if (args.length > 0) { key = (K) args[0]; if (args.length > 1) { CorfuRecord record = (CorfuRecord) args[1]; payload = (V) record.getPayload(); metadata = (M) record.getMetadata(); } } return new CorfuStreamEntry<K, V, M>(key, payload, metadata, epoch, address, operationType); }</code><technical_language>want throw exception default path, explicit delete</technical_language>

Target:
CorfuStreamEntry<K, V, M> fromSMREntry(SMREntry entry, @Nonnull final long epoch, @Nonnull final Class<K> keyClass, @Nonnull final Class<V> payloadClass, @Nullable final Class<M> metadataClass) { long address = entry.getGlobalAddress(); OperationType operationType; log.trace("fromSRMEntry: Table streamer got SMR {}", keyClass.getName(), entry.getSMRMethod()); switch(entry.getSMRMethod()) { case "put": case "putAll": operationType = OperationType.UPDATE; break; case "clear": operationType = OperationType.CLEAR; break; case "remove": operationType = OperationType.DELETE; break; default: throw new RuntimeException("SMRMethod "+entry.getSMRMethod() + " cannot be translated to CorfuStreamEntry"); } Object[] args = entry.getSMRArguments(); log.trace("Converting SMREntry at address to CorfuStreamEntry: Operation: Length of arguments: {}. " + "({} -> {}, {})", address, operationType, args.length, keyClass.getCanonicalName(), payloadClass.getCanonicalName(), (metadataClass != null) ? metadataClass.getCanonicalName() : "null"); K key = null; V payload = null; M metadata = null; if (args.length > 0) { key = (K) args[0]; if (args.length > 1) { CorfuRecord record = (CorfuRecord) args[1]; payload = (V) record.getPayload(); metadata = (M) record.getMetadata(); } } return new CorfuStreamEntry<K, V, M>(key, payload, metadata, epoch, address, operationType); }
Source:
<code>public AsynchronousFileChannel newAsynchronousFileChannel(final Path path, final Set<? extends OpenOption> options, final ExecutorService executor, <START> FileAttribute<?>... attrs) { <END> checkNotNull("path", path); throw new UnsupportedOperationException(); }</code><technical_language>please final due consistency rest of parameters</technical_language>

Target:
public AsynchronousFileChannel newAsynchronousFileChannel(final Path path, final Set<? extends OpenOption> options, final ExecutorService executor, FileAttribute<?>... attrs) throws IllegalArgumentException, UnsupportedOperationException, IOException, SecurityException { checkNotNull("path", path); throw new UnsupportedOperationException(); }
Source:
<code>public String generate(final U profile) { try { final JWSSigner signer = new MACSigner(this.secret); final JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder() .subject(profile.getTypedId()) .issueTime(new Date()) .issuer(this.getClass().getSimpleName()); final Map<String, Object> attributes = profile.getAttributes(); for (final String key : attributes.keySet()) { builder.claim(key, attributes.get(key)); } final JWTClaimsSet claims = builder.build(); <START> final SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256, JOSEObjectType.JWT, null, null, null, null, null, null, null, null, null, null, null), claims); <END> signedJWT.sign(signer); if (encrypted) { final JWEObject jweObject = new JWEObject( new JWEHeader.Builder(JWEAlgorithm.DIR, EncryptionMethod.A256GCM).contentType("JWT").build(), new Payload(signedJWT)); jweObject.encrypt(new DirectEncrypter(this.secret.getBytes("UTF-8"))); return jweObject.serialize(); } else { return signedJWT.serialize(); } } catch (final Exception e) { throw new TechnicalException("Cannot generate JWT", e); } }</code><technical_language>I a method parameters exists ;-)</technical_language>

Target:
public String generate(final U profile) { try { final JWSSigner signer = new MACSigner(this.secret); final JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder() .subject(profile.getTypedId()) .issueTime(new Date()) .issuer(this.getClass().getSimpleName()); final Map<String, Object> attributes = profile.getAttributes(); for (final String key : attributes.keySet()) { builder.claim(key, attributes.get(key)); } final JWTClaimsSet claims = builder.build(); final SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claims); signedJWT.sign(signer); if (encrypted) { final JWEObject jweObject = new JWEObject( new JWEHeader.Builder(JWEAlgorithm.DIR, EncryptionMethod.A256GCM).contentType("JWT").build(), new Payload(signedJWT)); jweObject.encrypt(new DirectEncrypter(this.secret.getBytes("UTF-8"))); return jweObject.serialize(); } else { return signedJWT.serialize(); } } catch (final Exception e) { throw new TechnicalException("Cannot generate JWT", e); } }
Source:
<code>protected void onConstructorFound(NewClassTree newClassTree) { ClassTree classTree = newClassTree.classBody(); if (classTree == null) { return; } List<Tree> members = classTree.members(); if (members.size() != 1) { return; } members.stream() .filter(tree -> tree.is(Tree.Kind.METHOD)) .map(t -> ((MethodTree) t)) <START> .filter(t -> "initialValue".equals(t.simpleName().name())) <END> .findFirst().ifPresent( t -> reportIssue(newClassTree.identifier(), "Replace this anonymous class with a call to \"ThreadLocal.withInitial\".") ); }</code><technical_language>I I pretty nasty corner case, checking parameters, end FP initialValue method is override. if want fix not. ThreadLocal<List<String>> threadLocal = new ThreadLocal<List<String>>() { protected java.util.List<String> initialValue(String s) { // FP - override method a method List<String> init = initialValue(); init.add(s); return init; }; };</technical_language>

Target:
protected void onConstructorFound(NewClassTree newClassTree) { ClassTree classTree = newClassTree.classBody(); if (classTree == null) { return; } List<Tree> members = classTree.members(); if (members.size() != 1) { return; } members.stream() .filter(tree -> tree.is(Tree.Kind.METHOD)) .map(t -> ((MethodTree) t)) .filter(t -> "initialValue".equals(t.simpleName().name())) .filter(t -> t.parameters().isEmpty()) .findFirst().ifPresent( t -> reportIssue(newClassTree.identifier(), "Replace this anonymous class with a call to \"ThreadLocal.withInitial\"."+context.getJavaVersion().java8CompatibilityMessage()) ); }
Source:
<code>public GitHubBranchCause check(GitHubBranchTrigger trigger, GHBranch remoteBranch, @CheckForNull GitHubBranch localBranch, GitHubBranchRepository localRepo, TaskListener listener) <START> throws IOException { <END> Function<GitHubBranchCommitCheck, GitHubBranchCause> function; if (localBranch == null) { GHCommit commit = getLastCommit(remoteBranch); function = event -> event.check(remoteBranch, localRepo, commit); } else { GHCompare.Commit[] commits = getComparedCommits(localBranch, remoteBranch); function = event -> event.check(remoteBranch, localRepo, commits); } return check(remoteBranch, function); }</code><technical_language>lloger is for printing stuff visible user</technical_language>

Target:
public GitHubBranchCause check(GitHubBranchTrigger trigger, GHBranch remoteBranch, @CheckForNull GitHubBranch localBranch, GitHubBranchRepository localRepo, TaskListener listener) throws IOException { final PrintStream logger = listener.getLogger(); Function<GitHubBranchCommitCheck, GitHubBranchCause> function; if (localBranch == null) { GHCommit commit = getLastCommit(remoteBranch); function = event -> event.check(remoteBranch, localRepo, commit); } else { GHCompare.Commit[] commits = getComparedCommits(localBranch, remoteBranch); function = event -> event.check(remoteBranch, localRepo, commits); } return check(remoteBranch, function, logger); }
Source:
<code>public static CopyFilter getCopyFilter(Configuration conf) { <START> String filtersClassName = conf.get(DistCpConstants.CONF_LABEL_FILTERS_CLASS); <END> if (filtersClassName != null) { try { Class<? extends CopyFilter> filtersClass = conf.getClassByName(filtersClassName).asSubclass(CopyFilter.class); filtersClassName = filtersClass.getName(); Constructor<? extends CopyFilter> constructor = filtersClass.getDeclaredConstructor(Configuration.class); return constructor.newInstance(conf); } catch (Exception e) { LOG.error("Unable to instantiate " + filtersClassName, e); } } return getDefaultCopyFilter(conf); }</code><technical_language>1. Configuration.getClass() 2. Treat a failure instantiate a disaster exception swallow</technical_language>

Target:
public static CopyFilter getCopyFilter(Configuration conf) { String filtersClassName = conf .get(DistCpConstants.CONF_LABEL_FILTERS_CLASS); if (filtersClassName != null) { try { Class<? extends CopyFilter> filtersClass = conf .getClassByName(filtersClassName) .asSubclass(CopyFilter.class); filtersClassName = filtersClass.getName(); Constructor<? extends CopyFilter> constructor = filtersClass .getDeclaredConstructor(Configuration.class); return constructor.newInstance(conf); } catch (Exception e) { LOG.error(DistCpConstants.CLASS_INSTANTIATION_ERROR_MSG + filtersClassName, e); throw new RuntimeException( DistCpConstants.CLASS_INSTANTIATION_ERROR_MSG + filtersClassName, e); } } else { return getDefaultCopyFilter(conf); } }
Source:
<code>public Group getCurrentRecord() { SimpleGroup simpleGroup = (SimpleGroup) root.getCurrentRecord(); <START> return simpleGroup.isNull() ? null : simpleGroup; <END> }</code><technical_language>do want skip a record values null? valid records</technical_language>

Target:
public Group getCurrentRecord() { return root.getCurrentRecord(); }
Source:
<code>private static Collection<Symbol> symbolsFromConditionsNotUpdated(ForStatementTree forStatementTree) { Collection<Symbol> conditionSymbols = getConditionSymbols(forStatementTree.condition()); Collection<Symbol> updateSymbols = getUpdatedSymbols(forStatementTree.update()); <START> return conditionSymbols.stream().filter(s -> !updateSymbols.contains(s)).collect(Collectors.toSet()); <END> }</code><technical_language>Collection.removeAll..</technical_language>

Target:
private static Collection<Symbol> symbolsFromConditionsNotUpdated(ForStatementTree forStatementTree) { Collection<Symbol> symbols = getConditionSymbols(forStatementTree.condition()); symbols.removeAll(getUpdatedSymbols(forStatementTree.update())); return symbols; }
Source:
<code>public final Response exit(final Response response, final Identity identity) throws IOException { <START> return response; <END> }</code><technical_language>@lautarobock I is a need exit call Pass instance index</technical_language>

Target:
public final Response exit(final Response response, final Identity identity) throws IOException { if (this.index < this.all.size()) { return this.all.get(this.index).exit(response, identity); } else { throw new IOException( "Index of identity is greater than Pass collection size" ); } }
Source:
<code><START> private Optional<ClusterProxyError> deserializeAsClusterProxyError(Response response) { ClusterProxyError clusterProxyError; try { clusterProxyError = response.readEntity(ClusterProxyError.class); if (!clusterProxyError.getCode().contains("cluster-proxy")) { return Optional.empty(); } } catch (Exception ex) { return Optional.empty(); } return Optional.of(clusterProxyError); } <END></code><technical_language>this simplified a bit: private Optional<ClusterProxyError> deserializeAsClusterProxyError(Response response) { try { ClusterProxyError clusterProxyError = response.readEntity(ClusterProxyError.class); if (clusterProxyError.getCode().contains("cluster-proxy")) { return Optional.of(clusterProxyError); } else { return Optional.empty(); } } catch (Exception ex) { return Optional.empty(); } }</technical_language>

Target:
private Optional<ClusterProxyError> deserializeAsClusterProxyError(Response response) { try { ClusterProxyError clusterProxyError = response.readEntity(ClusterProxyError.class); if (clusterProxyError.getCode().contains("cluster-proxy")) { return Optional.of(clusterProxyError); } else { return Optional.empty(); } } catch (Exception ex) { return Optional.empty(); } }
Source:
<code>public void prepare() { <START> KieBaseConfiguration kieBaseConfiguration = KieServices.Factory.get().newKieBaseConfiguration(); <END> kieBaseConfiguration.setOption(EventProcessingOption.STREAM); KieSessionConfiguration kieSessionConfiguration = KieServices.Factory.get().newKieSessionConfiguration(); kieSessionConfiguration.setOption(TimerJobFactoryOption.get("trackable")); Resource resource = KieServices.Factory.get().getResources().newReaderResource(new StringReader(DRL)); resource.setTargetPath(TestConstants.DRL_TEST_TARGET_PATH); final KieBuilder kbuilder = KieBaseUtil.getKieBuilderFromResources(true, resource); final KieContainer kcontainer = KieServices.Factory.get().newKieContainer(kbuilder.getKieModule().getReleaseId()); final KieBase kbase = kcontainer.newKieBase(kieBaseConfiguration); this.ksession = kbase.newKieSession(kieSessionConfiguration, null); }</code><technical_language>Please move KieBaseConfiguration KieSessionConfiguration KieBase KieSession is created. configurations KieBase KieSession is created sense here. improves readability code is place place, reading code need search for it</technical_language>

Target:
public void prepare() { final Resource resource = KieServices.Factory.get().getResources().newReaderResource(new StringReader(DRL)); resource.setTargetPath(TestConstants.DRL_TEST_TARGET_PATH); final KieBuilder kbuilder = KieBaseUtil.getKieBuilderFromResources(true, resource); final KieContainer kcontainer = KieServices.Factory.get().newKieContainer(kbuilder.getKieModule().getReleaseId()); final KieBaseConfiguration kieBaseConfiguration = KieServices.Factory.get().newKieBaseConfiguration(); kieBaseConfiguration.setOption(EventProcessingOption.STREAM); final KieSessionConfiguration kieSessionConfiguration = KieServices.Factory.get().newKieSessionConfiguration(); kieSessionConfiguration.setOption(TimerJobFactoryOption.get("trackable")); final KieBase kbase = kcontainer.newKieBase(kieBaseConfiguration); this.ksession = kbase.newKieSession(kieSessionConfiguration, null); }
Source:
<code>private void putECDHKeyAgreementImplClass(String className) { String prefix = getClass().getPackage().getName() + "."; String supportedKeyClasses = prefix + "OpenSSLKeyHolder" + "|" + <START> ECPrivateKey.class.getName(); <END> String supportedKeyFormats = "PKCS#8"; putImplClassWithKeyConstraints( "KeyAgreement.ECDH", prefix + className, supportedKeyClasses, supportedKeyFormats); }</code><technical_language>do need .class.getName() here? more time provider is loading</technical_language>

Target:
private void putECDHKeyAgreementImplClass(String className) { String prefix = getClass().getPackage().getName() + "."; String supportedKeyClasses = prefix + "OpenSSLKeyHolder" + "|" + STANDARD_EC_PRIVATE_KEY_INTERFACE_CLASS_NAME; String supportedKeyFormats = "PKCS#8"; putImplClassWithKeyConstraints( "KeyAgreement.ECDH", prefix + className, supportedKeyClasses, supportedKeyFormats); }
Source:
<code>private static boolean matchesSuffix(Optional<String> summary, Optional<String> summary1) { if (!summary.isPresent() && !summary1.isPresent()) return true; else if (summary.isPresent() && summary1.isPresent()) { int startOfRealSummary = summary.get().indexOf(")") + 1; int startOfRealSummary1 = summary1.get().indexOf(")") + 1; <START> return summary.get().substring(startOfRealSummary).equals(summary1.get().substring(startOfRealSummary1)); <END> } return false; }</code><technical_language>For safety, trim whitespace beginning / end of substring comparing</technical_language>

Target:
private static boolean matchesSuffix(Optional<String> summary, Optional<String> summary1) { if (!summary.isPresent() && !summary1.isPresent()) return true; else if (summary.isPresent() && summary1.isPresent()) { int endOfPrefix = summary.get().indexOf(")") + 1; int endOfPrefix1 = summary1.get().indexOf(")") + 1; String trimmedSummaryWithoutPrefix = summary.get().substring(endOfPrefix).trim(); String trimmedSummaryWithoutPrefix1 = summary1.get().substring(endOfPrefix1).trim(); return trimmedSummaryWithoutPrefix.equals(trimmedSummaryWithoutPrefix1); } return false; }
Source:
<code>public void retireOrderType_shouldRetiredTheGivenUnretiredOrderType() { OrderService orderService = Context.getOrderService(); OrderType orderType = orderService.getOrderType(10); assertFalse(orderType.getRetired()); orderService.retireOrderType(orderType, "Retire for testing purposes"); orderType = orderService.getOrderType(10); <START> assertTrue(orderType.getRetired()); <END> }</code><technical_language>need check other retireable related fields null null i.e dateRetired, retiredBy, retireReason</technical_language>

Target:
public void retireOrderType_shouldRetiredTheGivenUnretiredOrderType() { OrderService orderService = Context.getOrderService(); OrderType orderType = orderService.getOrderType(15); assertFalse(orderType.getRetired()); assertNull(orderType.getRetiredBy()); assertNull(orderType.getRetireReason()); assertNull(orderType.getDateRetired()); orderService.retireOrderType(orderType, "Retire for testing purposes"); orderType = orderService.getOrderType(15); assertTrue(orderType.getRetired()); assertNotNull(orderType.getRetiredBy()); assertNotNull(orderType.getRetireReason()); assertNotNull(orderType.getDateRetired()); }
Source:
<code>public void loadWorkflowsFromDatabase() { try { <START> List<ConfigItem<WorkflowRepresentation>> load = getPersistence().load(null); <END> for (ConfigItem<WorkflowRepresentation> configItem : load) { final WorkflowRepresentation content = configItem.getContent(); workflows.put(content.getName(), content); } } catch (InvalidConfigurationException e) { throw new RuntimeException(e); } catch (PersistenceException e) { throw new RuntimeException(e); } }</code><technical_language>wrap null in a constant: BackendPersistence.ALL (or similar)</technical_language>

Target:
public void loadWorkflowsFromDatabase() throws PersistenceException { try { List<ConfigItem<WorkflowRepresentation>> load = getPersistence().load(new HashMap<String, String>()); for (ConfigItem<WorkflowRepresentation> configItem : load) { final WorkflowRepresentation content = configItem.getContent(); workflows.put(content.getName(), content); } } catch (InvalidConfigurationException e) { LOGGER.error("Invalid Configuration: " + e.getMessage()); throw new PersistenceException(e); } }
Source:
<code>public static File getFileById(final String id) throws IOException { ensureDirExists(); <START> try (DirectoryStream<Path> stream = Files.newDirectoryStream(getTempdir(), "*" + id + RECOVERY_FILE_EXTENSION)) { <END> final Iterator<Path> iterator = stream.iterator(); if (iterator.hasNext()) { return iterator.next().toFile(); } throw new IOException("File not found matching ID: " + id); } catch (final IOException e) { throw new IOException("Could not open file for ID:" + id, e); } }</code><technical_language>final</technical_language>

Target:
public static File getFileById(final String id) throws IOException { ensureDirExists(); try (final DirectoryStream<Path> stream = Files.newDirectoryStream(getTempdir(), "*" + id + RECOVERY_FILE_EXTENSION)) { final Iterator<Path> iterator = stream.iterator(); if (iterator.hasNext()) { return iterator.next().toFile(); } throw new IOException("File not found matching ID: " + id); } catch (final IOException e) { throw new IOException("Could not open file for ID:" + id, e); } }
Source:
<code>private void checkNotTranslation(XWikiDocument doc) { <START> if (isTranslation(doc)) { <END> throw new IllegalStateException("Trying to access XObjects on translation '" + doc.getLanguage() + "' of doc '" + doc.getDocumentReference() + "'"); } }</code><technical_language>MessageFormat.format fix wrong usage. I expect single quotes problem. Extract Error-Message a constant check in a simple unit test replacement MessageFormat is working</technical_language>

Target:
void checkNotTranslation(XWikiDocument doc) { checkState(!isTranslation(doc), MessageFormat.format( "Trying to access XObjects on translation ''{0}'' of doc ''{1}''", doc.getLanguage(), doc.getDocumentReference())); }
Source:
<code><START> public static Status fromValue(String status) { <END> try { return valueOf(checkNotNull(status, "type")); } catch (IllegalArgumentException e) { return UNRECOGNIZED; } }</code><technical_language>Is this method necessary? default valueOf() method suffice</technical_language>

Target:
public static Status fromValue(String status) { try { return valueOf(checkNotNull(status, "status")); } catch (IllegalArgumentException e) { return UNRECOGNIZED; } }
Source:
<code>private static void checkKeyValue(String[] keyValue) { if (keyValue.length != 2) { final String exMessage = <START> "Illegal key - value format, key value should be " + <END> "separated with single `:` character"; throw conversionArgumentException(exMessage); } }</code><technical_language>some changes for you: Illegal key-value format. separated a single : character</technical_language>

Target:
private static void checkKeyValue(String[] keyValue) { if (keyValue.length != 2 || !isQuotedKeyValue(keyValue[0], keyValue[1])) { final String exMessage = "Illegal key-value format. The key-value should be quoted " + "and separated with the `" + KEY_VALUE_DELIMITER + "` character."; throw newIllegalArgumentException(exMessage); } }
Source:
<code>public void assertOpen() { if ( terminationReason != null ) { <START> throw new TransactionTerminatedException( terminationReason ); <END> } }</code><technical_language>grab store terminationReason in a local variable, in general a volatile field change read another</technical_language>

Target:
public void assertOpen() { Status reason = this.terminationReason; if ( reason != null ) { throw new TransactionTerminatedException( reason ); } }
Source:
<code>private SourceResponse cloneResponse(SourceResponse sourceResponse) { List<Result> clonedResults = new ArrayList<>(); sourceResponse .getResults() .forEach( <START> result -> { <END> Metacard metacard = result.getMetacard(); Metacard clonedMetacard = new MetacardImpl(metacard, metacard.getMetacardType()); Result clonedResult = new ResultImpl(clonedMetacard); ((ResultImpl) clonedResult).setDistanceInMeters(result.getDistanceInMeters()); ((ResultImpl) clonedResult).setRelevanceScore(result.getRelevanceScore()); clonedResults.add(clonedResult); }); return new QueryResponseImpl( sourceResponse.getRequest(), clonedResults, true, sourceResponse.getHits(), sourceResponse.getProperties()); }</code><technical_language>Large lambdas extracted methods. If do so, ability set return type of method a Result able a map collect stream structure</technical_language>

Target:
private SourceResponse cloneResponse(SourceResponse sourceResponse) { List<Result> clonedResults = sourceResponse.getResults().stream().map(this::cloneResult).collect(Collectors.toList()); return new QueryResponseImpl( sourceResponse.getRequest(), clonedResults, true, sourceResponse.getHits(), sourceResponse.getProperties()); }