auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void fitBiggestContainerIgnoresCoresIfMissing() { Set<HeronMasterDriver.HeronWorker> workers = new HashSet<>(); workers.add(new HeronMasterDriver.HeronWorker(1, 3, ByteAmount.fromMegabytes(3))); AllocatedEvaluator mockEvaluator = createMockEvaluator("test", 1, ByteAmount.fromMegabytes(3)); Optional<HeronMasterDriver.HeronWorker> result = spyDriver.findLargestFittingWorker(mockEvaluator, workers, false); Assert.assertFalse(result.isPresent()); result = spyDriver.findLargestFittingWorker(mockEvaluator, workers, true); assertTrue(result.isPresent()); assertEquals(1, result.get().getWorkerId()); }

Target:
public void fitBiggestContainerIgnoresCoresIfMissing() { Set<HeronMasterDriver.HeronWorker> workers = new HashSet<>(); workers.add(new HeronMasterDriver.HeronWorker(1, 3, ByteAmount.fromGigabytes(3))); AllocatedEvaluator mockEvaluator = createMockEvaluator("test", 1, ByteAmount.fromGigabytes(3)); Optional<HeronMasterDriver.HeronWorker> result = spyDriver.findLargestFittingWorker(mockEvaluator, workers, false); Assert.assertFalse(result.isPresent()); result = spyDriver.findLargestFittingWorker(mockEvaluator, workers, true); assertTrue(result.isPresent()); assertEquals(1, result.get().getWorkerId()); }
Source:
public final <J extends IsProperties> J strip() { return getDataImpl(); }

Target:
public final <J extends IsProperties> J strip() { return (J)this; }
Source:
default TimeDimensionProjection toTimeGrain(TimeGrain newGrain) { if (getTimeDimension().getSupportedGrains().stream().noneMatch(g -> g.getGrain().equals(newGrain))) { throw new InvalidValueException(getTimeDimension().getId() + " doesn't support grain " + newGrain); } TimeDimensionProjection projection = this; return new TimeDimensionProjection() { @Override public TimeDimension getTimeDimension() { return projection.getTimeDimension(); } @Override public TimeGrain getGrain() { return newGrain; } @Override public String getAlias() { return projection.getAlias(); } }; }

Target:
default TimeDimensionProjection toTimeGrain(TimeGrain newGrain) { if (getTimeDimension().getSupportedGrains().stream() .noneMatch(supportedGrain -> supportedGrain.getGrain().equals(newGrain))) { throw new InvalidValueException(getTimeDimension().getId() + " doesn't support grain " + newGrain); } TimeDimensionProjection projection = this; return new TimeDimensionProjection() { @Override public TimeDimension getTimeDimension() { return projection.getTimeDimension(); } @Override public TimeGrain getGrain() { return newGrain; } @Override public TimeZone getTimeZone() { return projection.getTimeZone(); } @Override public String getAlias() { return projection.getAlias(); } }; }
Source:
protected DefaultIndexBuilder fillIndexBuilder(Path path) throws Exception { final DefaultIndexBuilder builder = getIndexBuilder(path); if (builder == null) { return null; } String formContent = ioService.readAllString(path); FormDefinition formDefinition = formDefinitionSerializer.deserialize(formContent); if (formDefinition != null) { Resource resParts = new Resource(formDefinition.getName(), ResourceType.FORM); FormDefinitionVisitor visitor = new FormDefinitionVisitor(resParts); visitor.visit(formDefinition); addReferencedResourcesToIndexBuilder(builder, visitor); FormModel model = formDefinition.getModel(); if (model != null) { FormModelVisitorProvider provider = visitorProviders.get(model.getClass()); if (provider != null) { FormModelVisitor modelVisitor = provider.getVisitor(); modelVisitor.index(formDefinition ,model); addReferencedResourcesToIndexBuilder(builder, modelVisitor); } } } else { logger.error("Unable to read FormDefinition on " + path.toUri().toString() + "."); return null; } return builder; }

Target:
protected DefaultIndexBuilder fillIndexBuilder(Path path) throws Exception { final DefaultIndexBuilder builder = getIndexBuilder(path); if (builder == null) { return null; } String formContent = ioService.readAllString(path); FormDefinition formDefinition = formDefinitionSerializer.deserialize(formContent); if (formDefinition != null) { Resource resParts = new Resource(formDefinition.getName(), ResourceType.FORM); FormDefinitionVisitor visitor = new FormDefinitionVisitor(resParts); visitor.visit(formDefinition); addReferencedResourcesToIndexBuilder(builder, visitor); FormModel model = formDefinition.getModel(); if (model != null) { FormModelVisitorProvider provider = getProviderForModel(model.getClass()); if (provider != null) { FormModelVisitor modelVisitor = provider.getVisitor(); modelVisitor.index(formDefinition, model); addReferencedResourcesToIndexBuilder(builder, modelVisitor); } } } else { logger.error("Unable to read FormDefinition on " + path.toUri().toString() + "."); return null; } return builder; }
Source:
public void testWorkflowRepresentationMarshalling_shouldMarshallWorkflowCorrectly() throws SAXException, IOException, JAXBException { WorkflowRepresentation representation = createWorkflow(); WorkflowRepresentationConverter workflowRepresentationMarshaller = new WorkflowRepresentationConverter(); String converted = workflowRepresentationMarshaller.marshallWorkflow(representation); WorkflowRepresentation rep = workflowRepresentationMarshaller.unmarshallWorkflow(converted); compareActionRepresentation(representation.getRoot(), rep.getRoot()); }

Target:
public void testWorkflowRepresentationMarshalling_shouldMarshallWorkflowCorrectly() throws JAXBException { WorkflowRepresentation representation = createWorkflow(); WorkflowRepresentationConverter workflowRepresentationMarshaller = new WorkflowRepresentationConverter(); String converted = workflowRepresentationMarshaller.marshallWorkflow(representation); WorkflowRepresentation rep = workflowRepresentationMarshaller.unmarshallWorkflow(converted); compareActionRepresentation(representation.getRoot(), rep.getRoot()); }
Source:
public void testEncodeOutputControl() { Tk103ProtocolEncoder encoder = new Tk103ProtocolEncoder(); Command command = new Command(); command.setDeviceId(1); command.setType(Command.TYPE_OUTPUT_CONTROL); command.set(Command.KEY_INDEX, 0); command.set(Command.KEY_DATA, "1"); assertEquals("(123456789012345AV001)", encoder.encodeCommand(command)); }

