auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<Pair<Guid, Integer>> score(Cluster cluster, List<VDS> hosts, VM vm, Map<String, String> parameters) { if (!vm.isDown()) { return Collections.emptyList(); } List<Pair<Guid, Integer>> weights = new ArrayList<>(); Set<Guid> preferredHosts = new HashSet<>(vm.getDedicatedVmForVdsList()); boolean isAnyPreferredHost = preferredHosts.size() > 0; for (VDS host: hosts) { if (isAnyPreferredHost && !preferredHosts.contains(host.getId())) { <START> log.info("Penalizing <END> host '{}' because it is not preferred.", host.getName()); weights.add(new Pair<Guid, Integer>(host.getId(), 10000)); } else { weights.add(new Pair<Guid, Integer>(host.getId(), 0)); } } return weights; }</code><technical_language>I change level debug. other weight policy units debug levels</technical_language>

Target:
public List<Pair<Guid, Integer>> score(Cluster cluster, List<VDS> hosts, VM vm, Map<String, String> parameters) { if (!vm.isDown()) { return Collections.emptyList(); } List<Pair<Guid, Integer>> weights = new ArrayList<>(); Set<Guid> preferredHosts = new HashSet<>(vm.getDedicatedVmForVdsList()); boolean isAnyPreferredHost = preferredHosts.size() > 0; for (VDS host: hosts) { if (isAnyPreferredHost && !preferredHosts.contains(host.getId())) { log.debug("Penalizing host '{}' because it is not preferred.", host.getName()); weights.add(new Pair<Guid, Integer>(host.getId(), 10000)); } else { weights.add(new Pair<Guid, Integer>(host.getId(), 0)); } } return weights; }
Source:
<code>public void cleanUp() { try { this.featuresCache.close(); <START> } catch (IOException e) { <END> LOG.error("Could not close features cache", e); } }</code><technical_language>final ![200x200](<LINK_0></technical_language>

Target:
public void cleanUp() { try { this.featuresCache.close(); } catch (final IOException e) { LOG.error("Could not close features cache", e); } }
Source:
<code>public static void existsBranch(final Git git, final String branch) { if (git.getRef(branch) == null) { <START> throw new GitException(String.format("Branch <<%s>> does not exists", <END> branch)); } }</code><technical_language>a small note - "exist" :)</technical_language>

Target:
public static void existsBranch(final Git git, final String branch) { if (git.getRef(branch) == null) { throw new GitException(String.format("Branch <<%s>> does not exist", branch)); } }
Source:
<code>@Override public Object instantiateItem(ViewGroup container, int position) { <START> LayoutInflater inflater = LayoutInflater.from(context); <END> DescriptionEditTutorialPage tutorialPage = DescriptionEditTutorialPage.of(position); ViewGroup layout = (ViewGroup) inflater.inflate(tutorialPage.getLayout(), container, false); container.addView(layout); return layout; }</code><technical_language>container.getContext() instead of a member variable</technical_language>

Target:
@Override public Object instantiateItem(ViewGroup container, int position) { LayoutInflater inflater = LayoutInflater.from(container.getContext()); DescriptionEditTutorialPage tutorialPage = DescriptionEditTutorialPage.of(position); View layout = inflater.inflate(tutorialPage.getLayout(), container, false); ButterKnife.bind(layout); container.addView(layout); ((DescriptionEditTutorialView) layout).setCallback(cb); return layout; }
Source:
<code><START> public static String getServicePrincipal(String serviceName) <END> throws UnknownHostException { requireNonNull(serviceName, "serviceName is null"); String fqdn = InetAddress.getLocalHost().getCanonicalHostName(); checkState(!fqdn.equalsIgnoreCase("localhost"), "Fully qualified host name for localhost is not retrieved"); return String.format("%s/%s", serviceName, fqdn.toLowerCase(Locale.US)); }</code><technical_language>Remove this server impl</technical_language>

Target:
public static String getServicePrincipal(String serviceName) throws UnknownHostException { requireNonNull(serviceName, "serviceName is null"); String fqdn = InetAddress.getLocalHost().getCanonicalHostName(); checkState(!fqdn.equalsIgnoreCase("localhost"), "Fully qualified host name for localhost is not retrieved"); return format("%s/%s", serviceName, fqdn.toLowerCase(Locale.US)); }
Source:
<code>public void testPair() { String first = "abcdef"; Long second = 23L; Pair<String, Long> pairOne = new Pair<>(first, second); Pair<String, Long> pairTwo = new Pair<>(first, second); Pair<String, Long> pairThree = new Pair<>(first, second + 1); Pair<Long, String> pairFour = new Pair<>(second, first); assertEquals("Invalid first item.", first, pairOne.getFirst()); assertEquals("Invalid second item.", second, pairOne.getSecond()); assertEquals("These pairs should be equivalent", pairTwo, pairOne); assertFalse("pairOne and pairThree should not be equal", pairOne.equals(pairThree)); <START> assertFalse("pairOne and pairFour should not be equal", pairOne.equals(pairFour)); <END> assertEquals("Hashcodes should be the same", pairOne.hashCode(), pairTwo.hashCode()); assertEquals("Pair{first=" + first + ", second=" + second + "}", pairOne.toString()); }</code><technical_language>hashCodes unequal</technical_language>

