auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
String getPathsForProfile(Model model, String profileIdentifier, @RequestParam(value = "typeFilter[]", required = false) String[] typeFilter, @RequestParam(value = "clientUUID", defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception { int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier); List<EndpointOverride> paths = PathOverrideService.getInstance().getPaths(profileId, clientUUID, typeFilter); logger.info("BEFORE JQGRID"); HashMap<String, Object> jqReturn = Utils.getJQGridJSON(paths, "paths"); ObjectMapper objectMapper = new ObjectMapper(); logger.info("BEFORE WRITER"); objectMapper.addMixInAnnotations(Object.class, ViewFilters.GetPathFilter.class); String[] ignorableFieldNames = { "possibleEndpoints", "enabledEndpoints" }; FilterProvider filters = new SimpleFilterProvider().addFilter("Filter properties from the PathController GET", SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames)); ObjectWriter writer = objectMapper.writer(filters); return writer.writeValueAsString(jqReturn); }

Target:
String getPathsForProfile(Model model, String profileIdentifier, @RequestParam(value = "typeFilter[]", required = false) String[] typeFilter, @RequestParam(value = "clientUUID", defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception { int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier); List<EndpointOverride> paths = PathOverrideService.getInstance().getPaths(profileId, clientUUID, typeFilter); HashMap<String, Object> jqReturn = Utils.getJQGridJSON(paths, "paths"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.addMixInAnnotations(Object.class, ViewFilters.GetPathFilter.class); String[] ignorableFieldNames = { "possibleEndpoints", "enabledEndpoints" }; FilterProvider filters = new SimpleFilterProvider().addFilter("Filter properties from the PathController GET", SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames)); ObjectWriter writer = objectMapper.writer(filters); return writer.writeValueAsString(jqReturn); }
Source:
public String[] getItemStrings(ITmfEvent event) { if (event instanceof TextTraceEvent) { List<TextTraceEventContent> fields = ((TextTraceEvent) event).getContent().getFields(); String[] strings = new String[fields.size()]; for (int i = 0; i < strings.length; i++) { strings[i] = fields.get(i).getValue().toString(); } return strings; } return EMPTY_STRING_ARRAY; }

Target:
public String[] getItemStrings(ITmfEvent event) { if (event instanceof TextTraceEvent) { List<TextTraceEventContent> fields = ((TextTraceEvent) event).getContent().getFields(); String[] strings = new String[fields.size()]; for (int i = 0; i < strings.length; i++) { Object value = fields.get(i).getValue(); strings[i] = (value == null ? EMPTY_STRING : value.toString()); } return strings; } return EMPTY_STRING_ARRAY; }
Source:
public DailyJobMoon(String thingUID, AstroThingHandler handler) { checkNotNull(thingUID, "Thing UID cannot be null"); checkNotNull(handler, "AstroThingHandler instance cannot be null"); this.thingUID = thingUID; this.handler = handler; }

Target:
public DailyJobMoon(String thingUID, AstroThingHandler handler) { checkArgument(thingUID != null, "Thing UID cannot be null"); checkArgument(handler != null, "AstroThingHandler instance cannot be null"); this.thingUID = thingUID; this.handler = handler; }
Source:
public FileInStream openFile(AlluxioURI path, OpenFilePOptions options) throws IOException, AlluxioException { try { return new LocalCacheFileInStream(path, options, mDelegatedFileSystem, mFsContext.getCacheManager()); } catch (IOException e) { SAMPLING_LOGGER.warn("Failed to create LocalCacheFileInStream {}", e.getMessage()); return mDelegatedFileSystem.openFile(path, options); } }

Target:
public FileInStream openFile(AlluxioURI path, OpenFilePOptions options) throws IOException, AlluxioException { if (sCacheManager == null || !sCacheManager.isPresent()) { return mDelegatedFileSystem.openFile(path, options); } return new LocalCacheFileInStream(path, options, mDelegatedFileSystem, sCacheManager.get()); }
Source:
void addTriggers(Map<String, Object> newTriggers) { triggerController.addTriggers(newTriggers); checkTriggerChanges(newTriggers); evaluateInAppMessages(); }

Target:
void addTriggers(Map<String, Object> newTriggers) { triggerController.addTriggers(newTriggers); makeRedisplayMessagesAvailableWithTriggers(newTriggers.keySet()); evaluateInAppMessages(); }
Source:
Text(TextFormat format, ImmutableList<Text> children, @Nullable ClickAction<?> clickAction, @Nullable HoverAction<?> hoverAction, @Nullable ShiftClickAction<?> shiftClickAction) { this.format = checkNotNull(format, "format"); this.children = checkNotNull(children, "children"); this.clickAction = Optional.<ClickAction<?>>ofNullable(clickAction); this.hoverAction = Optional.<HoverAction<?>>ofNullable(hoverAction); this.shiftClickAction = Optional.<ShiftClickAction<?>>ofNullable(shiftClickAction); this.childrenIterable = () -> this.children.isEmpty() ? Iterators.singletonIterator(this) : new TextIterator(this); }

Target:
Text(TextFormat format, ImmutableList<Text> children, @Nullable ClickAction<?> clickAction, @Nullable HoverAction<?> hoverAction, @Nullable ShiftClickAction<?> shiftClickAction) { this.format = checkNotNull(format, "format"); this.children = checkNotNull(children, "children"); this.clickAction = Optional.ofNullable(clickAction); this.hoverAction = Optional.ofNullable(hoverAction); this.shiftClickAction = Optional.ofNullable(shiftClickAction); this.childrenIterable = () -> new TextIterator(this); }
Source:
String findRoleForPorts(Offer offer) { String role = null; for (Resource resource : offer.getResourcesList()) { if (resource.getName().equals(PORT_RESOURCE_NAME)) { role = resource.getRole(); } } return role; }

Target:
String findRoleForPorts(Offer offer) { String role = MESOS_DEFAULT_ROLE; for (Resource resource : offer.getResourcesList()) { if (resource.getName().equals(PORT_RESOURCE_NAME)) { role = resource.getRole(); } } return role; }
Source:
private RenderedImage getImageFromParentCoverage(GridCoverage2D parentCoverage) { if (parentCoverage == null) { return null; } RenderedImage ri = parentCoverage.getRenderedImage(); if (ri != null) { PlanarImage pi = PlanarImage.wrapRenderedImage(ri); pi.setProperty("ParentCoverage", parentCoverage); ri = pi; } return ri; }

Target:
private RenderedImage getImageFromParentCoverage(GridCoverage2D parentCoverage) { if (parentCoverage == null) { return null; } RenderedImage ri = parentCoverage.getRenderedImage(); if (ri != null) { PlanarImage pi = PlanarImage.wrapRenderedImage(ri); pi.setProperty(PARENT_COVERAGE_PROPERTY, parentCoverage); ri = pi; } return ri; }
Source:
public void adReceived(final AppLovinAd ad) { log( DEBUG, "Rewarded video did load ad: " + ad.getAdIdNumber() ); MoPubRewardedVideoManager.onRewardedVideoLoadSuccess( this.getClass(), "" ); }

Target:
public void adReceived(final AppLovinAd ad) { log( DEBUG, "Rewarded video did load ad: " + ad.getAdIdNumber() ); MoPubRewardedVideoManager.onRewardedVideoLoadSuccess( this.getClass(), getAdNetworkId() ); }
Source:
public String getProblemsStr() { String problemsStr = ""; int i = 1; for( RegisteredProject.Problem prb : problems ) { problemsStr += "["+i+"] : " + prb.message + "\n"; i++; } return problemsStr; }

Target:
public String getProblemsStr() { StringBuilder builder = new StringBuilder(); int i = 0; for( RegisteredProject.Problem prb : problems ) { builder.append("[").append(i++).append("] : ").append(prb.message).append("\n"); } return builder.toString(); }
Source:
protected boolean canDoAction() { VdsValidator vdsValidator = new VdsValidator(getVds()); return validate(vdsValidator.exists()) && validate(vdsValidator.isUp()) && validate(vdsValidator.validateMinimumVersionSupport(Version.v3_3)); }

Target:
protected boolean canDoAction() { VdsValidator vdsValidator = new VdsValidator(getVds()); return validate(vdsValidator.exists()) && validate(vdsValidator.isUp()) && validate(validateMinimumVersionSupport()); }
Source:
private static void setStatics(Context inContext) { currentContext = inContext; packageName = currentContext.getPackageName(); contextResources = currentContext.getResources(); PackageManager packageManager = currentContext.getPackageManager(); Intent intent = new Intent(currentContext, NotificationOpenedReceiver.class); intent.setPackage(currentContext.getPackageName()); if (packageManager.queryBroadcastReceivers(intent, 0).size() > 0) notificationCloseClass = NotificationOpenedReceiver.class; OneSignal.onesignalLog(OneSignal.LOG_LEVEL.DEBUG, "GenerateNotification notificationCloseClass: " + notificationCloseClass); }

Target:
private static void setStatics(Context inContext) { currentContext = inContext; packageName = currentContext.getPackageName(); contextResources = currentContext.getResources(); }
Source:
@Subscribe public void on(@NonNull PageDownloadEvent event) { int pagePosition = getPagePositionInList(event.getPage()) + 1; if (pagePosition != 0) { ((PageItemView) (recyclerView.findViewHolderForAdapterPosition(pagePosition).itemView)).makeProgress(event.getProgress()); } }

Target:
public void on(@NonNull PageDownloadEvent event) { int pagePosition = getPagePositionInList(event.getPage()); if (pagePosition != -1) { displayedPages.get(pagePosition).downloadProgress(event.getPage().downloadProgress()); adapter.notifyDataSetChanged(); } }
Source:
public static RoboAttributeSet create(Context context, Attribute... attrs) { List<Attribute> attributesList = Lists.newArrayList(attrs); return new RoboAttributeSet(attributesList, shadowOf(context.getAssets()).getResourceLoader()); }

Target:
public static AttributeSet create(Context context, Attribute... attrs) { List<Attribute> attributesList = Lists.newArrayList(attrs); return create(context, attributesList); }
Source:
public ExecutorException(Exception e) { super("Continuation failed to executed due to exception raised in the Executor", e); }

Target:
public ExecutorException(Exception e) { super("An exception was thrown by a Executor", e); }
Source:
public OutputStream getOutputStream(boolean overwrite, boolean lock) throws IOException { final FileOutputStream fileOutputStream; try { if (!isExists()) { fileOutputStream = new FileOutputStream(getLocalFile()); } else { if (overwrite) { fileOutputStream = new FileOutputStream(getLocalFile()); } else { fileOutputStream = new FileOutputStream(getLocalFile(), true); } } if (lock) { final FileLock fileLock; try { fileLock = fileOutputStream.getChannel().lock(); } catch (IOException ex) { fileOutputStream.close(); throw ex; } catch (Exception ex) { fileOutputStream.close(); throw new IOException(ex); } if (fileLock == null) { fileOutputStream.close(); throw new OverlappingFileLockException(); } return new OutputStream() { @Override public void write(int b) throws IOException { fileOutputStream.write(b); } @Override public void close() throws IOException { fileLock.release(); fileOutputStream.close(); } @Override public void flush() throws IOException { fileOutputStream.flush(); } @Override public void write(byte[] b) throws IOException { fileOutputStream.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { fileOutputStream.write(b, off, len); } }; } return fileOutputStream; } catch (FileNotFoundException ex) { throw ex; } }

Target:
public OutputStream getOutputStream(boolean overwrite, boolean lock) throws IOException { final OutputStream fileOutputStream; final File outstreamFile; if (lock) { boolean newLock = !isHeldByCurrentThread(); if (!tryLock()) { throw new IOException("Could not attain lock!"); } outstreamFile = getLockFile(); if (newLock) { fileOutputStream = new GitLockOutputStream(getLocalFile(), outstreamFile, overwrite) { @Override public void close() throws IOException { super.close(); unlock(); } }; } else { fileOutputStream = new GitLockOutputStream(getLocalFile(), outstreamFile, overwrite); } } else { outstreamFile = getLocalFile(); if (!isExists()) { fileOutputStream = new FileOutputStream(outstreamFile); } else { if (overwrite) { fileOutputStream = new FileOutputStream(outstreamFile); } else { fileOutputStream = new FileOutputStream(outstreamFile, true); } } } return fileOutputStream; }
Source:
public abstract InputChannel toInputChannel() throws IOException; protected void readRecoveredState(ChannelStateReader reader) throws IOException, InterruptedException { ReadResult result = ReadResult.HAS_MORE_DATA; while (result == ReadResult.HAS_MORE_DATA) { Buffer buffer = bufferManager.requestBufferBlocking(); result = internalReaderRecoveredState(reader, buffer); } bufferManager.releaseFloatingBuffers(); }

Target:
public abstract InputChannel toInputChannel() throws IOException; CompletableFuture<?> getStateConsumedFuture() { return stateConsumedFuture; }
Source:
public AttachSessionResponse(DataInputStream inNet) throws IOException { byte[] data = new byte[size()]; inNet.readFully(data, 0, size()); ByteBuffer bb = ByteBuffer.wrap(data); bb.order(ByteOrder.BIG_ENDIAN); fStatus = AttachReturnCode.values()[bb.getInt() - 1]; fStreamsCount = bb.getInt(); ArrayList<StreamResponse> sl = new ArrayList<>(); for (int i = 0; i < getNbStreams(); i++) { sl.add(new StreamResponse(inNet)); } fStreamList = ImmutableList.copyOf(sl); }

Target:
public AttachSessionResponse(DataInputStream inNet) throws IOException { byte[] data = new byte[size()]; inNet.readFully(data, 0, size()); ByteBuffer bb = ByteBuffer.wrap(data); bb.order(ByteOrder.BIG_ENDIAN); fStatus = AttachReturnCode.values()[bb.getInt() - 1]; fStreamsCount = bb.getInt(); Builder<StreamResponse> streamResponses = ImmutableList.builder(); for (int i = 0; i < getNbStreams(); i++) { streamResponses.add(new StreamResponse(inNet)); } fStreamList = streamResponses.build(); }
Source:
private Handler getHandler() { if (mHandler == null) { mHandler = new Handler(mContext.getMainLooper()); } return mHandler; }

Target:
private synchronized Handler getHandler() { if (mHandler == null) { mHandler = new Handler(mContext.getMainLooper()); } return mHandler; }
Source:
public void handleCreated(Event event) { Compliance compliance; ComplianceStatus status; Consumer consumer; Owner owner; ConsumerState cstate; String uuid; String ownerKey; Date eventDate; try { compliance = mapper.readValue(event.getNewEntity(), Compliance.class); consumer = compliance.getConsumer(); if (consumer == null) { throw new RuntimeException( "Unable to read consumer information from compliance status event." ); } status = compliance.getStatus(); if (status == null) { throw new RuntimeException( "Unable to read compliance status from compliance status event." ); } owner = consumer.getOwner(); if (owner == null) { throw new RuntimeException( "Unable to read owner information from compliance status event." ); } uuid = consumer.getUuid(); eventDate = status.getDate(); cstate = this.consumerStateCurator.findByUuid(uuid); if (cstate == null) { ownerKey = owner.getKey(); cstate = this.consumerStateCurator.create(new ConsumerState(uuid, ownerKey, eventDate)); } consumer.setConsumerState(cstate); compliance.setDate(eventDate); } catch (IOException e) { throw new RuntimeException("Could not deserialize compliance snapshot data.", e); } complianceCurator.create(compliance); }

Target:
public void handleCreated(Event event) { Compliance compliance; ComplianceStatus status; Consumer consumer; Owner owner; ConsumerState cstate; String uuid; String ownerKey; Date eventDate; try { compliance = mapper.readValue(event.getNewEntity(), Compliance.class); } catch (IOException e) { throw new RuntimeException("Could not deserialize compliance snapshot data.", e); } consumer = compliance.getConsumer(); if (consumer == null) { throw new RuntimeException( "Unable to read consumer information from compliance status event." ); } status = compliance.getStatus(); if (status == null) { throw new RuntimeException( "Unable to read compliance status from compliance status event." ); } owner = consumer.getOwner(); if (owner == null) { throw new RuntimeException( "Unable to read owner information from compliance status event." ); } uuid = consumer.getUuid(); eventDate = status.getDate(); cstate = this.consumerStateCurator.findByUuid(uuid); if (cstate == null) { ownerKey = owner.getKey(); cstate = this.consumerStateCurator.create(new ConsumerState(uuid, ownerKey, eventDate)); } consumer.setConsumerState(cstate); compliance.setDate(eventDate); complianceCurator.create(compliance); }
Source:
public synchronized void deleteAll(List<K> keys) { cache.invalidateAll(); }

Target:
public void deleteAll(List<K> keys) { keys.forEach(k -> delete(k)); }
Source:
public static void getNextPageGroupCategoriesInCourse(String nextURL, CanvasCallback<GroupCategory[]> callback) { if (APIHelpers.paramIsNull(callback, nextURL)) { return; } callback.setIsNextPage(true); buildInterface(callback).getNextPageGroupCategories(nextURL, callback); }

Target:
public static void getNextPageGroupCategoriesInCourse(String nextURL, CanvasCallback<GroupCategory[]> callback) { if (APIHelpers.paramIsNull(callback, nextURL)) return; callback.setIsNextPage(true); buildInterface(callback).getNextPageGroupCategories(nextURL, callback); }
Source:
protected void executeCommand() { storage_pool_iso_map domainPoolMap = TransactionSupport.executeInNewTransaction( new TransactionMethod<storage_pool_iso_map>() { @Override public storage_pool_iso_map runInTransaction() { storage_pool_iso_map domainPoolMap = new storage_pool_iso_map(getRecoveryStoragePoolParametersData() .getNewMasterDomainId(), getRecoveryStoragePoolParametersData().getStoragePoolId(), StorageDomainStatus.Active); DbFacade.getInstance().getStoragePoolIsoMapDao().save(domainPoolMap); return domainPoolMap; } }); getStoragePool().setstatus(StoragePoolStatus.Problematic); try { if (StorageHelperDirector.getInstance().getItem(getStorageDomain().getstorage_type()) .ConnectStorageToDomainByVdsId(getNewMaster(false), getVds().getId())) { super.executeCommand(); } else { getReturnValue().setFault(new VdcFault(new VdcBLLException(VdcBllErrors.StorageServerConnectionError, "Failed to connect storage"), VdcBllErrors.StorageServerConnectionError)); } } finally { if (!reconstructOpsSucceeded) { DbFacade.getInstance().getStoragePoolIsoMapDao().remove(new StoragePoolIsoMapId(getRecoveryStoragePoolParametersData() .getNewMasterDomainId(), getRecoveryStoragePoolParametersData().getStoragePoolId())); } } }

Target:
protected void executeCommand() { storage_pool_iso_map domainPoolMap = TransactionSupport.executeInNewTransaction( new TransactionMethod<storage_pool_iso_map>() { @Override public storage_pool_iso_map runInTransaction() { storage_pool_iso_map domainPoolMap = new storage_pool_iso_map(getRecoveryStoragePoolParametersData() .getNewMasterDomainId(), getRecoveryStoragePoolParametersData().getStoragePoolId(), StorageDomainStatus.Active); DbFacade.getInstance().getStoragePoolIsoMapDao().save(domainPoolMap); return domainPoolMap; } }); getStoragePool().setstatus(StoragePoolStatus.Problematic); try { if (StorageHelperDirector.getInstance().getItem(getStorageDomain().getstorage_type()) .ConnectStorageToDomainByVdsId(getNewMaster(false), getVds().getId())) { super.executeCommand(); } else { getReturnValue().setFault(new VdcFault(new VdcBLLException(VdcBllErrors.StorageServerConnectionError, "Failed to connect storage"), VdcBllErrors.StorageServerConnectionError)); } } finally { if (!reconstructOpSucceeded) { getStoragePoolIsoMapDAO().remove(new StoragePoolIsoMapId(getRecoveryStoragePoolParametersData() .getNewMasterDomainId(), getRecoveryStoragePoolParametersData().getStoragePoolId())); } } }
Source:
private Map<Guid, DiskImage> getSnapshotIdToDiskImage(List<DiskImage> diskImages) { Map<Guid, DiskImage> snapshotIdToDiskImageMap = new HashMap<>(); for (DiskImage disk : diskImages) { snapshotIdToDiskImageMap.put(disk.getImage().getSnapshotId(), disk); } return snapshotIdToDiskImageMap; }

Target:
private Map<Guid, DiskImage> getSnapshotIdToDiskImage(List<DiskImage> diskImages) { Map<Guid, DiskImage> snapshotIdToDiskImageMap; snapshotIdToDiskImageMap = diskImages.stream() .collect(Collectors.toMap(disk -> disk.getImage().getSnapshotId(), Function.identity())); return snapshotIdToDiskImageMap; }
Source:
public Actor() { users = new HashSet<String>(); groups = new HashSet<String>(); roles = new HashSet<String>(); memberships = new HashSet<BEntry<String, String>>(); }

Target:
public Actor() { memberships = new HashSet<>(); }
Source:
private void updateOptionsNonLocalFS() { if (clusters == null || allStorageDomains == null || attachedStorageDomains == null || isoStorageDomains == null || allHosts == null) { return; } updateAddClusterAvailability(); Set<Guid> clusterIds = clusters.stream().map(Cluster::getId).collect(Collectors.toSet()); List<VDS> hosts = allHosts.stream().filter(h -> clusterIds.contains(h.getClusterId())).collect(Collectors.toList()); List<VDS> availableHosts = allHosts.stream() .filter(v -> v.getStatus() == VDSStatus.Maintenance || v.getStatus() == VDSStatus.PendingApproval) .filter(v -> doesHostSupportAnyCluster(clusters, v)) .collect(Collectors.toList()); List<VDS> upHosts = allHosts.stream() .filter(v -> v.getStatus() == VDSStatus.Up) .filter(h -> clusterIds.contains(h.getClusterId())) .collect(Collectors.toList()); updateAddAndSelectHostAvailability(hosts, availableHosts); List<StorageDomain> unattachedStorages = getUnattachedStorages(); List<StorageDomain> attachedDataStorages = new ArrayList<>(); List<StorageDomain> attachedIsoStorages = new ArrayList<>(); for (StorageDomain sd : attachedStorageDomains) { if (sd.getStorageDomainType().isDataDomain()) { attachedDataStorages.add(sd); } else if (sd.getStorageDomainType() == StorageDomainType.ISO) { attachedIsoStorages.add(sd); } } updateAddAndAttachDataDomainAvailability(upHosts, unattachedStorages, attachedDataStorages); updateAddAndAttachIsoDomainAvailability(upHosts, attachedDataStorages, attachedIsoStorages); stopProgress(); }

Target:
private void updateOptionsNonLocalFS() { if (clusters == null || allStorageDomains == null || attachedStorageDomains == null || isoStorageDomains == null || allHosts == null) { return; } updateAddClusterAvailability(); Set<Guid> clusterIds = clusters.stream().map(Cluster::getId).collect(Collectors.toSet()); List<VDS> hosts = allHosts.stream().filter(h -> clusterIds.contains(h.getClusterId())).collect(Collectors.toList()); List<VDS> upHosts = hosts.stream().filter(v -> v.getStatus() == VDSStatus.Up).collect(Collectors.toList()); List<VDS> availableHosts = allHosts.stream() .filter(v -> v.getStatus() == VDSStatus.Maintenance || v.getStatus() == VDSStatus.PendingApproval) .filter(v -> doesHostSupportAnyCluster(clusters, v)) .collect(Collectors.toList()); updateAddAndSelectHostAvailability(hosts, availableHosts); List<StorageDomain> unattachedStorages = getUnattachedStorages(); List<StorageDomain> attachedDataStorages = new ArrayList<>(); List<StorageDomain> attachedIsoStorages = new ArrayList<>(); for (StorageDomain sd : attachedStorageDomains) { if (sd.getStorageDomainType().isDataDomain()) { attachedDataStorages.add(sd); } else if (sd.getStorageDomainType() == StorageDomainType.ISO) { attachedIsoStorages.add(sd); } } updateAddAndAttachDataDomainAvailability(upHosts, unattachedStorages, attachedDataStorages); updateAddAndAttachIsoDomainAvailability(upHosts, attachedDataStorages, attachedIsoStorages); stopProgress(); }
Source:
private void getColsForSelectTree(final CubeQueryContext cubeql) throws SemanticException { int exprInd = 1; for (int i = 0; i < cubeql.getSelectAST().getChildCount(); i++) { ASTNode selectExpr = (ASTNode)cubeql.getSelectAST().getChild(i); Set<String> cols = new HashSet<String>(); addColumnsForSelectExpr(cubeql, selectExpr, cubeql.getSelectAST(), cols); ASTNode alias = HQLParser.findNodeByPath(selectExpr, Identifier); String selectAlias; String selectFinalAlias = null; if (alias != null) { cubeql.addExprToAlias(selectExpr, alias); if (HQLParser.hasSpaces(alias.getText())) { selectFinalAlias = alias.getText(); selectAlias = "expr" + exprInd; } else { selectAlias = alias.getText().trim(); } } else if (cols.size() == 1) { selectAlias = cols.iterator().next().toLowerCase(); } else { selectAlias = "expr" + exprInd; } exprInd++; cubeql.addSelectAlias(selectAlias, selectFinalAlias); } }

Target:
private void getColsForSelectTree(final CubeQueryContext cubeql) throws SemanticException { int exprInd = 1; for (int i = 0; i < cubeql.getSelectAST().getChildCount(); i++) { ASTNode selectExpr = (ASTNode)cubeql.getSelectAST().getChild(i); Set<String> cols = new HashSet<String>(); addColumnsForSelectExpr(cubeql, selectExpr, cubeql.getSelectAST(), cols); ASTNode alias = HQLParser.findNodeByPath(selectExpr, Identifier); String selectAlias; String selectFinalAlias = null; if (alias != null) { cubeql.addExprToAlias(selectExpr, alias); if (HQLParser.hasSpaces(alias.getText())) { selectFinalAlias = alias.getText(); selectAlias = SELECT_ALIAS_PREFIX + exprInd; } else { selectAlias = alias.getText().trim(); } } else if (cols.size() == 1) { selectAlias = cols.iterator().next().toLowerCase(); } else { selectAlias = SELECT_ALIAS_PREFIX + exprInd; } exprInd++; cubeql.addSelectAlias(selectAlias, selectFinalAlias); } }
Source:
public static void main(String[] args) throws Exception { final String clientId = "user"; final String clientSecret = "password"; final String idpEndpoint = "http://idp-host:idp-port/auth/realms/master/protocol/openid-connect/token"; final String stsEndpoint = "http://sts-host:sts-port/sts"; final String idpClientId = "minio-client-id"; final CredentialsProvider credentialsProvider = new ClientGrantsCredentialsProvider( stsEndpoint, () -> getTokenAndExpiry(clientId, clientSecret, idpClientId, idpEndpoint)); final MinioClient minioClient = MinioClient.builder() .endpoint("http://minio-host:minio-port") .credentialsProvider(credentialsProvider) .build(); final List<Bucket> buckets = minioClient.listBuckets(); for (Bucket bucket : buckets) { System.out.print(bucket.name() + " created at "); System.out.println(bucket.creationDate()); } }

Target:
public static void main(String[] args) throws Exception { final String clientId = "user"; final String clientSecret = "password"; final String idpEndpoint = "http://idp-host:idp-port/auth/realms/master/protocol/openid-connect/token"; final String stsEndpoint = "http://sts-host:sts-port/"; final String idpClientId = "minio-client-id"; final Provider credentialsProvider = new ClientGrantsProvider( stsEndpoint, () -> getTokenAndExpiry(clientId, clientSecret, idpClientId, idpEndpoint)); final MinioClient minioClient = MinioClient.builder() .endpoint("http://minio-host:minio-port") .credentialsProvider(credentialsProvider) .build(); final List<Bucket> buckets = minioClient.listBuckets(); for (Bucket bucket : buckets) { System.out.print(bucket.name() + " created at "); System.out.println(bucket.creationDate()); } }
Source:
public InputStream getInputStream(SevenZArchiveEntry entry) throws IOException { int entryIndex = -1; for(int i = 0; i < this.archive.files.length;i++) { if(entry == this.archive.files[i]) { entryIndex = i; } } if(entryIndex < 0) { throw new IllegalArgumentException("Can not find " + entry.getName() + " in " + this.fileName); } if(entry.getSize() == 0) { return new ByteArrayInputStream(new byte[0]); } final int folderIndex = archive.streamMap.fileFolderIndex[entryIndex]; final Folder folder = archive.folders[folderIndex]; final int firstPackStreamIndex = archive.streamMap.folderFirstPackStreamIndex[folderIndex]; final long folderOffset = SIGNATURE_HEADER_SIZE + archive.packPos + archive.streamMap.packStreamOffsets[firstPackStreamIndex]; InputStream folderInputStream = buildDecoderStack(folder, folderOffset, firstPackStreamIndex, entry); final int firstFileInFolderIndex = archive.streamMap.folderFirstFileIndex[folderIndex]; if(firstFileInFolderIndex < entryIndex) { long skipSize = 0; for(int i = firstFileInFolderIndex; i < entryIndex;i++) { skipSize += archive.files[i].getSize(); } InputStream inputStreamToSkip = new BoundedInputStream(folderInputStream, skipSize); IOUtils.skip(inputStreamToSkip, Long.MAX_VALUE); } return new BoundedInputStream(folderInputStream, entry.getSize()); }

Target:
public InputStream getInputStream(SevenZArchiveEntry entry) throws IOException { int entryIndex = -1; for(int i = 0; i < this.archive.files.length;i++) { if(entry == this.archive.files[i]) { entryIndex = i; } } if(entryIndex < 0) { throw new IllegalArgumentException("Can not find " + entry.getName() + " in " + this.fileName); } buildDecodingStream(entryIndex); currentEntryIndex = entryIndex; currentFolderIndex = archive.streamMap.fileFolderIndex[entryIndex]; return getCurrentStream(); }
Source:
public boolean performOk() { Set<String> perspectives = new HashSet<>(); for (Object descriptor : fPerspectiveViewer.getCheckedElements()) { perspectives.add( ((IPerspectiveDescriptor)descriptor).getId() ); } if (perspectives.equals(ViewContextService.getDefaultEnabledPerspectives())) { getPreferenceStore().setValue(IDebugUIConstants.PREF_MANAGE_VIEW_PERSPECTIVES, IDebugUIConstants.PREF_MANAGE_VIEW_PERSPECTIVES_DEFAULT); } else { StringBuilder buffer= new StringBuilder(); for (String string : perspectives) { buffer.append(string).append(','); } getPreferenceStore().setValue(IDebugUIConstants.PREF_MANAGE_VIEW_PERSPECTIVES, buffer.toString()); } boolean trackViews = fTrackViewsButton.getSelection(); getPreferenceStore().setValue(IInternalDebugUIConstants.PREF_TRACK_VIEWS, trackViews); if (fResetPressed || !trackViews) { getPreferenceStore().setValue(IInternalDebugUIConstants.PREF_USER_VIEW_BINDINGS, IInternalDebugCoreConstants.EMPTY_STRING); } return super.performOk(); }

Target:
public boolean performOk() { Set<String> perspectives = new HashSet<>(); for (Object descriptor : fPerspectiveViewer.getCheckedElements()) { perspectives.add( ((IPerspectiveDescriptor)descriptor).getId() ); } if (perspectives.equals(ViewContextService.getDefaultEnabledPerspectives())) { getPreferenceStore().setValue(IDebugUIConstants.PREF_MANAGE_VIEW_PERSPECTIVES, IDebugUIConstants.PREF_MANAGE_VIEW_PERSPECTIVES_DEFAULT); } else { StringBuilder buffer= new StringBuilder(); for (String id : perspectives) { buffer.append(id).append(','); } getPreferenceStore().setValue(IDebugUIConstants.PREF_MANAGE_VIEW_PERSPECTIVES, buffer.toString()); } boolean trackViews = fTrackViewsButton.getSelection(); getPreferenceStore().setValue(IInternalDebugUIConstants.PREF_TRACK_VIEWS, trackViews); if (fResetPressed || !trackViews) { getPreferenceStore().setValue(IInternalDebugUIConstants.PREF_USER_VIEW_BINDINGS, IInternalDebugCoreConstants.EMPTY_STRING); } return super.performOk(); }
Source:
private CompletableFuture<Result> missingAuthentication() { logger.debug("Missing authentication"); return completedFuture(unauthorized()) .thenApply(result -> result .withHeader(WWW_AUTHENTICATE, httpAuthentication.getWwwAuthenticateHeader())); }

Target:
private CompletableFuture<Result> missingAuthentication() { logger.debug("Missing authentication"); final Result result = unauthorized() .withHeader(WWW_AUTHENTICATE, httpAuthentication.getWwwAuthenticateHeaderValue()); return completedFuture(result); }
Source:
public TaskSideInputHandler( TaskName taskName, TaskMode taskMode, File storeBaseDir, Map<String, StorageEngine> storeToStorageEngines, Map<String, Set<SystemStreamPartition>> storeToSSPs, Map<String, SideInputsProcessor> storeToProcessor, SystemAdmins systemAdmins, StreamMetadataCache streamMetadataCache, Clock clock) { this.taskName = taskName; this.systemAdmins = systemAdmins; this.streamMetadataCache = streamMetadataCache; this.storeToProcessor = storeToProcessor; this.sspToStores = storeToSSPs.entrySet().stream() .flatMap(storeAndSSPs -> storeAndSSPs.getValue().stream() .map(ssp -> new AbstractMap.SimpleImmutableEntry<>(ssp, storeAndSSPs.getKey()))) .collect(Collectors.groupingBy( Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toSet()))); this.taskSideInputStorageManager = new TaskSideInputStorageManager(taskName, taskMode, storeBaseDir, storeToStorageEngines, storeToSSPs, clock); validateProcessorConfiguration(); }

Target:
public TaskSideInputHandler(TaskName taskName, TaskMode taskMode, File storeBaseDir, Map<String, StorageEngine> storeToStorageEngines, Map<String, Set<SystemStreamPartition>> storeToSSPs, Map<String, SideInputsProcessor> storeToProcessor, SystemAdmins systemAdmins, StreamMetadataCache streamMetadataCache, Clock clock) { validateProcessorConfiguration(storeToSSPs.keySet(), storeToProcessor); this.taskName = taskName; this.systemAdmins = systemAdmins; this.streamMetadataCache = streamMetadataCache; this.storeToProcessor = storeToProcessor; this.sspToStores = new HashMap<>(); storeToSSPs.forEach((store, ssps) -> { for (SystemStreamPartition ssp: ssps) { this.sspToStores.computeIfAbsent(ssp, key -> new HashSet<>()); this.sspToStores.computeIfPresent(ssp, (key, value) -> { value.add(store); return value; }); } }); this.taskSideInputStorageManager = new TaskSideInputStorageManager(taskName, taskMode, storeBaseDir, storeToStorageEngines, storeToSSPs, clock); }
Source:
public ResponseEntity checkBundle(@PathVariable("id") Long bundleId) throws PermissionDeniedException { DownloadBundle bundle = downloadBundleService.get(bundleId); AthenaUser currentUser = userService.getCurrentUser(); vocabularyService.checkBundleUser(currentUser, bundle); vocabularyService.checkBundleVocabularies(bundle, currentUser.getId()); return ResponseEntity.ok(new LicenseExceptionDTO(true)); }

Target:
public LicenseExceptionDTO checkBundle(@PathVariable("id") Long bundleId) throws PermissionDeniedException { DownloadBundle bundle = downloadBundleService.get(bundleId); AthenaUser currentUser = userService.getCurrentUser(); vocabularyService.checkBundleUser(currentUser, bundle); vocabularyService.checkBundleVocabularies(bundle, currentUser.getId()); return new LicenseExceptionDTO(true); }
Source:
private void updateBrokerPositionMetadata(ConsumerRecords<?, ?> records, Instant readTime) { BiPredicate<MetricName, TopicPartition> matchesKip92 = (metricName, topicPartition) -> metricName != null && metricName.name() != null && metricName.name() .equals(topicPartition + ".records-lag"); BiPredicate<MetricName, TopicPartition> matchesKip225 = (metricName, topicPartition) -> metricName != null && metricName.name() != null && metricName.name() .equals("records-lag") && metricName.tags() != null && metricName.tags().containsKey("topic") && metricName.tags().get("topic").equals(topicPartition.topic()) && metricName.tags() .containsKey("partition") && metricName.tags() .get("partition") .equals(String.valueOf(topicPartition.partition())); for (TopicPartition topicPartition : records.partitions()) { for (MetricName metricName : _consumer.metrics().keySet()) { if (matchesKip92.or(matchesKip225).test(metricName, topicPartition)) { long consumerLag = (long) _consumer.metrics().get(metricName).value(); long consumerPosition = _consumer.position(topicPartition); long brokerPosition = consumerPosition + consumerLag; _endOffsets.put(topicPartition, brokerPosition); _endOffsetsLastUpdate.put(topicPartition, readTime.toEpochMilli()); } } } }

Target:
private void updateBrokerPositionMetadata(ConsumerRecords<?, ?> records, Instant readTime) { BiPredicate<MetricName, TopicPartition> matchesKip92 = (metricName, topicPartition) -> metricName != null && metricName.name() != null && metricName.name() .equals(topicPartition + ".records-lag"); BiPredicate<MetricName, TopicPartition> matchesKip225 = (metricName, topicPartition) -> metricName != null && metricName.name() != null && metricName.name() .equals("records-lag") && metricName.tags() != null && metricName.tags().containsKey("topic") && metricName.tags().get("topic").equals(topicPartition.topic()) && metricName.tags() .containsKey("partition") && metricName.tags() .get("partition") .equals(String.valueOf(topicPartition.partition())); for (TopicPartition topicPartition : records.partitions()) { for (MetricName metricName : _consumer.metrics().keySet()) { if (matchesKip92.or(matchesKip225).test(metricName, topicPartition)) { long consumerLag = (long) _consumer.metrics().get(metricName).value(); long consumerPosition = _consumer.position(topicPartition); long brokerPosition = consumerPosition + consumerLag; PhysicalSourcePosition offsetPosition = new PhysicalSourcePosition(); offsetPosition.setPositionType(PhysicalSourcePosition.KAFKA_OFFSET_POSITION_TYPE); offsetPosition.setSourceQueriedTimeMs(readTime.toEpochMilli()); offsetPosition.setSourcePosition(Long.toString(brokerPosition)); _offsetPositions.update(topicPartition.toString(), offsetPosition); } } } }
Source:
@Override public Environment setUp(AbstractBuild build, final Launcher launcher, BuildListener listener) throws IOException, InterruptedException { final List<MultiBinding.MultiEnvironment> m = new ArrayList<MultiBinding.MultiEnvironment>(); for (MultiBinding binding : bindings) { m.add(binding.bind(build, build.getWorkspace(), launcher, listener)); IdCredentials id = CredentialsProvider.findCredentialById(binding.getCredentialsId(), binding.type(), build); CredentialsProvider.track(build, id); } return new Environment() { @Override public void buildEnvVars(Map<String,String> env) { for (MultiBinding.MultiEnvironment e : m) { env.putAll(e.getValues()); } } @Override public boolean tearDown(AbstractBuild build, BuildListener listener) throws IOException, InterruptedException { for (MultiBinding.MultiEnvironment e : m) { e.getUnbinder().unbind(build, build.getWorkspace(), launcher, listener); } return true; } }; }

Target:
@Override public Environment setUp(AbstractBuild build, final Launcher launcher, BuildListener listener) throws IOException, InterruptedException { final List<MultiBinding.MultiEnvironment> m = new ArrayList<MultiBinding.MultiEnvironment>(); for (MultiBinding binding : bindings) { m.add(binding.bind(build, build.getWorkspace(), launcher, listener)); } return new Environment() { @Override public void buildEnvVars(Map<String,String> env) { for (MultiBinding.MultiEnvironment e : m) { env.putAll(e.getValues()); } } @Override public boolean tearDown(AbstractBuild build, BuildListener listener) throws IOException, InterruptedException { for (MultiBinding.MultiEnvironment e : m) { e.getUnbinder().unbind(build, build.getWorkspace(), launcher, listener); } return true; } }; }
Source:
public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((commandId == null) ? 0 : commandId.hashCode()); return result; }