Target:
public void testEncodeOutputControl() { Tk103ProtocolEncoder encoder = new Tk103ProtocolEncoder(); Command command = new Command(); command.setDeviceId(1); command.setType(Command.TYPE_OUTPUT_CONTROL); command.set(Command.KEY_DATA, "1"); assertEquals("(123456789012345AV001)", encoder.encodeCommand(command)); }
Source:
public void refresh() { if (getManagedForm() == null || getManagedForm().getForm().isDisposed()) { return; } try { showEditorBusy(true); boolean hasIncoming = false; if (getTask() != null) { hasIncoming = getTask().getSynchronizationState().isIncoming(); } if (model != null) { doSave(new NullProgressMonitor()); refreshInput(); } else { initModel(getTaskEditor().getTaskEditorInput()); } if (taskData != null) { try { setReflow(false); Menu menu = editorComposite.getMenu(); CommonUiUtil.setMenu(editorComposite, null); if (focusTracker != null) { focusTracker.reset(); } lastSelection = null; editorComposite.setMenu(menu); if (!shouldAutoRefresh) { createFormContentInternal(); } getTaskEditor().setMessage(null, 0); if (hasIncoming) { getTaskEditor().setActivePage(getId()); } setSubmitEnabled(true); } finally { setReflow(true); } } updateOutlinePage(); updateHeaderMessage(); getManagedForm().dirtyStateChanged(); getTaskEditor().updateHeaderToolBar(); } finally { showEditorBusy(false); } reflow(); }

Target:
public void refresh() { if (getManagedForm() == null || getManagedForm().getForm().isDisposed()) { return; } try { showEditorBusy(true); boolean hasIncoming = false; if (getTask() != null) { hasIncoming = getTask().getSynchronizationState().isIncoming(); } if (model != null) { doSave(new NullProgressMonitor()); refreshInput(); } else { initModel(getTaskEditor().getTaskEditorInput()); } if (taskData != null) { try { setReflow(false); if (focusTracker != null) { focusTracker.reset(); } lastSelection = null; boolean recreatePage = false; for (AbstractTaskEditorSection section : sections) { if (!section.supportsRefreshing()) { recreatePage = true; break; } } if (recreatePage) { Menu menu = editorComposite.getMenu(); CommonUiUtil.setMenu(editorComposite, null); for (AbstractTaskEditorSection section : sections) { section.dispose(); } sections.clear(); editorComposite.setMenu(menu); createFormContentInternal(); } getTaskEditor().setMessage(null, 0); if (hasIncoming) { getTaskEditor().setActivePage(getId()); } setSubmitEnabled(true); } finally { setReflow(true); } } updateOutlinePage(); updateHeaderMessage(); getManagedForm().dirtyStateChanged(); getTaskEditor().updateHeaderToolBar(); } finally { showEditorBusy(false); } reflow(); }
Source:
public LnkFile parse(byte[] rawLnkShortcutByteArray) { final byte dataFlags = rawLnkShortcutByteArray[20]; final LnkFileAttribute fileAttributes = fetchFilesAttributes(rawLnkShortcutByteArray); final LnkData lnkData = fetchLnkData(rawLnkShortcutByteArray); final boolean isDirectory = fileAttributes.hasDirMask(); final boolean hasArguments = lnkData.hasArguments(); final int fileStart = fetchFileStart(rawLnkShortcutByteArray, lnkData); final byte[] rawLnkContentWithoutHeader = Arrays.copyOfRange(rawLnkShortcutByteArray, fileStart, rawLnkShortcutByteArray.length - 1); final boolean isLocal = this.isLnkLocal(rawLnkContentWithoutHeader); final String fileName = parseLnkContent(rawLnkContentWithoutHeader, isLocal); return new LnkFile(isDirectory, isLocal, fileName, hasArguments); }

Target:
public LnkFile parse(byte[] rawLnkShortcutByteArray) { final LnkFileAttributeFlagsParser fileAttributes = fetchFilesAttributes(rawLnkShortcutByteArray); final LnkLinkFlagsParser lnkDataFlag = fetchLnkData(rawLnkShortcutByteArray); final boolean isDirectory = fileAttributes.hasDirMask(); final boolean hasArguments = lnkDataFlag.hasArguments(); final int fileStart = fetchFileStart(rawLnkShortcutByteArray, lnkDataFlag); final byte[] rawLnkContentWithoutHeader = Arrays.copyOfRange(rawLnkShortcutByteArray, fileStart, rawLnkShortcutByteArray.length - 1); final boolean isLocal = this.isLnkLocal(rawLnkContentWithoutHeader); final String fileName = parseLnkContent(rawLnkContentWithoutHeader, isLocal); final LnkStringData lnkStringData = fetchStringData( rawLnkContentWithoutHeader, lnkDataFlag); return new LnkFile(isDirectory, isLocal, fileName, hasArguments, lnkStringData); }
Source:
public SeekableByteChannel buildChannel(final String key) throws IOException { final String strippedKey = Ds3ClientHelpers.stripLeadingPath(key, prefix); Files.createDirectories(Paths.get(strippedKey).getParent()); return this.channelBuilder.buildChannel(strippedKey); }

Target:
public SeekableByteChannel buildChannel(final String key) throws IOException { return this.channelBuilder.buildChannel(Ds3ClientHelpers.stripLeadingPath(key, prefix)); }
Source:
public Map getDetails() { Map<String, String> detailsMap = null; if (!details.isEmpty()) { detailsMap = new HashMap<String, String>(); Collection<?> servicesCollection = details.values(); Iterator<?> iter = servicesCollection.iterator(); while (iter.hasNext()) { HashMap<String, String> services = (HashMap<String, String>)iter.next(); String key = services.get("key"); String value = services.get("value"); detailsMap.put(key, value); } } return detailsMap; }

Target:
public Map getDetails() { Map<String, String> detailsMap = new HashMap<String, String>();; if (!details.isEmpty()) { Collection<?> servicesCollection = details.values(); Iterator<?> iter = servicesCollection.iterator(); while (iter.hasNext()) { HashMap<String, String> services = (HashMap<String, String>)iter.next(); String key = services.get("key"); String value = services.get("value"); detailsMap.put(key, value); } } return detailsMap; }
Source:
private void changeZ(int zOffset) { SceneElement element = getSelectedSceneElement(); Scene scene = getCurrentScene(); List list = scene.getChildren(); int index = list.indexOf(element); controller.command(new ReorderInListCommand(list, element, Math.max(0, Math.min(index + zOffset, list.size() - 1)))); }

