auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String getDatastreamUrl(BriefObjectMetadata metadata, String datastreamName) { Datastream preferredDS = getPreferredDatastream(metadata, datastreamName); if (preferredDS == null) { return ""; } StringBuilder url = new StringBuilder(); if (!isBlank(preferredDS.getExtension())) { if (INDEXABLE_EXTENSIONS.contains(preferredDS.getExtension())) { url.append("indexable"); } } url.append("content/"); if (isBlank(preferredDS.getOwner())) { url.append(metadata.getId()); } else { url.append(preferredDS.getOwner()); } if (!ORIGINAL_FILE.equals(datastreamName)) { <START> url.append("/").append(preferredDS.getName()); <END> } return url.toString(); }</code><technical_language>is preferredDS.getName() appended url datastreamName</technical_language>

Target:
public static String getDatastreamUrl(BriefObjectMetadata metadata, String datastreamName) { Datastream preferredDS = getPreferredDatastream(metadata, datastreamName); if (preferredDS == null) { return ""; } StringBuilder url = new StringBuilder(); if (!isBlank(preferredDS.getExtension())) { if (INDEXABLE_EXTENSIONS.contains(preferredDS.getExtension())) { url.append("indexable"); } } url.append("content/"); if (isBlank(preferredDS.getOwner())) { url.append(metadata.getId()); } else { url.append(preferredDS.getOwner()); } if (!ORIGINAL_FILE.equals(preferredDS.getName())) { url.append("/").append(preferredDS.getName()); } return url.toString(); }
Source:
<code>public void errorReporting() throws SQLException { final int maxRetries = 2; final int retryBackoffMs = 1000; Set<SinkRecord> records = Collections.singleton(new SinkRecord("stub", 0, null, null, null, null, 0)); final JdbcDbWriter mockWriter = createMock(JdbcDbWriter.class); SinkTaskContext ctx = createMock(SinkTaskContext.class); mockWriter.write(records); SQLException chainedException = new SQLException("cause 1"); chainedException.setNextException(new SQLException("cause 2")); chainedException.setNextException(new SQLException("cause 3")); expectLastCall().andThrow(chainedException).times(1); mockWriter.write(anyObject()); expectLastCall(); JdbcSinkTask task = new JdbcSinkTask() { @Override void initWriter() { this.writer = mockWriter; } }; task.initialize(ctx); <START> ErrantRecordReporter reporter = createMock(ErrantRecordReporter.class); <END> expect(ctx.errantRecordReporter()).andReturn(reporter); replayAll(); Map<String, String> props = new HashMap<>(); props.put(JdbcSinkConfig.CONNECTION_URL, "stub"); props.put(JdbcSinkConfig.MAX_RETRIES, String.valueOf(maxRetries)); props.put(JdbcSinkConfig.RETRY_BACKOFF_MS, String.valueOf(retryBackoffMs)); task.start(props); task.put(records); verifyAll(); }</code><technical_language>a testcase calls wirter.write() failed reporter is called send DLQ</technical_language>

Target:
public void errorReporting() throws SQLException { final int maxRetries = 2; final int retryBackoffMs = 1000; Set<SinkRecord> records = Collections.singleton(new SinkRecord("stub", 0, null, null, null, null, 0)); final JdbcDbWriter mockWriter = createMock(JdbcDbWriter.class); SinkTaskContext ctx = createMock(SinkTaskContext.class); mockWriter.write(records); SQLException exception = new SQLException("cause 1"); expectLastCall().andThrow(exception); mockWriter.write(anyObject()); expectLastCall().andThrow(exception); JdbcSinkTask task = new JdbcSinkTask() { @Override void initWriter() { this.writer = mockWriter; } }; task.initialize(ctx); ErrantRecordReporter reporter = createMock(ErrantRecordReporter.class); expect(ctx.errantRecordReporter()).andReturn(reporter); expect(reporter.report(anyObject(), anyObject())).andReturn(CompletableFuture.completedFuture(null)); replayAll(); Map<String, String> props = new HashMap<>(); props.put(JdbcSinkConfig.CONNECTION_URL, "stub"); props.put(JdbcSinkConfig.MAX_RETRIES, String.valueOf(maxRetries)); props.put(JdbcSinkConfig.RETRY_BACKOFF_MS, String.valueOf(retryBackoffMs)); task.start(props); task.put(records); verifyAll(); }
Source:
<code>public WidgetResult isValid(IValueProvider valueProvider, IAtsWidgetDefinition widgetDef) { for (String attrStr : valueProvider.getValues()) { <START> if (StringUtils.isNumeric(attrStr)) { <END> return checkValid(widgetDef, Double.parseDouble(attrStr), valueProvider.getName()); } else { return new WidgetResult(WidgetStatus.Invalid_Type, widgetDef, "[%s] value [%s] is not a valid number", valueProvider.getName(), attrStr); } } return WidgetResult.Valid; }</code><technical_language>isNumeric work decimal points (e.g. 3.0). NumberUtils.isNumber is more here. need check if this is deprecated if current version support this. alternative a regex. This is root issue tests failing build</technical_language>

Target:
public WidgetResult isValid(IValueProvider valueProvider, IAtsWidgetDefinition widgetDef) { for (String attrStr : valueProvider.getValues()) { if (attrStr.matches("[-+]?\\d*\\.?\\d*")) { return checkValid(widgetDef, Double.parseDouble(attrStr), valueProvider.getName()); } else { return new WidgetResult(WidgetStatus.Invalid_Type, widgetDef, "[%s] value [%s] is not a valid number", valueProvider.getName(), attrStr); } } return WidgetResult.Valid; }
Source:
<code>private boolean isJobOverridingCancelingMethod() { Method cancelingMethod = null; try { cancelingMethod = currentJob.getClass().getDeclaredMethod("canceling"); } catch (NoSuchMethodException | SecurityException e) { return false; } return <START> (cancelingMethod != null); <END> }</code><technical_language>Redundant parentheses</technical_language>

Target:
private boolean isJobOverridingCancelingMethod() { Method cancelingMethod = null; try { cancelingMethod = currentJob.getClass().getDeclaredMethod("canceling"); } catch (NoSuchMethodException | SecurityException e) { return false; } return cancelingMethod != null; }
Source:
<code>public static Run setMode(Run run, Mode mode) { run.set(LaunchUtils.Mode.class.getName(), mode.name()); <START> return run; <END> }</code><technical_language>Returning Run a bit cheeky for this method API</technical_language>

