auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public RyaClient( final Install install, final Optional<CreatePCJ> createPcj, final Optional<DeletePCJ> deletePcj, final Optional<CreatePeriodicPCJ> createPeriodicPcj, final Optional<DeletePeriodicPCJ> deletePeriodicPcj, final Optional<ListIncrementalQueries> listIncrementalQueries, final Optional<BatchUpdatePCJ> batchUpdatePcj, final GetInstanceDetails getInstanceDetails, final InstanceExists instanceExists, final ListInstances listInstances, final Optional<AddUser> addUser, final Optional<RemoveUser> removeUser, final Uninstall uninstall, final LoadStatements loadStatements, final LoadStatementsFile loadStatementsFile, final ExecuteSparqlQuery executeSparqlQuery) { this.install = requireNonNull(install); this.createPcj = requireNonNull(createPcj); this.deletePcj = requireNonNull(deletePcj); this.createPeriodicPcj = requireNonNull(createPeriodicPcj); this.deletePeriodicPcj = requireNonNull(deletePeriodicPcj); this.listIncrementalQueries = requireNonNull(listIncrementalQueries); this.bactchUpdatePCJ = requireNonNull(batchUpdatePcj); this.getInstanceDetails = requireNonNull(getInstanceDetails); this.instanceExists = requireNonNull(instanceExists); this.listInstances = requireNonNull(listInstances); this.addUser = requireNonNull(addUser); this.removeUser = requireNonNull(removeUser); this.uninstall = requireNonNull(uninstall); this.loadStatements = loadStatements; this.loadStatementsFile = loadStatementsFile; this.executeSparqlQuery = executeSparqlQuery; }

Target:
public RyaClient( final Install install, final Optional<CreatePCJ> createPcj, final Optional<DeletePCJ> deletePcj, final Optional<CreatePeriodicPCJ> createPeriodicPcj, final Optional<DeletePeriodicPCJ> deletePeriodicPcj, final Optional<ListIncrementalQueries> listIncrementalQueries, final Optional<BatchUpdatePCJ> batchUpdatePcj, final GetInstanceDetails getInstanceDetails, final InstanceExists instanceExists, final ListInstances listInstances, final Optional<AddUser> addUser, final Optional<RemoveUser> removeUser, final Uninstall uninstall, final LoadStatements loadStatements, final LoadStatementsFile loadStatementsFile, final ExecuteSparqlQuery executeSparqlQuery) { this.install = requireNonNull(install); this.createPcj = requireNonNull(createPcj); this.deletePcj = requireNonNull(deletePcj); this.createPeriodicPcj = requireNonNull(createPeriodicPcj); this.deletePeriodicPcj = requireNonNull(deletePeriodicPcj); this.listIncrementalQueries = requireNonNull(listIncrementalQueries); this.bactchUpdatePCJ = requireNonNull(batchUpdatePcj); this.getInstanceDetails = requireNonNull(getInstanceDetails); this.instanceExists = requireNonNull(instanceExists); this.listInstances = requireNonNull(listInstances); this.addUser = requireNonNull(addUser); this.removeUser = requireNonNull(removeUser); this.uninstall = requireNonNull(uninstall); this.loadStatements = requireNonNull(loadStatements); this.loadStatementsFile = requireNonNull(loadStatementsFile); this.executeSparqlQuery = requireNonNull(executeSparqlQuery); }
Source:
public void cancel(Locality locality) { for (I id: expirationTracker.getTrackedIds()) { if (Thread.currentThread().isInterrupted()) break; if (!locality.isLocal(id)) { this.cancel(id); } } }

Target:
public void cancel(Locality locality) { for (I id: this.expirationFutures.keySet()) { if (Thread.currentThread().isInterrupted()) break; if (!locality.isLocal(id)) { this.cancel(id); } } }
Source:
public void selectAllAdvancedOptions() { clickAdvancedButton(); chooseAdvancedOption(0); }

Target:
public void selectAllAdvancedOptions() { clickAdvancedButton(); chooseAdvancedOption(0); PageObjectLogging.log("selectAllAdvancedOptions", "All advance options are selected", true, driver); }
Source:
public int hashCode() { return AvailableConnectionManager.class.hashCode(); }

Target:
public int hashCode() { return Objects.hash(predicate, connectionThatMatched); }
Source:
public OneCoreTickCounters(Integer[] c) { assert (c != null && c.length >= 7); fUser = c[0]; fNice = c[1]; fSystem = c[2]; fIdle = c[3]; fIowait = c[4]; fIrq = c[5]; fSoftirq = c[6]; }

Target:
public OneCoreTickCounters(Integer[] c) { assert (c != null && c.length >= 7); if (c == null || c.length < 7) return; fUser = c[0]; fNice = c[1]; fSystem = c[2]; fIdle = c[3]; fIowait = c[4]; fIrq = c[5]; fSoftirq = c[6]; }
Source:
public void connectionChanged(String property, Object oldValue, Object newValue) { if (ConnectionProperties.PROPERTY_RESOURCE.equals(property)) { if (newValue != null) { IResource newResource = (IResource) newValue; ProjectWrapper projectWrapper = findProjectWrapper(newResource); if (projectWrapper != null) { if (projectWrapper.getResource().equals(newResource)) { projectWrapper.updateWith((IProject) newResource); } else { IResource oldVersion = resourceCache.getCachedVersion(newResource); if (oldVersion == null) { handleAdd(projectWrapper, newResource); } else if (OpenshiftUIModel.isOlder(oldVersion, newResource)) { handleUpdate(projectWrapper, newResource); } } } } else if (oldValue != null) { IResource oldResource = resourceCache.getCachedVersion((IResource) oldValue); if (oldResource != null) { ProjectWrapper projectWrapper = findProjectWrapper(oldResource); handleRemove(projectWrapper, oldResource); } } else { OpenShiftUIActivator.log(IStatus.WARNING, "old and new value are null", new RuntimeException("Warnign origing")); } } else if (ConnectionProperties.PROPERTY_PROJECTS.equals(property) && (newValue instanceof List)) { handleProjectsChanged((List<IProject>)newValue); } }