Target:
private void changeZ(int zOffset) { SceneElement element = getSelectedSceneElement(); Scene scene = getCurrentScene(); List list = scene.getChildren(); controller.action(Reorder.class, element, zOffset, true, list); }
Source:
protected Object doWork() { JavaSparkContext ctx = null; if (!isDisableSpark) { SparkConf sparkConf = new SparkConf().setAppName(getProgramName()) .set("spark.serializer", KryoSerializer.class.getCanonicalName()) .set("spark.kryo.registrator", "org.broadinstitute.hellbender.engine.spark.GATKRegistrator") .set("spark.kryoserializer.buffer.max", "512m") .set("spark.driver.maxResultSize", "0") .set("spark.driver.userClassPathFirst", "true") .set("spark.executor.userClassPathFirst", "true") .set("spark.io.compression.codec", "lzf") .set("spark.yarn.executor.memoryOverhead", "600") .setMaster(sparkMaster); ctx = new JavaSparkContext(sparkConf); } else { logger.info("Spark disabled. sparkMaster option (" + this.sparkMaster + ") ignored."); } try{ runPipeline(ctx); return null; } finally { afterPipeline(ctx); } }

Target:
protected Object doWork() { JavaSparkContext ctx = null; if (!isDisableSpark) { ctx = SparkContextFactory.getSparkContext(getProgramName(), sparkMaster); } else { logger.info("Spark disabled. sparkMaster option (" + this.sparkMaster + ") ignored."); } try{ runPipeline(ctx); return null; } finally { afterPipeline(ctx); } }
Source:
private Number readNumberFromConfig(Config config, String parameterName) { Number paramValue; try { paramValue = config.getAny(parameterName); } catch (ClassCastException e) { throw new IllegalArgumentException("Required parameter " + parameterName + " should be a number."); } return paramValue; }

Target:
private Number readNumberFromConfig(Config config, String parameterName) { try { return config.getAny(parameterName); } catch (ClassCastException e) { throw new IllegalArgumentException("Required parameter " + parameterName + " should be a number."); } }
Source:
protected IProcess addProcessToLaunch(Process p, ILaunch launch, IServer s, boolean terminal) { Map<String, String> processAttributes = new HashMap<String, String>(); String vagrantcmdloc = VagrantBinaryUtility.getVagrantLocation(s); String progName = new Path(vagrantcmdloc).lastSegment(); if( terminal ) { launch.setAttribute(DebugPlugin.ATTR_CAPTURE_OUTPUT, "false"); } processAttributes.put(IProcess.ATTR_PROCESS_TYPE, progName); IProcess process = null; if( terminal ) { process = new RuntimeProcess(launch, p, vagrantcmdloc, processAttributes) { protected IStreamsProxy createStreamsProxy() { return null; } }; } else { process = new RuntimeProcess(launch, p, vagrantcmdloc, processAttributes); } launch.addProcess(process); return process; }

Target:
protected IProcess addProcessToLaunch(Process p, ILaunch launch, IServer s, boolean terminal) { String cmdLoc = VagrantBinaryUtility.getVagrantLocation(s); return addProcessToLaunch(p, launch, s, terminal, cmdLoc); }
Source:
public void testCreateNoteWithSubject() throws IOException, SchedulerException, RepositoryException { AuthenticationInfo subject = new AuthenticationInfo("user1"); Note note = notebook.createNote(subject); Notebook notebook = new Notebook( conf, notebookRepo, schedulerFactory, new InterpreterFactory(conf, null, null, null, depResolver), this, null, notebookAuthorization, null); assertNotNull(notebook.getNotebookAuthorization().getOwners(note.getId())); assertEquals(1, notebook.getNotebookAuthorization().getOwners(note.getId()).size()); Set<String> owners = new HashSet<>(); owners.add("user1"); assertEquals(owners, notebook.getNotebookAuthorization().getOwners(note.getId())); }

Target:
public void testCreateNoteWithSubject() throws IOException, SchedulerException, RepositoryException { AuthenticationInfo subject = new AuthenticationInfo("user1"); Note note = notebook.createNote(subject); assertNotNull(notebook.getNotebookAuthorization().getOwners(note.getId())); assertEquals(1, notebook.getNotebookAuthorization().getOwners(note.getId()).size()); Set<String> owners = new HashSet<>(); owners.add("user1"); assertEquals(owners, notebook.getNotebookAuthorization().getOwners(note.getId())); }
Source:
public List<Media> searchImages(String query, int offset) { List<CustomApiResult> imageNodes = null; List<CustomApiResult> authorNodes = null; CustomApiResult apiResult=null; try { apiResult= api.action("query") .param("format", "xml") .param("generator", "search") .param("gsrwhat", "text") .param("gsrnamespace", "6") .param("gsrlimit", "25") .param("gsroffset",offset) .param("gsrsearch", query) .param("prop", "imageinfo") .param("iiprop", "url|extmetadata") .get(); imageNodes= apiResult.getNodes("/api/query/pages/page/@title"); authorNodes= apiResult.getNodes("/api/query/pages/page/imageinfo/ii/@user"); } catch (IOException e) { Timber.e(e, "Failed to obtain searchImages"); } if (imageNodes == null) { return new ArrayList<>(); } CustomApiResult searchImagesNode = apiResult.getNode("/api/query/pages"); if (searchImagesNode == null || searchImagesNode.getDocument() == null || searchImagesNode.getDocument().getChildNodes() == null || searchImagesNode.getDocument().getChildNodes().getLength() == 0) { return new ArrayList<>(); } NodeList childNodes = searchImagesNode.getDocument().getChildNodes(); return CategoryImageUtils.getMediaList(childNodes); }

