auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Expression visitSpatialJoin(SpatialJoinNode node, Void context) { Expression leftPredicate = node.getLeft().accept(this, context); Expression rightPredicate = node.getRight().accept(this, context); switch (node.getType()) { case INNER: return combineConjuncts(ImmutableList.<Expression>builder() .add(pullExpressionThroughSymbols(leftPredicate, node.getOutputSymbols())) .add(pullExpressionThroughSymbols(rightPredicate, node.getOutputSymbols())) .build()); case LEFT: return combineConjuncts(ImmutableList.<Expression>builder() .add(pullExpressionThroughSymbols(leftPredicate, node.getOutputSymbols())) .addAll(pullNullableConjunctsThroughOuterJoin(extractConjuncts(rightPredicate), node.getOutputSymbols(), node.getRight().getOutputSymbols()::contains)) .build()); default: throw new UnsupportedOperationException("Unknown spatial join type: " + node.getType()); } }

Target:
public Expression visitSpatialJoin(SpatialJoinNode node, Void context) { Expression leftPredicate = node.getLeft().accept(this, context); Expression rightPredicate = node.getRight().accept(this, context); switch (node.getType()) { case INNER: return combineConjuncts(ImmutableList.<Expression>builder() .add(pullExpressionThroughSymbols(leftPredicate, node.getOutputSymbols())) .add(pullExpressionThroughSymbols(rightPredicate, node.getOutputSymbols())) .build()); case LEFT: return combineConjuncts(ImmutableList.<Expression>builder() .add(pullExpressionThroughSymbols(leftPredicate, node.getOutputSymbols())) .addAll(pullNullableConjunctsThroughOuterJoin(extractConjuncts(rightPredicate), node.getOutputSymbols(), node.getRight().getOutputSymbols()::contains)) .build()); default: throw new IllegalArgumentException("Unsupported spatial join type: " + node.getType()); } }
Source:
public int readData(byte[] buffer) throws IOException { int readBytes = 0; if (getInputStream() != null && getInputStream().available() > 0) { int numBytesToRead = getInputStream().available(); if (numBytesToRead > buffer.length) numBytesToRead = buffer.length; readBytes = getInputStream().read(buffer, 0, numBytesToRead); } return readBytes; }

Target:
public int readData(byte[] buffer) throws IOException { if (buffer == null) throw new NullPointerException("Buffer cannot be null."); int readBytes = 0; if (getInputStream() != null && getInputStream().available() > 0) { int numBytesToRead = getInputStream().available(); if (numBytesToRead > buffer.length) numBytesToRead = buffer.length; readBytes = getInputStream().read(buffer, 0, numBytesToRead); } return readBytes; }
Source:
public SliceDictionaryColumnWriter(int column, Type type, CompressionKind compression, int bufferSize, OrcEncoding orcEncoding, DataSize stringStatisticsLimit) { checkArgument(column >= 0, "column is negative"); this.column = column; this.type = requireNonNull(type, "type is null"); this.compression = requireNonNull(compression, "compression is null"); try { this.orcDecompressor = createOrcDecompressor(orcDataSourceId, compression, 1024 * 1024); } catch (OrcCorruptionException e) { throw new RuntimeException(e); } this.bufferSize = bufferSize; this.orcEncoding = requireNonNull(orcEncoding, "orcEncoding is null"); this.stringStatisticsLimitInBytes = toIntExact(requireNonNull(stringStatisticsLimit, "stringStatisticsLimit is null").toBytes()); if (orcEncoding == DWRF) { this.dataStream = new LongOutputStreamV1(compression, bufferSize, false, DATA); this.tempDictionaryIdDataStream = new LongOutputStreamV1(compression, bufferSize, false, DATA); } else { this.dataStream = new LongOutputStreamV2(compression, bufferSize, false, DATA); this.tempDictionaryIdDataStream = new LongOutputStreamV2(compression, bufferSize, false, DATA); } this.presentStream = new PresentOutputStream(compression, bufferSize); this.dictionaryDataStream = new ByteArrayOutputStream(compression, bufferSize, StreamKind.DICTIONARY_DATA); this.dictionaryLengthStream = createLengthOutputStream(compression, bufferSize, orcEncoding); this.statisticsBuilder = newStringStatisticsBuilder(); }

Target:
public SliceDictionaryColumnWriter(int column, Type type, CompressionKind compression, int bufferSize, OrcEncoding orcEncoding, DataSize stringStatisticsLimit) { checkArgument(column >= 0, "column is negative"); this.column = column; this.type = requireNonNull(type, "type is null"); this.compression = requireNonNull(compression, "compression is null"); this.bufferSize = bufferSize; this.orcEncoding = requireNonNull(orcEncoding, "orcEncoding is null"); this.stringStatisticsLimitInBytes = toIntExact(requireNonNull(stringStatisticsLimit, "stringStatisticsLimit is null").toBytes()); if (orcEncoding == DWRF) { this.dataStream = new LongOutputStreamV1(compression, bufferSize, false, DATA); this.tempDictionaryIdDataStream = new LongOutputStreamV1(compression, bufferSize, false, DATA); } else { this.dataStream = new LongOutputStreamV2(compression, bufferSize, false, DATA); this.tempDictionaryIdDataStream = new LongOutputStreamV2(compression, bufferSize, false, DATA); } this.presentStream = new PresentOutputStream(compression, bufferSize); this.dictionaryDataStream = new ByteArrayOutputStream(compression, bufferSize, StreamKind.DICTIONARY_DATA); this.dictionaryLengthStream = createLengthOutputStream(compression, bufferSize, orcEncoding); this.statisticsBuilder = newStringStatisticsBuilder(); }
Source:
public GlusterStorageDomainDRSyncJob() { super(); backend = Injector.get(BackendInternal.class); storageDomainDao = Injector.get(StorageDomainDao.class); geoRepDao = Injector.get(GlusterGeoRepDao.class); }

Target:
public GlusterStorageDomainDRSyncJob() { super(); }
Source:
public SipMessage.Builder<T> withRecordRouteHeaders(final RecordRouteHeader... recordRoutes) { if (recordRoutes != null) { this.recordRouteHeaders = ensureList(this.recordRouteHeaders); this.recordRouteHeaders.clear(); recordRouteHeader = recordRoutes[0]; this.recordRouteHeaders.addAll(Arrays.asList(recordRoutes)); } return this; }