Target:
void connectionChanged(String property, Object oldValue, Object newValue) { if (ConnectionProperties.PROPERTY_RESOURCE.equals(property)) { if (newValue != null) { IResource newResource = (IResource) newValue; ProjectWrapper projectWrapper = findProjectWrapper(newResource); if (projectWrapper != null) { if (projectWrapper.getWrapped().equals(newResource)) { projectWrapper.updateWith((IProject) newResource); } else { IResource oldVersion = resourceCache.getCachedVersion(newResource); if (oldVersion == null) { handleAdd(projectWrapper, newResource); } else if (OpenshiftUIModel.isOlder(oldVersion, newResource)) { handleUpdate(projectWrapper, newResource); } } } } else if (oldValue != null) { IResource oldResource = resourceCache.getCachedVersion((IResource) oldValue); if (oldResource != null) { ProjectWrapper projectWrapper = findProjectWrapper(oldResource); handleRemove(projectWrapper, oldResource); } } else { OpenShiftUIActivator.log(IStatus.WARNING, "old and new value are null", new RuntimeException("Warning origing")); } } else if (ConnectionProperties.PROPERTY_PROJECTS.equals(property) && (newValue instanceof List)) { updateWithResources((List<IProject>)newValue); } }
Source:
private EntityInteractHandler onRightClickEntity() { return (e, item, hand) -> { if ((e.getRightClicked() instanceof Sheep) && (e.getRightClicked() instanceof LivingEntity)) { Sheep s = (Sheep) e.getRightClicked(); if (s.getCustomName() != null) { if (s.getCustomName().equals(ChatColor.DARK_PURPLE+"Tainted Sheep") && s.getColor() == DyeColor.PURPLE) { return; } } if (e.getPlayer().getGameMode() != GameMode.CREATIVE) { ItemUtils.consumeItem(item, false); } s.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 60, 2)); s.setColor(DyeColor.PURPLE); s.setCustomName(ChatColor.DARK_PURPLE+"Tainted Sheep"); e.setCancelled(true); } }; }

Target:
private EntityInteractHandler onRightClickEntity() { return (e, item, hand) -> { if (e.getRightClicked() instanceof Sheep) { Sheep s = (Sheep) e.getRightClicked(); if (s.getCustomName() != null) { e.setCancelled(true); return; } if (e.getPlayer().getGameMode() != GameMode.CREATIVE) { ItemUtils.consumeItem(item, false); } s.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 60, 2)); s.setColor(DyeColor.PURPLE); s.setCustomName(ChatColor.DARK_PURPLE + "Tainted Sheep"); e.setCancelled(true); } }; }
Source:
public void does_not_generate_events_for_same_markers() throws Exception { IMarker marker = this.testFile.createMarker(IMarker.PROBLEM); marker.setAttribute(IMarker.LINE_NUMBER, 1); IMarker marker2 = this.testFile.createMarker(IMarker.PROBLEM); marker2.setAttribute(IMarker.LINE_NUMBER, 2); this.workspace.save(true, null); Job.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_BUILD, null); this.testFile.appendContents(generateFileStreamLines(10), true, true, null); this.workspace.save(true, null); Job.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_BUILD, null); ArgumentCaptor<StaticAnalysisWarningEvent> captor = ArgumentCaptor.forClass(StaticAnalysisWarningEvent.class); Mockito.verify(this.trackingEventManager, Mockito.times(2)).addEvent(captor.capture()); assertTrue(captor.getAllValues().stream() .allMatch(event -> event.getType() == TrackingEventType.SA_WARNING_CREATED)); }

Target:
public void does_not_generate_events_for_same_markers() throws Exception { IMarker marker = this.testFile.createMarker(IMarker.PROBLEM); marker.setAttribute(IMarker.LINE_NUMBER, 1); IMarker marker2 = this.testFile.createMarker(IMarker.PROBLEM); marker2.setAttribute(IMarker.LINE_NUMBER, 2); this.saveWorkspaceAndWaitForBuild(); this.testFile.appendContents(generateFileStreamLines(10), true, true, null); this.saveWorkspaceAndWaitForBuild(); assertEquals(generatedEvents.size(), 2); assertTrue(generatedEvents.stream() .allMatch(TrackingEventType.SA_WARNING_CREATED::equals)); }
Source:
protected void updateConfiguration() { Configuration configuration = getConfig(); universe = new Universe(MIN_UNIVERSE_ID); receiverNodes.clear(); if (configuration.get(CONFIG_ADDRESS) == null) { receiverNodes.put(new IpNode("localhost:9020"), null); logger.debug("sending to for {}", receiverNodes, this.thing.getUID()); } else { for (IpNode receiverNode : IpNode.fromString((String) configuration.get(CONFIG_ADDRESS), DEFAULT_PORT)) { receiverNodes.put(receiverNode, null); logger.debug("sending to for {}", receiverNode, this.thing.getUID()); } } super.updateConfiguration(); updateStatus(ThingStatus.ONLINE); logger.debug("updated configuration for Lib485 bridge {}", this.thing.getUID()); }

Target:
protected void updateConfiguration() { Configuration configuration = getConfig(); universe = new Universe(MIN_UNIVERSE_ID); receiverNodes.clear(); if (configuration.get(CONFIG_ADDRESS) == null) { receiverNodes.put(new IpNode("localhost:9020"), null); logger.debug("sending to for {}", receiverNodes, this.thing.getUID()); } else { try { for (IpNode receiverNode : IpNode.fromString((String) configuration.get(CONFIG_ADDRESS), DEFAULT_PORT)) { receiverNodes.put(receiverNode, null); logger.debug("sending to for {}", receiverNode, this.thing.getUID()); } } catch (IllegalArgumentException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage()); return; } } super.updateConfiguration(); updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.NONE); logger.debug("updated configuration for Lib485 bridge {}", this.thing.getUID()); }
Source:
private void updateProperties() { String selectedFileFormatDefinitionStr = format.getValue(); if (!StringUtils.isEmpty(selectedFileFormatDefinitionStr) && !StringUtils.equals(previousFormatValue, selectedFileFormatDefinitionStr)) { V props = referenceMemento.get(selectedFileFormatDefinitionStr); if (props == null) { Definition<V> fileFormatDefinition = getDefinitionRegistry().getDefinitionsMapByType(getDefinitionClass()) .get(selectedFileFormatDefinitionStr); props = getDefinitionRegistry().createProperties(fileFormatDefinition, FORMAT_PROPERTIES_NAME); referenceMemento.put(selectedFileFormatDefinitionStr, props); } formatProperties = props; } else if (!StringUtils.isEmpty(selectedFileFormatDefinitionStr) && StringUtils.equals(previousFormatValue, selectedFileFormatDefinitionStr)) { referenceMemento.put(selectedFileFormatDefinitionStr, (V) formatProperties); } else { formatProperties = PropertiesImpl.createNewInstance(PropertiesImpl.class, FORMAT_PROPERTIES_NAME); } previousFormatValue = selectedFileFormatDefinitionStr; }

