auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testUpdateAllBrickTasksByHostIdBrickDir() { GlusterBrickEntity existingBrick = dao.getById(FixturesTool.GLUSTER_BRICK_UUID1); GlusterBrickEntity existingBrick2 = dao.getById(FixturesTool.GLUSTER_BRICK_UUID2); GlusterAsyncTask asyncTask = new GlusterAsyncTask(); asyncTask.setTaskId(FixturesTool.GLUSTER_ASYNC_TASK_ID1); GlusterBrickEntity updateBrick = new GlusterBrickEntity(); updateBrick.setBrickDirectory(existingBrick.getBrickDirectory()); updateBrick.setServerId(existingBrick.getServerId()); updateBrick.setAsyncTask(asyncTask); GlusterBrickEntity updateBrick2 = new GlusterBrickEntity(); updateBrick2.setBrickDirectory(existingBrick2.getBrickDirectory()); updateBrick2.setServerId(existingBrick2.getServerId()); updateBrick2.setAsyncTask(asyncTask); List<GlusterBrickEntity> bricks = new ArrayList<>(); bricks.add(updateBrick); bricks.add(updateBrick2); <START> dao.updateAllBrickTasksByHostIdBrickDir(bricks); <END> GlusterBrickEntity newEntity1 = dao.getById(FixturesTool.GLUSTER_BRICK_UUID1); GlusterBrickEntity newEntity2 = dao.getById(FixturesTool.GLUSTER_BRICK_UUID1); assertEquals(FixturesTool.GLUSTER_ASYNC_TASK_ID1, newEntity1.getAsyncTask().getTaskId()); assertEquals(FixturesTool.GLUSTER_ASYNC_TASK_ID1, newEntity2.getAsyncTask().getTaskId()); }</code><technical_language>call this method updateAllBrickTasksByHostIdBrickDirInBatch()? a thought</technical_language>

Target:
public void testUpdateAllBrickTasksByHostIdBrickDir() { GlusterBrickEntity existingBrick = dao.getById(FixturesTool.GLUSTER_BRICK_UUID1); GlusterBrickEntity existingBrick2 = dao.getById(FixturesTool.GLUSTER_BRICK_UUID2); GlusterAsyncTask asyncTask = new GlusterAsyncTask(); asyncTask.setTaskId(FixturesTool.GLUSTER_ASYNC_TASK_ID1); GlusterBrickEntity updateBrick = new GlusterBrickEntity(); updateBrick.setBrickDirectory(existingBrick.getBrickDirectory()); updateBrick.setServerId(existingBrick.getServerId()); updateBrick.setAsyncTask(asyncTask); GlusterBrickEntity updateBrick2 = new GlusterBrickEntity(); updateBrick2.setBrickDirectory(existingBrick2.getBrickDirectory()); updateBrick2.setServerId(existingBrick2.getServerId()); updateBrick2.setAsyncTask(asyncTask); List<GlusterBrickEntity> bricks = new ArrayList<>(); bricks.add(updateBrick); bricks.add(updateBrick2); dao.updateAllBrickTasksByHostIdBrickDirInBatch(bricks); GlusterBrickEntity newEntity1 = dao.getById(FixturesTool.GLUSTER_BRICK_UUID1); GlusterBrickEntity newEntity2 = dao.getById(FixturesTool.GLUSTER_BRICK_UUID1); assertEquals(FixturesTool.GLUSTER_ASYNC_TASK_ID1, newEntity1.getAsyncTask().getTaskId()); assertEquals(FixturesTool.GLUSTER_ASYNC_TASK_ID1, newEntity2.getAsyncTask().getTaskId()); }
Source:
<code>private void processWorkerMetrics(final String srcId, final MetricMsg metricMsg) { for (final ByteBuffer encodedBuffer : metricMsg.getCustomMetrics()) { final DolphinWorkerMetrics workerMetrics = metricMsgCodec.decode(encodedBuffer.array()); final Map<String, Integer> tableToNumBlocks = metricMsg.getTableToNumBlocks(); final String hostname = metricMsg.getHostname(); switch (workerMetrics.getType()) { case BatchMetrics: final BatchMetrics batchMetrics = workerMetrics.getBatchMetrics(); final WorkerMetrics convertedBatchMetrics = convertBatchMetrics(metricMsg, tableToNumBlocks, hostname, batchMetrics); metricManager.storeWorkerMetrics(srcId, convertedBatchMetrics); break; case EpochMetrics: final EpochMetrics epochMetrics = workerMetrics.getEpochMetrics(); final WorkerMetrics convertedEpochMetrics = convertEpochMetrics(metricMsg, hostname, epochMetrics); metricManager.storeWorkerMetrics(srcId, convertedEpochMetrics); break; default: throw new RuntimeException("Unknown message type"); } <START> LOG.log(Level.INFO, "Received a worker metric from {0}: {1}", new Object[] {workerMetrics, srcId}); <END> } }</code><technical_language>Arguments switched</technical_language>

Target:
private void processWorkerMetrics(final String srcId, final MetricMsg metricMsg) { for (final ByteBuffer encodedBuffer : metricMsg.getCustomMetrics()) { final DolphinWorkerMetrics workerMetrics = metricMsgCodec.decode(encodedBuffer.array()); final Map<String, Integer> tableToNumBlocks = metricMsg.getTableToNumBlocks(); final String hostname = metricMsg.getHostname(); switch (workerMetrics.getType()) { case BatchMetrics: final BatchMetrics batchMetrics = workerMetrics.getBatchMetrics(); final WorkerMetrics convertedBatchMetrics = convertBatchMetrics(metricMsg, tableToNumBlocks, hostname, batchMetrics); metricManager.storeWorkerMetrics(srcId, convertedBatchMetrics); break; case EpochMetrics: final EpochMetrics epochMetrics = workerMetrics.getEpochMetrics(); final WorkerMetrics convertedEpochMetrics = convertEpochMetrics(metricMsg, hostname, epochMetrics); metricManager.storeWorkerMetrics(srcId, convertedEpochMetrics); break; default: throw new RuntimeException("Unknown message type"); } LOG.log(Level.INFO, "Received a worker metric from {0}: {1}", new Object[] {srcId, workerMetrics}); } }
Source:
<code>public BoundedContext build() { if (this.name == null) { this.name = DEFAULT_NAME; } checkNotNull(storageFactory, "storageFactory must be set"); checkNotNull(commandBus, "commandDispatcher must be set"); checkNotNull(eventBus, "eventBus must be set"); <START> commandBus.setIsMultitenant(this.multitenant); <END> final BoundedContext result = new BoundedContext(this); log().info(result.nameForLogging() + " created."); return result; }</code><technical_language>setMultitenant sounds imperative is OK for this case. new name is harder read pronounce. Please revert</technical_language>