Target:
public void testPair() { String first = "abcdef"; Long second = 23L; Pair<String, Long> pairOne = new Pair<>(first, second); Pair<String, Long> pairTwo = new Pair<>(first, second); Pair<String, Long> pairThree = new Pair<>(first, second + 1); Pair<String, Long> pairFour = new Pair<>(first + "extra", second); Pair<Long, String> pairFive = new Pair<>(second, first); assertEquals("Invalid first item.", first, pairOne.getFirst()); assertEquals("Invalid second item.", second, pairOne.getSecond()); assertEquals("These pairs should be equivalent", pairTwo, pairOne); assertFalse("pairOne and pairThree should not be equal", pairOne.equals(pairThree)); assertFalse("pairOne and pairFour should not be equal", pairOne.equals(pairFour)); assertFalse("pairOne and pairFive should not be equal", pairOne.equals(pairFive)); assertEquals("Hashcodes should be the same", pairOne.hashCode(), pairTwo.hashCode()); assertEquals("Pair{first=" + first + ", second=" + second + "}", pairOne.toString()); }
Source:
<code>public void commonDefaultDropsHandling(CreateBlockDropsEvent event, EntityRef entity, Vector3i location, Block block) { BlockDamageModifierComponent blockDamageModifierComponent = event.getDamageType().getComponent(BlockDamageModifierComponent.class); float chanceOfBlockDrop = 1; if (blockDamageModifierComponent != null) { chanceOfBlockDrop = 1 - blockDamageModifierComponent.blockAnnihilationChance; } if (random.nextFloat() < chanceOfBlockDrop) { EntityRef item = blockItemFactory.newInstance(block.getBlockFamily(), entity); entity.send(new OnBlockToItem(item)); if (shouldDropToWorld(event, block, blockDamageModifierComponent, item)) { float impulsePower; if (blockDamageModifierComponent != null) { impulsePower = blockDamageModifierComponent.impulsePower; } else { impulsePower = 0; <START> } <END> processDropping(item, location, impulsePower); } } }</code><technical_language>I feel this more readable if else removed impulsePower initialised 0 time is declared</technical_language>

Target:
public void commonDefaultDropsHandling(CreateBlockDropsEvent event, EntityRef entity, Vector3i location, Block block) { BlockDamageModifierComponent blockDamageModifierComponent = event.getDamageType().getComponent(BlockDamageModifierComponent.class); float chanceOfBlockDrop = 1; if (blockDamageModifierComponent != null) { chanceOfBlockDrop = 1 - blockDamageModifierComponent.blockAnnihilationChance; } if (random.nextFloat() < chanceOfBlockDrop) { EntityRef item = blockItemFactory.newInstance(block.getBlockFamily(), entity); entity.send(new OnBlockToItem(item)); if (shouldDropToWorld(event, block, blockDamageModifierComponent, item)) { float impulsePower = 0; if (blockDamageModifierComponent != null) { impulsePower = blockDamageModifierComponent.impulsePower; } processDropping(item, location, impulsePower); } } }
Source:
<code>public static SqlDataTypeSpec convertTypeToSpec(RelDataType type, String charSetName, int maxPrecision) { SqlTypeName typeName = type.getSqlTypeName(); assert typeName != null; SqlTypeNameSpec typeNameSpec; <START> if (isAtomic(type)) { <END> int precision = typeName.allowsPrec() ? type.getPrecision() : -1; if (maxPrecision > 0 && precision > maxPrecision) { precision = maxPrecision; } int scale = typeName.allowsScale() ? type.getScale() : -1; typeNameSpec = new SqlBasicTypeNameSpec( typeName, precision, scale, charSetName, SqlParserPos.ZERO); } else if (isCollection(type)) { typeNameSpec = new SqlCollectionTypeNameSpec( convertTypeToSpec(type.getComponentType()).getTypeNameSpec(), typeName, SqlParserPos.ZERO); } else if (isRow(type)) { RelRecordType recordType = (RelRecordType) type; List<RelDataTypeField> fields = recordType.getFieldList(); List<SqlIdentifier> fieldNames = fields.stream() .map(f -> new SqlIdentifier(f.getName(), SqlParserPos.ZERO)) .collect(Collectors.toList()); List<SqlDataTypeSpec> fieldTypes = fields.stream() .map(f -> convertTypeToSpec(f.getType())) .collect(Collectors.toList()); typeNameSpec = new SqlRowTypeNameSpec(SqlParserPos.ZERO, fieldNames, fieldTypes); } else { throw new UnsupportedOperationException( "Unsupported type when convertTypeToSpec: " + typeName); } return new SqlDataTypeSpec(typeNameSpec, SqlParserPos.ZERO); }</code><technical_language>If possible, typeNameSpec final</technical_language>

Target:
public static SqlDataTypeSpec convertTypeToSpec(RelDataType type, String charSetName, int maxPrecision) { SqlTypeName typeName = type.getSqlTypeName(); assert typeName != null; final SqlTypeNameSpec typeNameSpec; if (isAtomic(type)) { int precision = typeName.allowsPrec() ? type.getPrecision() : -1; if (maxPrecision > 0 && precision > maxPrecision) { precision = maxPrecision; } int scale = typeName.allowsScale() ? type.getScale() : -1; typeNameSpec = new SqlBasicTypeNameSpec( typeName, precision, scale, charSetName, SqlParserPos.ZERO); } else if (isCollection(type)) { typeNameSpec = new SqlCollectionTypeNameSpec( convertTypeToSpec(type.getComponentType()).getTypeNameSpec(), typeName, SqlParserPos.ZERO); } else if (isRow(type)) { RelRecordType recordType = (RelRecordType) type; List<RelDataTypeField> fields = recordType.getFieldList(); List<SqlIdentifier> fieldNames = fields.stream() .map(f -> new SqlIdentifier(f.getName(), SqlParserPos.ZERO)) .collect(Collectors.toList()); List<SqlDataTypeSpec> fieldTypes = fields.stream() .map(f -> convertTypeToSpec(f.getType())) .collect(Collectors.toList()); typeNameSpec = new SqlRowTypeNameSpec(SqlParserPos.ZERO, fieldNames, fieldTypes); } else { throw new UnsupportedOperationException( "Unsupported type when convertTypeToSpec: " + typeName); } return new SqlDataTypeSpec(typeNameSpec, SqlParserPos.ZERO); }
Source:
<code><START> private boolean contributeObjectActionsOld(IMenuManager manager) { <END> Class<ObjectActionContributorManager> cl = ObjectActionContributorManager.class; Method meth; try { meth = cl.getDeclaredMethod("contributeObjectActions", IWorkbenchPart.class, IMenuManager.class, ISelectionProvider.class); if (meth != null) { meth.invoke(ObjectActionContributorManager.getManager(), null, manager, activeTaskSelectionProvider); return true; } } catch (SecurityException e) { } catch (NoSuchMethodException e) { return false; } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return false; }</code><technical_language>a method org.apache.commons.lang.reflect.MethodUtils here</technical_language>

