auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean offer(E e) { Objects.requireNonNull(e); final ReentrantLock lock = this.lock; lock.lock(); try { if (this.queue.size() == this.maxSize) { final E discard = this.queue.remove(); LOG.debug("Queue if full. Discarding oldest element: {}", discard); } this.queue.add(e); this.notEmpty.signal(); } finally { lock.unlock(); } return true; }

Target:
public boolean offer(E e) { Objects.requireNonNull(e); final ReentrantLock lock = this.lock; lock.lock(); try { if (this.queue.size() == this.maxSize) { final E discard = this.queue.remove(); this.droppedCount++; LOG.debug("Queue is full. Discarding oldest element [count={}]: {}", this.droppedCount, discard); } this.queue.add(e); this.notEmpty.signal(); } finally { lock.unlock(); } return true; }
Source:
public void create(Username currentUser, SecurityAuthConfig securityAuthConfig, LocalizedOperationResult result) { SecurityAuthConfigCreateCommand command = new SecurityAuthConfigCreateCommand(goConfigService, securityAuthConfig, authorizationExtension, currentUser, result); validatePluginProperties(command, securityAuthConfig); update(currentUser, securityAuthConfig, result, command); }

Target:
public void create(Username currentUser, SecurityAuthConfig securityAuthConfig, LocalizedOperationResult result) { SecurityAuthConfigCreateCommand command = new SecurityAuthConfigCreateCommand(goConfigService, securityAuthConfig, authorizationExtension, currentUser, result); update(currentUser, securityAuthConfig, result, command); }
Source:
public synchronized List<Product> getTopNProducts(int n) throws CatalogException { List<Product> products = new Vector<Product>(); IndexSearcher searcher = null; try { try { reader = DirectoryReader.open(indexDir); } catch (IOException e) { e.printStackTrace(); } searcher = new IndexSearcher(reader); BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder(); TermQuery tq = new TermQuery(new Term("myfield", "myvalue")); booleanQuery.add(tq, BooleanClause.Occur.MUST); Sort sort = new Sort(new SortField("CAS.ProductReceivedTime", SortField.Type.STRING, true)); LOG.log(Level.FINE, "Querying LuceneCatalog: q: [" + booleanQuery + "]"); TopDocs check = searcher.search(booleanQuery.build(), 1, sort); if(check.totalHits>0) { TopDocs topDocs = searcher.search(booleanQuery.build(), check.totalHits, sort); ScoreDoc[] hits = topDocs.scoreDocs; if (hits.length > 0) { int i = 0; while (products.size() < Math.min(n, hits.length)) { Document productDoc = searcher.doc(hits[i].doc); CompleteProduct prod = toCompleteProduct(productDoc, false, false); products.add(prod.getProduct()); i++; } } else { LOG.log(Level.WARNING, "Top N query produced no products!"); } } else{ return products; } } catch (IOException e) { LOG.log(Level.WARNING, "IOException when opening index directory: [" + indexFilePath + "] for search: Message: " + e.getMessage()); throw new CatalogException(e.getMessage(), e); } finally { if (searcher != null) { try { } catch (Exception ignore) { } } } return products; }

Target:
public synchronized List<Product> getTopNProducts(int n) throws CatalogException { List<Product> products = new Vector<Product>(); IndexSearcher searcher = null; try { try { reader = DirectoryReader.open(indexDir); } catch (IOException e) { e.printStackTrace(); } searcher = new IndexSearcher(reader); BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder(); TermQuery tq = new TermQuery(new Term("myfield", "myvalue")); booleanQuery.add(tq, BooleanClause.Occur.MUST); Sort sort = new Sort(new SortField("CAS.ProductReceivedTime", SortField.Type.STRING, true)); LOG.log(Level.FINE, "Querying LuceneCatalog: q: [" + booleanQuery + "]"); TopDocs check = searcher.search(booleanQuery.build(), 1, sort); if(check.totalHits>0) { TopDocs topDocs = searcher.search(booleanQuery.build(), check.totalHits, sort); ScoreDoc[] hits = topDocs.scoreDocs; if (hits.length > 0) { int i = 0; while (products.size() < Math.min(n, hits.length)) { Document productDoc = searcher.doc(hits[i].doc); CompleteProduct prod = toCompleteProduct(productDoc, false, false); products.add(prod.getProduct()); i++; } } else { LOG.log(Level.WARNING, "Top N query produced no products!"); } } } catch (IOException e) { LOG.log(Level.WARNING, "IOException when opening index directory: [" + indexFilePath + "] for search: Message: " + e.getMessage()); throw new CatalogException(e.getMessage(), e); } finally { if (searcher != null) { try { } catch (Exception ignore) { } } } return products; }
Source:
private void cleanNativeReferences() { NativeObjectReference reference = (NativeObjectReference) referenceQueue.poll(); while (reference != null) { reference.cleanup(); reference.clear(); referencesPool.freeIndexList.add(reference.refIndex); reference = (NativeObjectReference) referenceQueue.poll(); } }

Target:
private void cleanNativeReferences() { NativeObjectReference reference = (NativeObjectReference) referenceQueue.poll(); while (reference != null) { reference.cleanup(); referencesPool.freeIndexList.add(reference.refIndex); reference = (NativeObjectReference) referenceQueue.poll(); } }
Source:
public StorageQuotaConfig(VerifiableProperties verifiableProperties) { zkClientConnectAddress = verifiableProperties.getString(ZK_CLIENT_CONNECT_ADDRESS); refresherPollingIntervalMs = verifiableProperties.getInt(REFRESHER_POLLING_INTERVAL_MS, 30 * 60 * 1000); containerStorageQuotaInJson = verifiableProperties.getString(CONTAINER_STORAGE_QUOTA_IN_JSON, ""); sourcePollingIntervalMs = verifiableProperties.getInt(SOURCE_POLLING_INTERVAL_MS, 30 * 60 * 1000); }