Target:
public BoundedContext build() { if (this.name == null) { this.name = DEFAULT_NAME; } checkNotNull(storageFactory, "storageFactory must be set"); checkNotNull(commandBus, "commandDispatcher must be set"); checkNotNull(eventBus, "eventBus must be set"); commandBus.setMultitenant(this.multitenant); final BoundedContext result = new BoundedContext(this); log().info(result.nameForLogging() + " created."); return result; }
Source:
<code>public final boolean has(Class<?> componentType, Direction direction) { <START> return getComponents(direction).has(componentType) | this.has(componentType); <END> }</code><technical_language>||</technical_language>

Target:
public final boolean has(Class<?> componentType, Direction direction) { return getComponents(direction).has(componentType) || this.has(componentType); }
Source:
<code>private PartitionStatistics createPartitionStatistics( ConnectorSession session, Map<String, Type> columnTypes, ComputedStatistics computedStatistics) { Map<ColumnStatisticMetadata, Block> computedColumnStatistics = computedStatistics.getColumnStatistics(); Block rowCountBlock = Optional.ofNullable(computedStatistics.getTableStatistics().get(ROW_COUNT)) <START> .orElseThrow(() -> new IllegalArgumentException("rowCount not present")); <END> verify(!rowCountBlock.isNull(0), "rowCount must never be null"); long rowCount = BIGINT.getLong(rowCountBlock, 0); Map<String, HiveColumnStatistics> columnStatistics = fromComputedStatistics( session, timeZone, computedColumnStatistics, columnTypes, rowCount); HiveBasicStatistics rowCountOnlyBasicStatistics = new HiveBasicStatistics(OptionalLong.empty(), OptionalLong.of(rowCount), OptionalLong.empty(), OptionalLong.empty()); return new PartitionStatistics(rowCountOnlyBasicStatistics, columnStatistics); }</code><technical_language>throw new VerifyException()</technical_language>

Target:
private PartitionStatistics createPartitionStatistics( ConnectorSession session, Map<String, Type> columnTypes, ComputedStatistics computedStatistics) { Map<ColumnStatisticMetadata, Block> computedColumnStatistics = computedStatistics.getColumnStatistics(); Block rowCountBlock = Optional.ofNullable(computedStatistics.getTableStatistics().get(ROW_COUNT)) .orElseThrow(() -> new VerifyException("rowCount not present")); verify(!rowCountBlock.isNull(0), "rowCount must never be null"); long rowCount = BIGINT.getLong(rowCountBlock, 0); HiveBasicStatistics rowCountOnlyBasicStatistics = new HiveBasicStatistics(OptionalLong.empty(), OptionalLong.of(rowCount), OptionalLong.empty(), OptionalLong.empty()); return createPartitionStatistics(session, rowCountOnlyBasicStatistics, columnTypes, computedColumnStatistics); }
Source:
<code>private MongoDbOutboundGatewaySpec queryOutboundGateway(String query, boolean expectSingleResult) { return MongoDb.outboundGateway(mongoDbFactory()) .query(query) <START> .collectionNameExpression(new LiteralExpression(TEST_COLLECTION)) <END> .expectSingleResult(expectSingleResult) .entityClass(PersonDomain.class); }</code><technical_language>introduce simple .collectionName(String collectionName) option</technical_language>

Target:
private MongoDbOutboundGatewaySpec queryOutboundGateway(String query, boolean expectSingleResult) { return MongoDb.outboundGateway(mongoDbFactory(), mongoConverter()) .query(query) .collectionNameExpression("headers.collection") .expectSingleResult(expectSingleResult) .entityClass(Person.class); }
Source:
<code>public void afterCompletion(int status) { if (trace) { log.tracef("AfterCompletion(xid=%s, status=%s, remote-caches=%s)", xid, transactionStatusToString(status), preparedCaches); } if (status == Status.STATUS_COMMITTED) { preparedCaches.forEach(this::commitContext); } else { preparedCaches.forEach(this::rollbackContext); } <START> cleanupTask.accept(transaction); <END> }</code><technical_language>put this finally</technical_language>

Target:
public void afterCompletion(int status) { if (trace) { log.tracef("AfterCompletion(xid=%s, status=%s, remote-caches=%s)", xid, transactionStatusToString(status), preparedCaches); } try { if (status == Status.STATUS_COMMITTED) { for (TransactionContext<?,?> ctx : preparedCaches) { commitContext(ctx); } } else { for (TransactionContext<?,?> ctx : preparedCaches) { rollbackContext(ctx); } } } finally { cleanupTask.accept(transaction); } }
Source:
<code>public T cloneData(int sourceIndex, int targetIndex) { if (sourceIndex < 0 || sourceIndex >= scesimData.size()) { throw new IllegalArgumentException(new StringBuilder().append("SourceIndex out of range ").append(sourceIndex).toString()); } if (targetIndex < 0 || targetIndex > scesimData.size()) { <START> throw new IllegalArgumentException(new StringBuilder().append("TargetIndex out of range ").append(targetIndex).toString()); <END> } T scesimDataByIndex = getDataByIndex(sourceIndex); T clonedScesimData = (T) scesimDataByIndex.cloneInstance(); scesimData.add(targetIndex, clonedScesimData); return clonedScesimData; }</code><technical_language>Suggestion throw IndexOutOfBoundsException</technical_language>

Target:
public T cloneData(int sourceIndex, int targetIndex) { if (sourceIndex < 0 || sourceIndex >= scesimData.size()) { throw new IndexOutOfBoundsException(new StringBuilder().append("SourceIndex out of range ").append(sourceIndex).toString()); } if (targetIndex < 0 || targetIndex > scesimData.size()) { throw new IndexOutOfBoundsException(new StringBuilder().append("TargetIndex out of range ").append(targetIndex).toString()); } T scesimDataByIndex = getDataByIndex(sourceIndex); T clonedScesimData = (T) scesimDataByIndex.cloneInstance(); scesimData.add(targetIndex, clonedScesimData); return clonedScesimData; }
Source:
<code>public String getFileName(String principalName, Object parsedFileContents, String userIdentifier) { String fileName = "cr_stale_" + principalName; if (StringUtils.isNotBlank(userIdentifier)) { fileName += "_" + userIdentifier; } <START> fileName = StringUtils.remove(fileName, " "); <END> return fileName; }</code><technical_language>KFSConstants a constant for a single-space string if want instead</technical_language>