Target:
public static void setMode(Run run, Mode mode) { run.set(LaunchUtils.Mode.class.getName(), mode.name()); }
Source:
<code>public static Configuration getDriverConfiguration() { return getNetworkConfigurationBuilder() .bindSetEntry(DriverStartHandler.class, NetworkDriverRegister.RegisterDriverHandler.class) <START> .bindNamedParameter(EMMessageHandler.class, ElasticMemoryMsgHandler.class) <END> .build(); }</code><technical_language>orginal style .bindNamedParameter(EMMessageHandler.class, edu.snu.cay.services.em.driver.impl.ElasticMemoryMsgHandler.class) For consistency distinguishment line 114</technical_language>

Target:
public static Configuration getDriverConfiguration() { return getNetworkConfigurationBuilder() .bindSetEntry(DriverStartHandler.class, NetworkDriverRegister.RegisterDriverHandler.class) .bindNamedParameter(EMMessageHandler.class, edu.snu.cay.services.em.driver.impl.ElasticMemoryMsgHandler.class) .build(); }
Source:
<code>public CatchEventPropertyWriter(CatchEvent event, VariableScope variableScope) { super(event, variableScope); this.event = event; <START> event.setOutputSet(bpmn2.createOutputSet()); <END> }</code><technical_language>@evacchi vote for creating output set outputs. outputSet is created matte if outputs not. This produce empty <bpmn2:dataOutput> tag in cases catching event outputs (there some of have) in cases process saved user completed event definition. for start events CatchEventPropertyWriter, events StartConditionalEvent outputs. I reasoning sense for ThrowEventPropertyWriter, events EndNoneEvent EndTerminateEvent inputs</technical_language>

Target:
public CatchEventPropertyWriter(CatchEvent event, VariableScope variableScope) { super(event, variableScope); this.event = event; }
Source:
<code>private boolean validateCanAmendDisk() { DiskImage disk = (DiskImage) getNewDisk(); setStoragePoolId(disk.getStoragePoolId()); if (!validate(new StoragePoolValidator(getStoragePool()).existsAndUp())) { return false; } DiskImagesValidator diskImagesValidator = new <START> DiskImagesValidator(Collections.singletonList(disk)); <END> return validate(diskImagesValidator.diskImagesNotIllegal()); }</code><technical_language>Consider new Java 11 List.of()</technical_language>

Target:
private boolean validateCanAmendDisk() { DiskImage disk = (DiskImage) getNewDisk(); setStoragePoolId(disk.getStoragePoolId()); if (!validate(new StoragePoolValidator(getStoragePool()).existsAndUp())) { return false; } DiskImagesValidator diskImagesValidator = new DiskImagesValidator(List.of(disk)); return validate(diskImagesValidator.diskImagesNotIllegal()); }
Source:
<code>public Response listTopologyWindows(@PathParam("topologyId") Long topologyId, @Context UriInfo uriInfo) { List<QueryParam> queryParams = WSUtils.buildTopologyIdAwareQueryParams(topologyId, uriInfo); try { Collection<RuleInfo> ruleInfos = catalogService.listRules(queryParams); if (ruleInfos != null) { Collection<RuleInfo> windowRules = getWindows(ruleInfos); Collection<WindowDto> windowDtos = Collections2.transform(windowRules, new Function<RuleInfo, WindowDto>() { @Nullable @Override public WindowDto apply(@Nullable RuleInfo ruleInfo) { return new WindowDto(ruleInfo); } }); return WSUtils.respond(OK, SUCCESS, windowDtos); } } catch (Exception ex) { <START> return WSUtils.respond(INTERNAL_SERVER_ERROR, EXCEPTION, ex.getMessage()); <END> } return WSUtils.respond(NOT_FOUND, ENTITY_NOT_FOUND_FOR_FILTER, queryParams.toString()); }</code><technical_language>lets log error server log</technical_language>

Target:
public Response listTopologyWindows(@PathParam("topologyId") Long topologyId, @Context UriInfo uriInfo) { List<QueryParam> queryParams = WSUtils.buildTopologyIdAwareQueryParams(topologyId, uriInfo); try { Collection<RuleInfo> ruleInfos = catalogService.listRules(queryParams); if (ruleInfos != null) { Collection<RuleInfo> windowRules = getWindows(ruleInfos); Collection<WindowDto> windowDtos = Collections2.transform(windowRules, new Function<RuleInfo, WindowDto>() { @Nullable @Override public WindowDto apply(@Nullable RuleInfo ruleInfo) { return new WindowDto(ruleInfo); } }); return WSUtils.respond(OK, SUCCESS, windowDtos); } } catch (Exception ex) { LOG.error("Got exception", ex); return WSUtils.respond(INTERNAL_SERVER_ERROR, EXCEPTION, ex.getMessage()); } return WSUtils.respond(NOT_FOUND, ENTITY_NOT_FOUND_FOR_FILTER, queryParams.toString()); }
Source:
<code>private Map<String, InstanceConfig> findTimeoutOfflineInstances(String clusterName, long offlineDuration) { Map<String, InstanceConfig> instanceConfigMap = new HashMap<>(); if (offlineDuration == VALUE_NOT_SET) { offlineDuration = _configAccessor.getClusterConfig(clusterName).getOfflineNodeTimeOutForPurge(); if (offlineDuration == VALUE_NOT_SET) { return instanceConfigMap; } } <START> HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); instanceConfigMap = accessor.getChildValuesMap(keyBuilder.instanceConfigs(), true); List<String> liveNodes = accessor.getChildNames(keyBuilder.liveInstances()); instanceConfigMap.keySet().removeAll(liveNodes); Set<String> toRemoveInstances = new HashSet<>(); for (String instanceName : instanceConfigMap.keySet()) { ParticipantHistory participantHistory = accessor.getProperty(keyBuilder.participantHistory(instanceName)); long lastOfflineTime = participantHistory.getLastOfflineTime(); if (lastOfflineTime == VALUE_NOT_SET || System.currentTimeMillis() - lastOfflineTime < offlineDuration) { <END> toRemoveInstances.add(instanceName); } } instanceConfigMap.keySet().removeAll(toRemoveInstances); return instanceConfigMap; }</code><technical_language>double-check if this zkclient is a RealmAwareZkClient</technical_language>