Target:
public StorageQuotaConfig(VerifiableProperties verifiableProperties) { zkClientConnectAddress = verifiableProperties.getString(ZK_CLIENT_CONNECT_ADDRESS); refresherPollingIntervalMs = verifiableProperties.getIntInRange(REFRESHER_POLLING_INTERVAL_MS, 30 * 60 * 1000, 0, Integer.MAX_VALUE); containerStorageQuotaInJson = verifiableProperties.getString(CONTAINER_STORAGE_QUOTA_IN_JSON, ""); sourcePollingIntervalMs = verifiableProperties.getInt(SOURCE_POLLING_INTERVAL_MS, 30 * 60 * 1000); }
Source:
private boolean filterBranch(Branch branch) { if (!includeBaseline && branch.getBranchType() == BranchType.BASELINE) { console.writeln( "Branch %s[%s] is a baseline branch and that option was not specified! It will not be purged!\n", branch, branch.getGuid()); return true; } else if (!includeUnarchived && branch.getArchiveState() == BranchArchivedState.UNARCHIVED) { console.writeln( "Branch %s[%s] is an unarchived branch and that option was not specified! It will not be purged!\n", branch, branch.getGuid()); return true; } else if (!includeUndeleted && !branch.isDeleted()) { console.writeln( "Branch %s[%s] is an undeleted branch and that option was not specified! It will not be purged!\n", branch, branch.getGuid()); return true; } return false; }

Target:
private boolean filterBranch(Branch branch) { if (!includeBaseline && branch.getBranchType() == BranchType.BASELINE) { console.writeln( "Branch %s[%s] is a %s branch and that option was not specified! It will not be purged!\n", branch, branch.getGuid(), branch.getBranchType()); return true; } else if (!includeUnarchived && branch.getArchiveState() == BranchArchivedState.UNARCHIVED) { console.writeln( "Branch %s[%s] is an unarchived branch and that option was not specified! It will not be purged!\n", branch, branch.getGuid()); return true; } else if (!includeUndeleted && !branch.isDeleted()) { console.writeln( "Branch %s[%s] is an undeleted branch and that option was not specified! It will not be purged!\n", branch, branch.getGuid()); return true; } return false; }
Source:
public boolean execute() throws Exception { String archivePathArg = requiredArgument(0, Messages.i18n.format("InvalidArgMsg.EntryPath")); String artifactTypeArg = requiredArgument(1, Messages.i18n.format("AddEntry.InvalidArgMsg.ArtifactType")); String pathToContent = optionalArgument(2); QName varName = new QName("archive", "active-archive"); SrampArchive archive = (SrampArchive) getContext().getVariable(varName); if (archive == null) { print(Messages.i18n.format("NO_ARCHIVE_OPEN")); return false; } if (archivePathArg.endsWith(File.separator)) { print(Messages.i18n.format("Archive.Path.Arg.should.not.contain.slash.end")); return false; } InputStream contentStream = null; try { ArtifactType type = ArtifactType.valueOf(artifactTypeArg); String name = new File(archivePathArg).getName(); if (pathToContent != null) { File contentFile = new File(pathToContent); contentStream = FileUtils.openInputStream(contentFile); } BaseArtifactType artifact = type.newArtifactInstance(); artifact.setName(name); archive.addEntry(archivePathArg, artifact, contentStream); print(Messages.i18n.format("AddEntry.Added", archivePathArg)); } catch (SrampArchiveException e) { print(e.getLocalizedMessage()); } finally { IOUtils.closeQuietly(contentStream); } return true; }

Target:
public boolean execute() throws Exception { super.initialize(); String archivePathArg = requiredArgument(0, Messages.i18n.format("InvalidArgMsg.EntryPath")); String artifactTypeArg = requiredArgument(1, Messages.i18n.format("AddEntry.InvalidArgMsg.ArtifactType")); String pathToContent = optionalArgument(2); if (!this.validate(archivePathArg)) { return false; } InputStream contentStream = null; try { ArtifactType type = ArtifactType.valueOf(artifactTypeArg); String name = new File(archivePathArg).getName(); if (pathToContent != null) { File contentFile = new File(pathToContent); contentStream = FileUtils.openInputStream(contentFile); } BaseArtifactType artifact = type.newArtifactInstance(); artifact.setName(name); archive.addEntry(archivePathArg, artifact, contentStream); print(Messages.i18n.format("AddEntry.Added", archivePathArg)); } catch (SrampArchiveException e) { print(Messages.i18n.format("AddEntry.SrampArchiveException", e.getLocalizedMessage())); } finally { IOUtils.closeQuietly(contentStream); } return true; }
Source:
public static void onWebViewProviderChanged(PackageInfo packageInfo) { LogPrinter printer = new LogPrinter(Log.DEBUG, LOGTAG); packageInfo.applicationInfo.dump(printer, ""); sPackage = packageInfo; if (!sMultiprocessEnabled) { return; } final String serviceName = getServiceName(); if (SystemService.isStopped(serviceName)) { SystemService.start(serviceName); } else if (sZygote != null) { SystemService.restart(serviceName); } try { SystemService.waitForState(serviceName, SystemService.State.RUNNING, 5000); } catch (TimeoutException e) { Log.e(LOGTAG, "Timed out waiting for " + serviceName); return; } connectToZygoteIfNeeded(); }

Target:
public static void onWebViewProviderChanged(PackageInfo packageInfo) { sPackage = packageInfo; if (!sMultiprocessEnabled) { return; } final String serviceName = getServiceName(); if (SystemService.isStopped(serviceName)) { SystemService.start(serviceName); } else if (sZygote != null) { SystemService.restart(serviceName); } try { SystemService.waitForState(serviceName, SystemService.State.RUNNING, 5000); } catch (TimeoutException e) { Log.e(LOGTAG, "Timed out waiting for " + serviceName); return; } connectToZygoteIfNeeded(); }
Source:
public void testConfigureDurableParquetAppender() throws IOException { Configuration conf = new Configuration(); FileSystem fs = FileSystem.getLocal(conf); FileSystemWriter<Object> writer = new FileSystemWriter<Object>( fs, new Path("/tmp"), new DatasetDescriptor.Builder() .property(FileSystemProperties.NON_DURABLE_PARQUET_PROP, "false") .schema(SchemaBuilder.record("test").fields() .requiredString("s") .endRecord()) .format("parquet") .build()); Assert.assertEquals("Should default to ParquetAppender", DurableParquetAppender.class, writer.appender.getClass()); }

