auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void addRunFacet(@Nonnull ContainerRecord record, @Nonnull Run<?,?> run) throws IOException { String imageId = record.getImageId(); if (imageId == null) { throw new IllegalArgumentException("Invalid ContainerRecord instance. ContainerRecords passed to addRunFacet must have an image ID."); } Fingerprint f = make(run, imageId); Collection<FingerprintFacet> facets = f.getFacets(); DockerRunFingerprintFacet runFacet = null; for (FingerprintFacet facet : facets) { if (facet instanceof DockerRunFingerprintFacet) { runFacet = (DockerRunFingerprintFacet) facet; break; } } BulkChange bc = new BulkChange(f); try { if (runFacet == null) { runFacet = new DockerRunFingerprintFacet(f, System.currentTimeMillis(), imageId); facets.add(runFacet); } runFacet.add(record); runFacet.addFor(run); bc.commit(); } finally { bc.abort(); } }

Target:
public static void addRunFacet(@Nonnull ContainerRecord record, @Nonnull Run<?,?> run) throws IOException { String imageId = record.getImageId(); Fingerprint f = make(run, imageId); Collection<FingerprintFacet> facets = f.getFacets(); DockerRunFingerprintFacet runFacet = null; for (FingerprintFacet facet : facets) { if (facet instanceof DockerRunFingerprintFacet) { runFacet = (DockerRunFingerprintFacet) facet; break; } } BulkChange bc = new BulkChange(f); try { if (runFacet == null) { runFacet = new DockerRunFingerprintFacet(f, System.currentTimeMillis(), imageId); facets.add(runFacet); } runFacet.add(record); runFacet.addFor(run); bc.commit(); } finally { bc.abort(); } }
Source:
private Injector setupEarlyInjector() throws Exception { final List<Module> modules = Lists.newArrayList(); modules.add(new AbstractModule() { @Singleton @Provides public Map<String, FilterDeserializer.PartialDeserializer> filters() { final Map<String, FilterDeserializer.PartialDeserializer> filters = new HashMap<>(); filters.put("key", new MatchKey.Deserializer()); filters.put("=", new MatchTag.Deserializer()); filters.put("true", new TrueFilter.Deserializer()); filters.put("false", new NotFilter.Deserializer()); filters.put("and", new AndFilter.Deserializer()); filters.put("or", new OrFilter.Deserializer()); filters.put("not", new NotFilter.Deserializer()); filters.put("type", new TypeFilter.Deserializer()); return filters; } @Singleton @Provides @Named("config") public SimpleModule configModule( Map<String, FilterDeserializer.PartialDeserializer> filters ) { final SimpleModule module = new SimpleModule(); module.addDeserializer(Filter.class, new FilterDeserializer(filters)); return module; } @Override protected void configure() { bind(PluginContext.class).toInstance(new PluginContextImpl()); } }); final Injector injector = Guice.createInjector(modules); for (final FastForwardModule m : loadModules(injector)) { log.info("Setting up {}", m); try { m.setup(); } catch (Exception e) { throw new Exception("Failed to call #setup() for module: " + m, e); } } return injector; }

Target:
private Injector setupEarlyInjector() throws Exception { final List<Module> modules = Lists.newArrayList(); modules.add(new AbstractModule() { @Singleton @Provides public Map<String, FilterDeserializer.PartialDeserializer> filters() { final Map<String, FilterDeserializer.PartialDeserializer> filters = new HashMap<>(); filters.put("key", new MatchKey.Deserializer()); filters.put("=", new MatchTag.Deserializer()); filters.put("true", new TrueFilter.Deserializer()); filters.put("false", new FalseFilter.Deserializer()); filters.put("and", new AndFilter.Deserializer()); filters.put("or", new OrFilter.Deserializer()); filters.put("not", new NotFilter.Deserializer()); filters.put("type", new TypeFilter.Deserializer()); return filters; } @Singleton @Provides @Named("config") public SimpleModule configModule( Map<String, FilterDeserializer.PartialDeserializer> filters ) { final SimpleModule module = new SimpleModule(); module.addDeserializer(Filter.class, new FilterDeserializer(filters)); return module; } @Override protected void configure() { bind(PluginContext.class).toInstance(new PluginContextImpl()); } }); final Injector injector = Guice.createInjector(modules); for (final FastForwardModule m : loadModules(injector)) { log.info("Setting up {}", m); try { m.setup(); } catch (Exception e) { throw new Exception("Failed to call #setup() for module: " + m, e); } } return injector; }
Source:
HazelcastSession(MapSession cached) { Assert.notNull("MapSession cannot be null"); this.delegate = cached; }

Target:
HazelcastSession(MapSession cached) { Assert.notNull(cached, "MapSession cannot be null"); this.delegate = cached; }
Source:
public ListenableFuture<Image> createImage(ImageTemplate template) { checkState(template instanceof CloneImageTemplate, "profitbricks only supports creating images through cloning."); final CloneImageTemplate cloneTemplate = (CloneImageTemplate) template; String serverId = cloneTemplate.getSourceNodeId(); Server server = api.serverApi().getServer(serverId); Storage bootDevice = Iterables.find(server.storages(), matchBootDevice); final Snapshot requested = api.snapshotApi().createSnapshot( Snapshot.Request.creatingBuilder() .storageId(bootDevice.id()) .name(template.getName()) .description(template.getName() + " (created with jclouds)") .build()); return userExecutor.submit(new Callable<Image>() { @Override public Image call() throws Exception { if (snapshotAvailablePredicate.apply(requested.id())) { Snapshot built = api.snapshotApi().getSnapshot(requested.id()); return imageTransformer.apply(built); } throw new UncheckedTimeoutException("Image was not created within the time limit: " + cloneTemplate.getName()); } }); }

Target:
public ListenableFuture<Image> createImage(ImageTemplate template) { checkState(template instanceof CloneImageTemplate, "profitbricks only supports creating images through cloning."); final CloneImageTemplate cloneTemplate = (CloneImageTemplate) template; String serverId = cloneTemplate.getSourceNodeId(); Server server = api.serverApi().getServer(serverId); Storage bootDevice = Iterables.find(server.storages(), matchBootDevice); final Snapshot requested = api.snapshotApi().createSnapshot( Snapshot.Request.creatingBuilder() .storageId(bootDevice.id()) .name(template.getName()) .description(template.getName() + " (created with jclouds)") .build()); logger.info(">> creating a snapshot from storage: %s", bootDevice.id()); return userExecutor.submit(new Callable<Image>() { @Override public Image call() throws Exception { if (snapshotAvailablePredicate.apply(requested.id())) { Snapshot built = api.snapshotApi().getSnapshot(requested.id()); Image newImage = imageTransformer.apply(built); logger.info(">> registering new image (%s) to cache", newImage.getId()); images.registerImage(newImage); return newImage; } throw new UncheckedTimeoutException("Image was not created within the time limit: " + cloneTemplate.getName()); } }); }
Source:
public String[] getTraceNames() { return TmfTraceManager.getTraceSet(fTrace).stream() .map(trace -> trace.getName()) .toArray(String[]::new); }