Target:
private boolean contributeObjectActionsOld(IMenuManager manager) { try { DummyPart part = new DummyPart(); MethodUtils.invokeExactMethod(ObjectActionContributorManager.getManager(), "contributeObjectActions", new Object[] { part, manager, activeTaskSelectionProvider }); } catch (NoSuchMethodException e) { return false; } catch (IllegalAccessException e) { return false; } catch (InvocationTargetException e) { return false; } return true; }
Source:
<code>public static void testMerge(MergeOp.Factory opFactory, Change change) { try { opFactory.create(change.getDest()).verifyMergeability(change); <START> } catch (Throwable e) { <END> LoggerFactory.getLogger(ChangeUtil.class).error( "Merge test attempt for change " + change.getChangeId() + " failed", e); } }</code><technical_language>enough catch MergeException here</technical_language>

Target:
public static void testMerge(MergeOp.Factory opFactory, Change change) { try { opFactory.create(change.getDest()).verifyMergeability(change); } catch (Throwable e) { log.error("Merge test attempt for change " + change.getChangeId() + " failed", e); } }
Source:
<code>public MatrixTriggerMode getMatrixTriggerMode() { if (matrixTriggerMode == null) { <START> return MatrixTriggerMode.ONLY_CONFIGURATIONS; <END> } else { return matrixTriggerMode; } }</code><technical_language>initialise this getter dumb</technical_language>

Target:
public MatrixTriggerMode getMatrixTriggerMode() { return matrixTriggerMode; }
Source:
<code>public void testBasic() throws IOException, InterruptedException, KeeperException { ZooKeeper zk = null; try { zk = createClient(new CountdownWatcher(), hostPort); zk.addPersistentWatch("/a/b", persistentWatcher); internalTestBasic(zk); } finally { if (zk != null) { <START> zk.close(); <END> } } }</code><technical_language>ZooKeeper supports try-with-resources this code cleaner</technical_language>

Target:
public void testBasic() throws IOException, InterruptedException, KeeperException { try ( ZooKeeper zk = createClient(new CountdownWatcher(), hostPort) ) { zk.addPersistentWatch("/a/b", persistentWatcher, false); internalTestBasic(zk); } }
Source:
<code>public void ensureServerUrlIsPassed() { EventBundle eventBundle = new EventBundleImpl(); eventBundle.push(new EventImpl("dummyEvent", buildCtx("johndoe"))); SegmentIOAsyncListener listener = new SegmentIOAsyncListener(); listener.handleEvent(eventBundle); assertEquals(1, testData.size()); assertEquals("unknown server url", testData.get(0).get("url")); <START> System.setProperty("nuxeo.url", "<LINK_1>"); <END> listener.handleEvent(eventBundle); assertEquals(2, testData.size()); assertEquals("<LINK_1>", testData.get(1).get("url")); }</code><technical_language>WithFrameworkProperty instead :) Sample here: <LINK_0></technical_language>

Target:
public void ensureServerUrlIsPassed() { EventBundle eventBundle = new EventBundleImpl(); eventBundle.push(new EventImpl("dummyEvent", buildCtx("johndoe"))); SegmentIOAsyncListener listener = new SegmentIOAsyncListener(); listener.handleEvent(eventBundle); assertEquals(1, testData.size()); assertEquals("<LINK_1>", testData.get(0).get("url")); }
Source:
<code><START> public NpmPackageGenerator(Path basedir){ <END> super(); this.basePath = basedir; }</code><technical_language>Cosmetic: Please, follow project's coding convention braces new lines. Thanks! :)</technical_language>

Target:
public NpmPackageGenerator(Path basedir) { this.basePath = basedir; }
Source:
<code>private static TagObject from(TagModel model, boolean includeChildren) { TagObject result = JavaScriptObject.createObject().cast(); result.setValueAsString("description", model.getDescription().getEntity()); result.setValueAsString("name", model.getName().getEntity()); result.setValueAsBoolean("selected", model.getSelection()); if (includeChildren) { JsArray<TagObject> children = JavaScriptObject.createArray().cast(); for (TagModel child : model.getChildren()) { children.push(TagObject.from(child, <START> includeChildren)); <END> } result.setValueAsJavaScriptObject("children", children); } return result; }</code><technical_language>this simply true a big deal</technical_language>

Target:
private static TagObject from(TagModel model, boolean includeChildren) { TagObject result = JavaScriptObject.createObject().cast(); result.setValueAsString("description", model.getDescription().getEntity()); result.setValueAsString("name", model.getName().getEntity()); result.setValueAsBoolean("selected", model.getSelection()); if (includeChildren) { JsArray<TagObject> children = JavaScriptObject.createArray().cast(); for (TagModel child : model.getChildren()) { children.push(TagObject.from(child, true)); } result.setValueAsJavaScriptObject("children", children); } return result; }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mAddressSearchView = (SearchView) findViewById(R.id.addressSearchView); mAddressSearchView.setIconified(false); mAddressSearchView.setFocusable(false); mAddressSearchView.setQueryHint(getResources().getString(R.string.address_search_hint)); BitmapDrawable pinDrawable = (BitmapDrawable) ContextCompat.getDrawable(this, R.drawable.pin); try { mPinSourceSymbol = PictureMarkerSymbol.createAsync(pinDrawable).get(); } catch (InterruptedException | ExecutionException e) { Log.e(TAG, "Picture Marker Symbol error: " + e.getMessage()); Toast.makeText(getApplicationContext(), "Failed to load pin drawable.", Toast.LENGTH_LONG).show(); } mPinSourceSymbol.setWidth(19f); mPinSourceSymbol.setHeight(72f); mLocatorTask = new LocatorTask("<LINK_0>"); mMapView = (MapView) findViewById(R.id.mapView); <START> mMapView.setWrapAroundMode(WrapAroundMode.DISABLED); <END> final ArcGISMap map = new ArcGISMap(Basemap.createTopographic()); mMapView.setMap(map); mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mMapView) { @Override public boolean onSingleTapConfirmed(MotionEvent motionEvent) { showCallout(motionEvent); return true; } }); mGraphicsOverlay = new GraphicsOverlay(); setupAddressSearchView(); }</code><technical_language>disabling wraparound? consider keeping default wraparound settings</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mAddressSearchView = (SearchView) findViewById(R.id.addressSearchView); mAddressSearchView.setIconified(false); mAddressSearchView.setFocusable(false); mAddressSearchView.setQueryHint(getResources().getString(R.string.address_search_hint)); BitmapDrawable pinDrawable = (BitmapDrawable) ContextCompat.getDrawable(this, R.drawable.pin); try { mPinSourceSymbol = PictureMarkerSymbol.createAsync(pinDrawable).get(); } catch (InterruptedException | ExecutionException e) { Log.e(TAG, "Picture Marker Symbol error: " + e.getMessage()); Toast.makeText(getApplicationContext(), "Failed to load pin drawable.", Toast.LENGTH_LONG).show(); } mPinSourceSymbol.setWidth(19f); mPinSourceSymbol.setHeight(72f); mLocatorTask = new LocatorTask("<LINK_0>"); mMapView = (MapView) findViewById(R.id.mapView); final ArcGISMap map = new ArcGISMap(Basemap.createStreetsVector()); mMapView.setMap(map); mMapView.setViewpoint(new Viewpoint(40, -100, 100000000)); mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mMapView) { @Override public boolean onSingleTapConfirmed(MotionEvent motionEvent) { identifyGraphic(motionEvent); return true; } }); mGraphicsOverlay = new GraphicsOverlay(); setupAddressSearchView(); }
Source:
<code><START> private static String stripQuotes(String text) { <END> if (text == null || text.isEmpty()) { return text; } if (text.startsWith("\"")) { text = text.substring(1); } if (text.endsWith("\"")) { text = text.substring(0, text.length() - 1); } return text; }</code><technical_language>I this method deserves protected tested</technical_language>