Target:
public SipMessage.Builder<T> withRecordRouteHeaders(final RecordRouteHeader... recordRoutes) { if (recordRoutes != null && recordRoutes.length > 0) { this.recordRouteHeaders = ensureList(this.recordRouteHeaders); this.recordRouteHeaders.clear(); recordRouteHeader = recordRoutes[0]; this.recordRouteHeaders.addAll(Arrays.asList(recordRoutes)); } return this; }
Source:
private String encodeAttributes(List<String> attributesToRetrieve, boolean forURL) throws UnsupportedEncodingException { if (attributesToRetrieve == null) { return null; } StringBuilder params = new StringBuilder(); if (forURL) { params.append("?attributes="); } for (int i = 0; i < attributesToRetrieve.size(); ++i) { if (i > 0) { params.append(","); } params.append(URLEncoder.encode(attributesToRetrieve.get(i), "UTF-8")); } return params.toString(); }

Target:
private String encodeAttributes(List<String> attributesToRetrieve, boolean forURL) throws UnsupportedEncodingException { if (attributesToRetrieve == null) { return null; } StringBuilder params = new StringBuilder(); if (forURL) { params.append("?attributesToRetrieve="); } for (int i = 0; i < attributesToRetrieve.size(); ++i) { if (i > 0) { params.append(","); } params.append(URLEncoder.encode(attributesToRetrieve.get(i), "UTF-8")); } return params.toString(); }
Source:
public ImageIcon getIcon() { if (confidence == Alert.CONFIDENCE_FALSE_POSITIVE) { return DisplayUtils.getScaledIcon(new ImageIcon(Constant.OK_FLAG_IMAGE_URL)); } switch (risk) { case Alert.RISK_INFO: return DisplayUtils.getScaledIcon(Constant.INFO_FLAG_IMAGE_URL); case Alert.RISK_LOW: return DisplayUtils.getScaledIcon(Constant.LOW_FLAG_IMAGE_URL); case Alert.RISK_MEDIUM: return DisplayUtils.getScaledIcon(Constant.MED_FLAG_IMAGE_URL); case Alert.RISK_HIGH: return DisplayUtils.getScaledIcon(Constant.HIGH_FLAG_IMAGE_URL); } return null; }