Target:
public String[] getTraceNames() { return TmfTraceManager.getTraceSet(fTrace).stream() .map(ITmfTrace::getName) .toArray(String[]::new); }
Source:
public boolean blockActivated(EntityPlayer player, EnumHand hand, @Nullable ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) { if (super.blockActivated(player, hand, heldItem, side, hitX, hitY, hitZ)) return true; if (player.isSneaking()) return false; if (heldItem == null || hand == EnumHand.OFF_HAND) return false; EnumColor color = EnumColor.dyeColorOf(heldItem); if (color == null || color == this.color) { return false; } if (!player.capabilities.isCreativeMode) player.setHeldItem(hand, InvTools.depleteItem(heldItem)); this.color = color; markDirty(); return true; }

Target:
public boolean blockActivated(EntityPlayer player, EnumHand hand, @Nullable ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) { if (super.blockActivated(player, hand, heldItem, side, hitX, hitY, hitZ)) return true; if (player.isSneaking()) return false; if (InvTools.isEmpty(heldItem) || hand == EnumHand.OFF_HAND) return false; EnumColor color = EnumColor.dyeColorOf(heldItem); if (color == null || color == this.color) { return false; } if (!player.capabilities.isCreativeMode) player.setHeldItem(hand, InvTools.depleteItem(heldItem)); this.color = color; markDirty(); return true; }
Source:
public MainTabBasicDetailsView(ApplicationResources resources) { operatingSystem = new EnumLabel<VmOsType>(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); Driver.driver.initialize(this); ViewIdHandler.idHandler.generateAndSetIds(this); }

Target:
public MainTabBasicDetailsView(ApplicationResources resources) { initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); Driver.driver.initialize(this); ViewIdHandler.idHandler.generateAndSetIds(this); }
Source:
public BackupState doBackup( OnlineBackupContext onlineBackupContext ) { wrappedAsRuntimeException( backupStrategyImplementation::init ); wrappedAsRuntimeException( backupStrategyImplementation::start ); BackupState state = performBackupWithoutLifecycle( onlineBackupContext ); wrappedAsRuntimeException( backupStrategyImplementation::stop ); wrappedAsRuntimeException( backupStrategyImplementation::shutdown ); return state; }

Target:
PotentiallyErroneousState<BackupStrategyOutcome> doBackup( OnlineBackupContext onlineBackupContext ) { LifeSupport lifeSupport = new LifeSupport(); lifeSupport.add( backupStrategy ); lifeSupport.start(); PotentiallyErroneousState<BackupStrategyOutcome> state = performBackupWithoutLifecycle( onlineBackupContext ); lifeSupport.shutdown(); return state; }
Source:
public JavaFile build() { Collections.sort(staticImports); return new JavaFile(this); }

Target:
public JavaFile build() { return new JavaFile(this); }
Source:
default Stream<T> dropRight(int n) { if(n <= 0) { return this; } else { return reverse().drop(n).reverse(); } }

Target:
default Stream<T> dropRight(int n) { if(n <= 0) { return this; } else if (length() <= n) { return empty(); } else { return reverse().drop(n).reverse(); } }
Source:
public void acknowledge(final MessageReference ref, final AckReason reason, final ServerConsumer consumer) throws Exception { if (isNonDestructive() && reason == AckReason.NORMAL) { decDelivering(ref); if (logger.isDebugEnabled()) { logger.debug("acknowledge ignored nonDestructive=true and reason=NORMAL"); } } else { if (ref.isPaged()) { pageSubscription.ack((PagedReference) ref); postAcknowledge(ref, reason); } else { Message message = ref.getMessage(); boolean durableRef = message.isDurable() && isDurable(); if (durableRef) { storageManager.storeAcknowledge(id, message.getMessageID()); } postAcknowledge(ref, reason); } ackAttempts.incrementAndGet(); if (server != null && server.hasBrokerMessagePlugins()) { server.callBrokerMessagePlugins(plugin -> plugin.messageAcknowledged(ref, reason, consumer)); } } }

Target:
public void acknowledge(final MessageReference ref, final AckReason reason, final ServerConsumer consumer) throws Exception { if (nonDestructive && reason == AckReason.NORMAL) { decDelivering(ref); if (logger.isDebugEnabled()) { logger.debug("acknowledge ignored nonDestructive=true and reason=NORMAL"); } } else { if (ref.isPaged()) { pageSubscription.ack((PagedReference) ref); postAcknowledge(ref, reason); } else { Message message = ref.getMessage(); boolean durableRef = message.isDurable() && isDurable(); if (durableRef) { storageManager.storeAcknowledge(id, message.getMessageID()); } postAcknowledge(ref, reason); } ackAttempts.incrementAndGet(); if (server != null && server.hasBrokerMessagePlugins()) { server.callBrokerMessagePlugins(plugin -> plugin.messageAcknowledged(ref, reason, consumer)); } } }
Source:
public void processElement(ProcessContext context) throws Exception { KV<ImmutableBytesWritable, Result> kv = context.element(); Cell[] cells = checkEmptyRow(kv); if (cells.length == 0) { return; } Put put = new Put(kv.getKey().get()); for (Cell cell : cells) { put.add(cell); } try { context.output(put); } catch (Exception e) { if (e instanceof RetriesExhaustedWithDetailsException) { for (Throwable t : ((RetriesExhaustedWithDetailsException) e).getCauses()) { logger.warn("Error sending mutation to downstream pipeline stage.", t); } } throw e; } }