Target:
public String getFileName(String principalName, Object parsedFileContents, String userIdentifier) { String fileName = "cr_stale_" + principalName; if (StringUtils.isNotBlank(userIdentifier)) { fileName += "_" + userIdentifier; } fileName = StringUtils.remove(fileName, KFSConstants.BLANK_SPACE); return fileName; }
Source:
<code>public String getMessageTextPreview() throws MessagingException { if (CryptoHelper.isPgpInlineEncrypted(message) || CryptoHelper.isPgpMimeEncrypted(message) || CryptoHelper.isSMimeEncrypted(message)) { <START> return "*Encrypted*"; <END> } getViewablesIfNecessary(); return MessagePreviewExtractor.extractPreview(context, viewables); }</code><technical_language>I this string needs externalized translated</technical_language>

Target:
public String getMessageTextPreview() throws MessagingException { if (CryptoHelper.isPgpInlineEncrypted(message) || CryptoHelper.isPgpMimeEncrypted(message) || CryptoHelper.isSMimeEncrypted(message)) { return context.getString(R.string.openpgp_message_preview); } getViewablesIfNecessary(); return MessagePreviewExtractor.extractPreview(context, viewables); }
Source:
<code>public void run() { connectionTimeout = config.getConnectionTimeout(); poolElf.setValidationTimeout(config.getValidationTimeout()); leakTask.updateLeakDetectionThreshold(config.getLeakDetectionThreshold()); final long now = clockSource.currentTime(); final long idleTimeout = config.getIdleTimeout(); if (now < previous || now > clockSource.plusMillis(previous, (2 * HOUSEKEEPING_PERIOD_MS))) { LOGGER.warn("{} - Unusual system clock change detected, soft-evicting connections from pool.", poolName); previous = now; softEvictConnections(); fillPool(); return; } else { previous = now; } logPoolState("Before cleanup "); final int minIdle = config.getMinimumIdle(); final List<PoolBagEntry> bag = connectionBag.values(STATE_NOT_IN_USE); int totIdle = bag.size(); for (PoolBagEntry bagEntry : bag) { if (connectionBag.reserve(bagEntry)) { if (bagEntry.evicted) { closeConnection(bagEntry, "(connection evicted)"); totIdle --; } else if (totIdle > minIdle && idleTimeout > 0L && clockSource.elapsedMillis(bagEntry.lastAccess, now) > idleTimeout) { closeConnection(bagEntry, "(connection passed idleTimeout)"); totIdle --; <START> } <END> else { connectionBag.unreserve(bagEntry); } } } logPoolState("After cleanup "); fillPool(); }</code><technical_language>Try: java final List<PoolBagEntry> bag = connectionBag.values(STATE_NOT_IN_USE); int removable = bag.size() - config.getMinimumIdle(); for (PoolBagEntry bagEntry : bag) { if (connectionBag.reserve(bagEntry)) { if (bagEntry.evicted) { closeConnection(bagEntry, "(connection evicted)"); removable--; } else if (removable > 0 && idleTimeout > 0L && clockSource.elapsedMillis(bagEntry.lastAccess, now) > idleTimeout){ closeConnection(bagEntry, "(connection passed idleTimeout)"); removable--; } else { connectionBag.unreserve(bagEntry); } } }</technical_language>

Target:
public void run() { connectionTimeout = config.getConnectionTimeout(); poolElf.setValidationTimeout(config.getValidationTimeout()); leakTask.updateLeakDetectionThreshold(config.getLeakDetectionThreshold()); final long now = clockSource.currentTime(); final long idleTimeout = config.getIdleTimeout(); if (now < previous || now > clockSource.plusMillis(previous, (2 * HOUSEKEEPING_PERIOD_MS))) { LOGGER.warn("{} - Unusual system clock change detected, soft-evicting connections from pool.", poolName); previous = now; softEvictConnections(); fillPool(); return; } else { previous = now; } logPoolState("Before cleanup "); final List<PoolBagEntry> bag = connectionBag.values(STATE_NOT_IN_USE); int removable = bag.size() - config.getMinimumIdle(); for (PoolBagEntry bagEntry : bag) { if (connectionBag.reserve(bagEntry)) { if (removable > 0 && idleTimeout > 0L && clockSource.elapsedMillis(bagEntry.lastAccess, now) > idleTimeout) { closeConnection(bagEntry, "(connection passed idleTimeout)"); removable--; } else { connectionBag.unreserve(bagEntry); } } } logPoolState("After cleanup "); fillPool(); }
Source:
<code>private void enterMultiSelect() { <START> FragmentActivity activity = requireActivity(); <END> ((AppCompatActivity) activity).startSupportActionMode(actionModeCallback); ((MediaOverviewActivity) activity).onEnterMultiSelect(); }</code><technical_language>cast MediaOverviewActivity here, instead of multiple casts next lines. fair, I feel this part of a single callback/listener call</technical_language>

Target:
private void enterMultiSelect() { MediaOverviewActivity activity = (MediaOverviewActivity) requireActivity(); activity.startSupportActionMode(actionModeCallback); activity.onEnterMultiSelect(); }
Source:
<code>public void prepareRun(BatchSinkContext context) throws Exception { ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); <START> Job job = JobUtils.createInstance(); <END> Thread.currentThread().setContextClassLoader(oldClassLoader); Configuration conf = job.getConfiguration(); HBaseConfiguration.addHbaseResources(conf); context.addOutput(Output.of(config.referenceName, new HBaseOutputFormatProvider(config, conf)) .alias(config.columnFamily)); }</code><technical_language>a failure here? enclose in a try...finally</technical_language>