Target:
private Map<String, InstanceConfig> findTimeoutOfflineInstances(String clusterName, long offlineDuration) { Map<String, InstanceConfig> instanceConfigMap = new HashMap<>(); if (offlineDuration == ClusterConfig.OFFLINE_DURATION_FOR_PURGE_NOT_SET) { offlineDuration = _configAccessor.getClusterConfig(clusterName).getOfflineDurationForPurge(); if (offlineDuration == ClusterConfig.OFFLINE_DURATION_FOR_PURGE_NOT_SET) { return instanceConfigMap; } } HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); instanceConfigMap = accessor.getChildValuesMap(keyBuilder.instanceConfigs(), true); List<String> liveNodes = accessor.getChildNames(keyBuilder.liveInstances()); instanceConfigMap.keySet().removeAll(liveNodes); Set<String> toRemoveInstances = new HashSet<>(); for (String instanceName : instanceConfigMap.keySet()) { ParticipantHistory participantHistory = accessor.getProperty(keyBuilder.participantHistory(instanceName)); long lastOfflineTime = participantHistory.getLastOfflineTime(); if (lastOfflineTime == ClusterConfig.OFFLINE_DURATION_FOR_PURGE_NOT_SET || System.currentTimeMillis() - lastOfflineTime < offlineDuration) { toRemoveInstances.add(instanceName); } } instanceConfigMap.keySet().removeAll(toRemoveInstances); return instanceConfigMap; }
Source:
<code>public void beforeBlockElement(ProgramState currentState, Tree element) { if (element.is(Kind.DOT_MEMBER_EXPRESSION)) { DotMemberExpressionTree memberExpression = (DotMemberExpressionTree) element; if (isArrayPropertyExecuted(currentState) && METHODS_WITH_CALLBACK.contains(memberExpression.property().name())) { checkArgumentToBeFunctionWithReturn(memberExpression, 0); } <START> if (isArrayFromMethod(memberExpression, currentState)) { <END> checkArgumentToBeFunctionWithReturn(memberExpression, 1); } } }</code><technical_language>@vilchik-elena "else if" "if" clearer (and a picosecond faster)</technical_language>

Target:
public void beforeBlockElement(ProgramState currentState, Tree element) { if (element.is(Kind.DOT_MEMBER_EXPRESSION)) { DotMemberExpressionTree memberExpression = (DotMemberExpressionTree) element; if (isArrayPropertyExecuted(currentState) && METHODS_WITH_CALLBACK.contains(memberExpression.property().name())) { checkArgumentToBeFunctionWithReturn(memberExpression, 0); } else if (isArrayFromMethod(memberExpression, currentState)) { checkArgumentToBeFunctionWithReturn(memberExpression, 1); } } }
Source:
<code><START> List<DiskImage> mapDisks(Disks disks) { <END> List<DiskImage> diskImages = null; if (disks.isSetDisks()) { diskImages = disks.getDisks().stream() .filter(Objects::nonNull) .map(d -> (DiskImage) DiskMapper.map(d, null)) .collect(Collectors.toList()); } return diskImages; }</code><technical_language>If changing visibility here, this private</technical_language>

Target:
List<DiskImage> mapDisks(Disks disks) { List<DiskImage> diskImages = null; if (disks != null && disks.isSetDisks()) { diskImages = disks.getDisks().stream() .filter(Objects::nonNull) .map(disk -> (DiskImage) DiskMapper.map(disk, null)) .collect(Collectors.toList()); } return diskImages; }
Source:
<code>public void testCompressedFrame() { EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerMessageDeflateEncoder(9, 15, false, NEVER_SKIP)); EmbeddedChannel decoderChannel = new EmbeddedChannel( ZlibCodecFactory.newZlibDecoder(ZlibWrapper.NONE)); byte[] payload = new byte[300]; random.nextBytes(payload); BinaryWebSocketFrame frame = new BinaryWebSocketFrame(true, WebSocketExtension.RSV3, Unpooled.wrappedBuffer(payload)); <START> encoderChannel.writeOutbound(frame); <END> BinaryWebSocketFrame compressedFrame = encoderChannel.readOutbound(); assertNotNull(compressedFrame); assertNotNull(compressedFrame.content()); assertEquals(WebSocketExtension.RSV1 | WebSocketExtension.RSV3, compressedFrame.rsv()); decoderChannel.writeInbound(compressedFrame.content()); decoderChannel.writeInbound(DeflateDecoder.FRAME_TAIL); ByteBuf uncompressedPayload = decoderChannel.readInbound(); assertEquals(300, uncompressedPayload.readableBytes()); byte[] finalPayload = new byte[300]; uncompressedPayload.readBytes(finalPayload); assertArrayEquals(finalPayload, payload); uncompressedPayload.release(); }</code><technical_language>this removed</technical_language>

Target:
public void testCompressedFrame() { EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerMessageDeflateEncoder(9, 15, false)); EmbeddedChannel decoderChannel = new EmbeddedChannel( ZlibCodecFactory.newZlibDecoder(ZlibWrapper.NONE)); byte[] payload = new byte[300]; random.nextBytes(payload); BinaryWebSocketFrame frame = new BinaryWebSocketFrame(true, WebSocketExtension.RSV3, Unpooled.wrappedBuffer(payload)); assertTrue(encoderChannel.writeOutbound(frame)); BinaryWebSocketFrame compressedFrame = encoderChannel.readOutbound(); assertNotNull(compressedFrame); assertNotNull(compressedFrame.content()); assertEquals(WebSocketExtension.RSV1 | WebSocketExtension.RSV3, compressedFrame.rsv()); assertTrue(decoderChannel.writeInbound(compressedFrame.content())); assertTrue(decoderChannel.writeInbound(Unpooled.wrappedBuffer(DeflateDecoder.FRAME_TAIL))); ByteBuf uncompressedPayload = decoderChannel.readInbound(); assertEquals(300, uncompressedPayload.readableBytes()); byte[] finalPayload = new byte[300]; uncompressedPayload.readBytes(finalPayload); assertArrayEquals(finalPayload, payload); uncompressedPayload.release(); }
Source:
<code>public void itemStateChanged(ItemEvent e) { if (e.getSource() instanceof JComboBox) { JComboBox combo = (JComboBox) e.getSource(); if(HTTP_SAMPLER_NAMING_MODE.equals(combo.getName())) { model.setHTTPSampleNamingMode(httpSampleNamingMode.getSelectedIndex()); } if(HTTP_SAMPLER_NUMBERING_MODE.equals(combo.getName())) { model.setHttpSampleNumberingMode(httpSampleNumberingMode.getSelectedIndex()); if (httpSampleNumberingMode.getSelectedIndex() == 0) { <START> JMeterUtils.setProperty("proxy.number.mode", "prefix"); <END> JMeterUtils.setProperty("proxy.number.requests", "true"); } if (httpSampleNumberingMode.getSelectedIndex() == 1) { JMeterUtils.setProperty("proxy.number.mode", "suffix"); JMeterUtils.setProperty("proxy.number.requests", "true"); } if (httpSampleNumberingMode.getSelectedIndex() == 2) { JMeterUtils.setProperty("proxy.number.requests", "false"); } } } else { enableRestart(); } }</code><technical_language>this setter/getters</technical_language>