Target:
public void processElement(ProcessContext context) throws Exception { KV<ImmutableBytesWritable, Result> kv = context.element(); Cell[] cells = checkEmptyRow(kv); if (cells.length == 0) { return; } Put put = new Put(kv.getKey().get()); for (Cell cell : cells) { put.add(cell); } context.output(put); }
Source:
public void saveDirtyResources(boolean force) { if (!force && !Configuration.getClientBehavior().isAutoSaveEnabled()) { return; } if (!force && !isDirty) { return; } if (resources == null) { return; } for (final Resource resource : resources) { if (resource.getURI() == null || resource.getURI().toString().equals(StringUtils.EMPTY)) { continue; } final ProjectSpace projectSpace = ESLocalProjectImpl.class.cast(localProject).toInternalAPI(); if (EMFStoreResource.class.isInstance(resource) && resource == projectSpace.getProject().eResource()) { final Map<EObject, String> eObjectToIdMapping = new LinkedHashMap<EObject, String>( projectSpace.getProject().getEObjectToIdMapping()); final Map<String, EObject> idToEObjectMapping = new LinkedHashMap<String, EObject>( projectSpace.getProject().getIdToEObjectMapping()); EMFStoreResource.class.cast(resource).setIdToEObjectMap(idToEObjectMapping, eObjectToIdMapping); } try { ModelUtil.saveResource(resource, WorkspaceUtil.getResourceLogger()); } catch (final IOException e) { } } isDirty = false; fireDirtyStateChangedNotification(); }

Target:
public void saveDirtyResources(boolean force) { if (!force && !Configuration.getClientBehavior().isAutoSaveEnabled()) { return; } if (!force && !isDirty) { return; } if (resources == null) { return; } for (final Resource resource : resources) { if (resource.getURI() == null || resource.getURI().toString().equals(StringUtils.EMPTY)) { continue; } final ProjectSpace projectSpace = ESLocalProjectImpl.class.cast(localProject).toInternalAPI(); if (EMFStoreResource.class.isInstance(resource) && resource == projectSpace.getProject().eResource()) { final Map<EObject, String> eObjectToIdMapping = new LinkedHashMap<EObject, String>( projectSpace.getProject().getEObjectToIdMapping()); final Map<String, EObject> idToEObjectMapping = new LinkedHashMap<String, EObject>( projectSpace.getProject().getIdToEObjectMapping()); EMFStoreResource.class.cast(resource).setIdToEObjectMap(idToEObjectMapping, eObjectToIdMapping); } try { if (projectSpace.getLocalChangePackage().eResource() == resource) { projectSpace.getLocalChangePackage().save(); } else { ModelUtil.saveResource(resource, WorkspaceUtil.getResourceLogger()); } } catch (final IOException e) { throw new RuntimeException( MessageFormat.format(Messages.ResourcePersister_SaveFailed, resource.getURI())); } } isDirty = false; fireDirtyStateChangedNotification(); }
Source:
public void init() { addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent mouseEvent) { int y = mouseEvent.getY(); int i = 0; while (i < myCurrentBottoms.length && y > myCurrentBottoms[i]) { ++i; } if (i < myCurrentBottoms.length) { mySelectedDistribution = DISTRIBUTIONS.get(i); if (myListener != null) { myListener.onDistributionSelected(mySelectedDistribution); } repaint(); } } }); if (DISTRIBUTIONS == null) { try { String jsonString = ResourceUtil.loadText(ResourceUtil.getResource(this.getClass(), "wizardData", "distributions.json")); loadDistributionsFromJson(jsonString); } catch (IOException e) { throw new RuntimeException(e); } } loadFonts(); }

Target:
public void init() { addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent mouseEvent) { int y = mouseEvent.getY(); int i = 0; while (i < myCurrentBottoms.length && y > myCurrentBottoms[i]) { ++i; } if (i < myCurrentBottoms.length) { mySelectedDistribution = ourDistributions.get(i); if (myListener != null) { myListener.onDistributionSelected(mySelectedDistribution); } repaint(); } } }); if (ourDistributions == null) { try { String jsonString = ResourceUtil.loadText(ResourceUtil.getResource(this.getClass(), "wizardData", "distributions.json")); ourDistributions = loadDistributionsFromJson(jsonString); } catch (IOException e) { throw new RuntimeException(e); } } loadFonts(); }
Source:
private TagModel feedTagStructureToGraph(Tag tag, Set<Tag> visited, int level) { if (visited.contains(tag)) return this.getUniqueByProperty(TagModel.PROP_NAME, tag.getName(), true); visited.add(tag); LOG.info(String.format("Creating TagModel for Tag: %s%s(%d) '%s' traits: %s", StringUtils.repeat(' ', level*2), tag.getName(), tag.getContainedTags().size(), tag.getTitle(), tag.getTraits())); TagModel tagModel = this.create(); tagModel.setName(tag.getName()); tagModel.setTitle(tag.getTitle()).setColor(tag.getColor()).setRoot(tag.isPrime()).setPseudo(tag.isPseudo()); if (null != tag.getTraits()) tagModel.putAllTraits(tag.getTraits()); tag.getContainedTags().forEach(tag2 -> { TagModel tag2model = feedTagStructureToGraph(tag2, visited, level+1); tagModel.addDesignatedTag(tag2model); }); return tagModel; }

Target:
private TagModel feedTagStructureToGraph(Tag tag, Set<Tag> visited, int level) { if (visited.contains(tag)) return this.getUniqueByProperty(TagModel.PROP_NAME, tag.getName(), true); visited.add(tag); LOG.fine(String.format("Creating TagModel for Tag: %s%s(%d) '%s' traits: %s", StringUtils.repeat(' ', level*2), tag.getName(), tag.getContainedTags().size(), tag.getTitle(), tag.getTraits())); TagModel tagModel = this.create(); tagModel.setName(tag.getName()); tagModel.setTitle(tag.getTitle()).setColor(tag.getColor()).setRoot(tag.isPrime()).setPseudo(tag.isPseudo()); if (null != tag.getTraits()) tagModel.putAllTraits(tag.getTraits()); tag.getContainedTags().forEach(tag2 -> { TagModel tag2model = feedTagStructureToGraph(tag2, visited, level+1); tagModel.addDesignatedTag(tag2model); }); return tagModel; }
Source:
public void MercuryWidgetTest_001_Twitter() { ArticleContent articleContent = new ArticleContent(); articleContent.clear(MercurySubpages.TWITTER_VERBATIM); articleContent.push("<twitter>", MercurySubpages.TWITTER_VERBATIM); TwitterWidgetPageObject twitterWidgetPageObject = new TwitterWidgetPageObject(driver); twitterWidgetPageObject.openMercuryArticleByName(wikiURL, MercurySubpages.TWITTER_VERBATIM); twitterWidgetPageObject.isLoadedOnMercury(); }

Target:
public void MercuryWidgetTest_001_Twitter() { TwitterWidgetPageObject twitterWidgetPageObject = new TwitterWidgetPageObject(driver); twitterWidgetPageObject.createAndNavigate(wikiURL); Assertion.assertTrue( twitterWidgetPageObject.isLoadedOnMercury(), MercuryMessages.INVISIBLE_MSG ); }
Source:
public void signalTorefreshSearcherManagers(List<String> subFiles, String host, int port) throws IOException { Message m = Message.createMessage("refresh"); m.setText("refresh"); for (String proj : subFiles) { m.addTag(new File(proj).getName()); } m.write(host, port); }

