auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected static String fullyEscapeValue(String value) { String escapedValue = value.replace("&", "&amp;"); escapedValue = escapedValue.replace("<", "&lt;"); escapedValue = escapedValue.replace(">", "&gt;"); escapedValue = escapedValue.replace("\"", "&quot;"); escapedValue = escapedValue.replace("\n", "&#10;"); escapedValue = escapedValue.replace("\t", <START> "&#09;"); <END> return escapedValue; }</code><technical_language>Nitpicking #2: %#9; this creates noise in existing files if version control</technical_language>

Target:
protected static String fullyEscapeValue(String value) { String escapedValue = value.replace("&", "&amp;"); escapedValue = escapedValue.replace("<", "&lt;"); escapedValue = escapedValue.replace(">", "&gt;"); escapedValue = escapedValue.replace("\"", "&quot;"); escapedValue = escapedValue.replace("\n", "&#10;"); escapedValue = escapedValue.replace("\t", "&#9;"); return escapedValue; }
Source:
<code>protected void executeCommand() { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.ResetGlusterVolumeOptions, new ResetGlusterVolumeOptionsVDSParameters(upServer.getId(), getGlusterVolumeName(), getParameters().getVolumeOption(), getParameters().isForceAction())); setSucceeded(returnValue.getSucceeded()); if (getSucceeded()) { if (getParameters().getVolumeOption() != null && !(getParameters().getVolumeOption().getKey().isEmpty())) { GlusterVolumeOptionEntity entity = getGlusterVolume().getOption(getParameters().getVolumeOption().getKey()); <START> removeOptionInDb(getGlusterVolume().getOption(getParameters().getVolumeOption().getKey())); <END> isResetAllOptions = false; getParameters().getVolumeOption().setValue((entity.getValue() != null) ? entity.getValue() : ""); } else { for (GlusterVolumeOptionEntity option : getGlusterVolume().getOptions()) { removeOptionInDb(option); } isResetAllOptions = true; } } else { handleVdsError(AuditLogType.GLUSTER_VOLUME_OPTIONS_RESET_FAILED, returnValue.getVdsError().getMessage()); return; } }</code><technical_language>Minor- reuse entity here</technical_language>

Target:
protected void executeCommand() { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.ResetGlusterVolumeOptions, new ResetGlusterVolumeOptionsVDSParameters(upServer.getId(), getGlusterVolumeName(), getParameters().getVolumeOption(), getParameters().isForceAction())); setSucceeded(returnValue.getSucceeded()); if (getSucceeded()) { if (getParameters().getVolumeOption() != null && !(getParameters().getVolumeOption().getKey().isEmpty())) { GlusterVolumeOptionEntity entity = getGlusterVolume().getOption(getParameters().getVolumeOption().getKey()); String optionValue = entity.getValue(); removeOptionInDb(entity); isResetAllOptions = false; getParameters().getVolumeOption().setValue(optionValue != null ? optionValue : ""); } else { for (GlusterVolumeOptionEntity option : getGlusterVolume().getOptions()) { removeOptionInDb(option); } isResetAllOptions = true; } } else { handleVdsError(AuditLogType.GLUSTER_VOLUME_OPTIONS_RESET_FAILED, returnValue.getVdsError().getMessage()); return; } }
Source:
<code>void setPendingMsgsMax(int max) { mu.lock(); try { if (conn == null) { throw new IllegalStateException(ERR_BAD_SUBSCRIPTION); } <START> this.dlvWorkerLock(); <END> pMsgsMax = (max <= 0) ? 0 : max; this.dlvWorkerUnlock(); } finally { mu.unlock(); } }</code><technical_language>Is *guaranteed* setDeliveryWorker() called *between* calls dlvWorkerLock() dlvWorkerUnlock() a call dlvWorker.unlock() lock() called? Unlikely, if happens, debugging fun</technical_language>

Target:
void setPendingMsgsMax(int max) { mu.lock(); try { if (this.closed) { throw new IllegalStateException(ERR_BAD_SUBSCRIPTION); } pMsgsMax = (max <= 0) ? 0 : max; } finally { mu.unlock(); } }
Source:
<code>public void restore(final IProgressMonitor monitor) { String branch = getBranch(); <START> if (branch != null) { <END> restore(branch, monitor); } }</code><technical_language>unrelated change</technical_language>