Target:
public ImageIcon getIcon() { if (confidence == Alert.CONFIDENCE_FALSE_POSITIVE) { return DisplayUtils.getScaledIcon(Constant.OK_FLAG_IMAGE_URL); } switch (risk) { case Alert.RISK_INFO: return DisplayUtils.getScaledIcon(Constant.INFO_FLAG_IMAGE_URL); case Alert.RISK_LOW: return DisplayUtils.getScaledIcon(Constant.LOW_FLAG_IMAGE_URL); case Alert.RISK_MEDIUM: return DisplayUtils.getScaledIcon(Constant.MED_FLAG_IMAGE_URL); case Alert.RISK_HIGH: return DisplayUtils.getScaledIcon(Constant.HIGH_FLAG_IMAGE_URL); } return null; }
Source:
public void afterPropertiesSet() { if (this.beanName == null) { LOGGER.error("The MessageHandler [" + this.handler + "] will be created without a 'componentName'. " + "Consider specifying the 'beanName' property on this ConsumerEndpointFactoryBean."); } else { try { if (!this.beanName.startsWith("org.springframework")) { MessageHandler targetHandler = this.handler; if (AopUtils.isAopProxy(targetHandler)) { Object target = ((Advised) targetHandler).getTargetSource().getTarget(); if (target instanceof MessageHandler) { targetHandler = (MessageHandler) target; } } if (targetHandler instanceof IntegrationObjectSupport) { ((IntegrationObjectSupport) targetHandler).setComponentName(this.beanName); } } } catch (Exception e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Could not set component name for handler " + this.handler + " for " + this.beanName + " :" + e.getMessage()); } } } if (!(this.handler instanceof ReactiveMessageHandlerAdapter)) { adviceChain(); } else { LOGGER.warn("the advice chain cannot be applied for 'ReactiveMessageHandler'"); } if (this.channelResolver == null) { this.channelResolver = ChannelResolverUtils.getChannelResolver(this.beanFactory); } initializeEndpoint(); }

Target:
public void afterPropertiesSet() { if (this.beanName == null) { LOGGER.error("The MessageHandler [" + this.handler + "] will be created without a 'componentName'. " + "Consider specifying the 'beanName' property on this ConsumerEndpointFactoryBean."); } else { try { if (!this.beanName.startsWith("org.springframework")) { MessageHandler targetHandler = this.handler; if (AopUtils.isAopProxy(targetHandler)) { Object target = ((Advised) targetHandler).getTargetSource().getTarget(); if (target instanceof MessageHandler) { targetHandler = (MessageHandler) target; } } if (targetHandler instanceof IntegrationObjectSupport) { ((IntegrationObjectSupport) targetHandler).setComponentName(this.beanName); } } } catch (Exception e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Could not set component name for handler " + this.handler + " for " + this.beanName + " :" + e.getMessage()); } } } if (!(this.handler instanceof ReactiveMessageHandlerAdapter)) { adviceChain(); } else if (!CollectionUtils.isEmpty(this.adviceChain)) { LOGGER.warn("the advice chain cannot be applied to a 'ReactiveMessageHandler'"); } if (this.channelResolver == null) { this.channelResolver = ChannelResolverUtils.getChannelResolver(this.beanFactory); } initializeEndpoint(); }
Source:
public static void copyResourceToProject(String resource, File destination) { try { InputStream inputStream = FileUtil.class.getResourceAsStream(resource); destination.getParentFile().mkdirs(); OutputStream outputStream = new FileOutputStream(destination); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(outputStream); } catch (IOException e) { throw new IllegalStateException(e); } }

Target:
public static void copyResourceToProject(String resource, File destination) { try { InputStream inputStream = FileUtil.class.getResourceAsStream(resource); destination.getParentFile().mkdirs(); OutputStream outputStream = new FileOutputStream(destination); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } catch (IOException e) { throw new IllegalStateException(e); } }
Source:
public Rational add(Rational that) { final int commonDenominator = this.denominator * that.denominator; return new Rational( this.numerator * that.denominator + that.numerator * this.denominator, commonDenominator); }

Target:
Rational add(Rational that) { final int commonDenominator = this.denominator * that.denominator; return new Rational( this.numerator * that.denominator + that.numerator * this.denominator, commonDenominator); }
Source:
void process(BitVector changedBits, BitVector deletedBits) { toEntityIntBags(changedBits, deletedBits); subscriptions.get(0).processAll(changed, deleted); for (int i = 0, s = subscriptions.size(); s > i; i++) { subscriptions.get(i).process(changed, deleted); } }

Target:
void process(BitVector changedBits, BitVector deletedBits) { toEntityIntBags(changedBits, deletedBits); subscriptions.get(0).processAll(changed, deleted); for (int i = 1, s = subscriptions.size(); s > i; i++) { subscriptions.get(i).process(changed, deleted); } }
Source:
public LockException(int statusCode) { this.statusCode = statusCode; }

Target:
public LockException(int statusCode) { super(statusCode); }
Source:
public void testGetConfigList() { String jdbcDriver = "com.mysql.jdbc.Driver"; String mysqlURL = "jdbc:mysql://gargamel.cs.illinois.edu/openeval_db"; String username = "oeroot"; String password = "Fow,10#"; try { Connection conn = DriverManager.getConnection(mysqlURL, username, password); String sql = "INSERT INTO configurations (datasetName, teamName, description, evaluator, taskType) VALUES ('testDataset', 'testTeamName', 'testDescription', 'testEvaluator', 'testTaskType')"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.executeUpdate(); sql = "SELECT MAX(id) from configurations;"; stmt = conn.prepareStatement(sql); ResultSet idOfConfig = stmt.executeQuery(); idOfConfig.first(); String id = Integer.toString(idOfConfig.getInt(1)); boolean inConfigList = false; FrontEndDBInterface f = new FrontEndDBInterface(); List<models.Configuration> configList = f.getConfigList(); if (configList != null) { for (int i = 0; i < configList.size(); i++) { if (configList.get(i).configuration_id.equals(id)) { inConfigList = true; break; } } } assertTrue(inConfigList); sql = "DELETE FROM configurations WHERE datasetName = 'testDataset'"; stmt = conn.prepareStatement(sql); stmt.executeUpdate(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } }

Target:
public void testGetConfigList() { String jdbcDriver = "com.mysql.jdbc.Driver"; String mysqlURL = "jdbc:mysql://gargamel.cs.illinois.edu/openeval_db"; String username = "oeroot"; String password = "Fow,10#"; try { Connection conn = DriverManager.getConnection(mysqlURL, username, password); String sql = "INSERT INTO configurations (datasetName, teamName, description, evaluator, taskType) VALUES ('testDataset', 'testTeamName', 'testDescription', 'testEvaluator', 'testTaskType')"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.executeUpdate(); sql = "SELECT MAX(id) from configurations;"; stmt = conn.prepareStatement(sql); ResultSet idOfConfig = stmt.executeQuery(); idOfConfig.first(); String id = Integer.toString(idOfConfig.getInt(1)); boolean inConfigList = false; FrontEndDBInterface f = new FrontEndDBInterface(); List<models.Configuration> configList = f.getConfigList(); if (configList != null) { for (int i = 0; i < configList.size(); i++) { if (configList.get(i).configuration_id.equals(id)) { inConfigList = true; break; } } } assertTrue(inConfigList); sql = "DELETE FROM configurations WHERE datasetName = 'testDataset'"; stmt = conn.prepareStatement(sql); stmt.executeUpdate(); conn.close(); } catch (SQLException e) { if (e.getMessage().contains("The driver has not received any packets from the server.")) return; } }
Source:
public void requiredFieldAttribute() { if (type == ObjectSchemaType.IMMUTABLE) { return; } String fieldName = "foo"; for (FieldType fieldType : FieldType.values()) { switch (fieldType) { case OBJECT: continue; default: schema.addField(fieldName, fieldType.getType(), FieldAttribute.REQUIRED); assertTrue(schema.isRequired(fieldName)); schema.removeField(fieldName); } } for (FieldListType fieldType : FieldListType.values()) { switch(fieldType) { case LIST: continue; default: schema.addRealmListField(fieldName, fieldType.getType()); if (fieldType.isNullable()) { schema.setRequired(fieldName, true); } assertTrue(schema.isRequired(fieldName)); schema.removeField(fieldName); } } }

Target:
public void requiredFieldAttribute() { if (type == ObjectSchemaType.IMMUTABLE) { return; } String fieldName = "foo"; for (FieldType fieldType : FieldType.values()) { switch (fieldType) { case OBJECT: continue; default: schema.addField(fieldName, fieldType.getType(), FieldAttribute.REQUIRED); assertTrue(schema.isRequired(fieldName)); schema.removeField(fieldName); } } for (FieldListType fieldType : FieldListType.values()) { switch(fieldType) { case LIST: continue; default: schema.addRealmListField(fieldName, fieldType.getType()); if (fieldType.isNullable()) { schema.setRequired(fieldName, true); } assertTrue(fieldName + " should be required", schema.isRequired(fieldName)); schema.removeField(fieldName); } } }
Source:
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = MediaStore.MediaColumns.DATA; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int columnIndex = cursor.getColumnIndex(column); if (columnIndex != -1) { return cursor.getString(columnIndex); } } } catch (Exception errReadingContentResolver) { AppLog.e(AppLog.T.UTILS, "Error reading _data column for URI: " + uri, errReadingContentResolver); } finally { if (cursor != null) { cursor.close(); } } return null; }

Target:
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = MediaStore.MediaColumns.DATA; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int columnIndex = cursor.getColumnIndex(column); if (columnIndex != -1) { return cursor.getString(columnIndex); } } } catch (SecurityException errReadingContentResolver) { AppLog.e(AppLog.T.UTILS, "Error reading _data column for URI: " + uri, errReadingContentResolver); } finally { if (cursor != null) { cursor.close(); } } return null; }
Source:
private void reloadPluginAdapterAndVisibility(@NonNull PluginListType pluginType, @Nullable ListNetworkResource<ImmutablePluginModel> listNetworkResource) { if (listNetworkResource == null || !(listNetworkResource instanceof ListNetworkResource.Ready || listNetworkResource instanceof ListNetworkResource.Success)) { return; } PluginBrowserAdapter adapter = null; View cardView = null; switch (pluginType) { case SITE: adapter = (PluginBrowserAdapter) mSitePluginsRecycler.getAdapter(); cardView = findViewById(R.id.installed_plugins_cardview); break; case FEATURED: adapter = (PluginBrowserAdapter) mFeaturedPluginsRecycler.getAdapter(); cardView = findViewById(R.id.featured_plugins_cardview); break; case POPULAR: adapter = (PluginBrowserAdapter) mPopularPluginsRecycler.getAdapter(); cardView = findViewById(R.id.popular_plugins_cardview); break; case NEW: adapter = (PluginBrowserAdapter) mNewPluginsRecycler.getAdapter(); cardView = findViewById(R.id.new_plugins_cardview); break; case SEARCH: return; } if (adapter == null || cardView == null) { return; } List<ImmutablePluginModel> plugins = listNetworkResource.getData(); adapter.setPlugins(plugins); int newVisibility = plugins.size() > 0 ? View.VISIBLE : View.GONE; int oldVisibility = cardView.getVisibility(); if (newVisibility == View.VISIBLE && oldVisibility != View.VISIBLE) { AniUtils.fadeIn(cardView, AniUtils.Duration.MEDIUM); } else if (newVisibility != View.VISIBLE && oldVisibility == View.VISIBLE) { AniUtils.fadeOut(cardView, AniUtils.Duration.MEDIUM); } }

Target:
private void reloadPluginAdapterAndVisibility(@NonNull PluginListType pluginType, @Nullable ListNetworkResource<ImmutablePluginModel> listNetworkResource) { if (!(listNetworkResource instanceof ListNetworkResource.Ready || listNetworkResource instanceof ListNetworkResource.Success)) { return; } PluginBrowserAdapter adapter = null; View cardView = null; switch (pluginType) { case SITE: adapter = (PluginBrowserAdapter) mSitePluginsRecycler.getAdapter(); cardView = findViewById(R.id.installed_plugins_cardview); break; case FEATURED: adapter = (PluginBrowserAdapter) mFeaturedPluginsRecycler.getAdapter(); cardView = findViewById(R.id.featured_plugins_cardview); break; case POPULAR: adapter = (PluginBrowserAdapter) mPopularPluginsRecycler.getAdapter(); cardView = findViewById(R.id.popular_plugins_cardview); break; case NEW: adapter = (PluginBrowserAdapter) mNewPluginsRecycler.getAdapter(); cardView = findViewById(R.id.new_plugins_cardview); break; case SEARCH: return; } if (adapter == null || cardView == null) { return; } List<ImmutablePluginModel> plugins = listNetworkResource.getData(); adapter.setPlugins(plugins); int newVisibility = plugins.size() > 0 ? View.VISIBLE : View.GONE; int oldVisibility = cardView.getVisibility(); if (newVisibility == View.VISIBLE && oldVisibility != View.VISIBLE) { AniUtils.fadeIn(cardView, AniUtils.Duration.MEDIUM); } else if (newVisibility != View.VISIBLE && oldVisibility == View.VISIBLE) { AniUtils.fadeOut(cardView, AniUtils.Duration.MEDIUM); } }
Source:
public static void loadKeyStore(String keyStorePath, String keyStorePassword) throws AuthenticationException { InputStream fis = null; try { TenantMgtAdminServiceClient.keyStorePassword = keyStorePassword.toCharArray(); keyStore = KeyStore.getInstance(keyStoreType); fis = new FileInputStream(keyStorePath); keyStore.load(fis, TenantMgtAdminServiceClient.keyStorePassword); } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) { throw new AuthenticationException("Error while trying to load Key Store.", e); } finally { try { if (fis != null) { fis.close(); } } catch (IOException e) { log.error("Failed to close file. ", e); } } }