Target:
public void signalTorefreshSearcherManagers(List<String> subFiles, String host, int port) throws IOException { Message m = Message.createMessage("refresh"); for (String proj : subFiles) { m.addTag(new File(proj).getName()); } m.write(host, port); }
Source:
public MapConfiguration createTmsMap(Profile profile, int nrOfZoomLevels) { switch (profile) { case GLOBAL_GEODETIC: return createTmsMap(profile, "EPSG:4326", CrsType.DEGREES, new Bbox(-180, -90, 360, 180), 256, nrOfZoomLevels); default: return createTmsMap(profile, "EPSG:3857", CrsType.METRIC, new Bbox(-MERCATOR, -MERCATOR, 2 * MERCATOR, 2 * MERCATOR), 256, nrOfZoomLevels); } }

Target:
protected MapConfiguration createTmsMap(Profile profile, int nrOfZoomLevels) { MapConfiguration mapConfiguration = null; switch (profile) { case GLOBAL_GEODETIC: mapConfiguration = createTmsMap("EPSG:4326", CrsType.DEGREES, new Bbox(-180, -90, 360, 180), 256, nrOfZoomLevels); break; case GLOBAL_MERCATOR: mapConfiguration = createTmsMap("EPSG:3857", CrsType.METRIC, new Bbox(-MERCATOR, -MERCATOR, 2 * MERCATOR, 2 * MERCATOR), 256, nrOfZoomLevels); break; default: throw new IllegalArgumentException("Local profiles not supported"); } mapConfiguration.setHintValue(PROFILE, profile); return mapConfiguration; }
Source:
private JButton buildOverrideConfButton(FormStatus form) { JButton button = new JButton("\uE900"); button.setFont(ic_settings); button.setToolTipText("Override the export configuration for this form"); button.setMargin(new Insets(0, 0, 0, 0)); updateConfButton(form, button); button.addActionListener(__ -> { ConfigurationDialog dialog = ConfigurationDialog.from( forms.getCustomConfiguration(form), forms.hasTransferSettings(form), BriefcasePreferences.getStorePasswordsConsentProperty() ); dialog.onRemove(() -> removeConfiguration(form)); dialog.onOK(configuration -> { if (configuration.isEmpty() && (((BriefcaseFormDefinition) form.getFormDefinition()).isFileEncryptedForm() || ((BriefcaseFormDefinition) form.getFormDefinition()).isFieldEncryptedForm())) { configuration.setFormNeedsPrivateKey(Boolean.TRUE); putConfiguration(form, configuration); } else if (configuration.isEmpty()) { removeConfiguration(form); } else { putConfiguration(form, configuration); } }); dialog.open(); }); return button; }

Target:
private JButton buildOverrideConfButton(FormStatus form) { JButton button = new JButton("\uE900"); button.setFont(ic_settings); button.setToolTipText("Override the export configuration for this form"); button.setMargin(new Insets(0, 0, 0, 0)); updateConfButton(form, button); button.addActionListener(__ -> { ConfigurationDialog dialog = ConfigurationDialog.from( forms.getCustomConfiguration(form).orElse(ExportConfiguration.empty(form)), forms.hasTransferSettings(form), BriefcasePreferences.getStorePasswordsConsentProperty() ); dialog.onRemove(() -> removeConfiguration(form)); dialog.onOK(configuration -> { if (configuration.isEmpty()) removeConfiguration(form); else putConfiguration(form, configuration); }); dialog.open(); }); return button; }
Source:
protected void initializeConfig() throws IOException, URISyntaxException { configSource = getConfigSource(); config = new ConfigurationObjectFactory(new KillbillPlatformConfigSource(configSource)).build(KillbillServerConfig.class); metricsGraphiteConfig = new ConfigurationObjectFactory(new KillbillPlatformConfigSource(configSource)).build(MetricsGraphiteConfig.class); }

Target:
protected void initializeConfig() throws IOException, URISyntaxException { configSource = getConfigSource(); final ConfigurationObjectFactory configFactory = new ConfigurationObjectFactory(new KillbillPlatformConfigSource(configSource)); config = configFactory.build(KillbillServerConfig.class); metricsGraphiteConfig = configFactory.build(MetricsGraphiteConfig.class); }
Source:
public void setVisible(final boolean visible) { super.setVisible(visible); fIsVisible = visible; if (visible) { getContainer().getShell().getDisplay().asyncExec(() -> updateViewer()); } else { getElementViewer().setInput(null); } }

Target:
public void setVisible(final boolean visible) { super.setVisible(visible); fIsVisible = visible; if (visible) { getContainer().getShell().getDisplay().asyncExec(this::updateViewer); } else { getElementViewer().setInput(null); } }
Source:
private void displayProtocol_SelectedItemChanged(Object sender, EventArgs args) { EntityModel entityModel = (EntityModel) getDisplayProtocol().getSelectedItem(); if (entityModel == null) { return; } DisplayType type = (DisplayType) entityModel.getEntity(); if (type == DisplayType.vnc) { getUsbPolicy().setSelectedItem(org.ovirt.engine.core.common.businessentities.UsbPolicy.DISABLED); getIsSmartcardEnabled().setEntity(false); } getBehavior().enableSinglePCI(type == DisplayType.qxl); getUsbPolicy().setIsChangable(type == DisplayType.qxl); getIsSmartcardEnabled().setIsChangable(type == DisplayType.qxl); getVncKeyboardLayout().setIsAvailable(type == DisplayType.vnc); updateNumOfMonitors(); }