Target:
public void restore(final IProgressMonitor monitor) { String branch = getBranch(); if (branch != null) restore(branch, monitor); }
Source:
<code>private CompletableFuture<Acknowledge> internalSubmitJob(JobGraph jobGraph) { log.info("Submitting job ({}).", jobGraph.getJobID(), jobGraph.getName()); <START> final CompletableFuture<Acknowledge> persistAndRunFuture = waitForTerminatingJobManager(jobGraph.getJobID(), jobGraph, <END> this::persistAndRunJob) .thenApply(ignored -> Acknowledge.get()); return persistAndRunFuture.handleAsync((acknowledge, throwable) -> { if (throwable != null) { cleanUpJobData(jobGraph.getJobID(), true); ClusterEntryPointExceptionUtils.tryEnrichClusterEntryPointError(throwable); final Throwable strippedThrowable = ExceptionUtils.stripCompletionException(throwable); log.error("Failed to submit job {}.", jobGraph.getJobID(), strippedThrowable); throw new CompletionException( new JobSubmissionException(jobGraph.getJobID(), "Failed to submit job.", strippedThrowable)); } else { return acknowledge; } }, getRpcService().getExecutor()); }</code><technical_language>suggestion final CompletableFuture<Acknowledge> persistAndRunFuture = waitForTerminatingJob(jobGraph.getJobID(), jobGraph,</technical_language>

Target:
private CompletableFuture<Acknowledge> internalSubmitJob(JobGraph jobGraph) { log.info("Submitting job ({}).", jobGraph.getJobID(), jobGraph.getName()); final CompletableFuture<Acknowledge> persistAndRunFuture = waitForTerminatingJob(jobGraph.getJobID(), jobGraph, this::persistAndRunJob) .thenApply(ignored -> Acknowledge.get()); return persistAndRunFuture.handleAsync((acknowledge, throwable) -> { if (throwable != null) { cleanUpJobData(jobGraph.getJobID(), true); ClusterEntryPointExceptionUtils.tryEnrichClusterEntryPointError(throwable); final Throwable strippedThrowable = ExceptionUtils.stripCompletionException(throwable); log.error("Failed to submit job {}.", jobGraph.getJobID(), strippedThrowable); throw new CompletionException( new JobSubmissionException(jobGraph.getJobID(), "Failed to submit job.", strippedThrowable)); } else { return acknowledge; } }, getRpcService().getExecutor()); }
Source:
<code>public void onNext(final AggregationMessage aggregationMessage) { final AvroClockMsg avroClockMsg = codec.decode(aggregationMessage.getData().array()); switch (avroClockMsg.getType()) { case ReplyInitClockMsg: globalMinimumClock = avroClockMsg.getReplyInitClockMsg().getGlobalMinClock(); workerClock = avroClockMsg.getReplyInitClockMsg().getInitClock(); latch.countDown(); break; case BroadcastMinClockMsg: globalMinimumClock = avroClockMsg.getBroadcastMinClockMsg().getGlobalMinClock(); <START> default: <END> } }</code><technical_language>Throw runtime exception</technical_language>

Target:
public void onNext(final AggregationMessage aggregationMessage) { final AvroClockMsg avroClockMsg = codec.decode(aggregationMessage.getData().array()); switch (avroClockMsg.getType()) { case ReplyInitClockMsg: globalMinimumClock = avroClockMsg.getReplyInitClockMsg().getGlobalMinClock(); workerClock = avroClockMsg.getReplyInitClockMsg().getInitClock(); latch.countDown(); break; case BroadcastMinClockMsg: globalMinimumClock = avroClockMsg.getBroadcastMinClockMsg().getGlobalMinClock(); break; default: throw new RuntimeException("Unexpected message type: " + avroClockMsg.getType().toString()); } }
Source:
<code>private static TmfView getNarrowestView(TmfTimeViewAlignmentInfo alignmentInfo) { IWorkbenchPage page = getWorkbenchWindow(alignmentInfo.getShell()).getActivePage(); int smallestWidth = Integer.MAX_VALUE; TmfView smallest = null; for (IViewReference ref : page.getViewReferences()) { IViewPart view = ref.getView(false); if (view instanceof TmfView && view instanceof ITmfTimeAligned) { TmfView tmfView = (TmfView) view; ITmfTimeAligned alignedView = (ITmfTimeAligned) view; Composite parentComposite = tmfView.getParentComposite(); TmfTimeViewAlignmentInfo timeViewAlignmentInfo = alignedView.getTimeViewAlignmentInfo(); int availableWidth = alignedView.getAvailableWidth(alignmentInfo.getTimeAxisOffset()); <START> if (parentComposite != null && parentComposite.isVisible() && timeViewAlignmentInfo != null && isViewLocationNear(parentComposite.toDisplay(0, 0), alignmentInfo.getViewLocation()) && availableWidth < smallestWidth && availableWidth > 0) { <END> smallestWidth = availableWidth; smallest = tmfView; } } } return smallest; }</code><technical_language>extract method</technical_language>

Target:
private static TmfView getNarrowestView(TmfTimeViewAlignmentInfo alignmentInfo) { IWorkbenchPage page = getWorkbenchWindow(alignmentInfo.getShell()).getActivePage(); int narrowestWidth = Integer.MAX_VALUE; TmfView narrowestView = null; for (IViewReference ref : page.getViewReferences()) { IViewPart view = ref.getView(false); if (isTimeAlignedView(view)) { TmfView tmfView = (TmfView) view; if (isCandidateForNarrowestView(tmfView, alignmentInfo, narrowestWidth)) { narrowestWidth = ((ITmfTimeAligned) tmfView).getAvailableWidth(getClampedTimeAxisOffset(alignmentInfo)); narrowestWidth = getClampedTimeAxisWidth(alignmentInfo, narrowestWidth); narrowestView = tmfView; } } } return narrowestView; }
Source:
<code>public Optional<Raid> getRaid() { <START> return Optional.ofNullable((Raid) shadow$getRaid()); <END> }</code><technical_language>this</technical_language>

Target:
public Optional<Raid> getRaid() { return Optional.ofNullable((Raid) this.shadow$getRaid()); }
Source:
<code>private void migrateToPropertyStore() { <START> adminForDc.forEach((dcName, helixAdmin) -> { <END> logger.info("Starting property store migration in {}", dcName); ClusterMapConfig config = getClusterMapConfig(clusterName, dcName, null); InstanceConfigToDataNodeConfigAdapter.Converter instanceConfigConverter = new InstanceConfigToDataNodeConfigAdapter.Converter(config); HelixPropertyStore<ZNRecord> propertyStore = createHelixPropertyStore(dcName); try { PropertyStoreToDataNodeConfigAdapter propertyStoreAdapter = new PropertyStoreToDataNodeConfigAdapter(propertyStore, config, dcName); List<String> instanceNames = helixAdmin.getInstancesInCluster(clusterName); logger.info("Found instances in cluster", instanceNames.size()); instanceNames.forEach(instanceName -> { logger.info("Copying config for node {}", instanceName); InstanceConfig instanceConfig = helixAdmin.getInstanceConfig(clusterName, instanceName); DataNodeConfig dataNodeConfig = instanceConfigConverter.convert(instanceConfig); logger.debug("Writing to property store in {}", dataNodeConfig, dcName); if (!propertyStoreAdapter.set(dataNodeConfig)) { logger.error("Failed to persist config for node in the property store.", dataNodeConfig.getInstanceName()); } }); } finally { propertyStore.stop(); } }); }</code><technical_language>Optional: considering making this multi-threaded (one thread colo). (Never mind, fine, one-off operation)</technical_language>

Target:
private void migrateToPropertyStore() throws InterruptedException { CountDownLatch migrationComplete = new CountDownLatch(adminForDc.size()); adminForDc.forEach((dcName, helixAdmin) -> Utils.newThread(() -> { try { logger.info("Starting property store migration in {}", dcName); ClusterMapConfig config = getClusterMapConfig(clusterName, dcName, null); InstanceConfigToDataNodeConfigAdapter.Converter instanceConfigConverter = new InstanceConfigToDataNodeConfigAdapter.Converter(config); HelixPropertyStore<ZNRecord> propertyStore = createHelixPropertyStore(dcName); try { PropertyStoreToDataNodeConfigAdapter propertyStoreAdapter = new PropertyStoreToDataNodeConfigAdapter(propertyStore, config); List<String> instanceNames = helixAdmin.getInstancesInCluster(clusterName); logger.info("Found instances in cluster", instanceNames.size()); instanceNames.forEach(instanceName -> { logger.info("Copying config for node {}", instanceName); InstanceConfig instanceConfig = helixAdmin.getInstanceConfig(clusterName, instanceName); DataNodeConfig dataNodeConfig = instanceConfigConverter.convert(instanceConfig); logger.debug("Writing to property store in {}", dataNodeConfig, dcName); if (!propertyStoreAdapter.set(dataNodeConfig)) { logger.error("Failed to persist config for node in the property store.", dataNodeConfig.getInstanceName()); } }); } finally { propertyStore.stop(); } logger.error("Successfully migrated to property store in {}", dcName); } catch (Throwable t) { logger.error("Error while migrating to property store in {}", dcName, t); } finally { migrationComplete.countDown(); } }, false).start()); migrationComplete.await(); }
Source:
<code>public void doChange(ScoreDirector<TaskAssigningSolution> scoreDirector) { final User workingUser = scoreDirector.lookUpWorkingObjectOrReturnNull(user); <START> if (workingUser != null) { <END> scoreDirector.beforeProblemPropertyChanged(workingUser); workingUser.setEnabled(false); scoreDirector.afterProblemPropertyChanged(workingUser); releaseNonPinnedTasks(workingUser, scoreDirector); scoreDirector.triggerVariableListeners(); } }</code><technical_language>I prefer following: if (workingUser == null) { return; } ... Avoids nesting, allows for code is easier understand. this is purely optional</technical_language>

Target:
public void doChange(ScoreDirector<TaskAssigningSolution> scoreDirector) { final User workingUser = scoreDirector.lookUpWorkingObjectOrReturnNull(user); if (workingUser == null) { return; } scoreDirector.beforeProblemPropertyChanged(workingUser); workingUser.setEnabled(false); scoreDirector.afterProblemPropertyChanged(workingUser); releaseNonPinnedTasks(workingUser, scoreDirector); scoreDirector.triggerVariableListeners(); }
Source:
<code>void createTopic() { final String queueName = "some-topic"; final CreateTopicOptions expected = new CreateTopicOptions(queueName) .setAutoDeleteOnIdle(Duration.ofSeconds(15)) .setDefaultMessageTimeToLive(Duration.ofSeconds(50)) .setDeadLetteringOnMessageExpiration(true) .setDuplicateDetectionHistoryTimeWindow(Duration.ofSeconds(13)) .setEnableBatchedOperations(false) .setEnablePartitioning(true) .setForwardTo("Forward-To-This-Queue") .setForwardDeadLetteredMessagesTo("Dead-Lettered-Forward-To") .setLockDuration(Duration.ofSeconds(120)) .setMaxDeliveryCount(15) .setMaxSizeInMegabytes(2048) .setRequiresDuplicateDetection(true) .setRequiresSession(true) .setStatus(EntityStatus.RECEIVE_DISABLED) .setUserMetadata("Test-queue-Metadata"); final TopicProperties actual = EntityHelper.createTopic(expected); assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getAutoDeleteOnIdle(), actual.getAutoDeleteOnIdle()); assertEquals(expected.getDefaultMessageTimeToLive(), actual.getDefaultMessageTimeToLive()); assertEquals(expected.getDuplicateDetectionHistoryTimeWindow(), actual.getDuplicateDetectionHistoryTimeWindow()); assertEquals(expected.enableBatchedOperations(), actual.enableBatchedOperations()); assertEquals(expected.enablePartitioning(), actual.enablePartitioning()); assertEquals(expected.requiresDuplicateDetection(), actual.requiresDuplicateDetection()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); <START> assertEquals(expected.getStatus(), actual.getStatus()); <END> }</code><technical_language>check other properties in "arrange" section for example RequiresSession , MaxDeliveryCount</technical_language>