Target:
public void prepareRun(BatchSinkContext context) throws Exception { Job job; ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); try { job = JobUtils.createInstance(); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } Configuration conf = job.getConfiguration(); HBaseConfiguration.addHbaseResources(conf); context.addOutput(Output.of(config.referenceName, new HBaseOutputFormatProvider(config, conf)) .alias(config.columnFamily)); }
Source:
<code>public int write(Iterable<StructuredRecord> structuredRecords, DataWriter dataWriter) throws Exception { int numRecordsWritten = 0; String solrFieldName; List<SolrInputDocument> documentList = new ArrayList<SolrInputDocument>(); SolrInputDocument document; <START> config.verifySolrConfiguration(); <END> for (StructuredRecord structuredRecord : structuredRecords) { config.validateKeyField(structuredRecord.getSchema()); config.validateInputFieldsDataType(structuredRecord.getSchema()); if (structuredRecord.get(uniqueKey) == null) { continue; } document = new SolrInputDocument(); for (Schema.Field field : structuredRecord.getSchema().getFields()) { solrFieldName = field.getName(); if (outputFieldMap.containsKey(solrFieldName)) { document.addField(outputFieldMap.get(solrFieldName), structuredRecord.get(solrFieldName)); } else { document.addField(solrFieldName, structuredRecord.get(solrFieldName)); } } documentList.add(document); numRecordsWritten++; } solrClient.add(documentList); solrClient.commit(); return numRecordsWritten; }</code><technical_language>verify in write method? in initialize method</technical_language>

Target:
public int write(Iterable<StructuredRecord> structuredRecords, DataWriter dataWriter) throws Exception { int numRecordsWritten = 0; String solrFieldName; List<SolrInputDocument> documentList = new ArrayList<SolrInputDocument>(); SolrInputDocument document; for (StructuredRecord structuredRecord : structuredRecords) { config.validateKeyField(structuredRecord.getSchema()); config.validateInputFieldsDataType(structuredRecord.getSchema()); if (structuredRecord.get(uniqueKey) == null) { continue; } document = new SolrInputDocument(); for (Schema.Field field : structuredRecord.getSchema().getFields()) { solrFieldName = field.getName(); if (outputFieldMap.containsKey(solrFieldName)) { document.addField(outputFieldMap.get(solrFieldName), structuredRecord.get(solrFieldName)); } else { document.addField(solrFieldName, structuredRecord.get(solrFieldName)); } } documentList.add(document); numRecordsWritten++; } solrClient.add(documentList); solrClient.commit(); return numRecordsWritten; }
Source:
<code>protected void executeCommand() { DiskImage diskImage = getImage(); <START> getParameters().setStoragePoolId(diskImage.getStoragePoolId().getValue()); <END> getParameters().setStorageDomainId(diskImage.getStorageIds().get(0)); getParameters().setImageGroupID(diskImage.getId()); lockImage(); VDSReturnValue vdsReturnValue = runVdsCommand(VDSCommandType.ExtendImageSize, createExtendImageSizeVDSCommandParameters(diskImage)); if (vdsReturnValue.getSucceeded()) { Guid taskId = createTask(vdsReturnValue.getCreationInfo(), VdcActionType.ExtendImageSize); getReturnValue().getTaskIdList().add(taskId); setSucceeded(true); } }</code><technical_language>class properties of parameters class set here? If this is is filled calling side command ,why define command class itself? confusing caller this object wrongly conclude needs fill parameters. If is a need fill parameters outside, wrongly overriden here, a validation + error thrown if missing</technical_language>

Target:
protected void executeCommand() { VDSReturnValue vdsReturnValue = runVdsCommand(VDSCommandType.ExtendImageSize, createExtendImageSizeVDSCommandParameters((DiskImage) getImage())); if (vdsReturnValue.getSucceeded()) { VdcActionType actionType = (getParameters().getParentCommand() != null) ? getParameters().getParentCommand() : VdcActionType.ExtendImageSize; getReturnValue().getInternalTaskIdList().add(createTask(vdsReturnValue.getCreationInfo(), actionType)); setSucceeded(true); } else { setSucceeded(false); } }
Source:
<code>public void noVariantsNothingShouldBeWritten() throws UnknownHostException { String dbName = "VariantMongoWriterNoVariant"; <START> objectMap.put("db.name", dbName); <END> MongoOperations mongoOperations = MongoDBHelper.getMongoOperationsFromPipelineOptions(objectMap); DBCollection dbCollection = mongoOperations.getCollection(collectionName); variantMongoWriter = new VariantMongoWriter(collectionName, mongoOperations, variantToMongoDbObjectConverter); variantMongoWriter.doWrite(Collections.EMPTY_LIST); assertEquals(0, dbCollection.count()); }</code><technical_language>This JobParametersNames</technical_language>

Target:
public void noVariantsNothingShouldBeWritten() throws UnknownHostException { String dbName = "VariantMongoWriterNoVariant"; objectMap.put(JobParametersNames.DB_NAME, dbName); MongoOperations mongoOperations = MongoDBHelper.getMongoOperationsFromPipelineOptions(objectMap); DBCollection dbCollection = mongoOperations.getCollection(collectionName); variantMongoWriter = new VariantMongoWriter(collectionName, mongoOperations, variantToMongoDbObjectConverter); variantMongoWriter.doWrite(Collections.EMPTY_LIST); assertEquals(0, dbCollection.count()); }
Source:
<code><START> public ArrayInterface setDictionary(int index, Dictionary value) { <END> return setObject(index, value); }</code><technical_language>I return Array here</technical_language>

Target:
public Array setDictionary(int index, Dictionary value) { return setObject(index, value); }
Source:
<code>protected void readValue(BlockBuilder blockBuilder, Type type) { if (definitionLevel == columnDescriptor.getMaxDefinitionLevel()) { type.writeBoolean(blockBuilder, valuesReader.readBoolean()); } else if (isNullValue()) { <START> blockBuilder.appendNull(); <END> } }</code><technical_language>ditto a final else block here</technical_language>