Target:
public void itemStateChanged(ItemEvent e) { if (e.getSource() instanceof JComboBox) { JComboBox combo = (JComboBox) e.getSource(); if(HTTP_SAMPLER_NAMING_MODE.equals(combo.getName())) { model.setHTTPSampleNamingMode(httpSampleNamingMode.getSelectedIndex()); } if(HTTP_SAMPLER_NUMBERING_MODE.equals(combo.getName())) { model.setHttpSampleNumberingMode(httpSampleNumberingMode.getSelectedIndex()); } } else { enableRestart(); } }
Source:
<code>private boolean checkClients() { long reqBytes = 0, respMsgs = 0, txns = 0; try { ClientInterface ci = VoltDB.instance().getClientInterface(); if (ci != null) { for (Pair<String,long[]> ent : ci.getLiveClientStats().values()) { long[] val = ent.getSecond(); reqBytes += val[1]; respMsgs += val[2]; txns += val[3]; } } } catch (Exception ex) { <START> warn("checkClients", ex); <END> } client_reqBytes = reqBytes; client_respMsgs = respMsgs; client_txns = txns; return isActive("client interface: outstanding txns %d, request bytes %d, responses %d", txns, reqBytes, respMsgs); }</code><technical_language>a useful error message</technical_language>

Target:
private boolean checkClients() { long reqBytes = 0, respMsgs = 0, txns = 0; try { ClientInterface ci = VoltDB.instance().getClientInterface(); if (ci != null) { for (Pair<String,long[]> ent : ci.getLiveClientStats().values()) { long[] val = ent.getSecond(); reqBytes += val[1]; respMsgs += val[2]; txns += val[3]; } } } catch (Exception ex) { warn("checkClients", ex); } clientReqBytes = reqBytes; clientRespMsgs = respMsgs; clientTxns = txns; return isActive("client interface: outstanding txns %d, request bytes %d, responses %d", txns, reqBytes, respMsgs); }
Source:
<code>public void putEntry(ArchiveOutputStream out, String path, FileMode mode, ObjectLoader loader) throws IOException { if (path.endsWith("/") != FileMode.TREE.equals(mode)) { throw new IllegalArgumentException( <START> "ZipFormat.putEntry: path " END> + path + " does not match mode " + mode); } final ZipArchiveEntry entry = new ZipArchiveEntry(path); if (FileMode.TREE.equals(mode)) { out.putArchiveEntry(entry); out.closeArchiveEntry(); return; } if (FileMode.REGULAR_FILE.equals(mode)) { } else if (mode == FileMode.EXECUTABLE_FILE || mode == FileMode.SYMLINK) { entry.setUnixMode(mode.getBits()); } else { throw new IllegalArgumentException( "ZipFormat.putEntry: Unsupported mode " + mode); } entry.setSize(loader.getSize()); out.putArchiveEntry(entry); loader.copyTo(out); out.closeArchiveEntry(); }</code><technical_language>Property (since reused classes a placeholder for method name part well)</technical_language>

Target:
public void putEntry(ArchiveOutputStream out, String path, FileMode mode, ObjectLoader loader) throws IOException { if (path.endsWith("/") && mode != FileMode.TREE) throw new IllegalArgumentException(MessageFormat.format( ArchiveText.get().pathDoesNotMatchMode, path, mode)); if (!path.endsWith("/") && mode == FileMode.TREE) path = path + "/"; final ZipArchiveEntry entry = new ZipArchiveEntry(path); if (mode == FileMode.TREE) { out.putArchiveEntry(entry); out.closeArchiveEntry(); return; } if (mode == FileMode.REGULAR_FILE) { } else if (mode == FileMode.EXECUTABLE_FILE || mode == FileMode.SYMLINK) { entry.setUnixMode(mode.getBits()); } else { throw new IllegalArgumentException(MessageFormat.format( ArchiveText.get().unsupportedMode, mode)); } entry.setSize(loader.getSize()); out.putArchiveEntry(entry); loader.copyTo(out); out.closeArchiveEntry(); }
Source:
<code>public Answer execute(final OvsDestroyTunnelCommand command, final LibvirtComputingResource libvirtComputingResource) { try { if (!libvirtComputingResource.findOrCreateTunnelNetwork(command.getBridgeName())) { s_logger.warn("Unable to find tunnel network for GRE key:" + command.getBridgeName()); return new Answer(command, false, "No network found"); } <START> final Script scriptCommand = new Script(libvirtComputingResource.getOvsTunnelPath(), libvirtComputingResource.getTimeout().getMillis(), s_logger); <END> scriptCommand.add("destroy_tunnel"); scriptCommand.add("--bridge", command.getBridgeName()); scriptCommand.add("--iface_name", command.getInPortName()); final String result = scriptCommand.execute(); if (result == null) { return new Answer(command, true, result); } else { return new Answer(command, false, result); } } catch (final Exception e) { s_logger.warn("caught execption when destroy ovs tunnel", e); return new Answer(command, false, e.getMessage()); } }</code><technical_language>Please consider adding overridden version of Script(String, int, Logger) constructor accepts Duration encapsulate this type conversion</technical_language>