Target:
private void updateProperties() { String selectedFileFormatDefinitionStr = format.getValue(); if (!StringUtils.isEmpty(selectedFileFormatDefinitionStr) && !StringUtils.equals(previousFormatValue, selectedFileFormatDefinitionStr)) { V props = referenceMemento.get(selectedFileFormatDefinitionStr); if (props == null) { Definition<V> fileFormatDefinition = getDefinitionRegistry().getDefinitionsMapByType(getDefinitionClass()) .get(selectedFileFormatDefinitionStr); props = getDefinitionRegistry().createProperties(fileFormatDefinition, FORMAT_PROPERTIES_NAME); referenceMemento.put(selectedFileFormatDefinitionStr, props); } formatProperties = props; } else if (!StringUtils.isEmpty(selectedFileFormatDefinitionStr) && StringUtils.equals(previousFormatValue, selectedFileFormatDefinitionStr)) { referenceMemento.put(selectedFileFormatDefinitionStr, (V) formatProperties); } previousFormatValue = selectedFileFormatDefinitionStr; }
Source:
public List<ChangeControl> controlsFor(Iterable<Change> changes) throws NoSuchChangeException { final List<ChangeControl> controls = new ArrayList<ChangeControl>(); for (Change c : changes) { controls.add(controlFor(c)); } return controls; }

Target:
private List<ChangeControl> controlsFor(Iterable<Change> changes) throws NoSuchChangeException { final List<ChangeControl> controls = new ArrayList<ChangeControl>(); for (Change c : changes) { controls.add(controlFor(c)); } return controls; }
Source:
public void mapGuestAgentSsoFromBackendToRest() throws Exception { SsoMethod backendSsoMethod = SsoMethod.GUEST_AGENT; Sso restSso = SsoMapper.map(backendSsoMethod, null); assertNotNull(restSso); assertNotNull(restSso.getMethods()); assertNotNull(restSso.getMethods().getMethods()); assertTrue(restSso.getMethods().getMethods().size() == 1); assertEquals(org.ovirt.engine.api.model.SsoMethod.GUEST_AGENT.toString(), restSso.getMethods().getMethods().get(0)); }

Target:
public void mapGuestAgentSsoFromBackendToRest() throws Exception { SsoMethod backendSsoMethod = SsoMethod.GUEST_AGENT; Sso restSso = SsoMapper.map(backendSsoMethod, null); assertNotNull(restSso); assertNotNull(restSso.getMethods()); assertNotNull(restSso.getMethods().getMethods()); assertEquals(1, restSso.getMethods().getMethods().size()); assertEquals(org.ovirt.engine.api.model.SsoMethod.GUEST_AGENT.toString(), restSso.getMethods().getMethods().get(0)); }
Source:
private static void onWriteCompleted(ResultHandler completeHandler, AtomicInteger openInstances, PersistenceManager<?> persistenceManager) { persistenceManager.shutdown(); openInstances.decrementAndGet(); if (openInstances.get() == 0) { log.info("flushAllDataToDisk completed"); UserThread.execute(completeHandler::handleResult); } }

Target:
private static void onWriteCompleted(ResultHandler completeHandler, AtomicInteger openInstances, PersistenceManager<?> persistenceManager) { persistenceManager.shutdown(); if (openInstances.decrementAndGet() == 0) { log.info("flushAllDataToDisk completed"); UserThread.execute(completeHandler::handleResult); } }
Source:
private void loadThumbnail(String imageUrl) { if (imageUrl == null) { AppLog.e(AppLog.T.MEDIA, "Image url is null! Show the default error image."); showErrorImage(); } Uri uri = Uri.parse(imageUrl); String filepath = uri.getLastPathSegment(); if (MediaUtils.isValidImage(filepath)) { int size = DisplayUtils.dpToPx( getActivity(), getResources().getDimensionPixelSize(R.dimen.image_settings_dialog_thumbnail_size) ); mImageView.setVisibility(View.GONE); mProgress.setVisibility(View.VISIBLE); mImageLoader.get(imageUrl, new ImageLoader.ImageListener() { @Override public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) { if (!isAdded()) { return; } if (response.getBitmap() != null) { mImageView.setVisibility(View.VISIBLE); mProgress.setVisibility(View.GONE); mImageView.setImageBitmap(response.getBitmap()); } else { if (!isImmediate) { showErrorImage(); } } } @Override public void onErrorResponse(VolleyError error) { AppLog.e(AppLog.T.MEDIA, error); if (!isAdded()) { return; } showErrorImage(); } }, size, 0); } else { showErrorImage(); } }

Target:
private void loadThumbnail(String imageUrl) { if (imageUrl == null) { AppLog.e(AppLog.T.MEDIA, "Image url is null! Show the default error image."); showErrorImage(); return; } Uri uri = Uri.parse(imageUrl); String filepath = uri.getLastPathSegment(); if (MediaUtils.isValidImage(filepath)) { int size = DisplayUtils.dpToPx( getActivity(), getResources().getDimensionPixelSize(R.dimen.image_settings_dialog_thumbnail_size) ); mImageView.setVisibility(View.GONE); mProgress.setVisibility(View.VISIBLE); mImageLoader.get(imageUrl, new ImageLoader.ImageListener() { @Override public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) { if (!isAdded()) { return; } if (response.getBitmap() != null) { mImageView.setVisibility(View.VISIBLE); mProgress.setVisibility(View.GONE); mImageView.setImageBitmap(response.getBitmap()); } else { if (!isImmediate) { showErrorImage(); } } } @Override public void onErrorResponse(VolleyError error) { AppLog.e(AppLog.T.MEDIA, error); if (!isAdded()) { return; } showErrorImage(); } }, size, 0); } else { showErrorImage(); } }
Source:
void stopProfileServices() { Class[] supportedProfileServices = Config.getSupportedProfiles(); if (mRunningProfiles.size() > 0) { setAllProfileServiceStates(supportedProfileServices, BluetoothAdapter.STATE_OFF); } debugLog("stopProfileServices() - No profiles services to stop or already stopped."); }

Target:
void stopProfileServices() { Class[] supportedProfileServices = Config.getSupportedProfiles(); if (mRunningProfiles.size() == 0) { debugLog("stopProfileServices() - No profiles services to stop or already stopped."); return; } setAllProfileServiceStates(supportedProfileServices, BluetoothAdapter.STATE_OFF); }
Source:
public Mono<IndexDocumentsResult> uploadDocuments(Iterable<?> documents) { return this.uploadDocumentsWithResponse(documents) .map(Response::getValue); }