Target:
public List<Media> searchImages(String query, int offset) { CustomApiResult apiResult=null; try { apiResult= api.action("query") .param("format", "xml") .param("generator", "search") .param("gsrwhat", "text") .param("gsrnamespace", "6") .param("gsrlimit", "25") .param("gsroffset",offset) .param("gsrsearch", query) .param("prop", "imageinfo") .param("iiprop", "url|extmetadata") .get(); } catch (IOException e) { Timber.e(e, "Failed to obtain searchImages"); } CustomApiResult searchImagesNode = apiResult.getNode("/api/query/pages"); if (searchImagesNode == null || searchImagesNode.getDocument() == null || searchImagesNode.getDocument().getChildNodes() == null || searchImagesNode.getDocument().getChildNodes().getLength() == 0) { return new ArrayList<>(); } NodeList childNodes = searchImagesNode.getDocument().getChildNodes(); return CategoryImageUtils.getMediaList(childNodes); }
Source:
protected boolean ConcreteAddVmImages(Guid itGuid) { boolean ret = true; if (getVmDisks().size() > 0) { for (Disk diskInfo : getVmDisks()) { VdcReturnValueBase tmpRetValue = null; AddImageFromScratchParameters tempVar = new AddImageFromScratchParameters(itGuid, getParameters() .getVmStaticData().getId(), (DiskImage) diskInfo); tempVar.setStorageDomainId(this.getStorageDomainId().getValue()); tempVar.setVmSnapshotId(getVmSnapshotId()); tempVar.setParentCommand(VdcActionType.AddVmFromScratch); tempVar.setEntityId(getParameters().getEntityId()); tempVar.setParentParameters(getParameters()); tmpRetValue = Backend.getInstance().runInternalAction( VdcActionType.AddImageFromScratch, tempVar, ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!tmpRetValue.getSucceeded()) { log.error("AddVmFromScratchCommand::ConcreteAddVmImages: AddImageFromScratch Command failed."); ret = false; } else { getReturnValue().getTaskIdList().addAll(tmpRetValue.getInternalTaskIdList()); } } VmHandler.LockVm(getParameters().getVmStaticData().getId()); } else { getVmDAO().incrementVmDbGeneration(getParameters().getVmStaticData().getId()); } return ret; }

Target:
protected boolean ConcreteAddVmImages(Guid itGuid) { boolean ret = true; if (getVmDisks().size() > 0) { for (Disk diskInfo : getVmDisks()) { VdcReturnValueBase tmpRetValue = null; AddImageFromScratchParameters tempVar = new AddImageFromScratchParameters(itGuid, getParameters() .getVmStaticData().getId(), (DiskImage) diskInfo); tempVar.setStorageDomainId(this.getStorageDomainId().getValue()); tempVar.setVmSnapshotId(getVmSnapshotId()); tempVar.setParentCommand(VdcActionType.AddVmFromScratch); tempVar.setEntityId(getParameters().getEntityId()); tempVar.setParentParameters(getParameters()); tmpRetValue = Backend.getInstance().runInternalAction( VdcActionType.AddImageFromScratch, tempVar, ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!tmpRetValue.getSucceeded()) { log.error("AddVmFromScratchCommand::ConcreteAddVmImages: AddImageFromScratch Command failed."); ret = false; } else { getReturnValue().getTaskIdList().addAll(tmpRetValue.getInternalTaskIdList()); } } VmHandler.LockVm(getParameters().getVmStaticData().getId()); } else { updateVmInSpm(getVm().getstorage_pool_id(), Arrays.asList(getVm())); } return ret; }
Source:
public static <T> String validationMethodFormatted(ConstraintViolation<T> v) { final ImmutableList<Path.Node> nodes = ImmutableList.copyOf(v.getPropertyPath()); final ImmutableList<Path.Node> usefulNodes = nodes.subList(0, nodes.size() - 1); final String msg = v.getMessage().startsWith(".") ? "%s%s" : "%s %s"; return String.format(msg, Joiner.on('.').join(usefulNodes), v.getMessage()).trim(); }

Target:
public static <T> String validationMethodFormatted(ConstraintViolation<T> v) { final ImmutableList<Path.Node> nodes = ImmutableList.copyOf(v.getPropertyPath()); String usefulNodes = DOT_JOINER.join(nodes.subList(0, nodes.size() - 1)); String msg = usefulNodes + (v.getMessage().startsWith(".") ? "" : " ") + v.getMessage(); return msg.trim(); }
Source:
private Vector<String> groupsFor(DirContext ctx, String dn) { Vector<String> out = new Vector<String>(); String parentDn; try { String attNames[] = { groupName, accountMemberField }; Attributes groupAtts = ctx.getAttributes(dn, attNames); String cn = String.valueOf(groupAtts.get(groupName)); cn = cn.replace(groupName + ": ", ""); out.add(cn); Attribute parentAttrs = ctx.getAttributes(dn).get(accountMemberField); if (parentAttrs != null) { NamingEnumeration parents = parentAttrs.getAll(); while (parents.hasMore()) { parentDn = String.valueOf(parents.next()); out.addAll(groupsFor(ctx, parentDn)); } } } catch (NamingException e) { } return out; }

Target:
private ArrayList<String> groupsFor(DirContext ctx, String dn) throws NamingException { ArrayList<String> out = new ArrayList<String>(); String parentDn; try { String attNames[] = { groupName, accountMemberField }; Attributes groupAtts = ctx.getAttributes(dn, attNames); String cn = (String) groupAtts.get(groupName).get(); out.add(cn); Attribute parentAttrs = ctx.getAttributes(dn).get(accountMemberField); if (parentAttrs != null) { NamingEnumeration parents = parentAttrs.getAll(); while (parents.hasMore()) { parentDn = String.valueOf(parents.next()); out.addAll(groupsFor(ctx, parentDn)); } } } catch (NamingException e) { log.warn("Could not find dn", e); } return out; }
Source:
public List<String> getUsernames(){ ArrayList<String> usernames = new ArrayList<String>(); Iterator<Entry<String, String>> it = connectedUsers.entrySet().iterator(); while (it.hasNext()) { Entry<String, String> entry = it.next(); usernames.add(entry.getKey()); } return usernames; }

Target:
public List<String> getUsernames(){ ArrayList<String> usernames = new ArrayList<String>(); Iterator<Entry<String, String>> userListIterator = connectedUsers.entrySet().iterator(); while (userListIterator.hasNext()) { Entry<String, String> entry = userListIterator.next(); usernames.add(entry.getKey()); } return usernames; }
Source:
public Map<Long, DrawableDbBuildStatusEnum> getDataSourceDbBuildStatus() throws TskCoreException { Statement statement = null; ResultSet rs = null; Map<Long, DrawableDbBuildStatusEnum> map = new HashMap<>(); dbReadLock(); try { statement = con.createStatement(); rs = statement.executeQuery("SELECT ds_obj_id, drawable_db_build_status FROM datasources "); while (rs.next()) { map.put(rs.getLong(1), DrawableDbBuildStatusEnum.valueOf(rs.getString(2))); } } catch (SQLException e) { throw new TskCoreException("SQLException while getting data source object ids", e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException ex) { LOGGER.log(Level.SEVERE, "Error closing resultset", ex); } } if (statement != null) { try { statement.close(); } catch (SQLException ex) { LOGGER.log(Level.SEVERE, "Error closing statement ", ex); } } dbReadUnlock(); } return map; }