Target:
public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Objects.hashCode(commandId); return result; }
Source:
public void testUpdateStatus() { when(dataStore.beginTransaction()).thenReturn(tx); when(elide.getElideSettings()).thenReturn(elideSettings); AsyncQuery result = asyncQueryDAO.updateStatus(asyncQuery, QueryStatus.PROCESSING); assertEquals(result, asyncQuery); verify(tx, times(1)).save(any(AsyncQuery.class), any(RequestScope.class)); verify(asyncQuery, times(1)).setStatus(QueryStatus.PROCESSING); }

Target:
public void testUpdateStatus() { AsyncQuery result = asyncQueryDAO.updateStatus(asyncQuery, QueryStatus.PROCESSING); assertEquals(result, asyncQuery); verify(tx, times(1)).save(any(AsyncQuery.class), any(RequestScope.class)); verify(asyncQuery, times(1)).setStatus(QueryStatus.PROCESSING); }
Source:
public void generateOpenApiSpec(Collection<Path> sourcesPaths, Path specOutputFile) { sourcesPaths.forEach(generator::addSourcePath); log.info("Parsing java files from {}", sourcesPaths); OpenAPI openAPI = generator.generateOpenApi(); try { if (openAPI.getPaths().size() > 0) { log.info("writing file {}", specOutputFile); FileUtils.writeStringToFile(specOutputFile.toFile(), Json.pretty(openAPI), StandardCharsets.UTF_8); } else { log.info("There are no Fusion endpoints to generate."); FileUtils.deleteQuietly(specOutputFile.toFile()); } } catch (IOException e) { String errorMessage = String.format( "Error while writing OpenAPI json file at %s", specOutputFile.toString()); log.error(errorMessage, specOutputFile, e); } }