Target:
void createTopic() { final String queueName = "some-topic"; final CreateTopicOptions expected = new CreateTopicOptions(queueName) .setStatus(EntityStatus.RECEIVE_DISABLED) .setUserMetadata("Test-topic-Metadata"); final TopicDescription actual = EntityHelper.getTopicDescription(expected); assertEquals(expected.getAutoDeleteOnIdle(), actual.getAutoDeleteOnIdle()); assertEquals(expected.getDefaultMessageTimeToLive(), actual.getDefaultMessageTimeToLive()); assertEquals(expected.getDuplicateDetectionHistoryTimeWindow(), actual.getDuplicateDetectionHistoryTimeWindow()); assertEquals(expected.enableBatchedOperations(), actual.isEnableBatchedOperations()); assertEquals(expected.enablePartitioning(), actual.isEnablePartitioning()); assertEquals(expected.getMaxSizeInMegabytes(), actual.getMaxSizeInMegabytes()); assertEquals(expected.getStatus(), actual.getStatus()); assertEquals(expected.requiresDuplicateDetection(), actual.isRequiresDuplicateDetection()); assertEquals(expected.isSupportOrdering(), actual.isSupportOrdering()); assertEquals(expected.getUserMetadata(), actual.getUserMetadata()); }
Source:
<code>public void postOpen(ObserverContext<RegionCoprocessorEnvironment> e) { final RegionCoprocessorEnvironment env = e.getEnvironment(); Logger deprecationLogger = Logger.getLogger("org.apache.hadoop.conf.Configuration.deprecation"); if (deprecationLogger != null) { deprecationLogger.setLevel(Level.WARN); } try { <START> Class.forName(PhoenixDriver.class.getName()); <END> DropChildViewsTask task = new DropChildViewsTask(e.getEnvironment(), timeMaxInterval); executor.scheduleWithFixedDelay(task, initialDelay, timeInterval, TimeUnit.MILLISECONDS); } catch (ClassNotFoundException ex) { LOG.error("ScheduleTask cannot start!", ex); } }</code><technical_language>dont need this anymore Java 1.5+, remove</technical_language>