Target:
static String stripQuotes(String text) { if (text == null || text.isEmpty()) { return text; } if (text.startsWith("\"")) { text = text.substring(1); } if (text.endsWith("\"")) { text = text.substring(0, text.length() - 1); } return text; }
Source:
<code>public CompletableFuture<FSDataInputStream> build() throws IOException { final Path absF = fixRelativePart(getPath()); OpenFileParameters parameters = new OpenFileParameters(); parameters.setMandatoryKeys(getMandatoryKeys()); parameters.setOptions(getOptions()); parameters.setBufferSize(getBufferSize()); parameters.setStatus(getStatus()); return new FSLinkResolver<CompletableFuture<FSDataInputStream>>() { @Override public CompletableFuture<FSDataInputStream> next( final AbstractFileSystem fs, final Path p) throws IOException { return fs.openFileWithOptions(p, <START> parameters); <END> } }.resolve(FileContext.this, absF); }</code><technical_language>nit: merge previous line longer 80</technical_language>

Target:
public CompletableFuture<FSDataInputStream> build() throws IOException { final Path absF = fixRelativePart(getPath()); OpenFileParameters parameters = new OpenFileParameters() .withMandatoryKeys(getMandatoryKeys()) .withOptions(getOptions()) .withBufferSize(getBufferSize()) .withStatus(getStatus()); return new FSLinkResolver<CompletableFuture<FSDataInputStream>>() { @Override public CompletableFuture<FSDataInputStream> next( final AbstractFileSystem fs, final Path p) throws IOException { return fs.openFileWithOptions(p, parameters); } }.resolve(FileContext.this, absF); }
Source:
<code>public NoSpecialCharactersWithDotValidation() { <START> setExpression(ValidationUtils.NO_SPECIAL_CHARACTERS_WITH_DOT); <END> setMessage(ConstantsManager.getInstance().getConstants().noSpecialCharactersWithDotMsg()); }</code><technical_language>a thought, this is reference UI ValidationUtils, this separation? frontend backend handles regex differently. do say</technical_language>

Target:
public NoSpecialCharactersWithDotValidation() { setExpression("[0-9a-zA-Z-_\\.]+"); setMessage(ConstantsManager.getInstance().getConstants().noSpecialCharactersWithDotMsg()); }
Source:
<code>private void addCloseHandler() { if (UserAgent.isChrome()) { Window.addCloseHandler(event -> workbenchCloseHandler.onWindowClose(workbenchCloseCommand, event)); Window.addWindowClosingHandler(event -> workbenchCloseHandler.onWindowClosing(workbenchClosingCommand, event)); } else { <START> Window.addWindowClosingHandler(event -> workbenchCloseHandler.onWindowClose(workbenchCloseCommand, null)); <END> } }</code><technical_language>is significance of passing null? Personally onWindowClose(..) overloaded single parameter version (rather caller knowing pass a null value). implementation pass null workbenchCloseCommand</technical_language>

Target:
private void addCloseHandler() { if (UserAgent.isChrome()) { setupMessageForUnsavedChanges(); Window.addCloseHandler(event -> workbenchCloseHandler.onWindowClose(workbenchCloseCommand)); } else { Window.addWindowClosingHandler(event -> workbenchCloseHandler.onWindowClose(workbenchCloseCommand)); } }
Source:
<code>private String getCertificateAlias() { <START> return System.getProperty("org.codice.ddf.external.hostname"); <END> }</code><technical_language>I system cert is aliased external hostname</technical_language>

Target:
private String getCertificateAlias() { return System.getProperty("org.codice.ddf.system.hostname"); }
Source:
<code>public GlucoseRanges(Context context) { this.mContext = context; if (!isInUnitTests()) { <START> dB = new DatabaseHandler(mContext); <END> this.preferredRange = dB.getUser(1).getPreferred_range(); if (preferredRange.equals("Custom range")) { this.customMin = dB.getUser(1).getCustom_range_min(); this.customMax = dB.getUser(1).getCustom_range_max(); } } }</code><technical_language>inject DatabasHandler instead of context mock need dirty method isInUnitTest()</technical_language>