Target:
public void testConfigureDurableParquetAppender() throws IOException { Configuration conf = new Configuration(); FileSystem fs = FileSystem.getLocal(conf); FileSystemWriter<Object> writer = new FileSystemWriter<Object>( fs, new Path("/tmp"), new DatasetDescriptor.Builder() .property(FileSystemProperties.NON_DURABLE_PARQUET_PROP, "false") .schema(SchemaBuilder.record("test").fields() .requiredString("s") .endRecord()) .format("parquet") .build()); Assert.assertEquals("Disabling the non-durable parquet appender should get us a durable appender", DurableParquetAppender.class, writer.newAppender(testDirectory).getClass()); }
Source:
public void shouldBeAbleToDeserializeADogWithoutRoot() throws Exception { InputStream stream = asStream("{'name':'Brutus','age':7}"); when(deserializeeInstance.get()).thenReturn(new Deserializee()); Object[] deserialized = deserializer.deserialize(stream, dogParameterWithoutRoot); assertThat(deserialized.length, is(1)); assertThat(deserialized[0], is(instanceOf(Dog.class))); Dog dog = (Dog) deserialized[0]; assertThat(dog.name, is("Brutus")); assertThat(dog.age, is(7)); }

Target:
public void shouldBeAbleToDeserializeADogWithoutRoot() throws Exception { InputStream stream = asStream("{'name':'Brutus','age':7}"); Object[] deserialized = deserializer.deserialize(stream, dogParameterWithoutRoot); assertThat(deserialized.length, is(1)); assertThat(deserialized[0], is(instanceOf(Dog.class))); Dog dog = (Dog) deserialized[0]; assertThat(dog.name, is("Brutus")); assertThat(dog.age, is(7)); }
Source:
public KeyStore getInternalKeyStore() throws Exception { if (tenantId == MultitenantConstants.SUPER_TENANT_ID) { if (internalKeyStore == null) { ServerConfigurationService config = this.getServerConfigService(); if (config. getFirstProperty(RegistryResources.SecurityManagement.SERVER_INTERNAL_KEYSTORE_FILE) == null) { return null; } String file = new File(config .getFirstProperty(RegistryResources.SecurityManagement.SERVER_INTERNAL_KEYSTORE_FILE)) .getAbsolutePath(); KeyStore store = KeyStore.getInstance(config .getFirstProperty(RegistryResources.SecurityManagement.SERVER_INTERNAL_KEYSTORE_TYPE)); String password = config .getFirstProperty(RegistryResources.SecurityManagement.SERVER_INTERNAL_KEYSTORE_PASSWORD); try (FileInputStream in = new FileInputStream(file)){ store.load(in, password.toCharArray()); internalKeyStore = store; } } return internalKeyStore; } else { throw new CarbonException("Permission denied for accessing internal key store"); } }

Target:
public KeyStore getInternalKeyStore() throws Exception { if (tenantId == MultitenantConstants.SUPER_TENANT_ID) { if (internalKeyStore == null) { ServerConfigurationService config = this.getServerConfigService(); if (config. getFirstProperty(RegistryResources.SecurityManagement.SERVER_INTERNAL_KEYSTORE_FILE) == null) { return null; } String file = new File(config .getFirstProperty(RegistryResources.SecurityManagement.SERVER_INTERNAL_KEYSTORE_FILE)) .getAbsolutePath(); KeyStore store = KeyStore.getInstance(config .getFirstProperty(RegistryResources.SecurityManagement.SERVER_INTERNAL_KEYSTORE_TYPE)); String password = config .getFirstProperty(RegistryResources.SecurityManagement.SERVER_INTERNAL_KEYSTORE_PASSWORD); try (FileInputStream in = new FileInputStream(file)) { store.load(in, password.toCharArray()); internalKeyStore = store; } } return internalKeyStore; } else { throw new CarbonException("Permission denied for accessing internal key store. The internal key store is " + "available only for the super tenant."); } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.display_points); mapButton = (Button)findViewById(R.id.mapButton); nextScenarioButton = (Button)findViewById(R.id.nextScenarioButton); Intent i = getIntent(); int currentPointsValue = i.getExtras().getInt("current_scenario_points"); currentPoints = (TextView)findViewById(R.id.current_points_text); totalPoints = (TextView)findViewById(R.id.total_points_text); currentPoints.setText(currentPointsValue + ""); totalPoints.setText(SessionHistory.totalPoints + ""); mapButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent returnIntent = new Intent(); setResult(Activity.RESULT_CANCELED, returnIntent); finish(); } }); nextScenarioButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent returnIntent = new Intent(); setResult(Activity.RESULT_OK, returnIntent); finish(); } }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.display_points); mapButton = (Button) findViewById(R.id.mapButton); nextScenarioButton = (Button) findViewById(R.id.nextScenarioButton); Integer currentPointsValue = getIntent().getExtras().getInt(getString(R.string.current_points_key)); currentPointsTextView = (TextView) findViewById(R.id.current_points_text); totalPointsTextView = (TextView) findViewById(R.id.total_points_text); currentPointsTextView.setText(currentPointsValue.toString()); Integer totalPointsValue = SessionHistory.totalPoints; totalPointsTextView.setText(totalPointsValue.toString()); mapButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(Activity.RESULT_CANCELED, new Intent()); finish(); } }); nextScenarioButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(Activity.RESULT_OK, new Intent()); finish(); } }); }
Source:
public List<Entity> resolve() { SelectorType selectorType = this.selector.getType(); int defaultCount = 1; if (INFINITE_TYPES.contains(selectorType)) { defaultCount = 0; } int maxToSelect = this.selector.get(ArgumentTypes.COUNT).orElse(defaultCount); boolean isReversed = maxToSelect < 0; maxToSelect = Math.abs(maxToSelect); Set<? extends Extent> extents = getExtentSet(); Stream<Entity> entityStream = extents.stream() .flatMap(ext -> ext.getEntities().stream()) .filter(this.selectorFilter); if (maxToSelect != 0) { if (selectorType == SelectorTypes.RANDOM) { List<Entity> holder = entityStream.collect(Collectors.toList()); Collections.shuffle(holder); entityStream = holder.stream(); } entityStream = entityStream.limit(maxToSelect); } return entityStream.sorted(distanceSort(isReversed)).collect(GuavaCollectors.toImmutableList()); }