Target:
public Map<Long, DrawableDbBuildStatusEnum> getDataSourceDbBuildStatus() throws TskCoreException { Statement statement = null; ResultSet rs = null; Map<Long, DrawableDbBuildStatusEnum> map = new HashMap<>(); dbReadLock(); try { statement = con.createStatement(); rs = statement.executeQuery("SELECT ds_obj_id, drawable_db_build_status FROM datasources "); while (rs.next()) { map.put(rs.getLong("ds_obj_id"), DrawableDbBuildStatusEnum.valueOf(rs.getString("drawable_db_build_status"))); } } catch (SQLException e) { throw new TskCoreException("SQLException while getting data source object ids", e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException ex) { LOGGER.log(Level.SEVERE, "Error closing resultset", ex); } } if (statement != null) { try { statement.close(); } catch (SQLException ex) { LOGGER.log(Level.SEVERE, "Error closing statement ", ex); } } dbReadUnlock(); } return map; }
Source:
protected Supplier<URI> provideStorageUrl(RegionIdToURISupplier.Factory factory, @ApiVersion String apiVersion, @Named(LocationConstants.PROPERTY_REGION) String region) { Supplier<Map<String, Supplier<URI>>> endpointsSupplier = factory.createForApiTypeAndVersion(ServiceType.OBJECT_STORE, apiVersion); if (!Strings.isNullOrEmpty(region)) { return getSpecificValueInMap(endpointsSupplier, region); } else { return getLastValueInMap(endpointsSupplier); } }

Target:
protected Supplier<URI> provideStorageUrl(RegionIdToURISupplier.Factory factory, @ApiVersion String apiVersion, @Named(LocationConstants.PROPERTY_REGION) String region) { Supplier<Map<String, Supplier<URI>>> endpointsSupplier = factory.createForApiTypeAndVersion(ServiceType.OBJECT_STORE, apiVersion); if (region.isEmpty()) { return getLastValueInMap(endpointsSupplier); } else { return getValueInMapOrNull(endpointsSupplier, region); } }
Source:
public void testMessageCustomCorrelation() throws Exception { this.fooMessage.getMessageProperties().setCorrelationId("foo".getBytes()); ListenableFuture<Message> future = this.template.sendAndReceive(this.fooMessage); Message result = checkMessageResult(future, "FOO"); assertEquals(new String("foo"), new String(result.getMessageProperties().getCorrelationId())); }

Target:
public void testMessageCustomCorrelation() throws Exception { this.fooMessage.getMessageProperties().setCorrelationId("foo".getBytes()); ListenableFuture<Message> future = this.template.sendAndReceive(this.fooMessage); Message result = checkMessageResult(future, "FOO"); assertEquals("foo", new String(result.getMessageProperties().getCorrelationId())); }
Source:
public MongoDbFactory mongoDbFactory() throws IOException { Properties properties = new Properties(); properties.load(MongoConfiguration.class.getResourceAsStream("/eva.properties")); MongoClient mongoClient = DBAdaptorConnector.getMongoClient(properties); return new MultiMongoDbFactory(mongoClient, "test"); }

Target:
public MongoDbFactory mongoDbFactory() throws IOException { Properties properties = new Properties(); properties.load(MongoConfiguration.class.getResourceAsStream("/eva.properties")); MongoClient mongoClient = DBAdaptorConnector.getMongoClient(properties); return new MultiMongoDbFactory(mongoClient, "unusedDefaultDB"); }
Source:
private ParquetProperties(WriterVersion writerVersion, int pageSize, int dictPageSize, boolean enableDict, int minRowCountForPageSizeCheck, int maxRowCountForPageSizeCheck, boolean estimateNextSizeCheck, ByteBufferAllocator allocator, ValuesWriterFactory writerFactory) { this.pageSizeThreshold = pageSize; int initialSlabSize = CapacityByteArrayOutputStream .initialSlabSizeHeuristic(MIN_SLAB_SIZE, pageSizeThreshold, 10); this.dictionaryPageSizeThreshold = dictPageSize; this.writerVersion = writerVersion; this.enableDictionary = enableDict; this.minRowCountForPageSizeCheck = minRowCountForPageSizeCheck; this.maxRowCountForPageSizeCheck = maxRowCountForPageSizeCheck; this.estimateNextSizeCheck = estimateNextSizeCheck; this.allocator = allocator; ValuesWriterFactoryParams params = new ValuesWriterFactoryParams(writerVersion, initialSlabSize, pageSizeThreshold, allocator, enableDictionary, dictionaryPageSizeThreshold); valuesWriterFactory = writerFactory; valuesWriterFactory.initialize(params); }

Target:
private ParquetProperties(WriterVersion writerVersion, int pageSize, int dictPageSize, boolean enableDict, int minRowCountForPageSizeCheck, int maxRowCountForPageSizeCheck, boolean estimateNextSizeCheck, ByteBufferAllocator allocator, ValuesWriterFactory writerFactory) { this.pageSizeThreshold = pageSize; this.initialSlabSize = CapacityByteArrayOutputStream .initialSlabSizeHeuristic(MIN_SLAB_SIZE, pageSizeThreshold, 10); this.dictionaryPageSizeThreshold = dictPageSize; this.writerVersion = writerVersion; this.enableDictionary = enableDict; this.minRowCountForPageSizeCheck = minRowCountForPageSizeCheck; this.maxRowCountForPageSizeCheck = maxRowCountForPageSizeCheck; this.estimateNextSizeCheck = estimateNextSizeCheck; this.allocator = allocator; this.valuesWriterFactory = writerFactory; }
Source:
default void validateParameters(long bucketCount, double sample, double weight, double min, double max) { throw new UnsupportedOperationException( format("Unsupported arguments for type: %s", getClass().getSimpleName())); }

Target:
default void validateParameters(long bucketCount, double sample, double weight, double min, double max) { throw new UnsupportedOperationException( format("In differential_entropy UDF, unsupported arguments for type: %s", getClass().getSimpleName())); }
Source:
private static String expressionLogicalOr(Set<String> fileExts) { StringBuilder pattern = new StringBuilder("("); for (String ext : fileExts) { if (pattern.length() != 1) pattern.append("|"); pattern.append("(").append(Pattern.quote(ext)); pattern.append(")"); ext = ext.toUpperCase(); if (!fileExts.contains(ext)) { pattern.append("|(").append(Pattern.quote(ext)); pattern.append(")"); } } pattern.append(")"); return pattern.toString(); }