Target:
public static void loadKeyStore(String keyStorePath, String keyStorePassword) throws AuthenticationException { InputStream fis = null; try { TenantMgtAdminServiceClient.keyStorePassword = keyStorePassword.toCharArray(); keyStore = KeyStore.getInstance(keyStoreType); fis = new FileInputStream(keyStorePath); keyStore.load(fis, TenantMgtAdminServiceClient.keyStorePassword); } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) { throw new AuthenticationException("Error while trying to load Key Store.", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { log.error("Failed to close file. ", e); } } } }
Source:
public void install() { String parentFQDN = entity.getParent().getAttribute(AmbariServer.FQDN); String fqdn = Strings.isNullOrEmpty(parentFQDN) ? entity.getId().toLowerCase() + AmbariCluster.DOMAIN_NAME : parentFQDN; getEntity().setFqdn(fqdn); ImmutableList<String> commands = ImmutableList.<String>builder() .add(defaultAmbariInstallHelper.installAmbariRequirements(getMachine())) .addAll(BashCommands.setHostname(fqdn)) .add(installPackage("ambari-agent")) .build(); newScript(INSTALLING).body .append(commands) .failOnNonZeroResultCode() .execute(); }

Target:
public void install() { String parentFQDN = entity.getParent() instanceof AmbariServer ? ((AmbariServer) entity.getParent()).getFqdn() : ""; String fqdn = parentFQDN.isEmpty() ? entity.getId().toLowerCase() + AmbariCluster.DOMAIN_NAME : parentFQDN; getEntity().setFqdn(fqdn); ImmutableList<String> commands = ImmutableList.<String>builder() .add(defaultAmbariInstallHelper.installAmbariRequirements(getMachine())) .addAll(BashCommands.setHostname(fqdn)) .add(installPackage("ambari-agent")) .build(); newScript(INSTALLING).body .append(commands) .failOnNonZeroResultCode() .execute(); }
Source:
public boolean equals(Object obj) { if (id == null || !(obj instanceof DummyObject)) { return false; } DummyObject other = (DummyObject) obj; return other.id != null && id.equals(other.id); }