Target:
public Answer execute(final OvsDestroyTunnelCommand command, final LibvirtComputingResource libvirtComputingResource) { try { if (!libvirtComputingResource.findOrCreateTunnelNetwork(command.getBridgeName())) { s_logger.warn("Unable to find tunnel network for GRE key:" + command.getBridgeName()); return new Answer(command, false, "No network found"); } final Script scriptCommand = new Script(libvirtComputingResource.getOvsTunnelPath(), libvirtComputingResource.getTimeout(), s_logger); scriptCommand.add("destroy_tunnel"); scriptCommand.add("--bridge", command.getBridgeName()); scriptCommand.add("--iface_name", command.getInPortName()); final String result = scriptCommand.execute(); if (result == null) { return new Answer(command, true, result); } else { return new Answer(command, false, result); } } catch (final Exception e) { s_logger.warn("caught execption when destroy ovs tunnel", e); return new Answer(command, false, e.getMessage()); } }
Source:
<code>private List<IndexEntry> getValidIndexEntriesForIndexSegment(Offset indexSegmentStartOffset, long deleteReferenceTimeMs, long expiryReferenceTimeMs) { List<IndexEntry> validEntries = new ArrayList<>(); for (Map.Entry<MockId, IndexValue> indexSegmentEntry : referenceIndex.get(indexSegmentStartOffset).entrySet()) { MockId key = indexSegmentEntry.getKey(); IndexValue value = indexSegmentEntry.getValue(); if (value.isFlagSet(IndexValue.Flags.Delete_Index)) { validEntries.add(new IndexEntry(key, value)); if (!isDeletedAt(key, deleteReferenceTimeMs) && !isExpiredAt(key, expiryReferenceTimeMs) <START> && value.getOriginalMessageOffset() != -1 <END> && value.getOriginalMessageOffset() >= indexSegmentStartOffset.getOffset()) { validEntries.add(new IndexEntry(key, allKeys.get(key).getFirst())); } } else if (!isExpiredAt(key, expiryReferenceTimeMs)) { if (!deletedKeys.contains(key)) { validEntries.add(new IndexEntry(key, value)); } else if (!isDeletedAt(key, deleteReferenceTimeMs)) { validEntries.add(new IndexEntry(key, value)); } } } return validEntries; }</code><technical_language>do need this check. Guess next condition encompass this (implicitly). Anyways, a suggestion</technical_language>

Target:
List<IndexEntry> getValidIndexEntriesForIndexSegment(Offset indexSegmentStartOffset, long deleteReferenceTimeMs, long expiryReferenceTimeMs) { List<IndexEntry> validEntries = new ArrayList<>(); for (Map.Entry<MockId, IndexValue> indexSegmentEntry : referenceIndex.get(indexSegmentStartOffset).entrySet()) { MockId key = indexSegmentEntry.getKey(); IndexValue value = indexSegmentEntry.getValue(); if (value.isFlagSet(IndexValue.Flags.Delete_Index)) { validEntries.add(new IndexEntry(key, value)); if (!isDeletedAt(key, deleteReferenceTimeMs) && !isExpiredAt(key, expiryReferenceTimeMs) && value.getOriginalMessageOffset() != -1 && value.getOriginalMessageOffset() >= indexSegmentStartOffset.getOffset()) { validEntries.add(new IndexEntry(key, allKeys.get(key).getFirst())); } } else if (!isExpiredAt(key, expiryReferenceTimeMs)) { if (!deletedKeys.contains(key)) { validEntries.add(new IndexEntry(key, value)); } else if (!isDeletedAt(key, deleteReferenceTimeMs)) { validEntries.add(new IndexEntry(key, value)); } } } return validEntries; }
Source:
<code>private void handleAdd() { IPluginModelBase model = (IPluginModelBase) getPage().getModel(); PluginSelectionDialog dialog = new PluginSelectionDialog(PDEPlugin.getActiveWorkbenchShell(), <START> getAvailablePlugins(model), getAvailablePluginImports(model), true); <END> dialog.create(); if (dialog.open() == Window.OK) { Object[] models = dialog.getResult(); IPluginImport[] imports = new IPluginImport[models.length]; try { for (int i = 0; i < models.length; i++) { IPluginModel candidate = (IPluginModel) models[i]; String pluginId = candidate.getPlugin().getId(); IPluginImport importNode = createImport(model.getPluginFactory(), pluginId); String version = VersionUtil.computeInitialPluginVersion(candidate.getPlugin().getVersion()); importNode.setVersion(version); imports[i] = importNode; } addImports(model.getPluginBase(), imports); } catch (CoreException e) { } } }</code><technical_language>Sorry, I rename method instead. (compare patch set 2)</technical_language>

Target:
private void handleAdd() { IPluginModelBase model = (IPluginModelBase) getPage().getModel(); PluginSelectionDialog dialog = new PluginSelectionDialog(PDEPlugin.getActiveWorkbenchShell(), getAvailablePlugins(model, false), getAvailablePlugins(model, true), true); dialog.create(); if (dialog.open() == Window.OK) { Object[] models = dialog.getResult(); IPluginImport[] imports = new IPluginImport[models.length]; try { for (int i = 0; i < models.length; i++) { IPluginModel candidate = (IPluginModel) models[i]; String pluginId = candidate.getPlugin().getId(); IPluginImport importNode = createImport(model.getPluginFactory(), pluginId); String version = VersionUtil.computeInitialPluginVersion(candidate.getPlugin().getVersion()); importNode.setVersion(version); imports[i] = importNode; } addImports(model.getPluginBase(), imports); } catch (CoreException e) { } } }
Source:
<code>private static String getUserAgentSuffix() { String suffix = ";" + USER_AGENT_SUFFIX; <START> return suffix; <END> }</code><technical_language>this inline. suggestion return ";" + USER_AGENT_SUFFIX;</technical_language>

Target:
private static String getUserAgentSuffix() { return ";" + USER_AGENT_SUFFIX; }
Source:
<code>public void connect() throws OpenEnergyMonitorException { try { CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000); serialPort = (SerialPort) commPort; serialPort.setSerialPortParams(BAUDRATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); serialPort.enableReceiveThreshold(1); serialPort.enableReceiveTimeout(100); try { serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); } catch (TooManyListenersException e) { <START> } <END> in = serialPort.getInputStream(); logger.debug("Open Energy Monitor Serial Port message listener started"); } catch (Exception e) { throw new OpenEnergyMonitorException(e); } }</code><technical_language>a DEBUG statement in this catch</technical_language>