Target:
private void displayProtocol_SelectedItemChanged(Object sender, EventArgs args) { if (getDisplayType() == null) { return; } DisplayType type = getDisplayType(); if (type == DisplayType.vnc) { getUsbPolicy().setSelectedItem(org.ovirt.engine.core.common.businessentities.UsbPolicy.DISABLED); getIsSmartcardEnabled().setEntity(false); } handleQxlClusterLevel(); getUsbPolicy().setIsChangable(type == DisplayType.qxl); getIsSmartcardEnabled().setIsChangable(type == DisplayType.qxl); getVncKeyboardLayout().setIsAvailable(type == DisplayType.vnc); updateNumOfMonitors(); }
Source:
private void testGrantedTablePermission(AccumuloClient test_user_client, TablePermission perm, String tableName) throws AccumuloException, AccumuloSecurityException, TableNotFoundException { log.debug("Confirming that the presence of the permission properly permits the user", perm); switch (perm) { case READ: try (Scanner scanner = test_user_client.createScanner(tableName, Authorizations.EMPTY)) { Iterator<Entry<Key,Value>> iter = scanner.iterator(); while (iter.hasNext()) iter.next(); } break; case WRITE: try (BatchWriter bw = test_user_client.createBatchWriter(tableName)) { Mutation m = new Mutation(new Text("row")); m.put(new Text("a"), new Text("b"), new Value("c".getBytes())); bw.addMutation(m); } break; case BULK_IMPORT: break; case ALTER_TABLE: Map<String,Set<Text>> groups = new HashMap<>(); groups.put("tgroup", new HashSet<>(Arrays.asList(new Text("t1"), new Text("t2")))); testArbitraryProperty(test_user_client, tableName, true); break; case DROP_TABLE: test_user_client.tableOperations().delete(tableName); break; case GRANT: test_user_client.securityOperations().grantTablePermission(getAdminPrincipal(), tableName, TablePermission.GRANT); break; case GET_SUMMARIES: List<Summary> summaries = test_user_client.tableOperations().summaries(tableName) .retrieve(); assertTrue(summaries.isEmpty()); break; default: throw new IllegalArgumentException("Unrecognized table Permission: " + perm); } }

Target:
private void testGrantedTablePermission(AccumuloClient test_user_client, TablePermission perm, String tableName) throws AccumuloException, AccumuloSecurityException, TableNotFoundException { log.debug("Confirming that the presence of the permission properly permits the user", perm); switch (perm) { case READ: try (Scanner scanner = test_user_client.createScanner(tableName, Authorizations.EMPTY)) { Iterator<Entry<Key,Value>> iter = scanner.iterator(); while (iter.hasNext()) iter.next(); } break; case WRITE: try (BatchWriter bw = test_user_client.createBatchWriter(tableName)) { Mutation m = new Mutation(new Text("row")); m.put(new Text("a"), new Text("b"), new Value("c".getBytes())); bw.addMutation(m); } break; case BULK_IMPORT: break; case ALTER_TABLE: testArbitraryProperty(test_user_client, tableName, true); break; case DROP_TABLE: test_user_client.tableOperations().delete(tableName); break; case GRANT: test_user_client.securityOperations().grantTablePermission(getAdminPrincipal(), tableName, TablePermission.GRANT); break; case GET_SUMMARIES: List<Summary> summaries = test_user_client.tableOperations().summaries(tableName) .retrieve(); assertTrue(summaries.isEmpty()); break; default: throw new IllegalArgumentException("Unrecognized table Permission: " + perm); } }
Source:
private List<@NonNull ITimeGraphRowModel> getRowModels(ITmfStateSystem ss, Map<Integer, Long> idToDisplayQuark, @Nullable List<Long> times, Map<String, Object> fetchParameters, @Nullable IProgressMonitor monitor) throws IndexOutOfBoundsException, TimeRangeException, StateSystemDisposedException { Map<@NonNull Integer, @NonNull Predicate<@NonNull Multimap<@NonNull String, @NonNull Object>>> predicates = new HashMap<>(); Multimap<@NonNull Integer, @NonNull String> regexesMap = DataProviderParameterUtils.extractRegexFilter(fetchParameters); if (regexesMap != null) { predicates.putAll(computeRegexPredicate(regexesMap)); } Map<Integer, ITimeGraphRowModel> quarkToRow = new HashMap<>(idToDisplayQuark.size()); for (Entry<Integer, Long> entry : idToDisplayQuark.entrySet()) { quarkToRow.put(entry.getKey(), new TimeGraphRowModel(entry.getValue(), new ArrayList<>())); } long currentEndTime = ss.getCurrentEndTime(); for (ITmfStateInterval interval : ss.query2D(idToDisplayQuark.keySet(), getTimes(ss, times))) { if (monitor != null && monitor.isCanceled()) { return Collections.emptyList(); } ITimeGraphRowModel row = quarkToRow.get(interval.getAttribute()); if (row != null) { List<@NonNull ITimeGraphState> states = row.getStates(); ITimeGraphState timeGraphState = getStateFromInterval(interval, currentEndTime); applyFilterAndAddState(states, timeGraphState, row.getEntryID(), predicates, monitor); } } for (ITimeGraphRowModel model : quarkToRow.values()) { model.getStates().sort(Comparator.comparingLong(ITimeGraphState::getStartTime)); } return new ArrayList<>(quarkToRow.values()); }

Target:
private List<@NonNull ITimeGraphRowModel> getRowModels(ITmfStateSystem ss, Map<Integer, Long> idToDisplayQuark, @Nullable List<Long> times, Map<String, Object> fetchParameters, @Nullable IProgressMonitor monitor) throws IndexOutOfBoundsException, TimeRangeException, StateSystemDisposedException { Map<@NonNull Integer, @NonNull Predicate<@NonNull Multimap<@NonNull String, @NonNull Object>>> predicates = new HashMap<>(); Multimap<@NonNull Integer, @NonNull String> regexesMap = DataProviderParameterUtils.extractRegexFilter(fetchParameters); if (regexesMap != null) { predicates.putAll(computeRegexPredicate(regexesMap)); } Map<Integer, ITimeGraphRowModel> quarkToRow = new HashMap<>(idToDisplayQuark.size()); for (Entry<Integer, Long> entry : idToDisplayQuark.entrySet()) { quarkToRow.put(entry.getKey(), new TimeGraphRowModel(entry.getValue(), new ArrayList<>())); } for (ITmfStateInterval interval : ss.query2D(idToDisplayQuark.keySet(), getTimes(ss, times))) { if (monitor != null && monitor.isCanceled()) { return Collections.emptyList(); } ITimeGraphRowModel row = quarkToRow.get(interval.getAttribute()); if (row != null) { List<@NonNull ITimeGraphState> states = row.getStates(); ITimeGraphState timeGraphState = getStateFromInterval(interval, ss.getCurrentEndTime()); applyFilterAndAddState(states, timeGraphState, row.getEntryID(), predicates, monitor); } } for (ITimeGraphRowModel model : quarkToRow.values()) { model.getStates().sort(Comparator.comparingLong(ITimeGraphState::getStartTime)); } return new ArrayList<>(quarkToRow.values()); }
Source:
public void new_target() { assertThat(JavaScriptLegacyGrammar.MEMBER_EXPRESSION) .matches("new . target") .notMatches("new . Target") .notMatches("a = target") .notMatches("var target"); }