Target:
public void generateOpenApiSpec(Collection<Path> sourcesPaths, Path specOutputFile) { sourcesPaths.forEach(generator::addSourcePath); log.info("Parsing java files from {}", sourcesPaths); OpenAPI openAPI = generator.generateOpenApi(); try { if (openAPI.getPaths().size() > 0) { log.info("writing file {}", specOutputFile); FileUtils.writeStringToFile(specOutputFile.toFile(), Json.pretty(openAPI), StandardCharsets.UTF_8); } else { log.info("There are no endpoints to generate."); FileUtils.deleteQuietly(specOutputFile.toFile()); } } catch (IOException e) { String errorMessage = String.format( "Error while writing OpenAPI json file at %s", specOutputFile.toString()); log.error(errorMessage, specOutputFile, e); } }
Source:
public void put(K key, T persistent) { Schema schema = persistent.getSchema(); Document doc = new Document(); List<org.apache.avro.Schema.Field> fields = schema.getFields(); for (org.apache.avro.Schema.Field field : fields) { if (!persistent.isDirty(field.name())) { continue; } String sf = mapping.getLuceneField(field.name()); if (sf == null) { continue; } Schema fieldSchema = field.schema(); Object o = persistent.get(field.pos()); if (o == null) { continue; } doc.add(convertToIndexableField(sf, fieldSchema, o)); } LOG.info("DOCUMENT: {}", doc); try { if (key instanceof Integer) { doc.add(new IntPoint(mapping.getPrimaryKey(), ((Integer) key).intValue())); } else if (key instanceof Long) { doc.add(new LongPoint(mapping.getPrimaryKey(), ((Long) key).longValue())); } else if (key instanceof Float) { doc.add(new FloatPoint(mapping.getPrimaryKey(), ((Float) key).floatValue())); } else if (key instanceof Double) { doc.add(new DoublePoint(mapping.getPrimaryKey(), ((Double) key).doubleValue())); } else { doc.add(new StringField(mapping.getPrimaryKey(), key.toString(), Store.YES)); } LOG.info("DOCUMENT: {}", doc); if (get(key, null) == null) { writer.addDocument(doc); } else { writer.updateDocument( new Term(mapping.getPrimaryKey(), key.toString()), doc); } searcherManager.maybeRefresh(); } catch (IOException e) { LOG.error("Error updating document: {}", e); } }