Target:
public GlucoseRanges(Context context) { this.mContext = context; dB = new DatabaseHandler(mContext); this.preferredRange = dB.getUser(1).getPreferred_range(); if (preferredRange.equals("Custom range")) { this.customMin = dB.getUser(1).getCustom_range_min(); this.customMax = dB.getUser(1).getCustom_range_max(); } }
Source:
<code>public void testBasicIO() throws Exception { Path path = new Path("/path/to/" + runtime.getMethodName()); assertFalse(fs.exists(path)); try (FSDataOutputStream out = fs.create(path)) { for (int i = 0; i < 100; i++) { out.writeBytes("line-" + i + "\n"); } out.flush(); } assertTrue(fs.exists(path)); <START> File tempFile = new File(newTempDir(runtime.getMethodName()), "test.bin"); <END> tempFile.delete(); Path localDst = new Path(tempFile.getPath()); fs.copyToLocalFile(path, localDst); fs.copyFromLocalFile(localDst, new Path(runtime.getMethodName() + "-copied")); Path dstPath = new Path(runtime.getMethodName() + "-renamed"); fs.rename(path, dstPath); assertFalse(fs.exists(path)); assertTrue(fs.exists(dstPath)); try (BufferedReader reader = new BufferedReader(new InputStreamReader(fs.open(dstPath, 1134)))) { int lineno = 0; String line; while ((line = reader.readLine()) != null) { assertEquals("line-" + lineno, line); ++lineno; } assertEquals(100, lineno); } fs.delete(dstPath, false); assertFalse(fs.exists(dstPath)); }</code><technical_language>this files deleted. new temp dir generate a new directory is deleted. I suggest JUnit temp folder. <LINK_1> <LINK_0></technical_language>

Target:
public void testBasicIO() throws Exception { Path path = new Path("/path/to/" + runtime.getMethodName()); assertFalse(fs.exists(path)); try (FSDataOutputStream out = fs.create(path)) { for (int i = 0; i < 100; i++) { out.writeBytes("line-" + i + "\n"); } out.flush(); } assertTrue(fs.exists(path)); File tempFile = tmpDir.newFile(); Path localDst = new Path(tempFile.getPath()); fs.copyToLocalFile(path, localDst); fs.copyFromLocalFile(localDst, new Path(runtime.getMethodName() + "-copied")); Path dstPath = new Path(runtime.getMethodName() + "-renamed"); fs.rename(path, dstPath); assertFalse(fs.exists(path)); assertTrue(fs.exists(dstPath)); try (BufferedReader reader = new BufferedReader(new InputStreamReader(fs.open(dstPath, 1134)))) { int lineno = 0; String line; while ((line = reader.readLine()) != null) { assertEquals("line-" + lineno, line); ++lineno; } assertEquals(100, lineno); } fs.delete(dstPath, false); assertFalse(fs.exists(dstPath)); }
Source:
<code>public BinaryContent createMetacard( HttpServletRequest httpServletRequest, String transformerParam) throws CatalogException { LOGGER.trace("ENTERING: createMetacard"); InputStream stream = null; String contentType = null; try { Part contentPart = httpServletRequest.getPart(FILE_ATTACHMENT_CONTENT_ID); if (contentPart != null) { if (contentPart.getContentType() != null) { contentType = contentPart.getContentType(); } try { <START> stream = contentPart.getInputStream(); <END> if (stream != null && stream.available() == 0) { stream.reset(); } } catch (IOException e) { LOGGER.info("IOException reading stream from file attachment in multipart body", e); } } else { LOGGER.debug("No file contents attachment found"); } } catch (ServletException | IOException e) { LOGGER.info("No file contents part found: ", e); } return createMetacard(stream, contentType, transformerParam); }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Extract this nested try block a separate method. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public BinaryContent createMetacard( HttpServletRequest httpServletRequest, String transformerParam) throws CatalogServiceException { LOGGER.trace("ENTERING: createMetacard"); InputStream stream = null; String contentType = null; try { Part contentPart = httpServletRequest.getPart(FILE_ATTACHMENT_CONTENT_ID); if (contentPart != null) { if (contentPart.getContentType() != null) { contentType = contentPart.getContentType(); } try { stream = contentPart.getInputStream(); if (stream != null && stream.available() == 0) { stream.reset(); } } catch (IOException e) { LOGGER.info("IOException reading stream from file attachment in multipart body", e); } } else { LOGGER.debug(NO_FILE_CONTENTS_ATT_FOUND); } } catch (ServletException | IOException e) { LOGGER.info("No file contents part found: ", e); } return createMetacard(stream, contentType, transformerParam); }
Source:
<code>public void init() throws FileNotFoundException, IOException, CTFException { Metadata md = new Metadata(fixture); File metadata = new File(fPathName + File.separator + <START> "metadata"); <END> try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(metadata)))) { StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } String result = sb.toString(); md.parseText(result); } }</code><technical_language>extract some constants while it</technical_language>

Target:
public void init() throws FileNotFoundException, IOException, CTFException { Metadata md = new Metadata(fixture); File metadata = new File(fPathName + File.separator + METADATA); try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(metadata)))) { StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } String result = sb.toString(); md.parseText(result); } }
Source:
<code>protected void performCachedLargeMessageDeletes() { <START> for (LargeServerMessage largeServerMessage : largeMessagesToDelete.values()) { <END> SequentialFile msg = createFileForLargeMessage(largeServerMessage.getMessageID(), LargeMessageExtension.DURABLE); try { msg.delete(); } catch (Exception e) { ActiveMQServerLogger.LOGGER.journalErrorDeletingMessage(e, largeServerMessage.getMessageID()); } if (replicator != null) { replicator.largeMessageDelete(largeServerMessage.getMessageID(), JournalStorageManager.this); } confirmLargeMessage(largeServerMessage); } largeMessagesToDelete.clear(); }</code><technical_language>Calling values() creates a new List, if iterating objects, simply call forEach method collection</technical_language>

Target:
protected void performCachedLargeMessageDeletes() { largeMessagesToDelete.forEach((messageId, largeServerMessage) -> { SequentialFile msg = createFileForLargeMessage(messageId, LargeMessageExtension.DURABLE); try { msg.delete(); } catch (Exception e) { ActiveMQServerLogger.LOGGER.journalErrorDeletingMessage(e, messageId); } if (replicator != null) { replicator.largeMessageDelete(messageId, JournalStorageManager.this); } confirmLargeMessage(largeServerMessage); }); largeMessagesToDelete.clear(); }
Source:
<code>private Mono<CosmosDatabaseResponse> createDatabaseIfNotExistsInternal(CosmosAsyncDatabase database, ThroughputProperties throughputProperties, Context context) { String spanName = "createDatabaseIfNotExists." + database.getId(); <START> Context nestedContext = context.addData(TracerProvider.COSMOS_CALL_DEPTH, TracerProvider.COSMOS_CALL_DEPTH_VAL); <END> Mono<CosmosDatabaseResponse> responseMono = createDatabaseIfNotExistsInternal(database.readInternal(new CosmosDatabaseRequestOptions(), nestedContext), database, throughputProperties, nestedContext); return tracerProvider.traceEnabledCosmosResponsePublisher(responseMono, context, spanName, database.getId(), this.serviceEndpoint); }</code><technical_language>I suggesting if a data structure Context type Context object is a linked list representation if populated enough result getData get slower</technical_language>