Target:
public void new_target() { assertThat(JavaScriptLegacyGrammar.MEMBER_EXPRESSION) .matches("new . target") .notMatches("new . Target"); }
Source:
public void copyFromLocalFile(File srcFile, URI dstUri) throws Exception { LOGGER.info("Copy from local to {}", srcFile.getAbsolutePath(), dstUri); URI base = getBase(dstUri); String prefix = sanitizePath(base.relativize(dstUri).getPath()); PutObjectRequest.Builder putReqBuilder = PutObjectRequest.builder().bucket(dstUri.getHost()).key(prefix); PutObjectRequest putObjectRequest; if (!disableAcl) { putObjectRequest = putReqBuilder.acl(ObjectCannedACL.BUCKET_OWNER_FULL_CONTROL).build(); } else { putObjectRequest = putReqBuilder.build(); } _s3Client.putObject(putObjectRequest, srcFile.toPath()); }

Target:
public void copyFromLocalFile(File srcFile, URI dstUri) throws Exception { LOGGER.info("Copy from local to {}", srcFile.getAbsolutePath(), dstUri); URI base = getBase(dstUri); String prefix = sanitizePath(base.relativize(dstUri).getPath()); PutObjectRequest.Builder putReqBuilder = PutObjectRequest.builder().bucket(dstUri.getHost()).key(prefix); if (!disableAcl) { putReqBuilder.acl(ObjectCannedACL.BUCKET_OWNER_FULL_CONTROL); } PutObjectRequest putObjectRequest = putReqBuilder.build(); _s3Client.putObject(putObjectRequest, srcFile.toPath()); }
Source:
public synchronized Video stopRecording() { if (!running) { throw new IllegalStateException("It seems you are not recording anything yet. Please call startRecording()"); } running = false; try { thread.join(); } catch (InterruptedException ignored) { throw new RuntimeException("Unable to stop video recording."); } timer = null; Video video = new WebcamVideo(); video.setResource(recordedVideo); video.setResourceType(VideoType.valueOf(configuration.getVideoType())); video.setWidth(screenBounds.width / 2); video.setHeight(screenBounds.height / 2); return video; }

Target:
public synchronized Video stopRecording() { if (!running) { throw new IllegalStateException("It seems you are not recording anything yet. Please call startRecording()"); } running = false; try { thread.join(); } catch (InterruptedException ignored) { throw new RuntimeException("Unable to stop video recording."); } timer = null; Video video = new WebcamVideo(); video.setResource(recordedVideo); video.setResourceType(VideoType.valueOf(configuration.getVideoType())); video.setWidth(screenBounds.width); video.setHeight(screenBounds.height); return video; }
Source:
public static void addOrUpdateTaskInDB(SPMAsyncTask asyncTask) { try { if (asyncTask.getParameters().getDbAsyncTask() != null) { if (DbFacade.getInstance().getAsyncTaskDAO().get(asyncTask.getTaskID()) == null) { log.infoFormat("BaseAsyncTask::AddOrUpdateTaskInDB: Adding task {0} to DataBase", asyncTask.getTaskID()); saveAsyncTaskInDB(asyncTask); } else { updateAsyncTaskInDB(asyncTask); } } } catch (RuntimeException e) { log.error(String.format( "BaseAsyncTask::AddOrUpdateTaskInDB: Adding/Updating task %1$s to DataBase threw an exception.", asyncTask.getTaskID()), e); } }

Target:
public static void addOrUpdateTaskInDB(SPMAsyncTask asyncTask) { try { if (asyncTask.getParameters().getDbAsyncTask() != null) { if (DbFacade.getInstance().getAsyncTaskDAO().get(asyncTask.getTaskID()) == null) { log.infoFormat("Adding task {0} to DataBase", asyncTask.getTaskID()); saveAsyncTaskInDB(asyncTask); } else { updateAsyncTaskInDB(asyncTask); } } } catch (RuntimeException e) { log.error(String.format( "Adding/Updating task %1$s to DataBase threw an exception.", asyncTask.getTaskID()), e); } }
Source:
private void setSystemErrorCode(int state, String description) { String itemName; itemName = getItemName(DSCAlarmItemType.PANEL_SYSTEM_ERROR, 0, 0); if (itemName != "") { updateItem(itemName, state, description); } }

Target:
private void setSystemErrorCode(int state, String description) { String itemName; itemName = getItemName(DSCAlarmItemType.PANEL_SYSTEM_ERROR, 0, 0); if (StringUtils.isNotEmpty(itemName)) { updateItem(itemName, state, description); } }
Source:
public void canStartupAndShutdown() throws Exception { activeMQ = app.createAndManageChild(EntitySpec.create(ActiveMQBroker.class)); activeMQ.start(ImmutableList.of(testLocation)); EntityTestUtils.assertAttributeEqualsEventually(ImmutableMap.of("timeout", 60*1000), activeMQ, Startable.SERVICE_UP, true); log.info("JMX URL is "+activeMQ.getAttribute(UsesJmx.JMX_URL)); activeMQ.stop(); assertFalse(activeMQ.getAttribute(Startable.SERVICE_UP)); }

Target:
public void canStartupAndShutdown() throws Exception { activeMQ = app.createAndManageChild(EntitySpec.create(ActiveMQBroker.class)); activeMQ.start(ImmutableList.of(testLocation)); EntityTestUtils.assertAttributeEqualsEventually(ImmutableMap.of("timeout", 10*60*1000), activeMQ, Startable.SERVICE_UP, true); log.info("JMX URL is "+activeMQ.getAttribute(UsesJmx.JMX_URL)); activeMQ.stop(); assertFalse(activeMQ.getAttribute(Startable.SERVICE_UP)); }
Source:
public void onMouseInput(MouseEvent event) { EntityPlayer player = Minecraft.getMinecraft().player; if (player == null) { return; } if (KeyBindings.placeItem.isPressed()) { handlePlaceItemKey(); } else if (KeyBindings.toolConfig.isPressed()) { Minecraft.getMinecraft().displayGuiScreen(new GuiToolConfig(player)); } else if (KeyBindings.toolProfileChange.isPressed() && player != null && HandHelper.getMainFirst(player) != null) { DraconicEvolution.network.sendToServer(new PacketSimpleBoolean(PacketSimpleBoolean.ID_TOOL_PROFILE_CHANGE, false)); ItemStack stack = HandHelper.getMainFirst(player); } int change = event.getDwheel(); if (change == 0 || !player.isSneaking()) return; ItemStack item = player.inventory.getStackInSlot(player.inventory.currentItem); if (item.getItem() == DEFeatures.dislocatorAdvanced) { if (event.isCancelable()) event.setCanceled(true); DraconicEvolution.network.sendToServer(new PacketDislocator(PacketDislocator.SCROLL, change < 0 ? -1 : 1, false)); } }