Target:
private static String expressionLogicalOr(Set<String> fileExts) { StringBuilder pattern = new StringBuilder('('); for (String ext : fileExts) { if (pattern.length() != 1) pattern.append('|'); pattern.append('(').append(Pattern.quote(ext)); pattern.append(')'); ext = ext.toUpperCase(); if (!fileExts.contains(ext)) { pattern.append("|(").append(Pattern.quote(ext)); pattern.append(')'); } } pattern.append(')'); return pattern.toString(); }
Source:
public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> items) { if(tab == EsteemedInnovation.tab) { for (int i = 0; i < ArmorModule.MAX_PLATE_META; i++) { items.add(ArmorModule.plateStack(i)); } } }

Target:
public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> items) { if (isInCreativeTab(tab)) { for (int i = 0; i < ArmorModule.MAX_PLATE_META; i++) { items.add(ArmorModule.plateStack(i)); } } }
Source:
public void shouldStagePartialChangeInCompareEditor() throws Exception { resetRepositoryToCreateInitialTag(); changeFilesInProject(); launchSynchronization(HEAD, HEAD, true); setGitChangeSetPresentationModel(); getCompareEditorForFileInGitChangeSet(FILE1, true).bot(); Display.getDefault().syncExec(new Runnable() { public void run() { CommonUtils.runCommand("org.eclipse.compare.copyLeftToRight", null); } }); bot.activeEditor().save(); FileRepository repo = lookupRepository(repositoryFile); Status status = new Git(repo).status().call(); assertThat(status.getChanged().size(), is(1)); assertThat(status.getChanged().iterator().next(), is(PROJ1 + "/" + FOLDER + "/" + FILE1)); }

Target:
public void shouldStagePartialChangeInCompareEditor() throws Exception { resetRepositoryToCreateInitialTag(); changeFilesInProject(); launchSynchronization(HEAD, HEAD, true); setGitChangeSetPresentationModel(); getCompareEditorForFileInGitChangeSet(FILE1, true).bot(); Display.getDefault().syncExec(new Runnable() { public void run() { CommonUtils.runCommand("org.eclipse.compare.copyLeftToRight", null); } }); bot.activeEditor().save(); FileRepository repo = lookupRepository(repositoryFile); Status status = new Git(repo).status().call(); assertThat(Long.valueOf(status.getChanged().size()), is(Long.valueOf(1L))); assertThat(status.getChanged().iterator().next(), is(PROJ1 + "/" + FOLDER + "/" + FILE1)); }
Source:
public void setup() { try { uri = new URI(broadcastURI); } catch (URISyntaxException e) { e.printStackTrace(); } }

Target:
public void setup() { try { uri = new URI(broadcastURI); } catch (URISyntaxException e) { LOGGER.error(e.getMessage()); } }
Source:
private void onNewTemplate() { UserPortalItemModel selectedItem = (UserPortalItemModel) getSelectedItem(); if (selectedItem == null) { cancel(); return; } UnitVmModel model = (UnitVmModel) getWindow(); if (!model.validate(false)) { model.setIsValid(false); } else if (model.getIsSubTemplate().getEntity()) { postNameUniqueCheck(this); } else { model.startProgress(null); String name = model.getName().getEntity(); AsyncDataProvider.getInstance().isTemplateNameUnique(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { UserPortalListModel userPortalListModel = (UserPortalListModel) target; boolean isNameUnique = (Boolean) returnValue; if (!isNameUnique) { UnitVmModel vmModel = (UnitVmModel) userPortalListModel.getWindow(); vmModel.getName().getInvalidityReasons().clear(); vmModel .getName() .getInvalidityReasons() .add(ConstantsManager.getInstance() .getConstants() .nameMustBeUniqueInvalidReason()); vmModel.getName().setIsValid(false); vmModel.setIsValid(false); stopProgress(target); } else { userPortalListModel.postNameUniqueCheck(userPortalListModel); } } }), name, model.getDataCenterWithClustersList().getSelectedItem().getDataCenter().getId()); } }

Target:
private void onNewTemplate() { UserPortalItemModel selectedItem = (UserPortalItemModel) getSelectedItem(); if (selectedItem == null) { cancel(); return; } UnitVmModel model = (UnitVmModel) getWindow(); if (!model.validate(false)) { model.setIsValid(false); } else if (model.getIsSubTemplate().getEntity()) { postNameUniqueCheck(this); } else { model.startProgress(null); String name = model.getName().getEntity(); AsyncDataProvider.getInstance().isTemplateNameUnique(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { UserPortalListModel userPortalListModel = (UserPortalListModel) target; boolean isNameUnique = (Boolean) returnValue; if (!isNameUnique) { UnitVmModel vmModel = (UnitVmModel) userPortalListModel.getWindow(); vmModel.getName().getInvalidityReasons().clear(); vmModel .getName() .getInvalidityReasons() .add(ConstantsManager.getInstance() .getConstants() .nameMustBeUniqueInvalidReason()); vmModel.getName().setIsValid(false); vmModel.setIsValid(false); stopProgress(target); } else { userPortalListModel.postNameUniqueCheck(userPortalListModel); } } }), name, model.getSelectedDataCenter().getId()); } }
Source:
private void generateFieldHashCode(FieldSpec field) { if (field.type() instanceof FieldType.BoolFieldType) { buffer.printf("hashCode = 31 * hashCode + (%s ? 1231 : 1237);%n", field.camelCaseName()); } else if ((field.type() instanceof FieldType.Int8FieldType) || (field.type() instanceof FieldType.Int16FieldType) || (field.type() instanceof FieldType.Int32FieldType)) { buffer.printf("hashCode = 31 * hashCode + %s;%n", field.camelCaseName()); } else if (field.type() instanceof FieldType.Int64FieldType) { buffer.printf("hashCode = 31 * hashCode + ((int) (%s >> 32) ^ (int) %s);%n", field.camelCaseName(), field.camelCaseName()); } else if (field.type() instanceof FieldType.UUIDFieldType) { buffer.printf("hashCode = 31 * hashCode + (%s == null ? 0 : %s.hashCode());%n", field.camelCaseName(), field.camelCaseName()); } else if (field.type().isString()) { buffer.printf("hashCode = 31 * hashCode + (%s == null ? 0 : %s.hashCode());%n", field.camelCaseName(), field.camelCaseName()); } else if (field.type().isBytes()) { headerGenerator.addImport(MessageGenerator.ARRAYS_CLASS); buffer.printf("hashCode = 31 * hashCode + Arrays.hashCode(%s);%n", field.camelCaseName()); } else if (field.type().isStruct() || field.type().isArray()) { buffer.printf("hashCode = 31 * hashCode + (%s == null ? 0 : %s.hashCode());%n", field.camelCaseName(), field.camelCaseName()); } else { throw new RuntimeException("Unsupported field type " + field.type()); } }