Target:
private Mono<CosmosDatabaseResponse> createDatabaseIfNotExistsInternal(CosmosAsyncDatabase database, ThroughputProperties throughputProperties, Context context) { String spanName = "createDatabaseIfNotExists." + database.getId(); Context nestedContext = context.addData(TracerProvider.COSMOS_CALL_DEPTH, TracerProvider.COSMOS_CALL_DEPTH_VAL); Mono<CosmosDatabaseResponse> responseMono = database.readInternal(new CosmosDatabaseRequestOptions(), nestedContext).onErrorResume(exception -> { final Throwable unwrappedException = Exceptions.unwrap(exception); if (unwrappedException instanceof CosmosException) { final CosmosException cosmosException = (CosmosException) unwrappedException; if (cosmosException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { CosmosDatabaseRequestOptions requestOptions = new CosmosDatabaseRequestOptions(); if (throughputProperties != null) { ModelBridgeInternal.setThroughputProperties(requestOptions, throughputProperties); } Database wrappedDatabase = new Database(); wrappedDatabase.setId(database.getId()); return createDatabaseInternal(wrappedDatabase, requestOptions, nestedContext); } } return Mono.error(unwrappedException); }); return tracerProvider.traceEnabledCosmosResponsePublisher(responseMono, context, spanName, database.getId(), this.serviceEndpoint); }
Source:
<code>protected void readOsSection(XmlNode section) { _vm.getStaticData().setId(new Guid(section.Attributes.get("ovf:id").getValue())); XmlNode node = section.SelectSingleNode("Description"); if (node != null) { <START> _vm.getStaticData().setOs(Integer.valueOf(node.InnerText)); <END> } else { _vm.getStaticData().setOs(0); } }</code><technical_language>images int a string representing VmOsType</technical_language>

Target:
protected void readOsSection(XmlNode section) { _vm.getStaticData().setId(new Guid(section.Attributes.get("ovf:id").getValue())); XmlNode node = section.SelectSingleNode("Description"); if (node != null) { _vm.getStaticData().setOs(OsRepositoryImpl.INSTANCE.getOsIdByUniqueName(node.InnerText)); } }
Source:
<code>public void returnsASetOfErrorsForAnObject() throws Exception { if ("en".equals(Locale.getDefault().getLanguage())) { final ImmutableList<String> errors = ConstraintViolations.format(validator.validate(new Example())); assertThat(errors) .containsOnly( "outOfRange must be between 10 MINUTES and 30 MINUTES", <START> "tooBig must be less than (or equal to, if in 'inclusive' mode) to 30 SECONDS", <END> "tooBigExclusive must be less than (or equal to, if in 'inclusive' mode) to 30 SECONDS", "tooSmall must be greater than (or equal to, if in 'inclusive' mode) to 30 SECONDS", "tooSmallExclusive must be greater than (or equal to, if in 'inclusive' mode) to 30 SECONDS", "maxDurs[0].<collection element> must be less than (or equal to, if in 'inclusive' mode) to 30 SECONDS", "minDurs[0].<collection element> must be greater than (or equal to, if in 'inclusive' mode) to 30 SECONDS", "rangeDurs[0].<collection element> must be between 10 MINUTES and 30 MINUTES"); } }</code><technical_language>ditto, for of</technical_language>

Target:
public void returnsASetOfErrorsForAnObject() throws Exception { if ("en".equals(Locale.getDefault().getLanguage())) { final ImmutableList<String> errors = ConstraintViolations.format(validator.validate(new Example())); assertThat(errors) .containsOnly( "outOfRange must be between 10 MINUTES and 30 MINUTES", "tooBig must be less than (or equal to, if in 'inclusive' mode) 30 SECONDS", "tooBigExclusive must be less than (or equal to, if in 'inclusive' mode) 30 SECONDS", "tooSmall must be greater than (or equal to, if in 'inclusive' mode) 30 SECONDS", "tooSmallExclusive must be greater than (or equal to, if in 'inclusive' mode) 30 SECONDS", "maxDurs[0].<collection element> must be less than (or equal to, if in 'inclusive' mode) 30 SECONDS", "minDurs[0].<collection element> must be greater than (or equal to, if in 'inclusive' mode) 30 SECONDS", "rangeDurs[0].<collection element> must be between 10 MINUTES and 30 MINUTES"); } }
Source:
<code>public void checkLimitMultithreaded() throws Exception { int opsPerSec = 1_000; int totalOps = 10_000; BasicRateLimiter limiter = new BasicRateLimiter(opsPerSec); int threads = Runtime.getRuntime().availableProcessors(); CyclicBarrier ready = new CyclicBarrier(threads + 1); AtomicInteger cntr = new AtomicInteger(); IgniteInternalFuture<Long> fut = GridTestUtils.runMultiThreadedAsync(() -> { ready.await(); do { limiter.acquire(1); } while (!Thread.currentThread().isInterrupted() && cntr.incrementAndGet() < totalOps); return null; }, threads, "worker"); ready.await(); long startTime = System.currentTimeMillis(); fut.get(); long timeSpent = System.currentTimeMillis() - startTime; <START> assertEquals(totalOps / opsPerSec, SECONDS.convert(timeSpent, MILLISECONDS)); <END> }</code><technical_language>In some circumstances, I timeSpent a bit 10 seconds</technical_language>

Target:
public void checkLimitMultithreaded() throws Exception { int permitsPerSec = 1_000; int totalOps = 10_000; BasicRateLimiter limiter = new BasicRateLimiter(permitsPerSec); int threads = Runtime.getRuntime().availableProcessors(); CyclicBarrier ready = new CyclicBarrier(threads + 1); AtomicInteger cntr = new AtomicInteger(); IgniteInternalFuture<Long> fut = GridTestUtils.runMultiThreadedAsync(() -> { ready.await(); do { limiter.acquire(1); } while (!Thread.currentThread().isInterrupted() && cntr.incrementAndGet() < totalOps); return null; }, threads, "worker"); ready.await(); long startTime = System.currentTimeMillis(); fut.get(); long timeSpent = System.currentTimeMillis() - startTime; assertEquals(1, Math.round((double)timeSpent / 1000 / totalOps * permitsPerSec)); }
Source:
<code><START> public String[] getAllBasePaths() { <END> List<String> basePaths = new ArrayList<>(); for (String subSection : cfg.getSubsections(SECTION_NAME)) { String basePath = cfg.getString(SECTION_NAME, subSection, BASE_PATH_NAME); if (basePath != null) { basePaths.add(basePath); } } return basePaths.toArray(new String[basePaths.size()]); }</code><technical_language>List (or ImmutableList) in public interfaces, gaining array here</technical_language>

Target:
public List<Path> getAllBasePaths() { List<Path> basePaths = new ArrayList<>(); for (String subSection : cfg.getSubsections(SECTION_NAME)) { String basePath = cfg.getString(SECTION_NAME, subSection, BASE_PATH_NAME); if (basePath != null) { basePaths.add(Paths.get(basePath)); } } return basePaths; }
Source:
<code>public void load(Path directoryPath) { try(DirectoryStream<Path> dirStream = Files.newDirectoryStream(directoryPath, "*.properties")) { List<Path> paths = new ArrayList<>(); for (Path path: dirStream) { paths.add(path); } <START> Collections.sort(paths); <END> for (Path path: paths) { loadFile(path); } } catch (IOException e) { } }</code><technical_language>In this case read files memory, is difference this File.listFiles()... saying... following? :) for ( File file : new TreeSet( Arrays.asList( dir.listFiles( new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith('.properties'); } } ) ) ) ) { loadFile(file); }</technical_language>