Target:
public Mono<IndexDocumentsResult> uploadDocuments(Iterable<?> documents) { try { return this.uploadDocumentsWithResponse(documents) .map(Response::getValue); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Source:
public Statement apply(final Statement base, FrameworkMethod method, Object target) { return new Statement() { @Override public void evaluate() throws Throwable { runCount++; base.evaluate(); } ; }; }

Target:
public Statement apply(final Statement base, FrameworkMethod method, Object target) { return new Statement() { @Override public void evaluate() throws Throwable { runCount++; base.evaluate(); } }; }
Source:
public void allowsOnlyProperlyNamedLocalVariables() throws Exception { this.validateCheckstyle( "LocalVariableNames.java", false, Matchers.allOf( Matchers.not( Matchers.stringContainsInOrder( Arrays.asList( "aaa", "twelveletter", "ise" ) ) ), Matchers.stringContainsInOrder( Arrays.asList( "LocalVariableNames.java", "Name 'prolongations' must match pattern", "Name 'camelCase' must match pattern '^[a-z]{3,12}$'.", "Name 'number1' must match pattern '^[a-z]{3,12}$'.", "Name 'ex' must match pattern '^[a-z]{3,12}$'.", "Name 'a' must match pattern '^[a-z]{3,12}$'.", "Name 'ae' must match pattern '^ex|[a-z]{3,12}$'.", "Name 'e' must match pattern '^ex|[a-z]{3,12}$'." ) ) ) ); }

Target:
public void allowsOnlyProperlyNamedLocalVariables() throws Exception { final String result = this.runValidation( "LocalVariableNames.java", false ); MatcherAssert.assertThat( StringUtils.countMatches(result, "LocalVariableNames.java"), Matchers.is(Tv.SEVEN) ); MatcherAssert.assertThat( result, Matchers.allOf( Matchers.not( Matchers.stringContainsInOrder( Arrays.asList( "aaa", "twelveletter", "ise" ) ) ), Matchers.stringContainsInOrder( Arrays.asList( "Name 'prolongations' must match pattern", "Name 'camelCase' must match pattern '^[a-z]{3,12}$'.", "Name 'number1' must match pattern '^[a-z]{3,12}$'.", "Name 'ex' must match pattern '^[a-z]{3,12}$'.", "Name 'a' must match pattern '^[a-z]{3,12}$'.", "Name 'ae' must match pattern '^ex|[a-z]{3,12}$'.", "Name 'e' must match pattern '^ex|[a-z]{3,12}$'." ) ) ) ); }
Source:
public void onPrepareOptionsMenu(Menu menu) { MenuItem sosItem = menu.findItem(R.id.sosBroadcast); if(sharedPreferences.getBoolean(KEY_STATUS, false)){ sosItem.setEnabled(false); } else { sosItem.setEnabled(true); } super.onPrepareOptionsMenu(menu); }

Target:
public void onPrepareOptionsMenu(Menu menu) { MenuItem sosItem = menu.findItem(R.id.sosBroadcast); sosItem.setEnabled(!sharedPreferences.getBoolean(KEY_STATUS, false)); super.onPrepareOptionsMenu(menu); }
Source:
public long transferFrom(FileChannel fileChannel, long position, long count) throws IOException { if (state == State.CLOSING) throw closingException(); if (state != State.READY) return 0; if (!flush(netWriteBuffer)) return 0; long channelSize = fileChannel.size(); if (position > channelSize) return 0; int bytesToWrite = (int) Math.min(Math.min(count, channelSize - position), Integer.MAX_VALUE); if (fileChannelBuffer == null) { int transferSize = 16384; fileChannelBuffer = ByteBuffer.allocateDirect(transferSize); } else { fileChannelBuffer.clear(); } int bytesWritten = 0; long pos = position; try { while (bytesWritten < bytesToWrite) { int bytesRemaining = bytesToWrite - bytesWritten; if (bytesRemaining < fileChannelBuffer.limit()) fileChannelBuffer.limit(bytesRemaining); int bytesRead = fileChannel.read(fileChannelBuffer, pos); if (bytesRead <= 0) break; fileChannelBuffer.flip(); int networkBytesWritten = write(fileChannelBuffer); bytesWritten += networkBytesWritten; if (networkBytesWritten != bytesRead) break; pos += networkBytesWritten; fileChannelBuffer.clear(); } return bytesWritten; } catch (IOException x) { if (bytesWritten > 0) return bytesWritten; throw x; } }

Target:
public long transferFrom(FileChannel fileChannel, long position, long count) throws IOException { if (state == State.CLOSING) throw closingException(); if (state != State.READY) return 0; if (!flush(netWriteBuffer)) return 0; long channelSize = fileChannel.size(); if (position > channelSize) return 0; int totalBytesToWrite = (int) Math.min(Math.min(count, channelSize - position), Integer.MAX_VALUE); if (fileChannelBuffer == null) { int transferSize = 32768; fileChannelBuffer = ByteBuffer.allocateDirect(transferSize); fileChannelBuffer.position(fileChannelBuffer.limit()); } int totalBytesWritten = 0; long pos = position; try { while (totalBytesWritten < totalBytesToWrite) { if (!fileChannelBuffer.hasRemaining()) { fileChannelBuffer.clear(); int bytesRemaining = totalBytesToWrite - totalBytesWritten; if (bytesRemaining < fileChannelBuffer.limit()) fileChannelBuffer.limit(bytesRemaining); int bytesRead = fileChannel.read(fileChannelBuffer, pos); if (bytesRead <= 0) break; fileChannelBuffer.flip(); } int networkBytesWritten = write(fileChannelBuffer); totalBytesWritten += networkBytesWritten; if (fileChannelBuffer.hasRemaining()) break; pos += networkBytesWritten; } return totalBytesWritten; } catch (IOException e) { if (totalBytesWritten > 0) return totalBytesWritten; throw e; } }
Source:
public Iterator<ItemStack> iterator() { return Iterators.singletonIterator(item.copy()); }

Target:
public Iterator<ItemStack> iterator() { return Iterators.singletonIterator(new ItemStack(item.get(), 1, damage)); }
Source:
private void restoreAutoCommitState(final Handle handle) { try { final LocalStuff stuff = localStuff.remove(handle); if (stuff != null) { handle.getConnection().setAutoCommit(stuff.getInitialAutocommit()); stuff.getCheckpoints().clear(); } } catch (SQLException e) { throw new UnableToRestoreAutoCommitStateException(e); } finally { if (localStuff.containsKey(handle)) { localStuff.remove(handle); } } }

Target:
private void restoreAutoCommitState(final Handle handle) { try { final LocalStuff stuff = localStuff.remove(handle); if (stuff != null) { handle.getConnection().setAutoCommit(stuff.getInitialAutocommit()); stuff.getCheckpoints().clear(); } } catch (SQLException e) { throw new UnableToRestoreAutoCommitStateException(e); } finally { localStuff.remove(handle); } }
Source:
public void closeDriverFactoryIfFullyCreated() { if (closed) { return; } if (isNoMoreDriverRunner() && pendingCreation.get() == 0) { driverFactory.noMoreDrivers(Lifespan.taskWide()); driverFactory.noMoreDrivers(); closed = true; } }

Target:
public void closeDriverFactoryIfFullyCreated() { if (closed.get()) { return; } if (isNoMoreDriverRunner() && pendingCreation.get() == 0) { if (!closed.compareAndSet(false, true)) { return; } driverFactory.noMoreDrivers(Lifespan.taskWide()); driverFactory.noMoreDrivers(); } }
Source:
protected CallbackTracker(RestRequest restRequest, String operationType, Histogram operationTimeTracker, Histogram callbackProcessingTimeTracker) { this.restRequest = restRequest; this.operationType = operationType; this.operationTimeTracker = operationTimeTracker; this.callbackProcessingTimeTracker = callbackProcessingTimeTracker; blobId = RestUtils.getOperationOrBlobIdFromUri(restRequest); }

Target:
CallbackTracker(RestRequest restRequest, String operationType, Histogram operationTimeTracker, Histogram callbackProcessingTimeTracker) { this.restRequest = restRequest; this.operationType = operationType; this.operationTimeTracker = operationTimeTracker; this.callbackProcessingTimeTracker = callbackProcessingTimeTracker; blobId = RestUtils.getOperationOrBlobIdFromUri(restRequest); }
Source:
public void channelInactive(ChannelHandlerContext ctx) throws Exception { LOG.trace("Channel inactive {}", ctx.channel()); allChannels.remove(ctx.channel()); NettyServerCnxn cnxn = ctx.channel().attr(CONNECTION_ATTRIBUTE).getAndSet(null); if (cnxn != null) { LOG.trace("Channel inactive caused close {}", cnxn); cnxn.close(); } }

Target:
public void channelInactive(ChannelHandlerContext ctx) throws Exception { if (LOG.isTraceEnabled()) { LOG.trace("Channel inactive {}", ctx.channel()); } allChannels.remove(ctx.channel()); NettyServerCnxn cnxn = ctx.channel().attr(CONNECTION_ATTRIBUTE).getAndSet(null); if (cnxn != null) { if (LOG.isTraceEnabled()) { LOG.trace("Channel inactive caused close {}", cnxn); } cnxn.close(); } }
Source:
public void aspectSkippingOrphanArtifactsWithLocation() throws Exception { scratch.file("aspects/BUILD", ""); scratch.file( "aspects/print.bzl", "def _print_expanded_copts_impl(target, ctx):", " # Make sure the rule has a srcs attribute.", " if hasattr(ctx.rule.attr, 'cmd'):", " cmd = ctx.rule.attr.cmd", " print(\"{} -> {}\".format(cmd, ctx.expand_location(cmd, [])))", " return []", "", "print_expanded_copts = aspect(", " implementation = _print_expanded_copts_impl,", " attr_aspects = ['deps'],", ")"); scratch.file("simple/BUILD", "filegroup(", " name = \"files\",", " srcs = [\"afile\"],", ")", "", "genrule(", " name = \"concat_all_files\",", " srcs = [\":files\"],", " outs = [\"concatenated.txt\"],", " cmd = \"cat $(location :files) > $@\"", ")"); reporter.removeHandler(failFastHandler); AnalysisResult result = update(ImmutableList.of("aspects/print.bzl%print_expanded_copts"), " assertThat(result.hasError()).isFalse(); }

Target:
public void aspectSkippingOrphanArtifactsWithLocation() throws Exception { scratch.file( "simple/print.bzl", "def _print_expanded_location_impl(target, ctx):", " return struct(result=ctx.expand_location(ctx.rule.attr.cmd, []))", "", "print_expanded_location = aspect(", " implementation = _print_expanded_location_impl,", ")"); scratch.file("simple/BUILD", "filegroup(", " name = \"files\",", " srcs = [\"afile\"],", ")", "", "genrule(", " name = \"concat_all_files\",", " srcs = [\":files\"],", " outs = [\"concatenated.txt\"],", " cmd = \"$(location :files)\"", ")"); reporter.removeHandler(failFastHandler); AnalysisResult analysisResult = update(ImmutableList.of(" assertThat(analysisResult.hasError()).isFalse(); AspectValue value = Iterables.getOnlyElement(analysisResult.getAspects()); String result = (String) value.getConfiguredAspect().get("result"); assertThat(result).isEqualTo("simple/afile"); }
Source:
private static <K, V> Cache.Entry<K, V> wrap(final K key, final OnHeapValueHolder<V> mappedValue) { return wrap(new Map.Entry<K, OnHeapValueHolder<V>>() { @Override public K getKey() { return key; } @Override public OnHeapValueHolder<V> getValue() { return mappedValue; } @Override public OnHeapValueHolder<V> setValue(OnHeapValueHolder<V> value) { throw new UnsupportedOperationException(); } }); }

Target:
private static <K, V> Cache.Entry<K, V> wrap(final K key, final OnHeapValueHolder<V> mappedValue) { return new Cache.Entry<K, V>() { @Override public K getKey() { return key; } @Override public V getValue() { return mappedValue.value(); } @Override public long getCreationTime(TimeUnit unit) { return mappedValue.creationTime(unit); } @Override public long getLastAccessTime(TimeUnit unit) { return mappedValue.lastAccessTime(unit); } @Override public float getHitRate(TimeUnit unit) { return mappedValue.hitRate(unit); } }; }
Source:
public void loadFileMetadata(File file) { boolean containsPackedVariable = false; GridDataset gridDs = null; try { setNcksSubsetParameters(file.getAbsoluteFile().toString()); setNcksExtraParameters(); this.timeUnlimited = time.isUnlimited(); } catch (Exception e) { logger.error(e.getMessage()); throw new GoGoDuckException(e.getMessage(), e); } try { if (goGoDuckConfig.getUnpackNetcdf(profile)) { this.containsPackedVariable = true; } else { String location = file.getAbsolutePath(); Set<NetcdfDataset.Enhance> enhanceMode = new HashSet<>(); enhanceMode.add(NetcdfDataset.Enhance.ScaleMissing); gridDs = GridDataset.open(location, enhanceMode); for (Variable var : gridDs.getNetcdfDataset().getVariables()) { VariableDS vds = new VariableDS(var.getGroup(), var, true); if (vds.hasScaleOffset()) { containsPackedVariable = true; break; } } this.containsPackedVariable = containsPackedVariable; } } catch (Exception e) { logger.error(e.getMessage()); throw new GoGoDuckException(e.getMessage(), e); } finally { try { if (gridDs != null) { gridDs.close(); } } catch (IOException e) { logger.error(e.getMessage()); throw new GoGoDuckException(e.getMessage(), e); } } }

Target:
public void loadFileMetadata(File file) { boolean fileContainPackedVariables = false; GridDataset gridDs = null; try { setTimeLatLon(file.getAbsoluteFile().toString()); String location = file.getAbsolutePath(); Set<NetcdfDataset.Enhance> enhanceMode = new HashSet<>(); enhanceMode.add(NetcdfDataset.Enhance.ScaleMissing); gridDs = GridDataset.open(location, enhanceMode); for (Variable var : gridDs.getNetcdfDataset().getVariables()) { VariableDS vds = new VariableDS(var.getGroup(), var, true); if (vds.hasScaleOffset()) { fileContainPackedVariables = true; break; } } boolean unpackPackedVariables = goGoDuckConfig.getUnpack(profile); if (fileContainPackedVariables && unpackPackedVariables) { this.unpack = true; } else { this.unpack = false; } } catch (Exception e) { logger.error(e.getMessage()); throw new GoGoDuckException(e.getMessage(), e); } finally { close(gridDs, GridDataset.class); } }
Source:
public void expandRow() { listGroupItemHeader.addClassName("list-view-pf-expand-active"); listGroupItemContainer.removeClassName("hidden"); faAngleRight.addClassName("fa-angle-down"); }

Target:
public void expandRow() { listGroupItemHeader.addClassName(LIST_VIEW_PF_EXPAND_ACTIVE); listGroupItemContainer.removeClassName(HIDDEN); faAngleRight.addClassName(FA_ANGLE_DOWN); }
Source:
public static int computeFetchSize(int initialSize) { int fetchSize = initialSize; if (fetchSize < 10) { fetchSize = 10; } fetchSize *= 20; if (fetchSize < 0 || fetchSize > RelationalConstants.MAX_FETCH_SIZE) { fetchSize = RelationalConstants.MAX_FETCH_SIZE; } return fetchSize; }

Target:
public static int computeFetchSize(int initialSize) { int fetchSize = initialSize; if (fetchSize < MINIMUM_FETCH_SIZE) { fetchSize = MINIMUM_FETCH_SIZE; } fetchSize *= APPROXIMATE_NUMBER_OF_SUB_ITEMS; if (fetchSize < 0 || fetchSize > RelationalConstants.MAX_FETCH_SIZE) { fetchSize = RelationalConstants.MAX_FETCH_SIZE; } return fetchSize; }
Source:
private PerAlleleCollection<Double> getHetGenotypeLogOdds(ReadLikelihoods<Allele> likelihoods, final boolean isNormal, final Strand strand) { final String sample = isNormal ? matchedNormalSampleName : tumorSampleName; final OptionalDouble givenAltAlleleFraction = isNormal ? OptionalDouble.of(0.5) : NO_FIXED_TUMOR_ALT_FRACTION; final PerAlleleCollection<Double> hetGenotypeLogLks = getHetGenotypeLogLikelihoods(likelihoods, sample, givenAltAlleleFraction, strand); final PerAlleleCollection<Double> lods = new PerAlleleCollection<>(PerAlleleCollection.Type.ALT_ONLY); final int flipLodFactor = isNormal ? -1 : 1; final List<Allele> altAlleles = likelihoods.alleles().stream().filter(Allele::isNonReference).collect(Collectors.toList()); lods.set(altAlleles, a -> flipLodFactor * (hetGenotypeLogLks.get(a) - hetGenotypeLogLks.getRef())); return lods; }

Target:
private PerAlleleCollection<Double> getHetGenotypeLogOdds(ReadLikelihoods<Allele> likelihoods, final boolean isNormal, final Strand strand) { final String sample = isNormal ? matchedNormalSampleName : tumorSampleName; final OptionalDouble givenAltAlleleFraction = isNormal ? GERMLINE_HET_ALT_FRACTION : NO_FIXED_TUMOR_ALT_FRACTION; final PerAlleleCollection<Double> hetGenotypeLogLks = getHetGenotypeLogLikelihoods(likelihoods, sample, givenAltAlleleFraction, strand); final PerAlleleCollection<Double> lods = new PerAlleleCollection<>(PerAlleleCollection.Type.ALT_ONLY); final int flipLodFactor = isNormal ? -1 : 1; final List<Allele> altAlleles = likelihoods.alleles().stream().filter(Allele::isNonReference).collect(Collectors.toList()); lods.set(altAlleles, a -> flipLodFactor * (hetGenotypeLogLks.get(a) - hetGenotypeLogLks.getRef())); return lods; }
Source:
protected static void buildChain(FormDefinitionFieldData previous, List<FormDefinitionFieldData> elements, List<FormDefinitionFieldData> originalList) { if (elements.isEmpty() || previous == null) { return; } FormDefinitionFieldData[] aux = elements.stream().filter(formElement -> previous.getName().equals(formElement.getAfterElement())).toArray(size -> new FormDefinitionFieldData[size]); elements.removeAll(Arrays.asList(aux)); for (FormDefinitionFieldData element : aux) { originalList.add(originalList.indexOf(previous) + 1, element); buildChain(element, elements, originalList); } }

Target:
protected static void buildChain(FormDefinitionFieldData previous, List<FormDefinitionFieldData> elements, List<FormDefinitionFieldData> originalList) { if (elements.isEmpty() || previous == null) { return; } List<FormDefinitionFieldData> aux = elements.stream().filter(formElement -> previous.getName().equals(formElement.getAfterElement())).collect(Collectors.toList()); elements.removeAll(aux); for (FormDefinitionFieldData element : aux) { originalList.add(originalList.indexOf(previous) + 1, element); buildChain(element, elements, originalList); } }
Source:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } if (tree.is(METHOD) || tree.is(CONSTRUCTOR)) { MethodTree methodTree = (MethodTree) tree; Optional<ModifierKeywordTree> modifier = findModifier(methodTree.modifiers(), SYNCHRONIZED); synchronizedStack.push(modifier.isPresent() ? new Counter(1) : new Counter(0)); methodTree(tree); } }

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } if (tree.is(METHOD, CONSTRUCTOR)) { MethodTree methodTree = (MethodTree) tree; int initialCounter = findModifier(methodTree.modifiers(), SYNCHRONIZED).map(m -> 1).orElse(0); synchronizedStack.push(new Counter(initialCounter)); findWaitOrNotifyInvocation(methodTree); } }
Source:
private Map<String, DbParameterAccessor> readIntoParams(String objname, String query) throws SQLException { String procName; if (objname.contains(".")) { String[] schemaAndName = objname.split("[\\.]", 2); objname = "[" + schemaAndName[0] + "].[" + schemaAndName[1] + "]"; procName = schemaAndName[1]; } else { objname = "[" + NameNormaliser.normaliseName(objname) + "]"; procName = NameNormaliser.normaliseName(objname); } PreparedStatement dc = currentConnection.prepareStatement(query); dc.setString(1, NameNormaliser.normaliseName(objname)); Log.log("executing query"); ResultSet rs = dc.executeQuery(); Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); int position = 0; while (rs.next()) { String paramName = rs.getString(1); if (paramName == null) paramName = ""; String dataType = rs.getString(2); String direction = rs.getString(4); DbParameterAccessor.Direction paramDirection; if (paramName.trim().length() == 0) paramDirection = DbParameterAccessor.Direction.RETURN_VALUE; else paramDirection = getParameterDirection(direction); DbParameterAccessor dbp = new DbParameterAccessor(paramName, paramDirection, getSqlType(dataType), getJavaClass(dataType), position++); allParams.put(NameNormaliser.normaliseName(paramName), dbp); } rs.close(); return allParams; }

Target:
private Map<String, DbParameterAccessor> readIntoParams(String objname, String query) throws SQLException { String procName; if (objname.contains(".")) { String[] schemaAndName = objname.split("[\\.]", 2); objname = "[" + schemaAndName[0] + "].[" + schemaAndName[1] + "]"; procName = schemaAndName[1]; } else { objname = "[" + NameNormaliser.normaliseName(objname) + "]"; procName = NameNormaliser.normaliseName(objname); } PreparedStatement dc = currentConnection.prepareStatement(query); dc.setString(1, NameNormaliser.normaliseName(objname)); Log.log("executing query"); ResultSet rs = dc.executeQuery(); Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); int position = 0; while (rs.next()) { String paramName = rs.getString(1); if (paramName == null) paramName = ""; String dataType = rs.getString(2); String direction = rs.getString(4); DbParameterAccessor.Direction paramDirection; int parameterPosition = position; if (paramName.trim().length() == 0) { paramDirection = DbParameterAccessor.Direction.RETURN_VALUE; parameterPosition = -1; } else { paramDirection = getParameterDirection(direction); ++position; } DbParameterAccessor dbp = new DbParameterAccessor(paramName, paramDirection, getSqlType(dataType), getJavaClass(dataType), parameterPosition); allParams.put(NameNormaliser.normaliseName(paramName), dbp); } rs.close(); return allParams; }
Source:
public void testWatchService() { String name = UUID.randomUUID().toString(); String serviceId1 = createAutoDeregisterServiceId(); String serviceId2 = createAutoDeregisterServiceId(); List<Map<String, CatalogService>> result = new CopyOnWriteArrayList<>(); CountDownLatch finish = new CountDownLatch(1); ServiceCatalogCache cache = ServiceCatalogCache.newCache(client.catalogClient(), name); cache.addListener(serviceMap -> { result.add(serviceMap); if (result.size() == 3) finish.countDown(); }); cache.start(); client.agentClient().register(20001, 20, name, serviceId1); client.agentClient().register(20002, 20, name, serviceId2); Uninterruptibles.awaitUninterruptibly(finish, 1, TimeUnit.SECONDS); assertEquals(0, result.get(0).size()); assertEquals(1, result.get(1).size()); assertEquals(2, result.get(2).size()); assertTrue(result.get(1).containsKey(serviceId1)); assertFalse(result.get(1).containsKey(serviceId2)); assertTrue(result.get(2).containsKey(serviceId1)); assertTrue(result.get(2).containsKey(serviceId2)); assertEquals(serviceId1, result.get(1).get(serviceId1).getServiceId()); assertEquals(serviceId2, result.get(2).get(serviceId2).getServiceId()); }

Target:
public void testWatchService() { String name = UUID.randomUUID().toString(); String serviceId1 = createAutoDeregisterServiceId(); String serviceId2 = createAutoDeregisterServiceId(); List<Map<String, CatalogService>> result = new CopyOnWriteArrayList<>(); CountDownLatch finish = new CountDownLatch(3); ServiceCatalogCache cache = ServiceCatalogCache.newCache(client.catalogClient(), name); cache.addListener(serviceMap -> { result.add(serviceMap); finish.countDown(); }); cache.start(); client.agentClient().register(20001, 20, name, serviceId1); Synchroniser.pause(Duration.ofMillis(100)); client.agentClient().register(20002, 20, name, serviceId2); Uninterruptibles.awaitUninterruptibly(finish, 1, TimeUnit.SECONDS); assertEquals(0, result.get(0).size()); assertEquals(1, result.get(1).size()); assertEquals(2, result.get(2).size()); assertTrue(result.get(1).containsKey(serviceId1)); assertFalse(result.get(1).containsKey(serviceId2)); assertTrue(result.get(2).containsKey(serviceId1)); assertTrue(result.get(2).containsKey(serviceId2)); assertEquals(serviceId1, result.get(1).get(serviceId1).getServiceId()); assertEquals(serviceId2, result.get(2).get(serviceId2).getServiceId()); }
Source:
private void runGodModeRoutine(boolean isPart) throws IOException { try { verifyHtml(OUTPUT_FILENAME, isPart); signalFailureToDetectException(); } catch (IOException|AssertionError e) { ignoreExpectedException(); } System.setProperty("godmode", "true"); verifyHtml(OUTPUT_FILENAME, isPart); System.clearProperty("godmode"); assertNull(System.getProperty("godmode")); verifyHtml(OUTPUT_FILENAME, isPart); String expectedOutputPage = FileHelper.readFile(TestProperties.TEST_PAGES_FOLDER + (isPart ? EXPECTED_PART_FILENAME : EXPECTED_FILENAME)); String actualOutputPage = FileHelper.readFile(OUTPUT_PATH); HtmlHelper.assertSameHtml(expectedOutputPage, actualOutputPage, isPart); }

Target:
private void runGodModeRoutine(boolean isPart) throws Exception { System.setProperty("godmode", "true"); verifyHtml(OUTPUT_FILENAME, isPart); System.clearProperty("godmode"); assertNull(System.getProperty("godmode")); verifyHtml(OUTPUT_FILENAME, isPart); String expectedOutputPage = FileHelper.readFile(isPart ? EXPECTED_PART_FILEPATH : EXPECTED_FILEPATH); String actualOutputPage = FileHelper.readFile(OUTPUT_FILEPATH); HtmlHelper.assertSameHtml(expectedOutputPage, actualOutputPage, isPart); }
Source:
private boolean copyDataDirectoryIfChanged(String origDir, String destDir) throws IOException { if(destDir != null && destDir.length() > 0 && !origDir.equals(destDir)) { log.debug("Moving data from " + origDir + " to " + destDir); File currentDir = new File(origDir); File newDir = new File(destDir); FileUtil.purge(newDir, true); FileUtil.copyDirectory(currentDir, newDir); return true; } return false; }

Target:
private boolean copyDataDirectoryIfChanged(String origDir, String destDir) throws IOException { if(destDir != null && destDir.length() > 0 && !origDir.equals(destDir)) { log.debug("Moving data from " + origDir + " to " + destDir); File currentDir = new File(origDir); File newDir = new File(destDir); FileUtil.copyDirectory(currentDir, newDir); return true; } return false; }
Source:
public List<FederatedSource> getFederatedSources() { ArrayList<FederatedSource> sources = new ArrayList<>(federatedSources); sources.addAll(oauthFederatedSources); return sources; }

Target:
public List<FederatedSource> getFederatedSources() { return federatedSources; }
Source:
public void run() { while (true) { try { Lease lease = leaseMaintainer.getCurrentLease(); if (lease instanceof LeaseImpl) { boolean validLease = lease.isValidAndContiguous(lease); if (!validLease) { connection.close(); } } timeSource.sleep(200L); } catch (IOException e) { LOGGER.error("Closing connection, due to lease expiry, caused an error", e); } catch (InterruptedException e) { Thread.interrupted(); break; } } }

Target:
public void run() { while (true) { try { Lease lease = leaseMaintainer.getCurrentLease(); if (!(lease instanceof NullLease)) { boolean validLease = lease.isValidAndContiguous(lease); if (!validLease) { connection.close(); } } timeSource.sleep(200L); } catch (IOException e) { LOGGER.error("Closing connection, due to lease expiry, caused an error", e); } catch (InterruptedException e) { Thread.interrupted(); break; } } }
Source:
public void setBeanProperty(final String propertyName) { String currBeanProperty = getBeanProperty(); if ((propertyName != null && currBeanProperty == null) || (currBeanProperty != null && (propertyName == null || !currBeanProperty.equals(propertyName)))) { getOrCreateComponentModel().setBeanProperty(propertyName); } }

Target:
public void setBeanProperty(final String propertyName) { String currBeanProperty = getBeanProperty(); if (!Objects.equals(propertyName, currBeanProperty)) { getOrCreateComponentModel().setBeanProperty(propertyName); } }
Source:
private boolean saveGlusterHostUuid() { VdsGlusterDao vdsGlusterDao = DbFacade.getInstance().getVdsGlusterDao(); VdsGluster vdsGluster = vdsGlusterDao.getById(getVds().getId()); if (vdsGluster == null) { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterHostUUID, new VdsIdVDSCommandParametersBase(getVds().getId())); if (returnValue.getSucceeded() && returnValue.getReturnValue() != null) { vdsGluster = new VdsGluster(); vdsGluster.setId(getVds().getId()); vdsGluster.setGlusterHostUuid(Guid.createGuidFromString((String) returnValue.getReturnValue())); vdsGlusterDao.save(vdsGluster); } else { return false; } } return true; }