Target:
private void generateFieldHashCode(FieldSpec field) { if (field.type() instanceof FieldType.BoolFieldType) { buffer.printf("hashCode = 31 * hashCode + (%s ? 1231 : 1237);%n", field.camelCaseName()); } else if ((field.type() instanceof FieldType.Int8FieldType) || (field.type() instanceof FieldType.Int16FieldType) || (field.type() instanceof FieldType.Int32FieldType)) { buffer.printf("hashCode = 31 * hashCode + %s;%n", field.camelCaseName()); } else if (field.type() instanceof FieldType.Int64FieldType) { buffer.printf("hashCode = 31 * hashCode + ((int) (%s >> 32) ^ (int) %s);%n", field.camelCaseName(), field.camelCaseName()); } else if (field.type().isBytes()) { headerGenerator.addImport(MessageGenerator.ARRAYS_CLASS); buffer.printf("hashCode = 31 * hashCode + Arrays.hashCode(%s);%n", field.camelCaseName()); } else if (field.type().isStruct() || field.type().isArray() || field.type().isString() || field.type() instanceof FieldType.UUIDFieldType ) { buffer.printf("hashCode = 31 * hashCode + (%s == null ? 0 : %s.hashCode());%n", field.camelCaseName(), field.camelCaseName()); } else { throw new RuntimeException("Unsupported field type " + field.type()); } }
Source:
public void onDestroyView() { if (!subscription.isUnsubscribed()) { subscription.unsubscribe(); } super.onDestroyView(); }

Target:
public void onDestroyView() { forceUnsubscribe(); super.onDestroyView(); }
Source:
private static SummaryReport calculateSummaryResult(long deviceId, Date from, Date to) throws SQLException { boolean ignoreOdometerConfig = Context.getConfig().getBoolean(ReportUtils.IGNORE_ODOMETER); SummaryReport result = new SummaryReport(); Device device = Context.getDeviceManager().getDeviceById(deviceId); result.setDeviceId(deviceId); result.setDeviceName(device.getName()); Collection<Position> positions = Context.getDataManager().getPositions(deviceId, from, to); if (positions != null && !positions.isEmpty()) { Position firstPosition = null; Position previousPosition = null; double speedSum = 0; for (Position position : positions) { if (firstPosition == null) { firstPosition = position; } if (previousPosition != null && position.getAttributes().get(Position.KEY_IGNITION) != null && Boolean.parseBoolean(position.getAttributes().get(Position.KEY_IGNITION).toString()) && previousPosition.getAttributes().get(Position.KEY_IGNITION) != null && Boolean.parseBoolean(previousPosition.getAttributes() .get(Position.KEY_IGNITION).toString())) { result.addEngineHours(position.getFixTime().getTime() - previousPosition.getFixTime().getTime()); } previousPosition = position; speedSum += position.getSpeed(); result.setMaxSpeed(position.getSpeed()); } boolean ignoreOdometer = false; if (device.getAttributes().containsKey(ReportUtils.IGNORE_ODOMETER)) { ignoreOdometer = Boolean.parseBoolean(device.getAttributes() .get(ReportUtils.IGNORE_ODOMETER).toString()); } else { ignoreOdometer = ignoreOdometerConfig; } result.setDistance(ReportUtils.calculateDistance(firstPosition, previousPosition, !ignoreOdometer)); result.setAverageSpeed(speedSum / positions.size()); } return result; }

Target:
private static SummaryReport calculateSummaryResult(long deviceId, Date from, Date to) throws SQLException { SummaryReport result = new SummaryReport(); result.setDeviceId(deviceId); result.setDeviceName(Context.getIdentityManager().getDeviceById(deviceId).getName()); Collection<Position> positions = Context.getDataManager().getPositions(deviceId, from, to); if (positions != null && !positions.isEmpty()) { Position firstPosition = null; Position previousPosition = null; double speedSum = 0; for (Position position : positions) { if (firstPosition == null) { firstPosition = position; } if (previousPosition != null && position.getAttributes().get(Position.KEY_IGNITION) != null && Boolean.parseBoolean(position.getAttributes().get(Position.KEY_IGNITION).toString()) && previousPosition.getAttributes().get(Position.KEY_IGNITION) != null && Boolean.parseBoolean(previousPosition.getAttributes() .get(Position.KEY_IGNITION).toString())) { result.addEngineHours(position.getFixTime().getTime() - previousPosition.getFixTime().getTime()); } previousPosition = position; speedSum += position.getSpeed(); result.setMaxSpeed(position.getSpeed()); } boolean ignoreOdometer = Context.getDeviceManager() .lookupConfigBoolean(deviceId, "report.ignoreOdometer", false); result.setDistance(ReportUtils.calculateDistance(firstPosition, previousPosition, !ignoreOdometer)); result.setAverageSpeed(speedSum / positions.size()); } return result; }
Source:
@Test void testSimplifyInValues() { RexNode a = vIntNotNull(1); RexNode literal1 = literal(1); RexNode literal2 = literal(2); RexNode literal3 = literal(3); RexNode literal4 = literal(4); RexNode literal5 = literal(5); RexNode literal6 = literal(6); RexNode expr = in(a, literal1, literal2, literal3, literal4, literal5); RexNode expected = and(ge(a, literal1), le(a, literal5)); RexNode simplifiedExpr = simplify.simplifyUnknownAs(expr, RexUnknownAs.UNKNOWN); assertThat(simplifiedExpr, is(expected)); expr = in(a, literal2, literal3, literal5, literal4, literal1); simplifiedExpr = simplify.simplifyUnknownAs(expr, RexUnknownAs.UNKNOWN); assertThat(simplifiedExpr, is(expected)); expr = in(a, literal1, literal2, literal4, literal5); expected = or(eq(a, literal1), eq(a, literal2), eq(a, literal4), eq(a, literal5)); simplifiedExpr = simplify.simplifyUnknownAs(expr, RexUnknownAs.UNKNOWN); assertThat(simplifiedExpr, is(expected)); expr = in(a, literal1, literal2, literal4, literal5, literal6); expected = or(and(ge(a, literal1), le(a, literal2)), and(ge(a, literal4), le(a, literal6))); simplifiedExpr = simplify.simplifyUnknownAs(expr, RexUnknownAs.UNKNOWN); assertThat(simplifiedExpr, is(expected)); RexNode b = vDecimalNotNull(1); expr = in(b, literal1, literal2, literal3, literal4, literal5); expected = or( eq(b, literal1), eq(b, literal2), eq(b, literal3), eq(b, literal4), eq(b, literal5)); simplifiedExpr = simplify.simplifyUnknownAs(expr, RexUnknownAs.UNKNOWN); assertThat(simplifiedExpr, is(expected)); }