Target:
public void connect() throws OpenEnergyMonitorException { try { CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000); serialPort = (SerialPort) commPort; serialPort.setSerialPortParams(BAUDRATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); serialPort.enableReceiveThreshold(1); serialPort.enableReceiveTimeout(100); try { serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); } catch (TooManyListenersException e) { logger.warn("Can't add serial port event listener. ", e); } in = serialPort.getInputStream(); logger.debug("Open Energy Monitor Serial Port message listener started"); } catch (Exception e) { throw new OpenEnergyMonitorException(e); } }
Source:
<code>public static void main(String[] args) { Properties props = new Properties(); if (args.length < 2) { System.out.println("testkafkaimporter: brokers topic [format]"); System.exit(1); } props.put("brokers", args[0]); props.put("topics", args[1]); String format = "csv"; if (args.length > 2) format = args[2]; props.put("procedure", "fake"); KafkaStreamImporterFactory factory = new KafkaStreamImporterFactory(); VoltCSVFormatterFactory ffactory = new VoltCSVFormatterFactory(); ffactory.create(format, props); FormatterBuilder fb = new FormatterBuilder(format, props); fb.setFormatterFactory(ffactory); System.out.println("Properties are: " + props); Map<URI, ImporterConfig> mmap = factory.createImporterConfigurations(props, fb); System.out.println("Number of Partitions for topic are: " + mmap.size()); <START> CountDownLatch cdl = new CountDownLatch(mmap.size()); <END> for (URI uri : mmap.keySet()) { KafkaTopicPartitionImporter importer = new KafkaTopicPartitionImporter((KafkaStreamImporterConfig )mmap.get(uri)); Runner runner = new Runner(importer, cdl); runner.start(); } try { cdl.await(); } catch (InterruptedException ex) { ex.printStackTrace(); } System.out.println("Exiting."); }</code><technical_language>Instead of a countdown latch simply wait for thread runner finish issueing runner.join()</technical_language>

Target:
public static void main(String[] args) { Properties props = new Properties(); if (args.length < 1) { System.out.println("testkafkaimporter: path-to-properties-file - The file should have brokers and topics properties at minimum."); System.exit(1); } String filename = args[0]; try (InputStream is = new FileInputStream(new File(filename))) { props.load(is); } catch (Exception ex) { ex.printStackTrace(); } String partition = props.getProperty("partition"); if (args.length > 2) { partition = args[2]; if (partition != null && partition.equals("all")) { partition = null; } } String format = props.getProperty("format"); if (format == null || format.length() <= 0) format = "csv"; System.out.println("Properties are: " + props); props.put("procedure", "fake"); KafkaStreamImporterFactory factory = new KafkaStreamImporterFactory(); VoltCSVFormatterFactory ffactory = new VoltCSVFormatterFactory(); ffactory.create(format, props); FormatterBuilder fb = new FormatterBuilder(format, props); fb.setFormatterFactory(ffactory); Map<URI, ImporterConfig> mmap = factory.createImporterConfigurations(props, fb); System.out.println("Number of Partitions for topic are: " + mmap.size() + " Requested partition: " + partition); CountDownLatch cdl = new CountDownLatch(mmap.size()); for (URI uri : mmap.keySet()) { if (partition != null && !uri.toString().endsWith(partition)) { cdl.countDown(); continue; } KafkaTopicPartitionImporter importer = new KafkaTopicPartitionImporter((KafkaStreamImporterConfig )mmap.get(uri)); Runner runner = new Runner(importer, cdl); runner.start(); } try { cdl.await(); } catch (InterruptedException ex) { ex.printStackTrace(); } System.out.println("Exiting."); }
Source:
<code>private void setFileTimes(final String filePath,final String creationTime,final String lastModifiedTime ,final String lastAccessedTime) { try { final BasicFileAttributeView attributes = Files.getFileAttributeView(Paths.get(filePath), BasicFileAttributeView.class); final FileTime timeCreation = FileTime.fromMillis(Long.parseLong(creationTime)); final FileTime timeModified = FileTime.fromMillis(Long.parseLong(lastModifiedTime)); final FileTime timeAccessed = FileTime.fromMillis(Long.parseLong(lastAccessedTime)); attributes.setTimes(timeModified, timeAccessed, timeCreation); } catch (final Exception e) { <START> e.printStackTrace(); <END> } }</code><technical_language>Customers exception thrown, print stream writer is pointed. This propagated client, letting exception bubble emitting a failure event</technical_language>

Target:
private void setFileTimes(final String filePath,final String creationTime,final String lastModifiedTime ,final String lastAccessedTime) { try { final BasicFileAttributeView attributes = Files.getFileAttributeView(Paths.get(filePath), BasicFileAttributeView.class); final FileTime timeCreation = FileTime.fromMillis(Long.parseLong(creationTime)); final FileTime timeModified = FileTime.fromMillis(Long.parseLong(lastModifiedTime)); final FileTime timeAccessed = FileTime.fromMillis(Long.parseLong(lastAccessedTime)); attributes.setTimes(timeModified, timeAccessed, timeCreation); } catch (final Exception e) { LOG.error("Unable to restore creation and modified time", e); metadataRestoreListener.metadataRestoreFailed("Unable to restore creation and modified time ::"+e.getMessage()); } }
Source:
<code>public void canExposeASingleEventType() throws Exception { final EventType expectedEventType = buildEventType(); when(repo.findByName(EVENT_TYPE_NAME)).thenReturn(expectedEventType); final MockHttpServletRequestBuilder requestBuilder = get("/event-types/" + EVENT_TYPE_NAME) .accept(APPLICATION_JSON); mockMvc.perform(requestBuilder) <START> .andExpect(status().is2xxSuccessful()) <END> .andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON)) .andExpect(content().json(asJsonString(expectedEventType))); }</code><technical_language>broad check? (I noticed in some other of tests) I more specific checking status codes specific status codes in API</technical_language>

Target:
public void canExposeASingleEventType() throws Exception { final EventType expectedEventType = buildEventType(); when(repo.findByName(EVENT_TYPE_NAME)).thenReturn(expectedEventType); final MockHttpServletRequestBuilder requestBuilder = get("/event-types/" + EVENT_TYPE_NAME) .accept(APPLICATION_JSON); mockMvc.perform(requestBuilder) .andExpect(status().is(200)) .andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON)) .andExpect(content().json(asJsonString(expectedEventType))); }
Source:
<code>public boolean isPlatformCaseSensitive() { <START> return !isMySql() && !isSqlServer(); <END> }</code><technical_language>Note: This is true. 'utf8mb4_bin' for mysql 'Latin1_General_100_BIN2' for SqlServer, need case sensitiveness places. unit tests of ebean run foconis a database settings. This means, tests fail here. do suggest? - change mysql/sqlserver test setup a case sensitive collation? - introduce a flag (Systemproperty), I run tests a case sensitve version of mysql/sqlserver? some special pay attention, if change collation/charset: - maximum index length mysql is 767 bytes, this means ~191 chars 4-byte UTF-8 charsets - setting collation sqlserver case sensitive, means columns case sensitive, I modify some tests for this. (I diff code create a PR for this, if want)</technical_language>