Target:
public void onMouseInput(MouseEvent event) { EntityPlayer player = Minecraft.getMinecraft().player; if (player == null) { return; } if (KeyBindings.placeItem.isPressed()) { handlePlaceItemKey(); } else if (KeyBindings.toolConfig.isPressed()) { Minecraft.getMinecraft().displayGuiScreen(new GuiToolConfig(player)); } else if (KeyBindings.toolProfileChange.isPressed() && player != null && HandHelper.getMainFirst(player) != null) { DraconicEvolution.network.sendToServer(new PacketSimpleBoolean(PacketSimpleBoolean.ID_TOOL_PROFILE_CHANGE, false)); ItemStack stack = HandHelper.getMainFirst(player); } int change = event.getDwheel(); if (change == 0 || !player.isSneaking()) return; ItemStack item = player.inventory.getStackInSlot(player.inventory.currentItem); if (item.getItem() == DEFeatures.dislocatorAdvanced) { event.setCanceled(true); DraconicEvolution.network.sendToServer(new PacketDislocator(PacketDislocator.SCROLL, change < 0 ? -1 : 1, false)); } }
Source:
public void testChronologize(){ Map<Long, Set<TObject>> map = Maps.newLinkedHashMap(); Set<TObject> set = Sets.newLinkedHashSet(); long recordId = TestData.getLong(); PrimaryKey primaryKey = PrimaryKey.wrap(recordId); PrimaryRecord record = PrimaryRecord.createPrimaryRecord(primaryKey); for (long i = 30; i <= 50; i++) { TObject tObject = Convert.javaToThrift("foo" + i); record.append(getRevision(primaryKey, Text.wrapCached("name"), Value.wrap(tObject))); } long start = Time.now(); for (long i = 51; i <= 70; i++) { set = Sets.newLinkedHashSet(set); TObject tObject = Convert.javaToThrift("foo" + i); record.append(getRevision(primaryKey, Text.wrapCached("name"), Value.wrap(tObject))); set.add(tObject); map.put(i, set); } long end = Time.now(); for (long i = 71; i <= 90; i++) { TObject tObject = Convert.javaToThrift("foo" + i); record.append(getRevision(primaryKey, Text.wrapCached("name"), Value.wrap(tObject))); } Map<Long, Set<TObject>> newMap = record.chronologize(Text.wrapCached("name"), start, end); long key = 51; for(Entry<Long, Set<TObject>> e : newMap.entrySet()){ Set<TObject> result = e.getValue(); Assert.assertEquals(map.get(key), result); key++; } }

Target:
public void testChronologize() { Map<Long, Set<Value>> map = Maps.newLinkedHashMap(); Set<Value> set = Sets.newLinkedHashSet(); Set<Value> allValues = Sets.newLinkedHashSet(); long recordId = TestData.getLong(); PrimaryKey primaryKey = PrimaryKey.wrap(recordId); PrimaryRecord record = PrimaryRecord.createPrimaryRecord(primaryKey); for (long i = 30; i <= 35; i++) { Value value = null; while (value == null || !allValues.add(value)) { value = TestData.getValue(); } record.append(getRevision(primaryKey, Text.wrapCached("name"), value)); set.add(value); } long start = Time.now(); for (long i = 36; i <= 45; i++) { set = Sets.newLinkedHashSet(set); Value value = null; while (value == null || !allValues.add(value)) { value = TestData.getValue(); } record.append(getRevision(primaryKey, Text.wrapCached("name"), value)); set.add(value); map.put(i, set); } long end = Time.now(); for (long i = 51; i <= 60; i++) { Value value = null; while (value == null || !allValues.add(value)) { value = TestData.getValue(); } record.append(getRevision(primaryKey, Text.wrapCached("name"), value)); } Map<PrimaryKey, Set<Value>> newMap = record.chronologize( Text.wrapCached("name"), start, end); long key = 36; for (Entry<PrimaryKey, Set<Value>> e : newMap.entrySet()) { Set<Value> result = e.getValue(); Assert.assertEquals(map.get(key), result); key++; } }
Source:
public boolean isEnabled() { ISearchResultPage page = getCurrentPage(); return page != null && WHITELISTED_IDS.contains(page.getID()); }

Target:
public boolean isEnabled() { List<StructuredViewer> viewers = getViewers(); ISearchResultPage page = getCurrentPage(); return viewers.size() > 0 && page != null && WHITELISTED_IDS.contains(page.getID()); }
Source:
public @Nullable Collection<MachineImageVolume> getVolumes() { return volumes; }

Target:
public @Nullable Iterable<MachineImageVolume> getVolumes() { return volumes; }
Source:
public void populateToolBar(IToolBarManager toolBarManager) { createActions(); toolBarManager.add(m_pinToDbgSessionAction); updateActions(); }

Target:
public void populateToolBar(IToolBarManager toolBarManager) { createActions(); toolBarManager.add(m_resumeAction); toolBarManager.add(m_suspendAction); toolBarManager.add(m_terminateAction); toolBarManager.add(m_separatorAction); toolBarManager.add(m_stepReturnAction); toolBarManager.add(m_stepOverAction); toolBarManager.add(m_stepIntoAction); toolBarManager.add(m_dropToFrameAction); toolBarManager.add(m_pinToDbgSessionAction); updateActions(); }
Source:
public void userApprovals(final Set<Change.Id> cids, final Account.Id aid, final AsyncCallback<ApprovalSummarySet> callback) { run(callback, new Action<ApprovalSummarySet>() { public ApprovalSummarySet run(ReviewDb db) throws OrmException { final Map<Change.Id, ApprovalSummary> approvals = new HashMap<Change.Id, ApprovalSummary>(); final List<AccountInfo> accounts = new ArrayList<AccountInfo>(); accounts.add(new AccountInfo(db.accounts().get(aid))); for (final Change.Id id : cids) { try { final ChangeControl cc = changeControlFactory.validateFor(id); final Change change = cc.getChange(); final PatchSet.Id ps_id = change.currentPatchSetId(); final List<PatchSetApproval> psas = new ArrayList<PatchSetApproval>(); final FunctionState fs = functionStateFactory.create(change, ps_id, psas); for (final PatchSetApproval ca : db.patchSetApprovals() .byPatchSetUser(ps_id, aid)) { fs.normalize(approvalTypes.getApprovalType(ca.getCategoryId()), ca); psas.add(ca); } approvals.put(id, new ApprovalSummary(accounts, psas)); } catch (NoSuchChangeException nsce) { } } return new ApprovalSummarySet(approvals); } }); }