Target:
public void postOpen(ObserverContext<RegionCoprocessorEnvironment> e) { final RegionCoprocessorEnvironment env = e.getEnvironment(); Logger deprecationLogger = Logger.getLogger("org.apache.hadoop.conf.Configuration.deprecation"); if (deprecationLogger != null) { deprecationLogger.setLevel(Level.WARN); } DropChildViewsTask task = new DropChildViewsTask(e.getEnvironment(), timeMaxInterval); executor.scheduleWithFixedDelay(task, initialDelay, timeInterval, TimeUnit.MILLISECONDS); }
Source:
<code>private void updateLaunchConfiguration(ILaunchConfiguration configuration) { try { String projectName = configuration.getAttribute(ATTR_PROJECT_NAME, (String) null); if (projectName == null) { <START> return; <END> } IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); IDEAndroidProject eclipseProject = factory.createAndroidProject(project); if (isAndroidJUnitLaunch(configuration) && eclipseProject.isAndroidProject() && isMavenProject(project)) { final ILaunchConfigurationWorkingCopy workingCopy = addCustomClasspathProvidersTo(configuration); new WorkspaceJob("Update launch configuration") { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { workingCopy.doSave(); return Status.OK_STATUS; } }.schedule(); } } catch (CoreException e) { e.printStackTrace(); } }</code><technical_language>Good, simple solution a bit nervous silently returning this method</technical_language>

Target:
private void updateLaunchConfiguration(ILaunchConfiguration configuration) { try { String projectName = configuration.getAttribute(ATTR_PROJECT_NAME, (String) null); if (projectName == null) { debug("Cannot update launch configuration because projectName is null."); return; } IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); IDEAndroidProject eclipseProject = factory.createAndroidProject(project); if (isAndroidJUnitLaunch(configuration) && eclipseProject.isAndroidProject() && isMavenProject(project)) { final ILaunchConfigurationWorkingCopy workingCopy = addCustomClasspathProvidersTo(configuration); new WorkspaceJob("Update launch configuration") { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { workingCopy.doSave(); return Status.OK_STATUS; } }.schedule(); } } catch (CoreException e) { e.printStackTrace(); } }
Source:
<code>public void testListAvailabilityZones() { ImmutableList<? extends AvailabilityZone> cinderZones = availabilityZoneApi.list().toList(); <START> assertTrue(cinderZones.size() > 0); <END> for (AvailabilityZone zone : cinderZones) { assertTrue(!Strings.isNullOrEmpty(zone.getName())); assertTrue(zone.getState().available()); } }</code><technical_language>Prefer isEmpty() size() > 0. This read assertTrue(!cinderZones.isEmpty())</technical_language>

Target:
public void testListAvailabilityZones() { ImmutableList<? extends AvailabilityZone> cinderZones = availabilityZoneApi.list().toList(); assertTrue(!cinderZones.isEmpty()); for (AvailabilityZone zone : cinderZones) { assertTrue(!Strings.isNullOrEmpty(zone.getName())); assertTrue(zone.getZoneState().available()); } }
Source:
<code><START> private Tuple2<Long, CollectCoordinationResponse> getAccumulatorResults() { <END> checkJobClientConfigured(); JobExecutionResult executionResult; try { executionResult = jobClient.getJobExecutionResult(getClass().getClassLoader()).get( DEFAULT_ACCUMULATOR_GET_MILLIS, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new RuntimeException("Failed to fetch job execution result", e); } ArrayList<byte[]> accResults = executionResult.getAccumulatorResult(accumulatorName); if (accResults == null) { return null; } try { List<byte[]> serializedResults = SerializedListAccumulator.deserializeList(accResults, BytePrimitiveArraySerializer.INSTANCE); byte[] serializedResult = serializedResults.get(0); return CollectSinkFunction.deserializeAccumulatorResult(serializedResult); } catch (ClassNotFoundException | IOException e) { throw new RuntimeException("Failed to deserialize accumulator results", e); } }</code><technical_language>suggestion private Tuple2<Long, CollectCoordinationResponse<T>> getAccumulatorResults() {</technical_language>

Target:
private Tuple2<Long, CollectCoordinationResponse<T>> getAccumulatorResults() throws IOException { checkJobClientConfigured(); JobExecutionResult executionResult; try { executionResult = jobClient.getJobExecutionResult(getClass().getClassLoader()).get( DEFAULT_ACCUMULATOR_GET_MILLIS, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new IOException("Failed to fetch job execution result", e); } ArrayList<byte[]> accResults = executionResult.getAccumulatorResult(accumulatorName); if (accResults == null) { throw new IOException("Job terminated abnormally, no job execution result can be fetched"); } try { List<byte[]> serializedResults = SerializedListAccumulator.deserializeList(accResults, BytePrimitiveArraySerializer.INSTANCE); byte[] serializedResult = serializedResults.get(0); return CollectSinkFunction.deserializeAccumulatorResult(serializedResult); } catch (ClassNotFoundException | IOException e) { throw new IOException("Failed to deserialize accumulator results", e); } }
Source:
<code>public void testRemoveValueUnequalStoreEntryCacheWriterException() throws Exception { final MockStore realStore = new MockStore(Collections.singletonMap("key", "unequalValue")); this.store = spy(realStore); final MockCacheWriter realCache = new MockCacheWriter(Collections.singletonMap("key", "value")); this.cacheWriter = spy(realCache); doThrow(new Exception()).when(this.cacheWriter).delete("key"); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); assertFalse(ehcache.remove("key", "value")); verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(realStore.getMap().get("key"), is(equalTo("unequalValue"))); <START> assertThat(realCache.getEntries().get("key"), is(equalTo("value"))); END> validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); }</code><technical_language>Again, broken initial setup - care in this case</technical_language>

Target:
public void testRemoveValueUnequalStoreEntryCacheWriterException() throws Exception { final FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", "unequalValue")); this.store = spy(fakeStore); final FakeCacheWriter fakeWriter = new FakeCacheWriter(Collections.singletonMap("key", "unequalValue")); this.cacheWriter = spy(fakeWriter); doThrow(new Exception()).when(this.cacheWriter).delete("key"); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); assertFalse(ehcache.remove("key", "value")); verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), is(equalTo("unequalValue"))); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); }
Source:
<code>public void onStartup(ServletContext sc) throws ServletException { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.register(SpringSecurityWebAppConfig.class); sc.addListener(new ContextLoaderListener(context)); DispatcherServlet dispatcherServlet = new DispatcherServlet(context); ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher", dispatcherServlet); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); FilterRegistration.Dynamic securityFilter = sc.addFilter(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME, DelegatingFilterProxy.class); securityFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*"); <START> FilterRegistration.Dynamic filter = sc.addFilter("stormpathFilter", new DelegatingFilterProxy()); <END> EnumSet<DispatcherType> types = EnumSet.of(DispatcherType.ERROR, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST); filter.addMappingForUrlPatterns(types, false, "/*"); }</code><technical_language>I this is older code, I curious a string literal here, a constant instantiate DelegatingFilterProxy passing in class (as above). update this well</technical_language>

Target:
public void onStartup(ServletContext sc) throws ServletException { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.register(SpringSecurityWebAppConfig.class); sc.addListener(new ContextLoaderListener(context)); DispatcherServlet dispatcherServlet = new DispatcherServlet(context); ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher", dispatcherServlet); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); FilterRegistration.Dynamic securityFilter = sc.addFilter(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME, DelegatingFilterProxy.class); securityFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*"); FilterRegistration.Dynamic stormpathFilter = sc.addFilter(StormpathFilter.DEFAULT_FILTER_NAME, DelegatingFilterProxy.class); EnumSet<DispatcherType> types = EnumSet.of(DispatcherType.ERROR, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST); stormpathFilter.addMappingForUrlPatterns(types, false, "/*"); }
Source:
<code>public void drawSelection(Player player, LocalSession session, @Arg(desc = "The new draw selection state", def = "") Boolean drawSelection) throws WorldEditException { if (!WorldEdit.getInstance().getConfiguration().serverSideCUI) { throw new DisallowedUsageException("This functionality is disabled in the configuration!"); } boolean useServerCui = session.shouldUseServerCUI(); if (drawSelection != null && drawSelection == useServerCui) { <START> player.printError(TranslatableComponent.of(useServerCui ? "worldedit.drawsel.enabled.already" : "worldedit.drawsel.disabled.already")); <END> return; } if (useServerCui) { session.setUseServerCUI(false); session.updateServerCUI(player); player.printInfo(TranslatableComponent.of("worldedit.drawsel.disabled")); } else { session.setUseServerCUI(true); session.updateServerCUI(player); player.printInfo(TranslatableComponent.of("worldedit.drawsel.enabled")); } }</code><technical_language>suggestion player.printError(TranslatableComponent.of("worldedit.drawsel.already." + (useServerCui ? "enabled" : "disabled")));</technical_language>