Target:
public List<Entity> resolve() { SelectorType selectorType = this.selector.getType(); int defaultCount = 1; if (INFINITE_TYPES.contains(selectorType)) { defaultCount = 0; } int maxToSelect = this.selector.get(ArgumentTypes.COUNT).orElse(defaultCount); boolean isReversed = maxToSelect < 0; maxToSelect = Math.abs(maxToSelect); Set<? extends Extent> extents = getExtentSet(); Stream<Entity> entityStream = extents.stream() .flatMap(ext -> ext.getEntities().stream()) .filter(this.selectorFilter); if (maxToSelect != 0) { if (selectorType == SelectorTypes.RANDOM) { List<Entity> holder = entityStream.collect(Collectors.toList()); Collections.shuffle(holder); entityStream = holder.stream(); } else { entityStream = entityStream.sorted(distanceSort(isReversed)); } entityStream = entityStream.limit(maxToSelect); } else { entityStream = entityStream.sorted(distanceSort(isReversed)); } return entityStream.collect(GuavaCollectors.toImmutableList()); }
Source:
private void watermarkText(final IMOperation op, final File source, final Map<Class<AbstractImageToolOption>, AbstractImageToolOption> options) throws Exception { WatermarkTextOption watermarkText = getOption(options, WatermarkTextOption.class); if (watermarkText != null) { final String[] imageInfo; DimensionOption dimension = getOption(options, DimensionOption.class); if (dimension != null) { imageInfo = new String[2]; imageInfo[0] = dimension.getWidth() != null ? String.valueOf(dimension.getWidth()) : getImageInfo(source, WIDTH_IN_PIXEL)[0]; imageInfo[1] = dimension.getHeight() != null ? String.valueOf(dimension.getHeight()) : getImageInfo(source, HEIGHT_IN_PIXEL)[0]; } else { imageInfo = getImageInfo(source, WIDTH_IN_PIXEL, HEIGHT_IN_PIXEL); } int width = Integer.valueOf(imageInfo[0]); int height = Integer.valueOf(imageInfo[1]); int pointSize = (int) Math.rint((width * 0.02) + Math.log(width)); pointSize = Math.min((int) (height * 0.2), pointSize); int minX = (int) Math.max(1, (height * 0.015)); int minY = (int) Math.max(1, (height * 0.025)); int x = (int) (minX + Math.max(1, (pointSize / 2.5))); int y = (int) (minY + Math.max(1, (pointSize / 1.75))); final String text = watermarkText.getText(); final AnchoringPosition anchoringPosition = watermarkText.getAnchoringPosition(); op.font(watermarkText.getFont()); op.pointsize(pointSize); String black = "rgba(0, 0, 0, 0.5)"; String white = "rgba(255, 255, 255, 0.5)"; drawText(op, black, text, anchoringPosition, x, y); drawText(op, white, text, anchoringPosition, minX, minY); } }

Target:
private void watermarkText(final IMOperation op, final File source, final Map<Class<AbstractImageToolOption>, AbstractImageToolOption> options) throws SilverpeasException { WatermarkTextOption watermarkText = getOption(options, WatermarkTextOption.class); if (watermarkText != null) { final String[] imageInfo; DimensionOption dimension = getOption(options, DimensionOption.class); if (dimension != null) { imageInfo = new String[2]; imageInfo[0] = dimension.getWidth() != null ? String.valueOf(dimension.getWidth()) : getImageInfo(source, WIDTH_IN_PIXEL)[0]; imageInfo[1] = dimension.getHeight() != null ? String.valueOf(dimension.getHeight()) : getImageInfo(source, HEIGHT_IN_PIXEL)[0]; } else { imageInfo = getImageInfo(source, WIDTH_IN_PIXEL, HEIGHT_IN_PIXEL); } int width = Integer.valueOf(imageInfo[0]); int height = Integer.valueOf(imageInfo[1]); int pointSize = (int) Math.rint((width * 0.02) + Math.log(width)); pointSize = Math.min((int) (height * 0.2), pointSize); int minX = (int) Math.max(1, (height * 0.015)); int minY = (int) Math.max(1, (height * 0.025)); int x = (int) (minX + Math.max(1, (pointSize / 2.5))); int y = (int) (minY + Math.max(1, (pointSize / 1.75))); final String text = watermarkText.getText(); final AnchoringPosition anchoringPosition = watermarkText.getAnchoringPosition(); op.font(watermarkText.getFont()); op.pointsize(pointSize); String black = "rgba(0, 0, 0, 0.5)"; String white = "rgba(255, 255, 255, 0.5)"; drawText(op, black, text, anchoringPosition, x, y); drawText(op, white, text, anchoringPosition, minX, minY); } }
Source:
getReplicationLoad(ServerName[] serverNames) { List<ReplicationPeerDescription> peerList = this.getReplicationPeerManager().listPeers(null); if (peerList == null) { return null; } HashMap<String, List<Pair<ServerName, ReplicationLoadSource>>> replicationLoadSourceMap = new HashMap<>(peerList.size()); peerList.stream() .forEach(peer -> replicationLoadSourceMap.put(peer.getPeerId(), new ArrayList<>())); for (ServerName serverName : serverNames) { List<ReplicationLoadSource> replicationLoadSources = getServerManager().getLoad(serverName).getReplicationLoadSourceList(); for (ReplicationLoadSource replicationLoadSource : replicationLoadSources) { List<Pair<ServerName, ReplicationLoadSource>> replicationLoadSourceList = replicationLoadSourceMap.get(replicationLoadSource.getPeerID()); if (replicationLoadSourceList == null) { LOG.debug(replicationLoadSource.getPeerID() + " does not exist, but it exists " + "in znode(/hbase/replication/rs). when the rs restarts, peerId is deleted, so " + "we just need to ignore it"); continue; } replicationLoadSourceList.add(new Pair<>(serverName, replicationLoadSource)); } } for (List<Pair<ServerName, ReplicationLoadSource>> loads : replicationLoadSourceMap.values()) { if (loads.size() > 0) { loads.sort(Comparator.comparingLong(load -> (-1) * load.getSecond().getReplicationLag())); } } return replicationLoadSourceMap; }