Target:
public boolean equals(Object obj) { if (!(obj instanceof DummyObject)) { return false; } DummyObject other = (DummyObject) obj; if (id == other.id) { return true; } return id != null && id.equals(other.id); }
Source:
protected final List<ObjectComponent<T>> parseRequest(StaplerRequest req) throws ServletException, Descriptor.FormException { LOGGER.fine("Parsing request..."); DescribableList<ObjectComponent<T>, ObjectComponentDescriptor<T>> components = new DescribableList<>(Saveable.NOOP); try { JSONObject componentsSection = new JSONObject(); if (req.getSubmittedForm() != null) { componentsSection = req.getSubmittedForm().getJSONObject("components"); } components.rebuild(req, componentsSection, getApplicableComponentsDescriptors()); } catch (IOException e) { throw new Descriptor.FormException(e, "components"); } return components; }

Target:
protected final List<ObjectComponent<T>> parseRequest(StaplerRequest req) throws ServletException, Descriptor.FormException { DescribableList<ObjectComponent<T>, ObjectComponentDescriptor<T>> components = new DescribableList<>(Saveable.NOOP); try { JSONObject componentsSection = req.getSubmittedForm().getJSONObject("components"); components.rebuild(req, componentsSection, getApplicableComponentsDescriptors()); } catch (IOException e) { throw new Descriptor.FormException(e, "components"); } return components; }
Source:
public static void trimSpaces(EOEnterpriseObject object) { for (Enumeration e=ERXEOControlUtilities.stringAttributeListForEntityNamed(object.editingContext(), object.entityName()).objectEnumerator(); e.hasMoreElements();) { String key=(String)e.nextElement(); String value=(String)object.storedValueForKey(key); if (!EOUtilities.entityForObject(object.editingContext(), object).attributeNamed(key).isReadOnly()) { if (value!=null) { String trimmedValue=value.trim(); if (trimmedValue.length()!=value.length()) object.takeStoredValueForKey(trimmedValue,key); } } } }

Target:
public static void trimSpaces(EOEnterpriseObject object) { for (Enumeration e=ERXEOControlUtilities.stringAttributeListForEntityNamed(object.editingContext(), object.entityName()).objectEnumerator(); e.hasMoreElements();) { String key=(String)e.nextElement(); String value=(String)object.storedValueForKey(key); if (value!=null) { if (!EOUtilities.entityForObject(object.editingContext(), object).attributeNamed(key).isReadOnly()) { String trimmedValue=value.trim(); if (trimmedValue.length()!=value.length()) object.takeStoredValueForKey(trimmedValue,key); } } } }
Source:
public static ResourceLocation resolveTexture(@Nullable String tex, IModelConfiguration owner) { if (tex == null) return new ResourceLocation("forge:white"); if (tex.startsWith("#")) return new ResourceLocation(owner.resolveTexture(tex)); Matcher match = FILESYSTEM_PATH_TO_RESLOC.matcher(tex); if (match.matches()) { String namespace = match.group("namespace"); String path = match.group("path").replace("\\", "/"); if (namespace != null) return new ResourceLocation(namespace, path); return new ResourceLocation(path); } return new ResourceLocation(tex); }

Target:
public static ResourceLocation resolveTexture(@Nullable String tex, IModelConfiguration owner) { if (tex == null) return new ResourceLocation(WHITE_TEXTURE); if (tex.startsWith("#")) return new ResourceLocation(owner.resolveTexture(tex)); Matcher match = FILESYSTEM_PATH_TO_RESLOC.matcher(tex); if (match.matches()) { String namespace = match.group("namespace"); String path = match.group("path").replace("\\", "/"); if (namespace != null) return new ResourceLocation(namespace, path); return new ResourceLocation(path); } return new ResourceLocation(tex); }
Source:
public void completeBuilderShouldThrowExceptionIfNoQueryWasSet() { PreparedGetObject.CompleteBuilder completeBuilder = new PreparedGetObject.Builder<Object>(mock(StorIOSQLite.class), Object.class) .withQuery(Query.builder().table("test_table").build()); completeBuilder.query = null; try { completeBuilder.prepare(); failBecauseExceptionWasNotThrown(IllegalStateException.class); } catch (IllegalStateException expected) { assertThat(expected).hasMessage("Please specify Query or RawQuery"); } }

Target:
public void completeBuilderShouldThrowExceptionIfNoQueryWasSet() { PreparedGetObject.CompleteBuilder completeBuilder = new PreparedGetObject.Builder<Object>(mock(StorIOSQLite.class), Object.class) .withQuery(Query.builder().table("test_table").build()); completeBuilder.query = null; try { completeBuilder.prepare(); failBecauseExceptionWasNotThrown(IllegalStateException.class); } catch (IllegalStateException expected) { assertThat(expected).hasMessage("Please specify Query or RawQuery"); assertThat(expected).hasNoCause(); } }
Source:
protected Issuer createIssuer(final CallbackProperties properties, final X509Certificate certificate) { String format = properties.getAssertionIssuerFormat(); String sIssuer = properties.getIssuer(); if (!(StringUtils.isNotBlank(format) && isValidNameidFormat(format))) { format = NhincConstants.AUTH_FRWK_NAME_ID_FORMAT_X509; } if (!(StringUtils.isNotBlank(sIssuer) && checkDistinguishedName(sIssuer))) { if (certificate != null) { sIssuer = certificate.getIssuerDN().getName(); } else { sIssuer = NhincConstants.SAML_DEFAULT_ISSUER_NAME; } } LOG.debug("Setting Assertion Issuer format to: {}", format); LOG.debug("Setting Assertion Issuer to: {}", sIssuer); return OpenSAML2ComponentBuilder.getInstance().createIssuer(format, sIssuer); }

Target:
protected Issuer createIssuer(final CallbackProperties properties, final X509Certificate certificate) { String format = properties.getAssertionIssuerFormat(); String sIssuer = properties.getIssuer(); if (!(StringUtils.isNotBlank(format) && isValidNameidFormat(format))) { format = NhincConstants.AUTH_FRWK_NAME_ID_FORMAT_X509; } if (!(StringUtils.isNotBlank(sIssuer) && checkDistinguishedName(sIssuer))) { if (certificate != null) { sIssuer = certificate.getSubjectX500Principal().getName(); } else { sIssuer = NhincConstants.SAML_DEFAULT_ISSUER_NAME; } } LOG.debug("Setting Assertion Issuer format to: {}", format); LOG.debug("Setting Assertion Issuer to: {}", sIssuer); return OpenSAML2ComponentBuilder.getInstance().createIssuer(format, sIssuer); }
Source:
private Element getSubjectAsElement(ServerSession session) { try { return SUBJECT_CACHE .get(session.getUsername(), () -> this.cacheAndReturnSubject(session)) .getPrincipals() .oneByType(SecurityAssertion.class) .getSecurityToken() .getToken(); } catch (ExecutionException e) { LOGGER.warn("Could not get Subject from token", e); return null; } }