Target:
private boolean saveGlusterHostUuid() { GlusterServerDao glusterServerDao = DbFacade.getInstance().getGlusterServerDao(); GlusterServer glusterServer = glusterServerDao.getByServerId(getVds().getId()); if (glusterServer == null) { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterHostUUID, new VdsIdVDSCommandParametersBase(getVds().getId())); if (returnValue.getSucceeded() && returnValue.getReturnValue() != null) { glusterServer = new GlusterServer(); glusterServer.setId(getVds().getId()); glusterServer.setGlusterServerUuid(Guid.createGuidFromString((String) returnValue.getReturnValue())); glusterServerDao.save(glusterServer); } else { return false; } } return true; }
Source:
void deprioritizeCase(final String caseName) throws AutoIngestManagerException { if (state != State.RUNNING) { return; } List<AutoIngestJob> prioritizedJobs = new ArrayList<>(); synchronized (jobsLock) { for (AutoIngestJob job : pendingJobs) { if (job.getManifest().getCaseName().equals(caseName)) { prioritizedJobs.add(job); } } if (!prioritizedJobs.isEmpty()) { for (AutoIngestJob job : prioritizedJobs) { int oldPriority = job.getPriority(); job.setPriority(DEFAULT_PRIORITY); try { this.updateCoordinationServiceManifestNode(job); } catch (CoordinationServiceException | InterruptedException ex) { job.setPriority(oldPriority); throw new AutoIngestManagerException("Error updating case priority", ex); } } } Collections.sort(pendingJobs, new AutoIngestJob.PriorityComparator()); } if (!prioritizedJobs.isEmpty()) { new Thread(() -> { eventPublisher.publishRemotely(new AutoIngestCaseDeprioritizedEvent(LOCAL_HOST_NAME, caseName)); }).start(); } }

Target:
void deprioritizeCase(final String caseName) throws AutoIngestManagerException { if (state != State.RUNNING) { return; } List<AutoIngestJob> jobsToDeprioritize = new ArrayList<>(); synchronized (jobsLock) { for (AutoIngestJob job : pendingJobs) { if (job.getManifest().getCaseName().equals(caseName)) { jobsToDeprioritize.add(job); } } if (!jobsToDeprioritize.isEmpty()) { for (AutoIngestJob job : jobsToDeprioritize) { int oldPriority = job.getPriority(); job.setPriority(DEFAULT_PRIORITY); try { this.updateCoordinationServiceManifestNode(job); } catch (CoordinationServiceException | InterruptedException ex) { job.setPriority(oldPriority); throw new AutoIngestManagerException("Error updating case priority", ex); } } } Collections.sort(pendingJobs, new AutoIngestJob.PriorityComparator()); } if (!jobsToDeprioritize.isEmpty()) { new Thread(() -> { eventPublisher.publishRemotely(new AutoIngestCasePrioritizedEvent(LOCAL_HOST_NAME, caseName)); }).start(); } }