Target:
public void drawSelection(Player player, LocalSession session, @Arg(desc = "The new draw selection state", def = "") Boolean drawSelection) throws WorldEditException { if (!WorldEdit.getInstance().getConfiguration().serverSideCUI) { throw new DisallowedUsageException("This functionality is disabled in the configuration!"); } boolean useServerCui = session.shouldUseServerCUI(); if (drawSelection != null && drawSelection == useServerCui) { player.printError(TranslatableComponent.of("worldedit.drawsel." + (useServerCui ? "enabled" : "disabled") + ".already")); return; } if (useServerCui) { session.setUseServerCUI(false); session.updateServerCUI(player); player.printInfo(TranslatableComponent.of("worldedit.drawsel.disabled")); } else { session.setUseServerCUI(true); session.updateServerCUI(player); player.printInfo(TranslatableComponent.of("worldedit.drawsel.enabled")); } }
Source:
<code>public double overnightIndexRatePeriod(OvernightIndex index, LocalDate startDate, LocalDate endDate) { ArgChecker.notNull(index, "index"); ArgChecker.notNull(startDate, "startDate"); ArgChecker.notNull(endDate, "endDate"); ArgChecker.isTrue(startDate.isBefore(endDate), "start date should be before end date"); <START> ArgChecker.isFalse(valuationDate.isAfter(startDate), "valuation date should be before or on the start date"); <END> double fixingYearFraction = index.getDayCount().yearFraction(startDate, endDate); return multicurve.getSimplyCompoundForwardRate( Legacy.overnightIndex(index), relativeTime(startDate), relativeTime(endDate), fixingYearFraction); }</code><technical_language>lines of a nice ArgChecker feature: ArgChecker.inOrderNotEqual(startDate, endDate, "startDate", "endDate"); ArgChecker.inOrderOrEqual(valuationDate, startDate, "valuationDate", "startDate");</technical_language>

Target:
public double overnightIndexRatePeriod(OvernightIndex index, LocalDate startDate, LocalDate endDate) { ArgChecker.notNull(index, "index"); ArgChecker.notNull(startDate, "startDate"); ArgChecker.notNull(endDate, "endDate"); ArgChecker.inOrderNotEqual(startDate, endDate, "startDate", "endDate"); ArgChecker.inOrderOrEqual(valuationDate, startDate, "valuationDate", "startDate"); double fixingYearFraction = index.getDayCount().yearFraction(startDate, endDate); return multicurve.getSimplyCompoundForwardRate( Legacy.overnightIndex(index), relativeTime(startDate), relativeTime(endDate), fixingYearFraction); }
Source:
<code>public Set<Diff> getDirectResultingMerges(Diff target, boolean mergeRightToLeft) { final Set<Diff> resulting = new LinkedHashSet<Diff>(); if (mergeRightToLeft) { if (DifferenceSource.LEFT == target.getSource()) { resulting.addAll(target.getImpliedBy()); } else { resulting.addAll(target.getImplies()); } } else { if (DifferenceSource.LEFT == target.getSource()) { resulting.addAll(target.getImplies()); } else { resulting.addAll(target.getImpliedBy()); } } if (target.getEquivalence() != null) { resulting.addAll(target.getEquivalence().getDifferences()); resulting.remove(target); } if (target.getConflict() != null && target.getConflict().getKind() == ConflictKind.PSEUDO) { resulting.addAll(target.getConflict().getDifferences()); resulting.remove(target); } if (target instanceof ReferenceChange && isSet((ReferenceChange)target, mergeRightToLeft)) { <START> final ReferenceChange ref = (ReferenceChange)target; <END> final Match match = target.getMatch(); final Set<Diff> diffsToCheck = new HashSet<Diff>(); for (Diff diff : match.getDifferences()) { diffsToCheck.add(diff); if (diff.getEquivalence() != null) { diffsToCheck.addAll(diff.getEquivalence().getDifferences()); } } final EObject sourceContainer = ComparisonUtil.getExpectedSide(target.getMatch(), target .getSource(), mergeRightToLeft); if (sourceContainer != null) { final Object lvalue = ReferenceUtil.safeEGet(sourceContainer, ref.getReference()); if (lvalue == sourceContainer) { resulting.addAll(findPseudoEquivalentDiffs(diffsToCheck, target, mergeRightToLeft)); } } } return resulting; }</code><technical_language>call referenceChange</technical_language>