Target:
private Element getSubjectAsElement(ServerSession session) { try { return SUBJECT_CACHE .get(session.getUsername(), () -> this.cacheAndReturnSubject(session)) .getPrincipals() .oneByType(SecurityAssertion.class) .getSecurityToken() .getToken(); } catch (ExecutionException e) { LOGGER.warn("Could not get Subject from token", e.getCause()); return null; } }
Source:
public void should_throw_error_if_consumer_array_is_null() { Consumer<String>[] consumers = null; Object o = null; String message = "The Consumer<? super E>... expressing the assertions consumers must not be null"; assertThatNullPointerException().isThrownBy(() -> assertThat(actual).satisfy(consumers)) .withMessage(message); }

Target:
public void should_throw_error_if_consumer_array_is_null() { Consumer<String>[] consumers = null; String message = "The Consumer<? super E>... expressing the assertions consumers must not be null"; assertThatNullPointerException().isThrownBy(() -> assertThat(actual).satisfy(consumers)) .withMessage(message); }
Source:
public void run() { List<Future> futures = new ArrayList<>(); for (Map.Entry<String, String> query : queries.entrySet()) { futures.add(executorService.submit(() -> { String metricName = query.getKey(); String measuresUrl = query.getValue() + "start=" + intervalStart(); try { URL url = new URL(measuresUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty(AUTHORIZATION, basicAuth); conn.setRequestMethod(GET); conn.setDoInput(true); List measures = JsonUtil.getMapper().readValue(conn.getInputStream(), List.class); List<Data> data = new ArrayList<>(); for (int i = 0; i < measures.size(); i++) { List measure = (List)measures.get(i); if (measure != null && measure.size() == 3) { String timestamp = (String)measure.get(0); Double value = (Double)measure.get(2); data.add(Data.forNumeric(trigger.getTenantId(), metricName, parseTimestamp(timestamp), value)); } } log.debugf("Sending [%s]", data); if (alerts != null) { alerts.sendData(data, true); } } catch (IOException e) { log.errorf(e,"Error querying Gnochi URL %s", measuresUrl); } catch (Exception e) { log.errorf(e, "Error sending data to the Alerting Engine"); } })); } for (Future future : futures) { try { future.get(); } catch (Exception e) { log.error(e); } } }

Target:
public void run() { List<Future> futures = new ArrayList<>(); for (Map.Entry<String, String> query : queries.entrySet()) { futures.add(executorService.submit(() -> { String metricName = query.getKey(); String measuresUrl = query.getValue() + "start=" + intervalStart(); try { URL url = new URL(measuresUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty(AUTHORIZATION, basicAuth); conn.setRequestMethod(GET); conn.setDoInput(true); List measures = JsonUtil.getMapper().readValue(conn.getInputStream(), List.class); List<Data> data = new ArrayList<>(); for (int i = 0; i < measures.size(); i++) { List measure = (List)measures.get(i); if (measure != null && measure.size() == 3) { String timestamp = (String) measure.get(0); Double granularity = (Double) measure.get(1); Double value = (Double) measure.get(2); Map<String, String> context = new HashMap<>(); context.put("granularity", String.valueOf(granularity)); data.add(Data.forNumeric(trigger.getTenantId(), metricName, parseTimestamp(timestamp), value, context)); } } log.debugf("Sending [%s]", data); if (alerts != null) { alerts.sendData(data, true); } } catch (IOException e) { log.errorf(e,"Error querying Gnochi URL %s", measuresUrl); } catch (Exception e) { log.errorf(e, "Error sending data to the Alerting Engine"); } })); } for (Future future : futures) { try { future.get(); } catch (Exception e) { log.error(e); } } }
Source:
protected void addResponseHandlers(ChannelPipeline p, Fulfiller<? super StreamedResponse> fulfiller) { if (requestSpecBacking.isDecompressResponse()) { p.addLast(new HttpContentDecompressor()); } p.addLast("httpResponseHandler", new SimpleChannelInboundHandler<HttpResponse>(false) { @Override public void channelRead0(ChannelHandlerContext ctx, HttpResponse msg) throws Exception { p.channel().config().setAutoRead(false); execution.onCleanup(() -> { if (!subscribedTo.get() && ctx.channel().isOpen()) { ctx.close(); } }); final Headers headers = new NettyHeadersBackedHeaders(msg.headers()); final Status status = new DefaultStatus(msg.status()); success(fulfiller, new DefaultStreamedResponse(p, status, headers)); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); error(fulfiller, cause); } }); }

Target:
protected void addResponseHandlers(ChannelPipeline p, Fulfiller<? super StreamedResponse> fulfiller) { p.addLast("httpResponseHandler", new SimpleChannelInboundHandler<HttpResponse>(false) { @Override public void channelRead0(ChannelHandlerContext ctx, HttpResponse msg) throws Exception { p.channel().config().setAutoRead(false); execution.onCleanup(() -> { if (!subscribedTo.get() && ctx.channel().isOpen()) { ctx.close(); } }); final Headers headers = new NettyHeadersBackedHeaders(msg.headers()); final Status status = new DefaultStatus(msg.status()); success(fulfiller, new DefaultStreamedResponse(p, status, headers)); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); error(fulfiller, cause); } }); }
Source:
public void doNotSaveUserSettingsWithNonExistingLanguage() { userRepository.save(new User(ID, USERNAME, FULL_NAME, AVATAR_URL, PROFILE_URL)); thrown.expect(ConstraintViolationException.class); UserSettings userSettings = new UserSettings(); userSettings.language = "xx"; userService.updateUserSettings(ID, userSettings); }