Target:
public void load(Path directoryPath) { File dir = directoryPath.toFile(); if (dir.exists()) { File[] files = directoryPath.toFile().listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".properties"); } }); if (files != null) { Arrays.sort(files); for (File file: files) { loadFile(file.toPath()); } } } else { log.errorFormat("directory {0} doesn't exist.", dir.getPath()); } }
Source:
<code>public void detectLanguageInvalidCountryHint() { Exception exception = assertThrows(TextAnalyticsException.class, () -> client.detectLanguage("")); <START> assertTrue(exception.getMessage().equals(INVALID_COUNTRY_HINT_EXPECTED_EXCEPTION_MESSAGE)); <END> }</code><technical_language>Passing in empty string invalid country hint error</technical_language>

Target:
public void detectLanguageInvalidCountryHint() { Exception exception = assertThrows(TextAnalyticsException.class, () -> client.detectLanguageWithResponse("Este es un document escrito en Español.", "en", Context.NONE)); assertTrue(exception.getMessage().equals(INVALID_COUNTRY_HINT_EXPECTED_EXCEPTION_MESSAGE)); }
Source:
<code><START> private GradleArguments getGradleArguments() { <END> org.eclipse.buildship.core.internal.configuration.BuildConfiguration config = DefaultGradleBuild.this.gradleBuild.getBuildConfig(); return GradleArguments.from( config.getRootProjectDirectory(), config.getGradleDistribution(), config.getGradleUserHome(), null, config.isBuildScansEnabled(), config.isOfflineMode(), Collections.emptyList(), Collections.emptyList()); }</code><technical_language>nit: extra space private</technical_language>

Target:
private GradleArguments getGradleArguments() { org.eclipse.buildship.core.internal.configuration.BuildConfiguration config = DefaultGradleBuild.this.gradleBuild.getBuildConfig(); return config.toGradleArguments(); }
Source:
<code>private void prepareForSending() { try { if (partitionId != null) { attemptedPartitionIds.add(partitionId); } partitionId = getPartitionForPut(attemptedPartitionIds); chunkBlobId = <START> new BlobId(blobIdFlag, clusterMap.getLocalDatacenterId(), passedInBlobProperties.getAccountId(), <END> passedInBlobProperties.getContainerId(), partitionId); chunkBlobProperties = new BlobProperties(buf.remaining(), passedInBlobProperties.getServiceId(), passedInBlobProperties.getOwnerId(), passedInBlobProperties.getContentType(), passedInBlobProperties.isPrivate(), passedInBlobProperties.getTimeToLiveInSeconds(), passedInBlobProperties.getCreationTimeInMs()); operationTracker = new SimpleOperationTracker(routerConfig.routerDatacenterName, partitionId, false, routerConfig.routerPutSuccessTarget, routerConfig.routerPutRequestParallelism); correlationIdToChunkPutRequestInfo.clear(); state = ChunkState.Ready; } catch (RouterException e) { setOperationExceptionAndComplete(e); } catch (Exception e) { setOperationExceptionAndComplete(new RouterException("Operation tracker could not be initialized", e, RouterErrorCode.UnexpectedInternalError)); } }</code><technical_language>BlobId.DEFAULT_FLAG here</technical_language>

Target:
private void prepareForSending() { try { if (partitionId != null) { attemptedPartitionIds.add(partitionId); } partitionId = getPartitionForPut(attemptedPartitionIds); chunkBlobId = new BlobId(BlobId.DEFAULT_FLAG, clusterMap.getLocalDatacenterId(), passedInBlobProperties.getAccountId(), passedInBlobProperties.getContainerId(), partitionId); chunkBlobProperties = new BlobProperties(buf.remaining(), passedInBlobProperties.getServiceId(), passedInBlobProperties.getOwnerId(), passedInBlobProperties.getContentType(), passedInBlobProperties.isPrivate(), passedInBlobProperties.getTimeToLiveInSeconds(), passedInBlobProperties.getCreationTimeInMs()); operationTracker = new SimpleOperationTracker(routerConfig.routerDatacenterName, partitionId, false, routerConfig.routerPutSuccessTarget, routerConfig.routerPutRequestParallelism); correlationIdToChunkPutRequestInfo.clear(); state = ChunkState.Ready; } catch (RouterException e) { setOperationExceptionAndComplete(e); } catch (Exception e) { setOperationExceptionAndComplete(new RouterException("Operation tracker could not be initialized", e, RouterErrorCode.UnexpectedInternalError)); } }
Source:
<code>public boolean isExploreWikiHeaderVisible() { try { <START> return exploreWikiHeader.isDisplayed(); <END> } catch (NoSuchElementException e) { PageObjectLogging.logInfo(e.getMessage()); return false; } }</code><technical_language>AFAIR this logic is duplicated in some other places. consider extract pass element argument</technical_language>