Target:
public Set<Diff> getDirectResultingMerges(Diff target, boolean mergeRightToLeft) { final Set<Diff> resulting = new LinkedHashSet<Diff>(); if (mergeRightToLeft) { if (DifferenceSource.LEFT == target.getSource()) { resulting.addAll(target.getImpliedBy()); } else { resulting.addAll(target.getImplies()); } } else { if (DifferenceSource.LEFT == target.getSource()) { resulting.addAll(target.getImplies()); } else { resulting.addAll(target.getImpliedBy()); } } if (target.getEquivalence() != null) { resulting.addAll(target.getEquivalence().getDifferences()); resulting.remove(target); } if (target.getConflict() != null && target.getConflict().getKind() == ConflictKind.PSEUDO) { resulting.addAll(target.getConflict().getDifferences()); resulting.remove(target); } if (target instanceof ReferenceChange && isSet((ReferenceChange)target, mergeRightToLeft)) { resulting.addAll(findInterlockedOneToOneDiffs((ReferenceChange)target, mergeRightToLeft)); } return resulting; }
Source:
<code>public MessageResponse onReceiveMessage(IMessageRecipient sender, String message) { if (!isReachable()) { return MessageResponse.UNREACHABLE; } User user = getUser(this); boolean afk = false; boolean isLastMessageReplyRecipient = ess.getSettings().isLastMessageReplyRecipient(); if (user != null) { if (user.isIgnoreMsg() && sender instanceof IUser && !((IUser) sender).isAuthorized("essentials.msgtoggle.bypass")) { return MessageResponse.MESSAGES_IGNORED; } afk = user.isAfk(); isLastMessageReplyRecipient = user.isLastMessageReplyRecipient(); if (sender instanceof IUser && user.isIgnoredPlayer((IUser) sender)) { return MessageResponse.SENDER_IGNORED; } } sendMessage(tl("msgFormat", sender.getDisplayName(), tl("meRecipient"), message)); if (user != null && !user.isIgnoreMsgSound()) { Sound dingSound; if (VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_9_R01)) { dingSound = Sound.ENTITY_EXPERIENCE_ORB_PICKUP; } else { <START> dingSound = Sound.valueOf("ORB_PICKUP"); <END> } Bukkit.getPlayer(user.getConfigUUID()).playSound(user.getLocation(), dingSound, 2.0f, 1.0f); } if (isLastMessageReplyRecipient) { long timeout = ess.getSettings().getLastMessageReplyRecipientTimeout() * 1000; if (getReplyRecipient() == null || !getReplyRecipient().isReachable() || System.currentTimeMillis() - this.lastMessageMs > timeout) { setReplyRecipient(sender); } } else { setReplyRecipient(sender); } this.lastMessageMs = System.currentTimeMillis(); return afk ? MessageResponse.SUCCESS_BUT_AFK : MessageResponse.SUCCESS; }</code><technical_language>literally sound configurable bool ? :</technical_language>

Target:
public MessageResponse onReceiveMessage(IMessageRecipient sender, String message) { if (!isReachable()) { return MessageResponse.UNREACHABLE; } User user = getUser(this); boolean afk = false; boolean isLastMessageReplyRecipient = ess.getSettings().isLastMessageReplyRecipient(); if (user != null) { if (user.isIgnoreMsg() && sender instanceof IUser && !((IUser) sender).isAuthorized("essentials.msgtoggle.bypass")) { return MessageResponse.MESSAGES_IGNORED; } afk = user.isAfk(); isLastMessageReplyRecipient = user.isLastMessageReplyRecipient(); if (sender instanceof IUser && user.isIgnoredPlayer((IUser) sender)) { return MessageResponse.SENDER_IGNORED; } } sendMessage(tl("msgFormat", sender.getDisplayName(), tl("meRecipient"), message)); if (user != null && !user.isIgnoreMsgSound()) { user.getBase().playSound(user.getLocation(), ORB_SOUND, 2.0f, 1.0f); } if (isLastMessageReplyRecipient) { long timeout = ess.getSettings().getLastMessageReplyRecipientTimeout() * 1000; if (getReplyRecipient() == null || !getReplyRecipient().isReachable() || System.currentTimeMillis() - this.lastMessageMs > timeout) { setReplyRecipient(sender); } } else { setReplyRecipient(sender); } this.lastMessageMs = System.currentTimeMillis(); return afk ? MessageResponse.SUCCESS_BUT_AFK : MessageResponse.SUCCESS; }
Source:
<code>public MailSender(MailSessionProvider mailSessionProvider) { this.mailSessionProvider = mailSessionProvider; this.executor = newFixedThreadPool( 2 * Runtime.getRuntime().availableProcessors(), new ThreadFactoryBuilder() .setNameFormat("MailNotificationsPool-%d") <START> .setDaemon(false) <END> .build()); }</code><technical_language>Please, add uncaught exceptions handler</technical_language>