Target:
protected void readValue(BlockBuilder blockBuilder, Type type) { if (definitionLevel == columnDescriptor.getMaxDefinitionLevel()) { type.writeBoolean(blockBuilder, valuesReader.readBoolean()); } else if (isValueNull()) { blockBuilder.appendNull(); } }
Source:
<code>protected void prepareToDeletePreviewBranch() { removedSnapshotId = getSnapshotDao().getId(getVmId(), SnapshotType.PREVIEW); Guid previewedSnapshotId = getSnapshotDao().getId(getVmId(), SnapshotType.REGULAR, SnapshotStatus.IN_PREVIEW); getSnapshotDao().updateStatus(previewedSnapshotId, SnapshotStatus.OK); snapshotsToRemove.add(removedSnapshotId); List<DiskImage> images = getDiskImageDao().getAllSnapshotsForVmSnapshot(removedSnapshotId); for (DiskImage image : images) { <START> if (image.getDiskStorageType() != DiskStorageType.CINDER) { <END> DiskImage parentImage = getDiskImageDao().getSnapshotById(image.getParentId()); Guid snapshotToRemove = (parentImage == null) ? null : parentImage.getVmSnapshotId(); while (parentImage != null && snapshotToRemove != null && !snapshotToRemove.equals(previewedSnapshotId)) { snapshotsToRemove.add(snapshotToRemove); parentImage = getDiskImageDao().getSnapshotById(parentImage.getParentId()); snapshotToRemove = (parentImage == null) ? null : parentImage.getVmSnapshotId(); } } else { snapshotsToRemove.remove(removedSnapshotId); } } List<DiskImage> cinderImagesForPreviewedSnapshot = getDiskImageDao().getAllSnapshotsForVmSnapshot(previewedSnapshotId); for (DiskImage image : cinderImagesForPreviewedSnapshot) { if (image.getDiskStorageType() == DiskStorageType.CINDER) { List<CinderDisk> cinderDisks = CINDERStorageHelper.getRedundantVolumeToDeleteAfterCommitSnapshot(image.getImageId(), image.getId()); for (CinderDisk cinderDisk : cinderDisks) { snapshotsToRemove.add(cinderDisk.getVmSnapshotId()); } } } }</code><technical_language>switch storage type, or, check '== Image' -> 'else if == Cinder'</technical_language>