Target:
public boolean isPlatformCaseSensitive() { return spiEbeanServer().getDatabasePlatform().isCaseSensitiveCollation(); }
Source:
<code>public void start() throws TTransportException { for (Engine engine : engines.values()) { engine.start(); } httpServer.start(); plugins.start(); System.out.println("The Concourse server has started"); server.serve(); <START> Thread managementd = new Thread(() -> { <END> managementServer.serve(); },"management-server"); managementd.setDaemon(true); managementd.start(); }</code><technical_language>run this thread call sever.serve() method is blocking</technical_language>

Target:
public void start() throws TTransportException { for (Engine engine : engines.values()) { engine.start(); } httpServer.start(); plugins.start(); Thread managementd = new Thread(() -> { managementServer.serve(); },"management-server"); managementd.setDaemon(true); managementd.start(); System.out.println("The Concourse server has started"); server.serve(); }
Source:
<code>public QueryBuilder make(EsHint hint, String fieldName, Object value) { CommonTermsQueryBuilder commonQuery = QueryBuilders.commonTermsQuery(fieldName, value); if (hint.analyzer != null) { <START> commonQuery.analyzer(hint.analyzer); <END> } return commonQuery; }</code><technical_language>need null check, analyzer method accepts a null issue</technical_language>

Target:
public QueryBuilder make(EsHint hint, String fieldName, Object value) { return QueryBuilders.commonTermsQuery(fieldName, value).analyzer(hint.analyzer); }
Source:
<code>public Iterator<HiveFileInfo> list(FileSystem fileSystem, Table table, Path path, NamenodeStats namenodeStats, NestedDirectoryPolicy nestedDirectoryPolicy, PathFilter pathFilter) { SchemaTableName schemaTableName = new SchemaTableName(table.getDatabaseName(), table.getTableName()); List<HiveFileInfo> files = cache.getIfPresent(path); if (files != null) { return files.iterator(); } if (cachedTableNames.contains(schemaTableName)) { RemoteIterator<LocatedFileStatus> iterator = null; try { <START> iterator = fileSystem.listLocatedStatus(path); <END> } catch (IOException e) { throw new PrestoException(HIVE_FILE_NOT_FOUND, "Hive file location does not exist: " + path); } HadoopFileInfoIterator fileIterator = new HadoopFileInfoIterator(cachingRemoteIterator(iterator, path)); return new HiveFileIterator(path, p -> fileIterator, namenodeStats, nestedDirectoryPolicy, pathFilter); } return delegate.list(fileSystem, table, path, namenodeStats, nestedDirectoryPolicy, pathFilter); }</code><technical_language>I imagining if do following: Iterator<HiveFileInfo> iterator = delegate.list(...); if (cachedTableNames.contains(schemaTableName)) { return cachingIterator(iterator, path); } return iterator; change cachingRemoteIterator to: Iterator<HiveFileInfo> cachingIterator(Iterator<HiveFileInfo> iterator, Path path) { return new Iterator<HiveFileInfo>() { private final List<HiveFileInfo> files = new ArrayList<>(); ... }; } reason asking is current design delegate DirectoryLister need leverage cache. :) Besides this, good</technical_language>

Target:
public Iterator<HiveFileInfo> list(FileSystem fileSystem, Table table, Path path, NamenodeStats namenodeStats, NestedDirectoryPolicy nestedDirectoryPolicy, PathFilter pathFilter) { SchemaTableName schemaTableName = new SchemaTableName(table.getDatabaseName(), table.getTableName()); List<HiveFileInfo> files = cache.getIfPresent(path); if (files != null) { return files.iterator(); } Iterator<HiveFileInfo> iterator = delegate.list(fileSystem, table, path, namenodeStats, nestedDirectoryPolicy, pathFilter); if (cachedTableNames.contains(schemaTableName)) { return cachingIterator(iterator, path); } return iterator; }
Source:
<code>public @Nullable Object resolve(@NonNull ISegment segment) { if (segment instanceof CalledFunction) { CalledFunction calledFunction = (CalledFunction) segment; ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); if (trace != null) { String symbolText; ISymbolProvider provider = SymbolProviderManager.getInstance().getSymbolProvider(trace); <START> if (calledFunction.getSymbol() instanceof Long) { <END> Long address=(Long) calledFunction.getSymbol(); symbolText = provider.getSymbolText(address); if(symbolText==null) { return "0x"+Long.toHexString(address); } return symbolText; } return calledFunction.getSymbol().toString(); } } return null; }</code><technical_language>adding a getsymbol for integers here</technical_language>

Target:
public @Nullable Object resolve(@NonNull ISegment segment) { if (segment instanceof CalledFunction) { CalledFunction calledFunction = (CalledFunction) segment; ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); if (trace != null) { String symbolText; ISymbolProvider provider = SymbolProviderManager.getInstance().getSymbolProvider(trace); ITmfStateValue symbol = ((ITmfStateValue) calledFunction.getSymbol()); switch (symbol.getType()) { case LONG: Long longAddress = symbol.unboxLong(); symbolText = provider.getSymbolText(longAddress); if (symbolText == null) { return "0x" + Long.toHexString(longAddress); } return symbolText; case STRING: return symbol.unboxStr(); case INTEGER: Integer intAddress = symbol.unboxInt(); symbolText = provider.getSymbolText(intAddress); if (symbolText == null) { return "0x" + Integer.toHexString(intAddress); } return symbolText; case DOUBLE: case NULL: case CUSTOM: default: break; } } } return null; }
Source:
<code>public long size() { build(); <START> return body.length() + partBoundary.length + partHeader.length; <END> }</code><technical_language>of TypedOutput instances return -1 length</technical_language>