Target:
public MailSender(MailSessionProvider mailSessionProvider) { this.mailSessionProvider = mailSessionProvider; this.executor = newFixedThreadPool( 2 * Runtime.getRuntime().availableProcessors(), new ThreadFactoryBuilder() .setNameFormat("MailNotificationsPool-%d") .setDaemon(false) .setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance()) .build()); }
Source:
<code>public static String getProperty(String key) { String value = null; Properties props = KuranetConfig.getProperties(); <START> if (!props.isEmpty()) { <END> value = props.getProperty(key); s_logger.debug("Got property " + key + " :: " + value); } return value; }</code><technical_language>point of returning empty Properties is avoid check. need update end date in copyright header for file change</technical_language>

Target:
public static String getProperty(String key) { Properties props = KuranetConfig.getProperties(); String value = props.getProperty(key); s_logger.debug("Got property :: {}", key, value); return value; }
Source:
<code>public ResourceGroupNameTemplate(String name) { this.name = requireNonNull(name, "name is null"); checkArgument(!name.isEmpty(), "Resource group name is empty"); checkArgument(name.indexOf('.') < 0, "Invalid resource group name. '%s' contains a '.'", name); String nameNoVariables = VARIABLE_PATTERN.matcher(name).replaceAll(""); checkArgument(!(nameNoVariables.contains("{") || nameNoVariables.contains("}") || nameNoVariables.contains("$")), <START> "Invalid resource group name. '%s' contains '$', '{', or '}", name); <END> }</code><technical_language>This error message is misleading. if @electrum suggestion</technical_language>

Target:
public ResourceGroupNameTemplate(String name) { checkArgument(!name.isEmpty(), "Resource group name is empty"); checkArgument(name.indexOf('.') < 0, "Invalid resource group name. '%s' contains a '.'", name); String nameNoVariables = VARIABLE_PATTERN.matcher(name).replaceAll(""); checkArgument( !(nameNoVariables.contains("{") || nameNoVariables.contains("}") || nameNoVariables.contains("$")), "Invalid resource group name. '%s' contains extraneous '$', '{', or '}", name); ImmutableList.Builder<NameFragment> builder = ImmutableList.builder(); Matcher matcher = VARIABLE_PATTERN.matcher(name); int lastMatchEnd = 0; while (matcher.find()) { int matchBegin = matcher.start(); int matchEnd = matcher.end(); if (matchBegin > lastMatchEnd) { builder.add(NameFragment.literal(name.substring(lastMatchEnd, matchBegin))); } builder.add(NameFragment.variable(name.substring(matchBegin + 2, matchEnd - 1))); lastMatchEnd = matchEnd; } if (lastMatchEnd != name.length()) { builder.add(NameFragment.literal(name.substring(lastMatchEnd, name.length()))); } this.fragments = builder.build(); }
Source:
<code>public static void updateGraphicsDevices(VmBase vmBase, Version clusterVersion) { if (vmBase == null || vmBase.getManagedDeviceMap() == null || clusterVersion == null) { return; } if (Version.v4_0.lessOrEquals(clusterVersion)) { if (removeVideoDevice(VmDeviceType.VNC, VmDeviceType.CIRRUS, vmBase.getManagedDeviceMap())) { <START> vmBase.setDefaultDisplayType(DisplayType.qxl); <END> } } List<VmDevice> videoDevs = getDevicesOfType(VmDeviceGeneralType.VIDEO, vmBase.getManagedDeviceMap()); boolean hasNoGraphics = getDevicesOfType(VmDeviceGeneralType.GRAPHICS, vmBase.getManagedDeviceMap()).isEmpty(); if (!videoDevs.isEmpty() && hasNoGraphics) { GraphicsDevice compatibleGraphics = getCompatibleGraphics(VmDeviceType.getByName(videoDevs.get(0).getDevice()), clusterVersion, vmBase); if (compatibleGraphics != null) { vmBase.getManagedDeviceMap().put(compatibleGraphics.getDeviceId(), compatibleGraphics); } } }</code><technical_language>if VM video device of type VNC+CIRRUS remove set default-display-type qxl, video device added kind of video type (vnc/spice) have</technical_language>

Target:
public static void updateGraphicsDevices(VmBase vmBase, Version clusterVersion) { if (vmBase == null || vmBase.getManagedDeviceMap() == null || clusterVersion == null) { return; } if (Version.v4_0.lessOrEquals(clusterVersion)) { if (removeVideoDevice(VmDeviceType.VNC, VmDeviceType.CIRRUS, vmBase.getManagedDeviceMap())) { vmBase.setDefaultDisplayType(DisplayType.qxl); addVideoDevice(vmBase); } } List<VmDevice> videoDevs = getDevicesOfType(VmDeviceGeneralType.VIDEO, vmBase.getManagedDeviceMap()); boolean hasNoGraphics = getDevicesOfType(VmDeviceGeneralType.GRAPHICS, vmBase.getManagedDeviceMap()).isEmpty(); if (!videoDevs.isEmpty() && hasNoGraphics) { GraphicsDevice compatibleGraphics = getCompatibleGraphics(VmDeviceType.getByName(videoDevs.get(0).getDevice()), clusterVersion, vmBase); if (compatibleGraphics != null) { vmBase.getManagedDeviceMap().put(compatibleGraphics.getDeviceId(), compatibleGraphics); } } }
Source:
<code>IgnoreNode load() throws IOException { IgnoreNode r; if (entry != null) { r = super.load(); if (r == null) r = new IgnoreNode(); } else { r = new IgnoreNode(); } <START> String p = repository.getConfig().getString( <END> ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_EXCLUDESFILE); File excludesfile; if (p.startsWith("~/")) excludesfile = new File(repository.getFS().userHome(), p.substring(2)); else excludesfile = new File(p); loadRulesFromFile(r, excludesfile); File exclude = new File(repository.getDirectory(), "info/exclude"); loadRulesFromFile(r, exclude); return r.getRules().isEmpty() ? null : r; }</code><technical_language>FWIW, getString() requires O(N) search locate relevant key. work this SectionParser stuff, CoreConfig. objects cached of a HashMap, reduces lookup cost closer O(1). Fortunately this code WorkingTreeIterator, EGit creating WTIs period of minutes time needs update decorations. pay a higher cost read file do for key in O(N) search, a bigger savings caching file contents. worth creating a new SectionParser for this, OK put this existing CoreConfig one</technical_language>