Target:
public void userApprovals(final Set<Change.Id> cids, final Account.Id aid, final AsyncCallback<ApprovalSummarySet> callback) { run(callback, new Action<ApprovalSummarySet>() { public ApprovalSummarySet run(ReviewDb db) throws OrmException { final Map<Change.Id, ApprovalSummary> approvals = new HashMap<Change.Id, ApprovalSummary>(); final AccountInfoCacheFactory aicFactory = accountInfoCacheFactory.create(); aicFactory.want(aid); for (final Change.Id id : cids) { try { final ChangeControl cc = changeControlFactory.validateFor(id); final Change change = cc.getChange(); final PatchSet.Id ps_id = change.currentPatchSetId(); final Map<ApprovalCategory.Id, PatchSetApproval> psas = new HashMap<ApprovalCategory.Id, PatchSetApproval>(); final FunctionState fs = functionStateFactory.create(change, ps_id, psas.values()); for (final PatchSetApproval ca : db.patchSetApprovals() .byPatchSetUser(ps_id, aid)) { fs.normalize(approvalTypes.getApprovalType(ca.getCategoryId()), ca); psas.put(ca.getCategoryId(), ca); } approvals.put(id, new ApprovalSummary(psas.values())); } catch (NoSuchChangeException nsce) { } } return new ApprovalSummarySet(aicFactory.create(), approvals); } }); }
Source:
public void close() { this.elementStreamReader.close(); }

Target:
public void close() { try (Closer closer = Closer.create()) { closer.register(() -> elementStreamReader.close()); } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
void processMetrics() { try { if (_usedMemory.get(_port) != null) { long nextMetricProcessTime = this.lastMetricProcessTime + 60L * 1000L; long currentTimeMsec = System.currentTimeMillis(); if (currentTimeMsec < nextMetricProcessTime) { return; } String hostname = Utils.hostname(); String metricName = "UsedMemory"; long timestamp = System.currentTimeMillis(); double value = _usedMemory.get(_port).memory; String componentId = "System"; String executorId = "-1"; String streamId = "None"; WorkerMetricFields workerMetric = new WorkerMetricFields(metricName, timestamp, value, componentId, executorId, streamId); WorkerMetricList metricList = new WorkerMetricList(); metricList.add_to_metrics(workerMetric); WorkerMetrics metrics = new WorkerMetrics(_topologyId, _port, hostname, metricList); try (NimbusClient client = NimbusClient.getConfiguredClient(_conf)) { client.getClient().processWorkerMetrics(metrics); } this.lastMetricProcessTime = currentTimeMsec; } } catch (Exception e) { LOG.error("Failed to process metrics", e); this.lastMetricProcessTime = System.currentTimeMillis(); } }

Target:
void processMetrics() { try { if (_usedMemory.get(_port) != null) { long nextMetricProcessTime = this.lastMetricProcessTime + 60L * 1000L; long currentTimeMsec = System.currentTimeMillis(); if (currentTimeMsec < nextMetricProcessTime) { return; } String hostname = Utils.hostname(); long timestamp = System.currentTimeMillis(); double value = _usedMemory.get(_port).memory; WorkerMetricPoint workerMetric = new WorkerMetricPoint(MEMORY_USED_METRIC, timestamp, value, SYSTEM_COMPONENT_ID, INVALID_EXECUTOR_ID, INVALID_STREAM_ID); WorkerMetricList metricList = new WorkerMetricList(); metricList.add_to_metrics(workerMetric); WorkerMetrics metrics = new WorkerMetrics(_topologyId, _port, hostname, metricList); try (NimbusClient client = NimbusClient.getConfiguredClient(_conf)) { client.getClient().processWorkerMetrics(metrics); } this.lastMetricProcessTime = currentTimeMsec; } } catch (Exception e) { LOG.error("Failed to process metrics", e); this.lastMetricProcessTime = System.currentTimeMillis(); } }
Source:
protected boolean isLunsAlreadyInUse(Set<String> lunIds) { List<LUNs> lunsFromDb = lunDao.getAll(); StringBuilder lunsUsedBySDs = new StringBuilder(); StringBuilder lunsUsedByDisks = new StringBuilder(); lunsFromDb.stream().filter(lun -> lunIds.contains(lun.getLUNId())).forEach(lun -> { if (lun.getStorageDomainId() != null) { addFormattedLunId(lunsUsedBySDs, lun, LUNs::getStorageDomainName); } if (lun.getDiskId() != null) { addFormattedLunId(lunsUsedByDisks, lun, LUNs::getDiskAlias); } }); if (lunsUsedBySDs.length() != 0) { addValidationMessage(EngineMessage.ACTION_TYPE_FAILED_LUNS_ALREADY_PART_OF_STORAGE_DOMAINS); addValidationMessageVariable("lunIds", lunsUsedBySDs.toString()); } if (lunsUsedByDisks.length() != 0) { addValidationMessage(EngineMessage.ACTION_TYPE_FAILED_LUNS_ALREADY_USED_BY_DISKS); addValidationMessageVariable("lunIds", lunsUsedByDisks.toString()); } return lunsUsedBySDs.length() != 0 || lunsUsedByDisks.length() != 0; }

Target:
protected boolean isLunsAlreadyInUse(Set<String> lunIds) { List<LUNs> lunsFromDb = lunDao.getAll(); StringBuilder lunsUsedBySDs = new StringBuilder(); StringBuilder lunsUsedByDisks = new StringBuilder(); lunsFromDb.stream().filter(lun -> lunIds.contains(lun.getLUNId())).forEach(lun -> { if (lun.getStorageDomainId() != null) { addFormattedLunId(lunsUsedBySDs, lun.getLUNId(), lun.getStorageDomainName()); } if (lun.getDiskId() != null) { addFormattedLunId(lunsUsedByDisks, lun.getLUNId(), lun.getDiskAlias()); } }); if (lunsUsedBySDs.length() != 0) { addValidationMessage(EngineMessage.ACTION_TYPE_FAILED_LUNS_ALREADY_PART_OF_STORAGE_DOMAINS); addValidationMessageVariable("lunIds", lunsUsedBySDs.toString()); } if (lunsUsedByDisks.length() != 0) { addValidationMessage(EngineMessage.ACTION_TYPE_FAILED_LUNS_ALREADY_USED_BY_DISKS); addValidationMessageVariable("lunIds", lunsUsedByDisks.toString()); } return lunsUsedBySDs.length() != 0 || lunsUsedByDisks.length() != 0; }