Target:
public void doNotSaveUserSettingsWithNonExistingLanguage() { userRepository.save(new User(ID, USERNAME, FULL_NAME, AVATAR_URL, PROFILE_URL)); UserSettings userSettings = new UserSettings(); userSettings.language = "xx"; userService.updateUserSettings(ID, userSettings); }
Source:
public DocumentModelList query(String query, String queryType, Filter filter, long limit, long offset, long countUpTo) { Span span = Tracing.getTracer().getCurrentSpan(); Map<String, AttributeValue> attributes = new HashMap<>(); attributes.put("nxql", AttributeValue.stringAttributeValue(query)); if (filter != null) { attributes.put("filter", AttributeValue.stringAttributeValue(filter.toString())); } attributes.put("limit", AttributeValue.longAttributeValue(limit)); attributes.put("offset", AttributeValue.longAttributeValue(offset)); attributes.put("countUpTo", AttributeValue.longAttributeValue(countUpTo)); span.addAnnotation("query", attributes); DocumentModelList ret = tracedQuery(query, queryType, filter, limit, offset, countUpTo); attributes.clear(); attributes.put("match", AttributeValue.longAttributeValue(ret.totalSize())); span.addAnnotation("query.done", attributes); return ret; }

Target:
public DocumentModelList query(String query, String queryType, Filter filter, long limit, long offset, long countUpTo) { Span span = Tracing.getTracer().getCurrentSpan(); Map<String, AttributeValue> map = new HashMap<>(); map.put("nxql", AttributeValue.stringAttributeValue(query)); if (filter != null) { map.put("filter", AttributeValue.stringAttributeValue(filter.toString())); } map.put("limit", AttributeValue.longAttributeValue(limit)); map.put("offset", AttributeValue.longAttributeValue(offset)); map.put("countUpTo", AttributeValue.longAttributeValue(countUpTo)); span.addAnnotation("AbstractSession#query", map); DocumentModelList ret = tracedQuery(query, queryType, filter, limit, offset, countUpTo); map.clear(); map.put("totalSize", AttributeValue.longAttributeValue(ret.totalSize())); span.addAnnotation("AbstractSession#query.done", map); return ret; }
Source:
public List<TypeSpec> generateTypes(final TypeElement annotatedTypeElement) { final List<ExecutableElement> propertyMethods = getPropertyMethodsSorted(annotatedTypeElement); final List<TypeSpec> typeSpecList = propertyMethods.stream() .filter(m -> isPrimitiveType(PropertyGenModel.of(m).getType())) .map(propertyMethod -> { final PropertyGenModel property = PropertyGenModel.of(propertyMethod); final MethodSpec getMethod = createGetMethodBuilder(propertyMethod).build(); final String actionPrefix = property.isOptional() ? "set" : "change"; final FieldSpec fieldSpec = createFieldBuilder(property, Modifier.PRIVATE) .addModifiers(Modifier.FINAL) .build(); final String updateAction = actionPrefix + StringUtils.capitalize(fieldSpec.name); final String updateActionClassName = StringUtils.capitalize(updateAction); final TypeSpec.Builder typeSpecBuilder = TypeSpec.classBuilder(updateActionClassName) .addJavadoc("$L $L to $L\n", property.isOptional() ? "Sets" : "Updates", fieldSpec.name, ClassName.get(annotatedTypeElement).simpleName()) .addJavadoc("\n") .addJavadoc("{@doc.gen intro}\n") .superclass(ParameterizedTypeName.get(ClassName.get(UpdateActionImpl.class), ClassName.get(annotatedTypeElement))) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", getClass().getCanonicalName()) .addMember("comments", "$S", "Generated from: " + annotatedTypeElement.getQualifiedName().toString()).build()) .addField(createFieldBuilder(property, Modifier.PRIVATE) .addModifiers(Modifier.FINAL) .build()) .addMethod(createConstructor(property, updateAction)) .addMethod(getMethod) .addMethod(createFactoryMethod(property, updateActionClassName)); if (property.isOptional()) { typeSpecBuilder.addMethod(createUnsetMethod(updateActionClassName)); } return typeSpecBuilder.build(); }).collect(Collectors.toList()); return typeSpecList; }

Target:
public List<TypeSpec> generateTypes(final TypeElement annotatedTypeElement) { final List<ExecutableElement> propertyMethods = getPropertyMethodsSorted(annotatedTypeElement); final List<TypeSpec> typeSpecList = propertyMethods.stream() .filter(m -> typeUtils.isPrimitiveType(PropertyGenModel.of(m).getType())) .map(propertyMethod -> generateUpdateAction(annotatedTypeElement, propertyMethod)).collect(Collectors.toList()); return typeSpecList; }
Source:
private Map<String, List<NameOccurrence>> getRuleAnnotatedExpectedExceptions(Scope classScope) { Map<String, List<NameOccurrence>> result = new HashMap<>(); Map<NameDeclaration, List<NameOccurrence>> decls = classScope.getDeclarations(); for (NameDeclaration decl : decls.keySet()) { Node parent = decl.getNode().jjtGetParent().jjtGetParent().jjtGetParent(); if (parent.hasDescendantOfType(ASTAnnotation.class) && parent.getFirstChildOfType(ASTFieldDeclaration.class) != null) { if (!"Rule" .equals(parent.getFirstDescendantOfType(ASTMarkerAnnotation.class).jjtGetChild(0).getImage())) { System.out.println( parent.getFirstDescendantOfType(ASTMarkerAnnotation.class).jjtGetChild(0).getImage()); continue; } Node type = parent.getFirstDescendantOfType(ASTReferenceType.class); if (!"ExpectedException".equals(type.jjtGetChild(0).getImage())) { System.out.println(type.jjtGetChild(0).getImage()); continue; } result.put(decl.getName(), decls.get(decl)); } } return result; }

Target:
private Map<String, List<NameOccurrence>> getRuleAnnotatedExpectedExceptions(Scope classScope) { Map<String, List<NameOccurrence>> result = new HashMap<>(); Map<NameDeclaration, List<NameOccurrence>> decls = classScope.getDeclarations(); for (NameDeclaration decl : decls.keySet()) { Node parent = decl.getNode().jjtGetParent().jjtGetParent().jjtGetParent(); if (parent.hasDescendantOfType(ASTAnnotation.class) && parent.getFirstChildOfType(ASTFieldDeclaration.class) != null) { String annot = parent.getFirstDescendantOfType(ASTMarkerAnnotation.class).jjtGetChild(0).getImage(); if (!"Rule".equals(annot) && !"org.junit.Rule".equals(annot)) { continue; } Node type = parent.getFirstDescendantOfType(ASTReferenceType.class); if (!"ExpectedException".equals(type.jjtGetChild(0).getImage())) { continue; } result.put(decl.getName(), decls.get(decl)); } } return result; }
Source:
public Matrix bernoulli(final int rows, final int columns, final float prob) { final int length = rows * columns; final float[] data = new float[length]; for (int i = 0; i < length; ++i) { if (randomGenerator.nextFloat() > prob) { data[i] = 1; } else { data[i] = 0; } } return create(data, rows, columns); }

Target:
public Matrix bernoulli(final int rows, final int columns, final float prob) { return bernoulli(rows, columns, prob, 1); }
Source:
public void addPremisEventsTest() throws IOException { File premisEventsDir = job.getEventsDirectory(); premisEventsDir.mkdir(); PID folderObjPid = repository.mintContentPid(); folderObjPid = repository.mintContentPid(); File premisEventsFile = new File(premisEventsDir, folderObjPid.getUUID() + ".xml"); premisEventsFile.createNewFile(); String label = "testfolder"; Model model = job.getWritableModel(); Bag depBag = model.createBag(depositPid.getRepositoryPath()); Bag folderBag = model.createBag(folderObjPid.getRepositoryPath()); folderBag.addProperty(RDF.type, Cdr.Folder); folderBag.addProperty(CdrDeposit.label, label); depBag.add(folderBag); FilePremisLogger premisLogger = new FilePremisLogger(folderObjPid, premisEventsFile, repository); Resource event1 = premisLogger.buildEvent(Premis.Normalization) .addEventDetail("Event 1") .addAuthorizingAgent(SoftwareAgent.depositService.getFullname()) .write(); Resource event2 = premisLogger.buildEvent(Premis.VirusCheck) .addEventDetail("Event 2") .addSoftwareAgent(SoftwareAgent.clamav.getFullname()) .write(); job.closeModel(); job.run(); FolderObject folder = repository.getFolderObject(folderObjPid); List<PremisEventObject> events = folder.getPremisLog().getEvents(); assertEquals(2, events.size()); assertTrue(events.contains(findPremisEventByType(events, Premis.Normalization))); assertTrue(events.contains(findPremisEventByType(events, Premis.VirusCheck))); }

Target:
public void addPremisEventsTest() throws IOException { File premisEventsDir = job.getEventsDirectory(); premisEventsDir.mkdir(); PID folderObjPid = repository.mintContentPid(); File premisEventsFile = new File(premisEventsDir, folderObjPid.getUUID() + ".xml"); premisEventsFile.createNewFile(); String label = "testfolder"; Model model = job.getWritableModel(); Bag depBag = model.createBag(depositPid.getRepositoryPath()); Bag folderBag = model.createBag(folderObjPid.getRepositoryPath()); folderBag.addProperty(RDF.type, Cdr.Folder); folderBag.addProperty(CdrDeposit.label, label); depBag.add(folderBag); FilePremisLogger premisLogger = new FilePremisLogger(folderObjPid, premisEventsFile, repository); Resource event1 = premisLogger.buildEvent(Premis.Normalization) .addEventDetail("Event 1") .addAuthorizingAgent(SoftwareAgent.depositService.getFullname()) .write(); Resource event2 = premisLogger.buildEvent(Premis.VirusCheck) .addEventDetail("Event 2") .addSoftwareAgent(SoftwareAgent.clamav.getFullname()) .write(); job.closeModel(); job.run(); FolderObject folder = repository.getFolderObject(folderObjPid); List<PremisEventObject> events = folder.getPremisLog().getEvents(); assertEquals(2, events.size()); assertTrue(events.contains(findPremisEventByType(events, Premis.Normalization))); assertTrue(events.contains(findPremisEventByType(events, Premis.VirusCheck))); }
Source:
public void removeObject(WordsObject object) { object.clearReferers(); for (HashMap<String, WordsObject> scope : objectsByName) { if (scope.get(object.getObjectName()) != null) { scope.remove(object.getObjectName()); break; } } for (WordsClass wordsClass : objectsByClass.keySet()) { HashSet<WordsObject> objectSet = objectsByClass.get(wordsClass); if (objectSet.contains(object)) { objectSet.remove(object); } } }

Target:
public void removeObject(WordsObject object) { object.clearReferers(); for (HashMap<String, WordsObject> scope : objectsByName) { if (scope.remove(object.getObjectName()) != null) { break; } } objectsByClass.get(object.getWordsClass()).remove(object); }
Source:
public boolean hasTemplatePath(TreeReference ref) { if (caseDbSpecTemplate != null) { return followsTemplateSpec(ref, caseDbSpecTemplate, 0); } else { Logger.log("CaseDb Warning", "Using default hasTemplatePath implementation: reference resolution will break!"); return super.hasTemplatePath(ref); } }

Target:
public boolean hasTemplatePath(TreeReference ref) { loadTemplateSpecLazily(); return followsTemplateSpec(ref, caseDbSpecTemplate, 0); }
Source:
public CloseableIterator<byte[]> keys(byte[] firstKey, byte[] lastKey) { final RocksIterator iterator = db.newIterator(optionCache); iterator.seek(firstKey); return new CloseableIterator<byte[]>() { @Override public boolean hasNext() { return iterator.isValid() && ByteComparator.compare(iterator.key(), lastKey) < 0; } @Override public byte[] next() { checkArgument(iterator.isValid()); byte[] key = iterator.key(); iterator.next(); return key; } @Override public void close() { iterator.close(); } }; }

Target:
public CloseableIterator<byte[]> keys(byte[] firstKey, byte[] lastKey) { final RocksIterator iterator = db.newIterator(optionCache); iterator.seek(firstKey); return new CloseableIterator<byte[]>() { @Override public boolean hasNext() { return iterator.isValid() && ByteComparator.compare(iterator.key(), lastKey) < 0; } @Override public byte[] next() { checkState(iterator.isValid()); byte[] key = iterator.key(); iterator.next(); return key; } @Override public void close() { iterator.close(); } }; }