Target:
public long size() { build(); if (body.length() > -1) { return body.length() + partBoundary.length + partHeader.length; } else { return -1; } }
Source:
<code>public void testGetSanitizedData() { testProps.put(SERVICE_PID, TEST_PID); testProps.put(SERVICE_FACTORYPID, TEST_PID); testProps.put(FELIX_FILENAME, temporaryFile.toURI()); testProps.put(FELIX_NEW_CONFIG, true); testProps.put(SERVICE_FACTORY_PIDLIST, new ArrayList<>()); <START> testProps.put(PROPERTY_REVISION, TEST_PID); <END> context = new ConfigurationContextImpl(TEST_PID, testProps); assertThat(context.getServicePid(), is(TEST_PID)); assertThat(context.getSanitizedProperties().size(), is(2)); }</code><technical_language>want a mimics in production; 5 lines</technical_language>

Target:
public void testGetSanitizedData() { testProps.put(SERVICE_PID, TEST_PID); testProps.put(SERVICE_FACTORYPID, TEST_PID); testProps.put(FELIX_FILENAME, temporaryFile.toURI()); testProps.put(FELIX_NEW_CONFIG, true); testProps.put(SERVICE_FACTORY_PIDLIST, new ArrayList<>()); testProps.put(PROPERTY_REVISION, TEST_REVISION); context = new ConfigurationContextImpl(TEST_PID, testProps); assertThat(context.getServicePid(), is(TEST_PID)); assertThat(context.getSanitizedProperties().size(), is(2)); }
Source:
<code>public APIResult updateDatasourceDependents(String datasourceName, Boolean skipDryRun) { try { Datasource datasource = EntityUtil.getEntity(EntityType.DATASOURCE, datasourceName); StringBuilder result = new StringBuilder(String.format("Updating feed entities " + "dependent on datasource : %s ", datasource.getName())); Pair<String, EntityType>[] dependentEntities = EntityIntegrityChecker.referencedBy(datasource); if (dependentEntities == null) { return new APIResult(APIResult.Status.SUCCEEDED, String.format("Datasource %s has " + "no dependent entities", datasourceName)); } for (Pair<String, EntityType> depEntity : dependentEntities) { Entity entity = EntityUtil.getEntity(depEntity.second, depEntity.first); if (entity.getEntityType() == EntityType.FEED) { Feed newFeed = (Feed) entity.copy(); for (org.apache.falcon.entity.v0.feed.Cluster feedCluster : newFeed.getClusters().getClusters()) { if (feedCluster.getType() == ClusterType.SOURCE) { boolean updatedFeed = isUpdateFeedDatasourceVersion(feedCluster, datasource, newFeed); if (updatedFeed) { result.append(getWorkflowEngine(entity).update(entity, newFeed, feedCluster.getName(), skipDryRun)); updateEntityInConfigStore(entity, newFeed); } } } } <START> } <END> return new APIResult(APIResult.Status.SUCCEEDED, result.toString()); } catch (FalconException e) { LOG.error("Update failed", e); throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } }</code><technical_language>check if type is FEED? isnt feed? throw error if is FEED</technical_language>

Target:
public APIResult updateDatasourceDependents(String datasourceName, Boolean skipDryRun) { try { Datasource datasource = EntityUtil.getEntity(EntityType.DATASOURCE, datasourceName); StringBuilder result = new StringBuilder(String.format("Updating feed entities " + "dependent on datasource : %s ", datasource.getName())); Pair<String, EntityType>[] dependentEntities = EntityIntegrityChecker.referencedBy(datasource); if (dependentEntities == null) { return new APIResult(APIResult.Status.SUCCEEDED, String.format("Datasource %s has " + "no dependent entities", datasourceName)); } for (Pair<String, EntityType> depEntity : dependentEntities) { Entity entity = EntityUtil.getEntity(depEntity.second, depEntity.first); if (entity.getEntityType() != EntityType.FEED) { throw FalconWebException.newAPIException("Datasource dependents should be FEEDS, but" + "encountered type : " + entity.getEntityType()); } Feed newFeed = (Feed) entity.copy(); for (org.apache.falcon.entity.v0.feed.Cluster feedCluster : newFeed.getClusters().getClusters()) { if (feedCluster.getType() == ClusterType.SOURCE) { boolean updatedFeed = isUpdateFeedDatasourceVersion(feedCluster, datasource, newFeed); if (updatedFeed) { result.append(getWorkflowEngine(entity).update(entity, newFeed, feedCluster.getName(), skipDryRun)); updateEntityInConfigStore(entity, newFeed); } } } } return new APIResult(APIResult.Status.SUCCEEDED, result.toString()); } catch (FalconException e) { LOG.error("Update failed", e); throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } }
Source:
<code>protected void initListeners(TreeViewer viewer) { super.initListeners(viewer); viewer.getControl().addMouseListener(new MouseAdapter() { @Override public void mouseUp(MouseEvent event) { SafeRunner.run(() -> { handleMiddleClick(event); }); } private void handleMiddleClick(MouseEvent event) throws CoreException { if (event.button == 2 && event.widget instanceof Tree) { TreeItem item = ((Tree) event.widget).getItem(new Point(event.x, event.y)); if (item == null) { return; } Object data = item.getData(); if (data instanceof IProject) { IProject project = (IProject) data; if (project.isOpen()) { <START> project.close(new NullProgressMonitor()); <END> } } } } }); }</code><technical_language>IProject.close simple bit in fact involves file system operations require some time. So, UI event processing wait for it. do this of UI thread extracting IProject instance? open ProgressMonitorDialog Display.asyncExec</technical_language>

Target:
protected void initListeners(TreeViewer viewer) { super.initListeners(viewer); viewer.getControl().addMouseListener(new MouseAdapter() { @Override public void mouseUp(MouseEvent event) { SafeRunner.run(() -> { handleMiddleClick(event); }); } private void handleMiddleClick(MouseEvent event) throws CoreException { if (event.button == 2 && event.widget instanceof Tree) { TreeItem item = ((Tree) event.widget).getItem(new Point(event.x, event.y)); if (item == null) { return; } Object data = item.getData(); if (data instanceof IProject) { IProject project = (IProject) data; CloseResourceAction cra = new CloseResourceAction(() -> null); cra.selectionChanged(new StructuredSelection(project)); cra.run(); } } } }); }
Source:
<code>private void onSave() { if (!validate()) { return; } flush(); <START> Frontend.RunAction(action, new ProviderParameters(provider), null, true); <END> cancel(); }</code><technical_language>do need this addition? default</technical_language>

Target:
private void onSave() { if (!validate()) { return; } flush(); Frontend.RunAction(action, new ProviderParameters(provider)); cancel(); }