Target:
public void put(K key, T persistent) { Schema schema = persistent.getSchema(); Document doc = new Document(); List<org.apache.avro.Schema.Field> fields = schema.getFields(); for (org.apache.avro.Schema.Field field : fields) { if (!persistent.isDirty(field.name())) { continue; } String sf = mapping.getLuceneField(field.name()); if (sf == null) { continue; } Schema fieldSchema = field.schema(); Object o = persistent.get(field.pos()); if (o == null) { continue; } doc.add(convertToIndexableField(sf, fieldSchema, o)); } LOG.info("DOCUMENT: {}", doc); try { if (key instanceof Integer) { doc.add(new IntPoint(mapping.getPrimaryKey(), (Integer) key)); } else if (key instanceof Long) { doc.add(new LongPoint(mapping.getPrimaryKey(), (Long) key)); } else if (key instanceof Float) { doc.add(new FloatPoint(mapping.getPrimaryKey(), (Float) key)); } else if (key instanceof Double) { doc.add(new DoublePoint(mapping.getPrimaryKey(), (Double) key)); } else { doc.add(new StringField(mapping.getPrimaryKey(), key.toString(), Store.YES)); } LOG.info("DOCUMENT: {}", doc); if (get(key, null) == null) { writer.addDocument(doc); } else { writer.updateDocument( new Term(mapping.getPrimaryKey(), key.toString()), doc); } searcherManager.maybeRefresh(); } catch (IOException e) { LOG.error("Error updating document: {}", e); } }
Source:
public void buildVariablesFor(AbstractBuild build, Map<String, String> variables) { final Executor executor = build.getExecutor(); if (executor != null && executor.getOwner() instanceof DockerComputer) { final DockerComputer dockerComputer = (DockerComputer) executor.getOwner(); variables.put("DOCKER_CONTAINER_ID", dockerComputer.getContainerId()); variables.put("JENKINS_CLOUD_ID", dockerComputer.getCloudId()); try { final URIBuilder uriBuilder = new URIBuilder(dockerComputer.getCloud().serverUrl); if (uriBuilder.getScheme() == "http" || uriBuilder.getScheme() == "https") { uriBuilder.setScheme("tcp"); } final String dockerHost = uriBuilder.toString(); variables.put("DOCKER_HOST", dockerHost); } catch (URISyntaxException e) { LOG.error("Can't build 'DOCKER_HOST' var: {}", e.getMessage()); } } }