Target:
public boolean isExploreWikiHeaderVisible() { return isElementVisible(exploreWikiHeader); }
Source:
<code>public Builder securityOpts(List<String> securityOpts) { <START> this.securityOpts = ImmutableList.copyOf(checkNotNull(securityOpts, "securityOpts")); <END> return this; }</code><technical_language>weird indent. this class is inconsistent safe copies. auto generate builders do safe copies, do it, ensure is calling this safe copies in</technical_language>

Target:
public Builder securityOpts(List<String> securityOpts) { this.securityOpts = securityOpts; return this; }
Source:
<code>protected void execute() { logger.debug("execute() method is called!"); if (!isProperlyConfigured()) { logger.debug("Binding is not yet configured"); return; <START> } <END> if (!bindingsExist()) { logger.debug("There is no existing DSMR binding configuration => refresh cycle aborted!"); return; } if (dsmrPort == null || !dsmrPort.isOpen()) { logger.debug("Creating DSMR Port:" + port); dsmrPort = new DSMRPort(port, version, DSMR_UPDATE_INTERVAL); } List<OBISMessage<? extends State>> messages = dsmrPort.read(); for (OBISMessage<? extends State> msg : messages) { logger.debug("Read message:" + msg); for (DSMRBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { String item = provider.getItem(itemName); if (item.equals(msg.getType().bindingReference)) { logger.debug("Publish data(" + item + ") to " + itemName); eventPublisher.postUpdate(itemName, msg.getOpenHabValue()); } } } } }</code><technical_language>calling setProperyConfigured(true) activates this Binding execute() called if Binding is properly configured. This condition is necessary though</technical_language>

Target:
protected void execute() { if (!bindingsExist()) { logger.debug("There is no existing DSMR binding configuration => refresh cycle aborted!"); return; } if (dsmrPort == null || !dsmrPort.isOpen()) { logger.debug("Creating DSMR Port:" + port); dsmrPort = new DSMRPort(port, version, dsmrMeters, DSMR_UPDATE_INTERVAL); } List<OBISMessage> messages = dsmrPort.read(); for (OBISMessage msg : messages) { logger.debug("Read message:" + msg); for (DSMRBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { String dsmrItemId = provider.getDSMRItemID(itemName); for (CosemValue<? extends State> openHABValue : msg .getOpenHABValues()) { if (dsmrItemId.equals(openHABValue.getDsmrItemId())) { logger.debug("Publish data(" + dsmrItemId + ") to " + itemName); eventPublisher.postUpdate(itemName, openHABValue.getValue()); } } } } } }
Source:
<code>public AABB(Vector3i firstCorner, Vector3i secondCorner) { <START> this(firstCorner.toDouble(), secondCorner.toDouble()); <END> }</code><technical_language>this(checkNotNull(firstCorner, "firstCorner").toDouble(), checkNotNull(secondCorner, "secondCorner").toDouble());</technical_language>

Target:
public AABB(Vector3i firstCorner, Vector3i secondCorner) { this(checkNotNull(firstCorner, "firstCorner").toDouble(), checkNotNull(secondCorner, "secondCorner").toDouble()); }
Source:
<code>public boolean equals(final Object o) { if (this == o) { return true; } if (o instanceof StateNodeMetadata) { if (super.equals(o)) { final StateNodeMetadata metadata = (StateNodeMetadata) o; <START> return new EqualsBuilder().append(stateMetadata, metadata.stateMetadata).isEquals(); <END> } } return false; }</code><technical_language>This Objects.equals(stateMetadata, metadata.stateMetadata); requires object construction</technical_language>

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (o instanceof StateNodeMetadata) { if (super.equals(o)) { final StateNodeMetadata metadata = (StateNodeMetadata) o; return Objects.equal(this.stateMetadata, metadata.stateMetadata); } } return false; }
Source:
<code>public Bundle[] getBundles(String symbolicName, String versionRange) { Map<String, String> directives = Collections.singletonMap(Namespace.REQUIREMENT_FILTER_DIRECTIVE, getRequirementFilter(symbolicName, versionRange)); Collection<BundleCapability> matchingBundleCapabilities = fwkWiring.findProviders(ModuleContainer .createRequirement(IdentityNamespace.IDENTITY_NAMESPACE, directives, Collections.emptyMap())); if (matchingBundleCapabilities.isEmpty()) { return null; } Bundle[] results = matchingBundleCapabilities.stream().map(c -> c.getRevision().getBundle()) .filter(bundle -> (bundle.getState() & (Bundle.INSTALLED | Bundle.UNINSTALLED)) == 0) <START> .sorted() END> .toArray(Bundle[]::new); return results.length > 0 ? results : null; }</code><technical_language>This Bundle.compareTo implementation sort bundle ID is want here. this (untested, compile): .sorted((b1, b2)-> b2.getVersion().compareTo(b1.getVersion))</technical_language>

Target:
public Bundle[] getBundles(String symbolicName, String versionRange) { Map<String, String> directives = Collections.singletonMap(Namespace.REQUIREMENT_FILTER_DIRECTIVE, getRequirementFilter(symbolicName, versionRange)); Collection<BundleCapability> matchingBundleCapabilities = fwkWiring.findProviders(ModuleContainer .createRequirement(IdentityNamespace.IDENTITY_NAMESPACE, directives, Collections.emptyMap())); if (matchingBundleCapabilities.isEmpty()) { return null; } Bundle[] results = matchingBundleCapabilities.stream().map(c -> c.getRevision().getBundle()) .filter(bundle -> (bundle.getState() & (Bundle.INSTALLED | Bundle.UNINSTALLED)) == 0) .sorted((b1, b2) -> b2.getVersion().compareTo(b1.getVersion())) .toArray(Bundle[]::new); return results.length > 0 ? results : null; }