Target:
IgnoreNode load() throws IOException { IgnoreNode r; if (entry != null) { r = super.load(); if (r == null) r = new IgnoreNode(); } else { r = new IgnoreNode(); } FS fs = repository.getFS(); String path = repository.getConfig().get(CoreConfig.KEY) .getExcludesFile(); if (path != null) { File excludesfile; if (path.startsWith("~/")) excludesfile = fs.resolve(fs.userHome(), path.substring(2)); else excludesfile = fs.resolve(null, path); loadRulesFromFile(r, excludesfile); } File exclude = fs .resolve(repository.getDirectory(), "info/exclude"); loadRulesFromFile(r, exclude); return r.getRules().isEmpty() ? null : r; }
Source:
<code>public PageRankVertexProgram generateProgram(final Memory memory, final Graph... graphs) { final Traversal.Admin<Vertex, Edge> detachedTraversal = this.edgeTraversal.getPure(); <START> detachedTraversal.setStrategies(TraversalStrategies.GlobalCache.getStrategies(graphs[0].getClass())); <END> final PageRankVertexProgram.Builder builder = PageRankVertexProgram.build() .property(this.pageRankProperty) .iterations(this.times + 1) .alpha(this.alpha) .edges(detachedTraversal); if (this.previousTraversalVertexProgram()) builder.initialRank(new HaltedTraversersCountTraversal()); return builder.create(graphs); }</code><technical_language>thought this through, I Graph instance in this case - validated all? If this want reviewed in other "steps" do this</technical_language>

Target:
public PageRankVertexProgram generateProgram(final Memory memory, final Graph... graphs) { if (graphs.length != 1) { throw new IllegalArgumentException("Must provide one graph to use, received " + graphs.length); } final Graph graph = graphs[0]; final Traversal.Admin<Vertex, Edge> detachedTraversal = this.edgeTraversal.getPure(); detachedTraversal.setStrategies(TraversalStrategies.GlobalCache.getStrategies(graph.getClass())); final PageRankVertexProgram.Builder builder = PageRankVertexProgram.build() .property(this.pageRankProperty) .iterations(this.times + 1) .alpha(this.alpha) .edges(detachedTraversal); if (this.previousTraversalVertexProgram()) builder.initialRank(new HaltedTraversersCountTraversal()); return builder.create(graph); }
Source:
<code>protected boolean validateAttributes() { boolean validate = false; try { validate = PropertyAccessor.getInstance().getPropertyBoolean(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.VALIDATE_ATTRIBUTES_PROP); <START> } catch (PropertyAccessException ex) { <END> LOG.warn("Unable to access property for validating SAML attributes due to: {}", ex.getLocalizedMessage()); } return validate; }</code><technical_language>need log.warn("msg {}", ex.getLocalizedMessage(),ex);</technical_language>

Target:
protected boolean validateAttributes() { boolean validate = false; try { validate = PropertyAccessor.getInstance().getPropertyBoolean(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.VALIDATE_ATTRIBUTES_PROP); } catch (PropertyAccessException ex) { LOG.warn("Unable to access property for validating SAML attributes due to: {}", ex.getLocalizedMessage(), ex); } return validate; }
Source:
<code>private void updateComputer(Node n, Map<String,Computer> byNameMap, Set<Computer> used, boolean automaticSlaveLaunch) { Map<Node,Computer> computers = getComputerMap(); Computer c; c = byNameMap.get(n.getNodeName()); if (c!=null) { try { c.setNode(n); used.add(c); } catch (RuntimeException e) { LOGGER.log(Level.WARNING, "Error updating node " + n.getNodeName() + ", continuing", e); } } else { if(n.getNumExecutors()>0 || n==Jenkins.getInstance()) { try { c = n.createComputer(); } catch(RuntimeException ex) { LOGGER.log(Level.WARNING, "Error retrieving computer for node " + n.getNodeName() + ", continuing", ex); } if (c == null) { LOGGER.log(Level.WARNING, "Cannot create computer for node {0}, the {1}#createComputer() method returned null. Skipping this node", new Object[]{n.getNodeName(), n.getClass().getName()}); return; } computers.put(n, c); if (!n.isHoldOffLaunchUntilSave() && automaticSlaveLaunch) { RetentionStrategy retentionStrategy = c.getRetentionStrategy(); if (retentionStrategy != null) { retentionStrategy.start(c); } else { c.connect(true); } } used.add(c); } else { <START> LOGGER.log(Level.WARNING, "Node {0} has not executors. Cannot udate the Computer instance for it", n.getNodeName()); <END> } } }</code><technical_language>update</technical_language>

Target:
private void updateComputer(Node n, Map<String,Computer> byNameMap, Set<Computer> used, boolean automaticSlaveLaunch) { Map<Node,Computer> computers = getComputerMap(); Computer c; c = byNameMap.get(n.getNodeName()); if (c!=null) { try { c.setNode(n); used.add(c); } catch (RuntimeException e) { LOGGER.log(Level.WARNING, "Error updating node " + n.getNodeName() + ", continuing", e); } } else { if(n.getNumExecutors()>0 || n==Jenkins.getInstance()) { try { c = n.createComputer(); } catch(RuntimeException ex) { LOGGER.log(Level.WARNING, "Error retrieving computer for node " + n.getNodeName() + ", continuing", ex); } if (c == null) { LOGGER.log(Level.WARNING, "Cannot create computer for node {0}, the {1}#createComputer() method returned null. Skipping this node", new Object[]{n.getNodeName(), n.getClass().getName()}); return; } computers.put(n, c); if (!n.isHoldOffLaunchUntilSave() && automaticSlaveLaunch) { RetentionStrategy retentionStrategy = c.getRetentionStrategy(); if (retentionStrategy != null) { retentionStrategy.start(c); } else { c.connect(true); } } used.add(c); } else { LOGGER.log(Level.WARNING, "Node {0} has no executors. Cannot update the Computer instance of it", n.getNodeName()); } } }