Target:
public void buildVariablesFor(AbstractBuild build, Map<String, String> variables) { final Executor executor = build.getExecutor(); if (executor != null && executor.getOwner() instanceof DockerComputer) { final DockerComputer dockerComputer = (DockerComputer) executor.getOwner(); variables.put("DOCKER_CONTAINER_ID", dockerComputer.getContainerId()); variables.put("JENKINS_CLOUD_ID", dockerComputer.getCloudId()); try { final URIBuilder uriBuilder = new URIBuilder(dockerComputer.getCloud().serverUrl); if (uriBuilder.getScheme() != "unix") { uriBuilder.setScheme("tcp"); } final String dockerHost = uriBuilder.toString(); variables.put("DOCKER_HOST", dockerHost); } catch (URISyntaxException e) { LOG.error("Can't build 'DOCKER_HOST' var: {}", e.getMessage()); } } }
Source:
private List<Map<String, Object>> parseDisks(XmlDocument document, List<VmDevice> devices) { List<VmDevice> dbDevices = filterDevices(devices, VmDeviceGeneralType.DISK); MemoizingSupplier<Map<Guid, String>> diskToLunSupplier = new MemoizingSupplier<>(() -> { return diskLunMapDao.getAll().stream().collect(Collectors.toMap( DiskLunMap::getDiskId, DiskLunMap::getLunId)); }); List<Map<String, Object>> result = new ArrayList<>(); for (XmlNode node : selectNodes(document, VmDeviceGeneralType.DISK)) { Map<String, Object> dev = new HashMap<>(); dev.put(VdsProperties.Type, VmDeviceGeneralType.DISK.getValue()); String diskType = parseAttribute(node, DEVICE); dev.put(VdsProperties.Device, diskType); dev.put(VdsProperties.Address, parseAddress(node)); dev.put(VdsProperties.Alias, parseAlias(node)); String path = parseDiskPath(node); VmDevice dbDev = dbDevices.stream() .filter(d -> d.getDevice().equals(diskType)) .filter(d -> { switch(diskType) { case "cdrom": String devicePath = (String) d.getSpecParams().get("path"); return devicePath == null || path.contains(devicePath); case "floppy": return true; default: Guid diskId = d.getId().getDeviceId(); return path.contains(diskId.toString()) || isPathContainsLunIdOfDisk(path, diskId, diskToLunSupplier); } }) .findFirst() .orElse(null); if (dbDev == null) { log.warn("unmanaged disk with path '{}' is ignored", path); continue; } dbDevices.remove(dbDev); dev.put(VdsProperties.DeviceId, dbDev.getId().getDeviceId().toString()); dev.put(VdsProperties.SpecParams, dbDev.getSpecParams()); result.add(dev); } return result; }