Target:
getReplicationLoad(ServerName[] serverNames) { List<ReplicationPeerDescription> peerList = this.getReplicationPeerManager().listPeers(null); if (peerList == null) { return null; } HashMap<String, List<Pair<ServerName, ReplicationLoadSource>>> replicationLoadSourceMap = new HashMap<>(peerList.size()); peerList.stream() .forEach(peer -> replicationLoadSourceMap.put(peer.getPeerId(), new ArrayList<>())); for (ServerName serverName : serverNames) { List<ReplicationLoadSource> replicationLoadSources = getServerManager().getLoad(serverName).getReplicationLoadSourceList(); for (ReplicationLoadSource replicationLoadSource : replicationLoadSources) { List<Pair<ServerName, ReplicationLoadSource>> replicationLoadSourceList = replicationLoadSourceMap.get(replicationLoadSource.getPeerID()); if (replicationLoadSourceList == null) { LOG.debug("{} does not exist, but it exists " + "in znode(/hbase/replication/rs). when the rs restarts, peerId is deleted, so " + "we just need to ignore it", replicationLoadSource.getPeerID()); continue; } replicationLoadSourceList.add(new Pair<>(serverName, replicationLoadSource)); } } for (List<Pair<ServerName, ReplicationLoadSource>> loads : replicationLoadSourceMap.values()) { if (loads.size() > 0) { loads.sort(Comparator.comparingLong(load -> (-1) * load.getSecond().getReplicationLag())); } } return replicationLoadSourceMap; }
Source:
public List<String> getBuildDirs(Review review) { return Lists.transform(review.getFiles(), new Function<ReviewFile, String>() { @Nullable @Override public String apply(ReviewFile file) { if (file.isSourceFile()) { return StringUtils.substringBeforeLast(file.getReviewFilename(), SRC_MAIN).concat(getMainBuildDir()); } else if (file.isTestFile()) { return StringUtils.substringBeforeLast(file.getReviewFilename(), SRC_TEST).concat(getTestBuildDir()); } return file.getSourceDir(); } }); }

Target:
public List<String> getBuildDirs(Review review) { return Lists.transform(review.getFiles(), new Function<ReviewFile, String>() { @Nullable @Override public String apply(ReviewFile file) { if (file.isSourceFile()) { return substringBeforeLast(file.getReviewFilename(), SRC_MAIN).concat(getMainBuildDir()); } if (file.isTestFile()) { return substringBeforeLast(file.getReviewFilename(), SRC_TEST).concat(getTestBuildDir()); } return file.getSourceDir(); } }); }
Source:
public void testEditReadOnlyLogFileConfiguration() throws Exception { final File path = tempFolder.newFolder(); final String logDirectory = emptyDirectory(path.getAbsolutePath()); LogFileConfiguration config = new LogFileConfiguration(logDirectory); testWithConfiguration(LogLevel.DEBUG, config, new Runnable() { @Override public void run() { thrown.expect(IllegalStateException.class); Database.log.getFile().getConfig().setMaxSize(1024); thrown.expect(IllegalStateException.class); Database.log.getFile().getConfig().setMaxRotateCount(3); thrown.expect(IllegalStateException.class); Database.log.getFile().getConfig().setUsePlaintext(true); } }); }

Target:
public void testEditReadOnlyLogFileConfiguration() throws IOException { final File path = tempFolder.newFolder(); final String logDirectory = emptyDirectory(path.getAbsolutePath()); LogFileConfiguration config = new LogFileConfiguration(logDirectory); testWithConfiguration(LogLevel.DEBUG, config, () -> { Database.log.getFile().setConfig(config); thrown.expect(IllegalStateException.class); Database.log.getFile().getConfig().setMaxSize(1024); thrown.expect(IllegalStateException.class); Database.log.getFile().getConfig().setMaxRotateCount(3); thrown.expect(IllegalStateException.class); Database.log.getFile().getConfig().setUsePlaintext(true); }); }
Source:
protected int doWork() { if (OUTPUT.exists()) { throw new PicardException(OUTPUT.getAbsolutePath() + " already exists. Delete this file and try again, or specify a different output file."); } try (BufferedWriter writer = makeWriter()) { SequenceDictionaryUtils.encodeDictionary(writer, new SAMSequenceRecordIterator(REFERENCE_SEQUENCE, TRUNCATE_NAMES_AT_WHITESPACE)); } catch (FileNotFoundException e) { throw new PicardException("File " + OUTPUT.getAbsolutePath() + " not found"); } catch (IOException e) { throw new PicardException("Can't write to or close output file " + OUTPUT.getAbsolutePath()); } catch (IllegalArgumentException e) { OUTPUT.delete(); throw new PicardException(e.getMessage()); } return 0; }

Target:
protected int doWork() { int sequencesWritten = 0; if (OUTPUT.exists()) { throw new PicardException(OUTPUT.getAbsolutePath() + " already exists. Delete this file and try again, or specify a different output file."); } final Map<String, Set<String>> aliasesByContig = loadContigAliasesMap(); try (BufferedWriter writer = makeWriter()) { final Iterable<SAMSequenceRecord> samSequenceRecordIterable = getSamSequenceRecordsIterable(); SAMSequenceDictionaryCodec samDictCodec = new SAMSequenceDictionaryCodec(writer); samDictCodec.encodeHeaderLine(false); for (SAMSequenceRecord samSequenceRecord : samSequenceRecordIterable) { final Set<String> aliases = aliasesByContig.get(samSequenceRecord.getSequenceName()); if (aliases != null) { samSequenceRecord.setAttribute(AN_ATTRIBUTE, String.join(",", aliases)); } samDictCodec.encodeSequenceRecord(samSequenceRecord); if (++sequencesWritten >= NUM_SEQUENCES) { break; } } } catch (FileNotFoundException e) { throw new PicardException("File " + OUTPUT.getAbsolutePath() + " not found"); } catch (IOException e) { throw new PicardException("Can't write to or close output file " + OUTPUT.getAbsolutePath()); } catch (IllegalArgumentException e) { OUTPUT.delete(); throw new PicardException("Unknown problem. Partial dictionary file was deleted.", e); } return 0; }
Source:
public Object getRootObject() { return new SecurityExpressionRoot(SecurityContextHolder.getContext().getAuthentication()) {}; }