Target:
@Test void testSimplifyInValues() { RexNode a = vIntNotNull(1); RexNode n1 = literal(1); RexNode n2 = literal(2); RexNode n3 = literal(3); RexNode n4 = literal(4); RexNode n5 = literal(5); RexNode n6 = literal(6); checkSimplify(in(a, n1, n2, n3, n4, n5), "AND(>=(?0.notNullInt1, 1), <=(?0.notNullInt1, 5))"); checkSimplify(in(a, n2, n3, n5, n4, n1), "AND(>=(?0.notNullInt1, 1), <=(?0.notNullInt1, 5))"); checkSimplify(in(a, n1, n2, n4, n5), "OR(=(?0.notNullInt1, 1), =(?0.notNullInt1, 2), " + "=(?0.notNullInt1, 4), =(?0.notNullInt1, 5))"); checkSimplify(in(a, n1, n2, n4, n5, n6), "OR(AND(>=(?0.notNullInt1, 1), <=(?0.notNullInt1, 2)), " + "AND(>=(?0.notNullInt1, 4), <=(?0.notNullInt1, 6)))"); RexNode b = vDecimalNotNull(1); checkSimplify(in(b, n1, n2, n3, n4, n5), "OR(=(?0.notNullDecimal1, 1), =(?0.notNullDecimal1, 2), " + "=(?0.notNullDecimal1, 3), =(?0.notNullDecimal1, 4), =(?0.notNullDecimal1, 5))"); }
Source:
public static boolean isConnectedInside(Port port) { UMLRTPort rt = (port == null) ? null : UMLRTPort.getInstance(port); return (rt != null) && rt.isConnectedInside(); }

Target:
public static boolean isConnectedInside(Port port) { UMLRTPort rt = UMLRTPort.getInstance(port); return (rt != null) && rt.isConnectedInside(); }
Source:
private void compareListOfBlobContent(String blobId, Map<ReplicaId, ServerResponse> replicaIdBlobContentMap) { Iterator<ReplicaId> replicaIdIterator = replicaIdBlobContentMap.keySet().iterator(); ReplicaId replicaId1 = replicaIdIterator.next(); ServerResponse replica1ServerResponse = replicaIdBlobContentMap.get(replicaId1); while (replicaIdIterator.hasNext()) { ReplicaId replicaId2 = replicaIdIterator.next(); ServerResponse replica2ServerResponse = replicaIdBlobContentMap.get(replicaId2); if (!replica1ServerResponse.equals(replica2ServerResponse)) { logger.error( "ServerResponse mismatch for " + blobId + " from " + replicaId1 + " and " + replicaId2 + " mismatch" + ". " + replicaId1 + " Content " + replica1ServerResponse + ", " + replicaId2 + " Content " + replica2ServerResponse); } } }

Target:
private void compareListOfBlobContent(String blobId, Map<ReplicaId, ServerResponse> replicaIdBlobContentMap) { Iterator<ReplicaId> replicaIdIterator = replicaIdBlobContentMap.keySet().iterator(); ReplicaId replicaId1 = replicaIdIterator.next(); ServerResponse replica1ServerResponse = replicaIdBlobContentMap.get(replicaId1); while (replicaIdIterator.hasNext()) { ReplicaId replicaId2 = replicaIdIterator.next(); ServerResponse replica2ServerResponse = replicaIdBlobContentMap.get(replicaId2); if (!replica1ServerResponse.equals(replica2ServerResponse)) { logger.error("ServerResponse mismatch for from and {}. Response from : {}, Response from : {}", blobId, replicaId1, replicaId2, replicaId1, replica1ServerResponse, replicaId2, replica2ServerResponse); } } }
Source:
public Map<String, List<String>> getInfrasToPoliciesMapping(@HeaderParam("sessionid") String sessionId) throws NotConnectedException { ResourceManager rm = checkAccess(sessionId); Map<String, List<String>> result = rm.getInfrasToPoliciesMapping(); Collection<PluginDescriptor> supportedInfrastructures = rm.getSupportedNodeSourceInfrastructures(); Collection<PluginDescriptor> supportedPolicies = rm.getSupportedNodeSourcePolicies(); Iterator<Map.Entry<String, List<String>>> iterator = result.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, List<String>> entry = iterator.next(); boolean found = false; for (PluginDescriptor supportedInfrastructure : supportedInfrastructures) { if (supportedInfrastructure.getPluginName().equals(entry.getKey())) { found = true; break; } } if (!found) { iterator.remove(); } } return result.entrySet().stream().map(entry -> { List<String> policies = entry.getValue().stream().filter(policy -> { for (PluginDescriptor supportedPolicy : supportedPolicies) { if (supportedPolicy.getPluginName().equals(policy)) { return true; } } return false; }).collect(Collectors.toList()); ; return new AbstractMap.SimpleEntry<>(entry.getKey(), policies); }).collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); }

Target:
public Map<String, List<String>> getInfrasToPoliciesMapping(@HeaderParam("sessionid") String sessionId) throws NotConnectedException { ResourceManager rm = checkAccess(sessionId); Collection<PluginDescriptor> supportedInfrastructures = rm.getSupportedNodeSourceInfrastructures(); Collection<PluginDescriptor> supportedPolicies = rm.getSupportedNodeSourcePolicies(); Map<String, List<String>> result = rm.getInfrasToPoliciesMapping().entrySet().stream().filter(entry -> { for (PluginDescriptor supportedInfrastructure : supportedInfrastructures) { if (supportedInfrastructure.getPluginName().equals(entry.getKey())) { return true; } } return false; }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return result.entrySet().stream().map(entry -> { List<String> policies = entry.getValue() .stream() .filter(policy -> containsPlugin(policy, supportedPolicies)) .collect(Collectors.toList()); return new AbstractMap.SimpleEntry<>(entry.getKey(), policies); }).collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); }