Target:
private List<Map<String, Object>> parseDisks(XmlDocument document, List<VmDevice> devices) { List<VmDevice> dbDevices = filterDevices(devices, VmDeviceGeneralType.DISK); MemoizingSupplier<Map<Guid, String>> diskToLunSupplier = new MemoizingSupplier<>(() -> { return diskLunMapDao.getAll().stream().collect(Collectors.toMap( DiskLunMap::getDiskId, DiskLunMap::getLunId)); }); List<Map<String, Object>> result = new ArrayList<>(); for (XmlNode node : selectNodes(document, VmDeviceGeneralType.DISK)) { Map<String, Object> dev = new HashMap<>(); dev.put(VdsProperties.Type, VmDeviceGeneralType.DISK.getValue()); String diskType = parseAttribute(node, DEVICE); dev.put(VdsProperties.Device, diskType); dev.put(VdsProperties.Address, parseAddress(node)); dev.put(VdsProperties.Alias, parseAlias(node)); String path = parseDiskPath(node); VmDevice dbDev = dbDevices.stream() .filter(d -> { switch(diskType) { case "cdrom": String devicePath = (String) d.getSpecParams().get("path"); return devicePath == null || path.contains(devicePath); case "floppy": return true; default: Guid diskId = d.getId().getDeviceId(); return path.contains(diskId.toString()) || isPathContainsLunIdOfDisk(path, diskId, diskToLunSupplier); } }) .findFirst() .orElse(null); if (dbDev == null) { log.warn("unmanaged disk with path '{}' is ignored", path); continue; } dbDevices.remove(dbDev); dev.put(VdsProperties.DeviceId, dbDev.getId().getDeviceId().toString()); dev.put(VdsProperties.SpecParams, dbDev.getSpecParams()); result.add(dev); } return result; }