Target:
public SecurityExpressionRoot getRootObject() { return new SecurityExpressionRoot(SecurityContextHolder.getContext().getAuthentication()) {}; }
Source:
public List<DeactivatedBeneficiary> findDeactivatedBeneficiariesOtherThanManualDeactivation(String externalId) { try { List<DeactivatedBeneficiary> deactivatedBeneficiaryWithSelectDeactivationReasons = new ArrayList<>(); List<DeactivatedBeneficiary> deactivatedBeneficiaries = deactivatedBeneficiaryDataService.findByExternalId(externalId); if (deactivatedBeneficiaries != null && deactivatedBeneficiaries.size() != 0) { for (DeactivatedBeneficiary deactivatedBeneficiary : deactivatedBeneficiaries ) { if (!DeactivationReason.LOW_LISTENERSHIP.equals(deactivatedBeneficiary.getDeactivationReason()) && !DeactivationReason.WEEKLY_CALLS_NOT_ANSWERED.equals(deactivatedBeneficiary.getDeactivationReason())) { deactivatedBeneficiaryWithSelectDeactivationReasons.add(deactivatedBeneficiary); } } } return deactivatedBeneficiaryWithSelectDeactivationReasons; } catch (ConstraintViolationException e) { LOGGER.debug("List of constraints: {}", e.getConstraintViolations()); throw e; } }

Target:
public List<DeactivatedBeneficiary> findDeactivatedBeneficiariesOtherThanManualDeactivation(String externalId) { try { List<DeactivatedBeneficiary> deactivatedBeneficiaryWithSelectDeactivationReasons = new ArrayList<>(); List<DeactivatedBeneficiary> deactivatedBeneficiaries = deactivatedBeneficiaryDataService.findByExternalId(externalId); if (deactivatedBeneficiaries != null && deactivatedBeneficiaries.size() != 0) { for (DeactivatedBeneficiary deactivatedBeneficiary : deactivatedBeneficiaries ) { if (!DeactivationReason.LOW_LISTENERSHIP.equals(deactivatedBeneficiary.getDeactivationReason()) && !DeactivationReason.WEEKLY_CALLS_NOT_ANSWERED.equals(deactivatedBeneficiary.getDeactivationReason())) { deactivatedBeneficiaryWithSelectDeactivationReasons.add(deactivatedBeneficiary); } } } return deactivatedBeneficiaryWithSelectDeactivationReasons; } catch (ConstraintViolationException e) { LOGGER.error("List of constraints: {}", e.getConstraintViolations()); throw e; } }
Source:
private static <C, R> R processClassHierarchy(C context, int[] aggregateIndex, Class<?> source, AnnotationsProcessor<C, R> processor, @Nullable BiPredicate<C, Class<?>> classFilter, boolean includeInterfaces, boolean includeEnclosing) { R result = processor.doWithAggregate(context, aggregateIndex[0]); if (result != null) { return result; } if (hasPlainJavaAnnotationsOnly(source)) { return null; } Annotation[] annotations = getDeclaredAnnotations(context, source, classFilter, false); result = processor.doWithAnnotations(context, aggregateIndex[0], source, annotations); if (result != null) { return result; } aggregateIndex[0]++; if (includeInterfaces) { for (Class<?> interfaceType : source.getInterfaces()) { R interfacesResult = processClassHierarchy(context, aggregateIndex, interfaceType, processor, classFilter, true, includeEnclosing); if (interfacesResult != null) { return interfacesResult; } } } Class<?> superclass = source.getSuperclass(); if (superclass != Object.class && superclass != null) { R superclassResult = processClassHierarchy(context, aggregateIndex, superclass, processor, classFilter, includeInterfaces, includeEnclosing); if (superclassResult != null) { return superclassResult; } } Class<?> enclosingClass = source.getEnclosingClass(); if (includeEnclosing && enclosingClass != null) { R enclosingResult = processClassHierarchy(context, aggregateIndex, enclosingClass, processor, classFilter, includeInterfaces, true); return enclosingResult; } return null; }

Target:
private static <C, R> R processClassHierarchy(C context, int[] aggregateIndex, Class<?> source, AnnotationsProcessor<C, R> processor, @Nullable BiPredicate<C, Class<?>> classFilter, boolean includeInterfaces, boolean includeEnclosing) { R result = processor.doWithAggregate(context, aggregateIndex[0]); if (result != null) { return result; } if (hasPlainJavaAnnotationsOnly(source)) { return null; } Annotation[] annotations = getDeclaredAnnotations(context, source, classFilter, false); result = processor.doWithAnnotations(context, aggregateIndex[0], source, annotations); if (result != null) { return result; } aggregateIndex[0]++; if (includeInterfaces) { for (Class<?> interfaceType : source.getInterfaces()) { R interfacesResult = processClassHierarchy(context, aggregateIndex, interfaceType, processor, classFilter, true, includeEnclosing); if (interfacesResult != null) { return interfacesResult; } } } Class<?> superclass = source.getSuperclass(); if (superclass != Object.class && superclass != null) { R superclassResult = processClassHierarchy(context, aggregateIndex, superclass, processor, classFilter, includeInterfaces, includeEnclosing); if (superclassResult != null) { return superclassResult; } } Class<?> enclosingClass = source.getEnclosingClass(); if (includeEnclosing && enclosingClass != null) { R enclosingResult = processClassHierarchy(context, aggregateIndex, enclosingClass, processor, classFilter, includeInterfaces, true); if (enclosingResult != null) { return enclosingResult; } } return null; }
Source:
public AutobatchingLeadershipObserverFactory( DisruptorAutobatcher<Map.Entry<Client, LeadershipEvent>, Void> leadershipEventProcessor) { this.leadershipEventProcessor = leadershipEventProcessor; }

Target:
private AutobatchingLeadershipObserverFactory( DisruptorAutobatcher<Map.Entry<Client, LeadershipEvent>, Void> leadershipEventProcessor) { this.leadershipEventProcessor = leadershipEventProcessor; }
Source:
public EnumTemperature getTemperature() { return EnumTemperature.getFromValue(ForestryAPI.climateManager.getTemperature(worldObj, pos)); }

Target:
public EnumTemperature getTemperature() { return EnumTemperature.getFromBiome(worldObj.getBiome(pos), worldObj, pos); }
Source:
public boolean remove(Object o) { return innerList.remove(o); }