Target:
protected void prepareToDeletePreviewBranch() { removedSnapshotId = getSnapshotDao().getId(getVmId(), SnapshotType.PREVIEW); Guid previewedSnapshotId = getSnapshotDao().getId(getVmId(), SnapshotType.REGULAR, SnapshotStatus.IN_PREVIEW); getSnapshotDao().updateStatus(previewedSnapshotId, SnapshotStatus.OK); snapshotsToRemove.add(removedSnapshotId); List<DiskImage> images = getDiskImageDao().getAllSnapshotsForVmSnapshot(removedSnapshotId); for (DiskImage image : images) { if (image.getDiskStorageType() == DiskStorageType.IMAGE) { DiskImage parentImage = getDiskImageDao().getSnapshotById(image.getParentId()); Guid snapshotToRemove = (parentImage == null) ? null : parentImage.getVmSnapshotId(); while (parentImage != null && snapshotToRemove != null && !snapshotToRemove.equals(previewedSnapshotId)) { snapshotsToRemove.add(snapshotToRemove); parentImage = getDiskImageDao().getSnapshotById(parentImage.getParentId()); snapshotToRemove = (parentImage == null) ? null : parentImage.getVmSnapshotId(); } } else if (image.getDiskStorageType() == DiskStorageType.CINDER){ snapshotsToRemove.remove(removedSnapshotId); } } addRedundantCinderSnapshots(previewedSnapshotId); }
Source:
<code>public void getPermissions_returnLoadedResults() { PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.getPermissions(new PermissionManager.Callback<RealmResults<Permission>>() { @Override public void onSuccess(RealmResults<Permission> permissions) { assertTrue(permissions.isLoaded()); <START> if (permissions.size() > 1) { <END> RealmLog.error("Unexpected number of permissions (%s):" + permissions.size()); for (Permission permission : permissions) { RealmLog.error(permission.toString()); } } assertEquals(1, permissions.size()); looperThread.testComplete(); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); }</code><technical_language>curious: this happen</technical_language>

Target:
public void getPermissions_returnLoadedResults() { PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.getPermissions(new PermissionManager.Callback<RealmResults<Permission>>() { @Override public void onSuccess(RealmResults<Permission> permissions) { assertTrue(permissions.isLoaded()); assertInitialPermissions(permissions); looperThread.testComplete(); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); }
Source:
<code>@Override protected RepositoryMetadata getRepositoryMetadata(Class<?> repoItf) { Assert.notNull(repoItf, "Repository interface must be set."); Assert.isAssignable(IgniteRepository.class, repoItf, "Repository must implement IgniteRepository interface."); RepositoryConfig annotation = repoItf.getAnnotation(RepositoryConfig.class); Assert.notNull(annotation, "Set a name of an Apache Ignite cache using @RepositoryConfig annotation to map " + "this repository to the underlying cache."); Assert.hasText(annotation.cacheName(), "Set a name of an Apache Ignite cache using @RepositoryConfig " + "annotation to map this repository to the underlying cache."); String cacheName = null; if (!looksLikeExpression(annotation.cacheName())) { <START> cacheName = annotation.cacheName(); <END> } else { SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression(annotation.cacheName()); StandardEvaluationContext ec = new StandardEvaluationContext(); ec.setBeanResolver(new BeanFactoryResolver(ctx.getAutowireCapableBeanFactory())); cacheName = (String)expression.getValue(ec); } repoToCache.put(repoItf, cacheName); repoToCache.put(repoItf, annotation.cacheName()); return super.getRepositoryMetadata(repoItf); }</code><technical_language>line if statements brackets: java if (!looksLikeExpression(annotation.cacheName())) cacheName = annotation.cacheName();</technical_language>

Target:
@Override protected RepositoryMetadata getRepositoryMetadata(Class<?> repoItf) { Assert.notNull(repoItf, "Repository interface must be set."); Assert.isAssignable(IgniteRepository.class, repoItf, "Repository must implement IgniteRepository interface."); RepositoryConfig annotation = repoItf.getAnnotation(RepositoryConfig.class); Assert.notNull(annotation, "Set a name of an Apache Ignite cache using @RepositoryConfig annotation to map " + "this repository to the underlying cache."); Assert.hasText(annotation.cacheName(), "Set a name of an Apache Ignite cache using @RepositoryConfig " + "annotation to map this repository to the underlying cache."); String cacheName = evaluateExpression(annotation.cacheName()); repoToCache.put(repoItf, cacheName); return super.getRepositoryMetadata(repoItf); }
Source:
<code>public void addSegments(Iterable<DataSegment> segments) { try { for (DataSegment segment : segments) { log.info("Loading segment %s", segment.getIdentifier()); try { serverManager.loadSegment(segment); } catch (Exception e) { removeSegment(segment); <START> throw new SegmentLoadingException(e, "Exception loading segment[%s]", segment.getIdentifier()); <END> } File segmentInfoCacheFile = new File(config.getSegmentInfoCacheDirectory(), segment.getIdentifier()); if (!segmentInfoCacheFile.exists()) { try { jsonMapper.writeValue(segmentInfoCacheFile, segment); } catch (IOException e) { removeSegment(segment); throw new SegmentLoadingException( e, "Failed to write to disk segment info cache file[%s]", segmentInfoCacheFile ); } } } try { announcer.announceSegments(segments); } catch (IOException e) { removeSegments(segments); throw new SegmentLoadingException(e, "Failed to announce segments[%s]", segments); } } catch (SegmentLoadingException e) { log.makeAlert(e, "Failed to load segments for dataSource") .addData("segments", segments) .emit(); } }</code><technical_language>I throwing this out kill startup process. recommend accumulate (or store exception) load rest of segments fail for loop if is exception stored. exception stop other loading. a try/catch initial loading of cache</technical_language>

Target:
public void addSegments(Iterable<DataSegment> segments) { try { final List<String> segmentFailures = Lists.newArrayList(); final List<DataSegment> validSegments = Lists.newArrayList(); for (DataSegment segment : segments) { log.info("Loading segment %s", segment.getIdentifier()); try { serverManager.loadSegment(segment); } catch (Exception e) { log.error(e, "Exception loading segment[%s]", segment.getIdentifier()); removeSegment(segment); segmentFailures.add(segment.getIdentifier()); continue; } File segmentInfoCacheFile = new File(config.getSegmentInfoCacheDirectory(), segment.getIdentifier()); if (!segmentInfoCacheFile.exists()) { try { jsonMapper.writeValue(segmentInfoCacheFile, segment); } catch (IOException e) { log.error(e, "Failed to write to disk segment info cache file[%s]", segmentInfoCacheFile); removeSegment(segment); segmentFailures.add(segment.getIdentifier()); continue; } } validSegments.add(segment); } try { announcer.announceSegments(validSegments); } catch (IOException e) { throw new SegmentLoadingException(e, "Failed to announce segments[%s]", segments); } if (!segmentFailures.isEmpty()) { for (String segmentFailure : segmentFailures) { log.error("%s failed to load", segmentFailure); } throw new SegmentLoadingException("%,d errors seen while loading segments", segmentFailures.size()); } } catch (SegmentLoadingException e) { log.makeAlert(e, "Failed to load segments for dataSource") .addData("segments", segments) .emit(); } }
Source:
<code>public BinList getBinsOverlapping(int referenceIndex, int startPos, int endPos) { <START> long refOffset = recordRangleInfo.getReferenceOffsets().get(referenceIndex); <END> long refLength = recordRangleInfo.getReferenceLengths().get(referenceIndex); long refStartPos = startPos - 1; long refEndPos = endPos; if (refEndPos >= refLength) { throw new RuntimeException("refEndPos is larger than reference length"); } int firstBinNumber = (int)refStartPos / SRA_BIN_SIZE; int lastBinNumber = (int)refEndPos / SRA_BIN_SIZE; int numberOfBins = ((int)refLength / SRA_BIN_SIZE) + 1; BitSet binBitSet = new BitSet(); binBitSet.set(0, SRA_BIN_INDEX_OFFSET, false); if (firstBinNumber > 0) { binBitSet.set(SRA_BIN_INDEX_OFFSET, SRA_BIN_INDEX_OFFSET + firstBinNumber, false); } binBitSet.set(SRA_BIN_INDEX_OFFSET + firstBinNumber, SRA_BIN_INDEX_OFFSET + lastBinNumber + 1, true); if (lastBinNumber + 1 < numberOfBins) { binBitSet.set(SRA_BIN_INDEX_OFFSET + lastBinNumber + 1, SRA_BIN_INDEX_OFFSET + numberOfBins, false); } return new BinList(referenceIndex, binBitSet); }</code><technical_language>refOffset is unused in this method -- explain able get Bins overlapping requested interval refOffset account</technical_language>

Target:
public BinList getBinsOverlapping(int referenceIndex, int startPos, int endPos) { long refLength = recordRangeInfo.getReferenceLengthsAligned().get(referenceIndex); long refStartPos = startPos - 1; long refEndPos = endPos; if (refEndPos >= refLength) { throw new RuntimeException("refEndPos is larger than reference length"); } int firstBinNumber = (int)refStartPos / SRA_BIN_SIZE; int lastBinNumber = (int)(refEndPos - 1) / SRA_BIN_SIZE; int numberOfBins = ((int)refLength / SRA_BIN_SIZE) + 1; BitSet binBitSet = new BitSet(); binBitSet.set(0, SRA_BIN_INDEX_OFFSET, false); if (firstBinNumber > 0) { binBitSet.set(SRA_BIN_INDEX_OFFSET, SRA_BIN_INDEX_OFFSET + firstBinNumber, false); } binBitSet.set(SRA_BIN_INDEX_OFFSET + firstBinNumber, SRA_BIN_INDEX_OFFSET + lastBinNumber + 1, true); if (lastBinNumber + 1 < numberOfBins) { binBitSet.set(SRA_BIN_INDEX_OFFSET + lastBinNumber + 1, SRA_BIN_INDEX_OFFSET + numberOfBins, false); } return new BinList(referenceIndex, binBitSet); }
Source:
<code>public Map<String, Long> getEventTypesInRange(ITmfTimestamp start, ITmfTimestamp end) { <START> Map<String, Long> map = new HashMap<String, Long>(); <END> long startTimestamp = checkStartTime(start.getValue()); long endTimestamp = checkEndTime(end.getValue()); try { int quark = stats.getQuarkAbsolute(Attributes.EVENT_TYPES); List<Integer> quarks = stats.getSubAttributes(quark, false); List<ITmfStateInterval> startState = stats.queryFullState(startTimestamp); List<ITmfStateInterval> endState = stats.queryFullState(endTimestamp); String curEventName; long countAtStart, countAtEnd, eventCount; for (int typeQuark : quarks) { curEventName = stats.getAttributeName(typeQuark); countAtStart = startState.get(typeQuark).getStateValue().unboxInt(); countAtEnd = endState.get(typeQuark).getStateValue().unboxInt(); if (startTimestamp == stats.getStartTime() || countAtStart == -1) { countAtStart = 0; } if (countAtEnd < 0) { ITmfStateInterval realInterval = stats.querySingleState(endTimestamp - 1, typeQuark); countAtEnd = realInterval.getStateValue().unboxInt() + 1; } if (countAtEnd < 0) { countAtEnd = 0; } eventCount = countAtEnd - countAtStart; map.put(curEventName, eventCount); } } catch (TimeRangeException e) { } catch (AttributeNotFoundException e) { e.printStackTrace(); } catch (StateValueTypeException e) { e.printStackTrace(); } return map; }</code><technical_language>ITmfTimestamp normalized nanoseconds</technical_language>

Target:
public Map<String, Long> getEventTypesInRange(ITmfTimestamp start, ITmfTimestamp end) { Map<String, Long> map = new HashMap<String, Long>(); long startTime = checkStartTime(start); long endTime = checkEndTime(end); try { int quark = stats.getQuarkAbsolute(Attributes.EVENT_TYPES); List<Integer> quarks = stats.getSubAttributes(quark, false); List<ITmfStateInterval> startState = stats.queryFullState(startTime); List<ITmfStateInterval> endState = stats.queryFullState(endTime); String curEventName; long countAtStart, countAtEnd, eventCount; for (int typeQuark : quarks) { curEventName = stats.getAttributeName(typeQuark); countAtStart = startState.get(typeQuark).getStateValue().unboxInt(); countAtEnd = endState.get(typeQuark).getStateValue().unboxInt(); if (startTime == stats.getStartTime() || countAtStart == -1) { countAtStart = 0; } if (countAtEnd < 0) { ITmfStateInterval realInterval = stats.querySingleState(endTime - 1, typeQuark); countAtEnd = realInterval.getStateValue().unboxInt() + 1; } if (countAtEnd < 0) { countAtEnd = 0; } eventCount = countAtEnd - countAtStart; map.put(curEventName, eventCount); } } catch (TimeRangeException e) { } catch (AttributeNotFoundException e) { e.printStackTrace(); } catch (StateValueTypeException e) { e.printStackTrace(); } return map; }
Source:
<code>public void addStoredKnowledge(String testID) { logger.info("addStoredKnowledge with testID: " + testID); AddStoredKnowledgeTask task = new AddStoredKnowledgeTask(testID); Future<?> future = taskExecutorService.submit(task); testTasks.put(testID, future); <START> try { <END> future.get(); if (testTaskScheduler.isTerminated(testID)) { return; } boolean hasRegressionModel = explorationModelDAO.hasRegressionModel(testID); TestRunningState nextState = hasRegressionModel ? DETERMINE_EXECUTE_VALIDATION_SET : DETERMINE_EXECUTE_EXPERIMENTS; testModelDAO.setTestRunningState(testID, nextState); testTaskScheduler.handleTestState(testID); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } catch (BenchFlowTestIDDoesNotExistException e) { logger.error("test ID does not exist - should not happen"); } }</code><technical_language>This handled waitForRunningTaskToComplete accepting a callback function executed code</technical_language>

Target:
public void addStoredKnowledge(String testID) { logger.info("addStoredKnowledge with testID: " + testID); AddStoredKnowledgeTask task = new AddStoredKnowledgeTask(testID); AbortableFutureTask<?> future = (AbortableFutureTask) taskExecutorService.submit(task); testTasks.put(testID, future); try { if (testTaskScheduler.getAbortableFutureTask(future).isAborted()) { logger.info("Task has been aborted for test: " + testID); return; } boolean hasRegressionModel = explorationModelDAO.hasRegressionModel(testID); TestRunningState nextState = hasRegressionModel ? DETERMINE_EXECUTE_VALIDATION_SET : DETERMINE_EXECUTE_EXPERIMENTS; testModelDAO.setTestRunningState(testID, nextState); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } catch (BenchFlowTestIDDoesNotExistException e) { logger.error("test ID does not exist - should not happen"); } }
Source:
<code>public SourceAppCommand getSourceCommand(AppCommand command, SourceColumn column) { for (SourceAppCommand cmd : sourceAppCommands_) { <START> if (cmd.getCommand() == command && <END> cmd.getColumn() == column.getName()) return cmd; } SourceAppCommand sourceCommand = new SourceAppCommand(command, column.getName(), this); sourceAppCommands_.add(sourceCommand); return sourceCommand; }</code><technical_language>Testing JavaScript objects for equality a bunch of weird edge cases recommend avoiding it. For example object cloned clone match, object in debugger obvious match! storing sourceAppCommands_ a HashMap, command ID (from command.getId()) column name a key? lookups faster, identity more reliable need check for existence in map</technical_language>

Target:
public SourceAppCommand getSourceCommand(AppCommand command, SourceColumn column) { String key = command.getId() + column.getName(); if (sourceAppCommands_.get(key) != null) return sourceAppCommands_.get(key); SourceAppCommand sourceCommand = new SourceAppCommand(command, column.getName(), this); sourceAppCommands_.put(key, sourceCommand); return sourceCommand; }
Source:
<code>protected final void addActiveMemberOfClause(BranchContext context, ExpressionBuilder queryBuilder) { addEclFilter(context, queryBuilder, SnomedComponentSearchRequest.OptionKey.ACTIVE_MEMBER_OF, SnomedComponentDocument.Expressions::referringRefSets); <START> addEclFilter(context, queryBuilder, SnomedComponentSearchRequest.OptionKey.ACTIVE_MEMBER_OF, SnomedComponentDocument.Expressions::referringMappingRefSets); <END> }</code><technical_language>expressions created addEclFilter calls wrapped a boolean expression clauses</technical_language>

Target:
protected final void addActiveMemberOfClause(BranchContext context, ExpressionBuilder queryBuilder) { if (containsKey(OptionKey.ACTIVE_MEMBER_OF)) { final Collection<String> refSetFilters = getCollection(OptionKey.ACTIVE_MEMBER_OF, String.class); final Collection<String> referringRefSetIds = evaluateEclFilter(context, refSetFilters); final Expression expression = Expressions .builder() .should(SnomedComponentDocument.Expressions.referringRefSets(referringRefSetIds)) .should(SnomedComponentDocument.Expressions.referringMappingRefSets(referringRefSetIds)) .build(); queryBuilder.filter(expression); } }
Source:
<code>protected boolean isIPv6(final char firstChar, String s, final boolean checkIPv6, final boolean checkIPv4MappedIPv6) { if (s.length() < 3 || !(isHexCharacter(firstChar) || firstChar == ':') || s.indexOf(':') < 0 <START> || StringUtils.countMatches(s, ':') < 2) { <END> return false; } Matcher matcher = IPV6_PATTERN.matcher(s); if (matcher.matches()) { boolean zeroSubstitution = false; if (s.startsWith("::")) { s = s.substring(2); zeroSubstitution = true; } else if (s.endsWith("::")) { s = s.substring(0, s.length() - 2); zeroSubstitution = true; } if (s.endsWith(":")) { return false; } int count = 0; boolean ipv4Mapped = false; String[] parts = s.split(":"); for (int i = 0; i < parts.length; i++) { final String part = parts[i]; if (part.length() == 0) { if (zeroSubstitution) { return false; } else { zeroSubstitution = true; } continue; } else { count++; } try { int value = Integer.parseInt(part, 16); if (value < 0 || value > 65535) { return false; } } catch (NumberFormatException e) { if (i != parts.length - 1 || !isIPv4(firstChar, part)) { return false; } ipv4Mapped = true; } } if (zeroSubstitution) { if (ipv4Mapped) { return checkIPv4MappedIPv6 && 1 <= count && count <= 6; } else { return checkIPv6 && 1 <= count && count <= 7; } } else { if (ipv4Mapped) { return checkIPv4MappedIPv6 && count == 7; } else { return checkIPv6 && count == 8; } } } else { return false; } }</code><technical_language>remove s.indexOf(':') < 0? this more restrictive</technical_language>

Target:
protected boolean isIPv6(final char firstChar, String s, final boolean checkIPv6, final boolean checkIPv4MappedIPv6) { if (s.length() < 3 || !(isHexCharacter(firstChar) || firstChar == ':') || StringUtils.countMatches(s, ':') < 2) { return false; } Matcher matcher = IPV6_PATTERN.matcher(s); if (matcher.matches()) { boolean zeroSubstitution = false; if (s.startsWith("::")) { s = s.substring(2); zeroSubstitution = true; } else if (s.endsWith("::")) { s = s.substring(0, s.length() - 2); zeroSubstitution = true; } if (s.endsWith(":")) { return false; } int count = 0; boolean ipv4Mapped = false; String[] parts = s.split(":"); for (int i = 0; i < parts.length; i++) { final String part = parts[i]; if (part.length() == 0) { if (zeroSubstitution) { return false; } else { zeroSubstitution = true; } continue; } else { count++; } try { int value = Integer.parseInt(part, 16); if (value < 0 || value > 65535) { return false; } } catch (NumberFormatException e) { if (i != parts.length - 1 || !isIPv4(firstChar, part)) { return false; } ipv4Mapped = true; } } if (zeroSubstitution) { if (ipv4Mapped) { return checkIPv4MappedIPv6 && 1 <= count && count <= 6; } else { return checkIPv6 && 1 <= count && count <= 7; } } else { if (ipv4Mapped) { return checkIPv4MappedIPv6 && count == 7; } else { return checkIPv6 && count == 8; } } } else { return false; } }
Source:
<code>protected String getRecentItemsUrl() { <START> return String.format("%s/recent_items", getBaseUri()); <END> }</code><technical_language>put constants "private static final String" variables</technical_language>

Target:
protected String getRecentItemsUrl() { return String.format("%s/" + ENDPOINT_NAME, getBaseUri()); }
Source:
<code>public SamplerConfig( @JsonProperty("numRows") Integer numRows, @JsonProperty("cacheKey") String cacheKey, @JsonProperty("skipCache") Boolean skipCache, @JsonProperty("timeoutMs") Integer timeoutMs ) { <START> this.numRows = numRows != null ? numRows : DEFAULT_NUM_ROWS; <END> this.cacheKey = cacheKey; this.skipCache = skipCache != null ? skipCache : DEFAULT_SKIP_CACHE; this.timeoutMs = timeoutMs != null ? timeoutMs : DEFAULT_TIMEOUT_MS; }</code><technical_language>sense limit max numRows avoid memory for sampling</technical_language>

Target:
public SamplerConfig( @JsonProperty("numRows") Integer numRows, @JsonProperty("cacheKey") String cacheKey, @JsonProperty("skipCache") Boolean skipCache, @JsonProperty("timeoutMs") Integer timeoutMs ) { this.numRows = numRows != null ? numRows : DEFAULT_NUM_ROWS; this.cacheKey = cacheKey; this.skipCache = skipCache != null ? skipCache : DEFAULT_SKIP_CACHE; this.timeoutMs = timeoutMs != null ? timeoutMs : DEFAULT_TIMEOUT_MS; Preconditions.checkArgument(this.numRows <= MAX_NUM_ROWS, "numRows must be <= %s", MAX_NUM_ROWS); }
Source:
<code>private void migrateProperties(SecureStore currentStore, SecureStore newStore) { log.info("Migrate entries"); for (EntryKey key : currentStore.list()) { String[] value = currentStore.getList(key.section, key.subsection, key.name); if (value != null) { newStore.setList(key.section, key.subsection, key.name, Arrays.asList(value)); } else { String msg = String.format("Cannot migrate entry for %s", key.section); if (key.subsection != null) { msg = msg + <START> String.format("[%s]", <END> key.subsection); } msg = msg + String.format(".%s", key.name); throw new RuntimeException(msg); } } }</code><technical_language>square brackets? formatting keys in subsections this: section.subsection.key</technical_language>

Target:
private void migrateProperties(SecureStore currentStore, SecureStore newStore) { log.info("Migrate entries"); for (EntryKey key : currentStore.list()) { String[] value = currentStore.getList(key.section, key.subsection, key.name); if (value != null) { newStore.setList(key.section, key.subsection, key.name, Arrays.asList(value)); } else { String msg = String.format("Cannot migrate entry for %s", key.section); if (key.subsection != null) { msg = msg + String.format(".%s", key.subsection); } msg = msg + String.format(".%s", key.name); throw new RuntimeException(msg); } } }