Target:
public boolean remove(Object o) { boolean remove = innerList.remove(o); if (o != null && o instanceof Node) ((Node) o).setParentNode(null); return remove; }
Source:
private HiveShellField loadScriptUnderTest(Object testCaseInstance, HiveShellBuilder hiveShellBuilder) { try { Set<Field> fields = ReflectionUtils.getAllFields(testCaseInstance.getClass(), withAnnotation(HiveSQL.class)); Preconditions.checkState(fields.size() == 1, "Exact one field should to be annotated with @HiveSQL"); Field field = fields.iterator().next(); HiveSQL annotation = field.getAnnotation(HiveSQL.class); List<Path> scriptPaths = getScriptPaths(annotation); boolean isAutoStart = annotation.autoStart(); Charset charset = annotation.encoding().equals("") ? Charset.defaultCharset() : Charset.forName(annotation.encoding()); hiveShellBuilder.setScriptsUnderTest(scriptPaths, charset); return new HiveShellField() { @Override public void setShell(HiveShell shell) { ReflectionUtils.setField(testCaseInstance, field.getName(), shell); } @Override public boolean isAutoStart() { return isAutoStart; } }; } catch (Throwable t) { throw new IllegalArgumentException("Failed to init field annotated with @HiveSQL: " + t.getMessage(), t); } }

Target:
private HiveShellField loadScriptUnderTest(Object testCaseInstance, HiveShellBuilder hiveShellBuilder) { try { Set<Field> fields = ReflectionUtils.getAllFields(testCaseInstance.getClass(), withAnnotation(HiveSQL.class)); Preconditions.checkState(fields.size() == 1, "Exact one field should to be annotated with @HiveSQL"); Field field = fields.iterator().next(); HiveSQL annotation = field.getAnnotation(HiveSQL.class); List<Path> scriptPaths = getScriptPaths(annotation); Charset charset = annotation.encoding().equals("") ? Charset.defaultCharset() : Charset.forName(annotation.encoding()); boolean isAutoStart = annotation.autoStart(); hiveShellBuilder.setScriptsUnderTest(scriptPaths, charset); return new HiveShellField() { @Override public void setShell(HiveShell shell) { ReflectionUtils.setField(testCaseInstance, field.getName(), shell); } @Override public boolean isAutoStart() { return isAutoStart; } }; } catch (Throwable t) { throw new IllegalArgumentException("Failed to init field annotated with @HiveSQL: " + t.getMessage(), t); } }
Source:
private String computeDynamicValue(AbstractBuild build, String parameterizedValue) throws IllegalStateException, InterruptedException, IOException { String value = parameterizedValue; while (value != null && value.contains("${")) { int start = value.indexOf("${", 0); int end = value.indexOf("}", start); String parameter = value.substring(start + 2, end); String parameterValue = build.getEnvironment(TaskListener.NULL).get(parameter); if (parameterValue == null) { throw new IllegalStateException(parameter); } value = value.substring(0, start) + parameterValue + (value.length() > end + 1 ? value.substring(end + 1) : ""); } logger.fine("oldValue = " + parameterizedValue + "; newValue = " + value); return value; }

Target:
private String computeDynamicValue(AbstractBuild build, String parameterizedValue) throws IllegalStateException, InterruptedException, IOException { final EnvVars envVars = build.getEnvironment(TaskListener.NULL); final VariableResolver<String> environmentVariables = new VariableResolver<String>() { public String resolve(String name) { return envVars.get(name); } }; final BuildVariableResolver buildVariables = new BuildVariableResolver(build.getProject()); @SuppressWarnings("unchecked") final Union<String> bothVariables = new VariableResolver.Union<String>(buildVariables, environmentVariables); String value = Util.replaceMacro(parameterizedValue, bothVariables); logger.fine("oldValue = " + parameterizedValue + "; newValue = " + value); return value; }
Source:
public static void createAndFillFileForCompare(String filePath, InputStream inputStream) { FileOutputStream outputStream = createFileForCompare(filePath); try { int read = 0; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); outputStream.flush(); } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { Thread.sleep(500); outputStream.close(); outputStream = null; } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } }

Target:
public static void createAndFillFileForCompare(String filePath, InputStream inputStream) { FileOutputStream outputStream = createFileForCompare(filePath); try { int read = 0; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Source:
default Range<Long> versionRange() { Optional<Long> firstVersion = timestampMapping() .values() .stream() .map(LockWatchVersion::version) .min(Long::compareTo); Optional<Long> lastVersion = timestampMapping() .values() .stream() .map(LockWatchVersion::version) .max(Long::compareTo); Preconditions.checkState(firstVersion.isPresent() && lastVersion.isPresent(), "Cannot compute timestamp mapping for empty map of timestamps"); return Range.closed(firstVersion.get(), lastVersion.get()); }

Target:
default Range<Long> versionRange() { LongSummaryStatistics summary = timestampMapping().values().stream().mapToLong( LockWatchVersion::version).summaryStatistics(); return Range.closed(summary.getMin(), summary.getMax()); }
Source:
public void onEntityFieldChange( String newValue ) { if ( getDataObject() != null ) { final Boolean doAdd = Boolean.TRUE.toString().equals( newValue ); if ( doAdd ) { if ( !hasIdField( getDataObject() ) ) { List<ObjectProperty> configurableFields = persistenceConfigurableFields( getDataObject() ); String message = buildOnSetPersistableRefactoringMessage( false, configurableFields ); view.showYesNoCancelPopup( CommonConstants.INSTANCE.Warning(), message, new Command() { @Override public void execute() { doEntityFieldChange( doAdd, true ); } }, Constants.INSTANCE.persistence_domain_objectEditor_add_identifier_action(), ButtonType.PRIMARY, new Command() { @Override public void execute() { doEntityFieldChange( doAdd, false ); } }, Constants.INSTANCE.persistence_domain_objectEditor_dont_add_identifier_action(), ButtonType.DANGER, new Command() { @Override public void execute() { updateEntityField( null ); loadPropertyEditor(); } }, CommonConstants.INSTANCE.Cancel(), ButtonType.DEFAULT ); } else { doEntityFieldChange( doAdd, false ); } } else { doEntityFieldChange( doAdd, false ); } } }

Target:
public void onEntityFieldChange( String newValue ) { if ( getDataObject() != null ) { final Boolean doAdd = Boolean.parseBoolean( newValue ); if ( doAdd ) { if ( !hasIdField( getDataObject() ) ) { List<ObjectProperty> configurableFields = persistenceConfigurableFields( getDataObject() ); String message = buildOnSetPersistableRefactoringMessage( false, configurableFields ); view.showYesNoCancelPopup( CommonConstants.INSTANCE.Warning(), message, new Command() { @Override public void execute() { doEntityFieldChange( doAdd, true ); } }, Constants.INSTANCE.persistence_domain_objectEditor_add_identifier_action(), ButtonType.PRIMARY, new Command() { @Override public void execute() { doEntityFieldChange( doAdd, false ); } }, Constants.INSTANCE.persistence_domain_objectEditor_dont_add_identifier_action(), ButtonType.DANGER, new Command() { @Override public void execute() { updateEntityField( null ); loadPropertyEditor(); } }, CommonConstants.INSTANCE.Cancel(), ButtonType.DEFAULT ); } else { doEntityFieldChange( doAdd, false ); } } else { doEntityFieldChange( doAdd, false ); } } }
Source:
public static Optional<WeightedSerializableObject<EntitySnapshot>> getNextSnapshot(MobSpawnerBaseLogic logic) { int weight = 1; if(logic.getRandomEntity() != null) { weight = logic.getRandomEntity().itemWeight; } Class<? extends Entity> entityClass = EntityList.stringToClassMapping.getOrDefault(logic.getEntityNameToSpawn(), EntityPig.class); EntityType type = EntityTypeRegistryModule.getInstance().getForClass(entityClass); Optional<Entity> nextEntity = createEntity(type, logic.getSpawnerWorld()); if(nextEntity.isPresent()) { logic.spawnNewEntity(nextEntity.get(), false); return Optional.of(new WeightedSerializableObject<>(new SpongeEntitySnapshotBuilder().from(nextEntity.get()).build(), weight)); } return Optional.empty(); }

Target:
public static Optional<WeightedSerializableObject<EntitySnapshot>> getNextSnapshot(MobSpawnerBaseLogic logic) { int weight = 1; if(logic.getRandomEntity() != null) { weight = logic.getRandomEntity().itemWeight; } EntityType type = getType(logic.getEntityNameToSpawn()).orElse(EntityTypes.PIG); NBTTagCompound data = logic.getRandomEntity() == null ? null : logic.getRandomEntity().nbtData; Optional<Entity> nextEntity = createEntity((World) logic.getSpawnerWorld(), type, data); if(nextEntity.isPresent()) { return Optional.of(new WeightedSerializableObject<>(EntitySnapshot.builder().from(nextEntity.get()).build(), weight)); } return Optional.empty(); }
Source:
public void initialise(String otherStatus, T value) { PollResponse<String> inProgressPollResponse = new PollResponse<>(PollResponse.OperationStatus.fromString("CUSTOM_OTHER_STATUS"), "my custom response"); END: com.azure.core.util.polling.pollresponse.custom.status }

Target:
public void initialise(String otherStatus, T value) { PollResponse<String> inProgressPollResponse = new PollResponse<>(OperationStatus.fromString("CUSTOM_OTHER_STATUS"), "my custom response"); END: com.azure.core.util.polling.pollresponse.custom.status }
Source:
public void disconnect(ChannelHandlerContext ctx, ChannelPromise future) throws Exception { if (requestInProgress) { requestInProgress = false; logDurations(); logMessage.append(" : Channel disconnected while request in progress."); publicAccessLogger.logError(logMessage.toString()); } super.disconnect(ctx, future); }

Target:
public void disconnect(ChannelHandlerContext ctx, ChannelPromise future) throws Exception { if (request != null) { logError(" : Channel disconnected while request in progress."); } super.disconnect(ctx, future); }
Source:
private boolean touch(QueryHistoryMetrics entry) { ConcurrentLinkedDeque8.Node<QueryHistoryMetrics> node = entry.link(); if (node == null) { node = evictionQueue.offerLastx(entry); if (!entry.setLinkIfAbsent(node)) { removeLink(node); return false; } else if (qryMetrics.get(entry.key()) != entry) { removeLink(node); return false; } return true; } else if (removeLink(node)) { ConcurrentLinkedDeque8.Node<QueryHistoryMetrics> newNode = evictionQueue.offerLastx(entry); if (!entry.replaceLink(node, newNode)) { removeLink(newNode); return false; } else if (qryMetrics.get(entry.key()) != entry) { removeLink(node); return false; } } return false; }

Target:
private boolean touch(QueryHistoryMetrics entry) { ConcurrentLinkedDeque8.Node<QueryHistoryMetrics> node = entry.link(); if (node == null) { node = evictionQueue.offerLastx(entry); if (!entry.replaceLink(null, node)) { removeLink(node); return false; } if (node.item() == null) { entry.replaceLink(node, null); return false; } return true; } else if (removeLink(node)) { ConcurrentLinkedDeque8.Node<QueryHistoryMetrics> newNode = evictionQueue.offerLastx(entry); if (!entry.replaceLink(node, newNode)) { removeLink(newNode); } } return false; }
Source:
private List<BootLogic> loadBootLogics(ClassLoader cl) { List<BootLogic> r = new ArrayList<>(); for (BootLogic b : ServiceLoader.load(BootLogic.class,cl)) { r.add(b); } Collections.sort(r, new Comparator<BootLogic>() { @Override public int compare(BootLogic o1, BootLogic o2) { return -Float.compare(o1.ordinal(),o2.ordinal()); } }); if (r.isEmpty()) { throw new IllegalStateException("No @BootLogic found. Aborting"); } return r; }

Target:
private List<BootLogic> loadBootLogics(ClassLoader cl) { List<BootLogic> r = new ArrayList<>(); for (BootLogic b : ServiceLoader.load(BootLogic.class,cl)) { r.add(b); } r.sort((o1, o2) -> -Float.compare(o1.ordinal(), o2.ordinal())); if (r.isEmpty()) { throw new IllegalStateException("No BootLogic found. Aborting"); } return r; }