auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void handleEvent(ITmfStateSystemBuilder ss, ITmfEvent event) throws AttributeNotFoundException { ITmfEventField content = event.getContent(); Integer cpuId = content.getFieldValue(Integer.class, CPU_ID_FIELD); Long cpuState = content.getFieldValue(Long.class, CPU_STATE); long timestamp = KernelEventHandlerUtils.getTimestamp(event); if (cpuId == null || cpuState == null) { return; <START> } <END> final int cpuQuark = KernelEventHandlerUtils.getCurrentCPUNode(cpuId, ss); int quark = ss.getQuarkRelativeAndAdd(cpuQuark, Attributes.CURRENT_FREQUENCY); ss.modifyAttribute(timestamp, cpuState, quark); quark = ss.getQuarkRelativeAndAdd(cpuQuark, Attributes.MIN_FREQUENCY); Object currentValue = ss.queryOngoing(quark); Long minVal = (!(currentValue instanceof Long)) ? cpuState : Long.min(cpuState, (Long) currentValue); ss.updateOngoingState(minVal, quark); quark = ss.getQuarkRelativeAndAdd(cpuQuark, Attributes.MAX_FREQUENCY); currentValue = ss.queryOngoing(quark); Long maxVal = (!(currentValue instanceof Long)) ? cpuState : Long.max(cpuState, (Long) currentValue); ss.updateOngoingState(maxVal, quark); }</code><technical_language>state *= 1000;</technical_language>

Target:
public void handleEvent(ITmfStateSystemBuilder ss, ITmfEvent event) throws AttributeNotFoundException { ITmfEventField content = event.getContent(); Integer cpuId = content.getFieldValue(Integer.class, CPU_ID_FIELD); Long cpuState = content.getFieldValue(Long.class, CPU_STATE); long timestamp = KernelEventHandlerUtils.getTimestamp(event); if (cpuId == null || cpuState == null) { return; } cpuState *= FREQUENCY_MULTIPLIER; final int cpuQuark = KernelEventHandlerUtils.getCurrentCPUNode(cpuId, ss); int quark = ss.getQuarkRelativeAndAdd(cpuQuark, Attributes.CURRENT_FREQUENCY); ss.modifyAttribute(timestamp, cpuState, quark); quark = ss.getQuarkRelativeAndAdd(cpuQuark, Attributes.MIN_FREQUENCY); Object currentValue = ss.queryOngoing(quark); Long minVal = (!(currentValue instanceof Long)) ? cpuState : Long.min(cpuState, (Long) currentValue); ss.updateOngoingState(minVal, quark); quark = ss.getQuarkRelativeAndAdd(cpuQuark, Attributes.MAX_FREQUENCY); currentValue = ss.queryOngoing(quark); Long maxVal = (!(currentValue instanceof Long)) ? cpuState : Long.max(cpuState, (Long) currentValue); ss.updateOngoingState(maxVal, quark); }
Source:
<code>public final T doCheckValid(RuleComponentModel data) { Map<String, ParameterModel> params = data.getParameters(); for (Map.Entry<String, ParameterDefinition> entry : this.getParameterDefinitions().entrySet()) { try{ entry.getValue().checkValid(params.get(entry.getKey())); }catch(InvalidConditionParameterException e){ <START> throw e; <END> } } T instance; try { instance = instanceFrom(params); } catch (RuleEngineException e) { throw e; } catch (Exception e) { throw new RuleConstructionFailedException(e, "Could not create Component Instance of type %s from provided model %s.", this.getId(), data.toString()); } return instance; }</code><technical_language>Leftover debug point</technical_language>

Target:
public final T doCheckValid(RuleComponentModel data) { Map<String, ParameterModel> params = data.getParameters(); for (Map.Entry<String, ParameterDefinition> entry : this.getParameterDefinitions().entrySet()) { entry.getValue().checkValid(params.get(entry.getKey())); } T instance; try { instance = instanceFrom(params); } catch (RuleEngineException e) { throw e; } catch (Exception e) { throw new RuleConstructionFailedException(e, "Could not create Component Instance of type %s from provided model %s.", this.getId(), data.toString()); } return instance; }
Source:
<code>private String readPid() throws IOException { @SuppressWarnings("DMI_HARDCODED_ABSOLUTE_FILENAME") Path pidFile = Paths.get(PID_FILE); <START> return (new String(Files.readAllBytes(pidFile))).trim(); <END> }</code><technical_language>closing files all, please try resources: private String readLine(String filename) { String pid; try (BufferedReader br = new BufferedReader(new FileReader(filename))) { pid = br.readLine(); } catch (IOException ex) { log.error("Error reading file '{}': {}, filename, ex.getMessage()); log.debug("Exception", ex); pid = null; } return pid; }</technical_language>

Target:
private String readPid() throws IOException { Path pidFile = Paths.get(PID_FILE); return (new String(Files.readAllBytes(pidFile))).trim(); }
Source:
<code>public void setAggregators(List<MetricAggregatorProvider> aggregators) { <START> for (MetricAggregatorProvider map : aggregators) { <END> aggregatorsWithSettings.add(new MetricAggregatorProviderWithSettings(map)); } }</code><technical_language>map - confusing name</technical_language>

Target:
public void setAggregators(List<MetricAggregatorProvider> aggregators) { for (MetricAggregatorProvider aggregator : aggregators) { settingsMap.put(aggregator, MetricAggregatorSettings.EMPTY_SETTINGS); } }
Source:
<code>private int addToDictionary(final String s) { int idx = reverseDictionary.getInt(s); if (idx == UNKNOWN_DICTIONARY_KEY) { final long additionalEstimatedSize = estimateStringKeySize(s); if (currentEstimatedSize + additionalEstimatedSize > maxDictionarySize) { return -1; } idx = dictionary.size(); reverseDictionary.put(s, idx); dictionary.add(s); <START> currentEstimatedSize += additionalEstimatedSize; <END> } return idx; }</code><technical_language>sortableIds updated</technical_language>

Target:
private int addToDictionary(final String s) { int idx = reverseDictionary.getInt(s); if (idx == UNKNOWN_DICTIONARY_ID) { final long additionalEstimatedSize = estimateStringKeySize(s); if (currentEstimatedSize + additionalEstimatedSize > maxDictionarySize) { return -1; } idx = dictionary.size(); reverseDictionary.put(s, idx); dictionary.add(s); currentEstimatedSize += additionalEstimatedSize; } return idx; }
Source:
<code>protected boolean canDoAction() { if (!validate(new StoragePoolValidator(getStoragePool()).isUp())) { return false; } if (getDiskImage() == null) { <START> return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_NOT_EXIST); <END> } if (!getDiskImage().getParentId().equals(Guid.Empty)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_CONFIGURATION_NOT_SUPPORTED); } for (VM vm : getVmDAO().getVmsListForDisk(getDiskImage().getId())) { if (vm.isRunningOrPaused()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_RUNNING); } } return true; }</code><technical_language>this SP validation</technical_language>

Target:
protected boolean canDoAction() { if (getDiskImage() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_NOT_EXIST); } if (!validate(new StoragePoolValidator(getStoragePool()).isUp())) { return false; } if (!getDiskImage().getParentId().equals(Guid.Empty)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_CONFIGURATION_NOT_SUPPORTED); } for (VM vm : getVmDAO().getVmsListForDisk(getDiskImage().getId())) { if (vm.getStatus() != VMStatus.Down) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_RUNNING); } } return true; }
Source:
<code>public static List<ElementTag> getNationalitiesAsElementTags(String existingNationality) { List<String> nationalities = NationalityHelper.getNationalities(); ArrayList<ElementTag> result = new ArrayList<ElementTag>(); boolean isEditingExistingNationality = existingNationality != null; for (String nationality : nationalities) { ElementTag option = createOption(nationality, nationality, <START> isEditingExistingNationality && nationality.equals(existingNationality)); <END> result.add(option); } return result; }</code><technical_language>condition is necessary existingNationality == null guarantee false</technical_language>

Target:
public static List<ElementTag> getNationalitiesAsElementTags(String existingNationality) { List<String> nationalities = NationalityHelper.getNationalities(); List<ElementTag> result = new ArrayList<ElementTag>(); result.add(createOption("--- Select ---", "", !nationalities.contains(existingNationality))); for (String nationality : nationalities) { ElementTag option = createOption(nationality, nationality, nationality.equals(existingNationality)); result.add(option); } return result; }
Source:
<code>protected ExecutionStrategy() { <START> super(); <END> dataFetcherExceptionHandler = params -> handleDataFetchingException( params.getExecutionContext(), params.getFieldDefinition(), params.getArgumentValues(), params.getPath(), params.getException() ); }</code><technical_language>public abstract class ExecutionStrategy { this super(); call need</technical_language>

Target:
protected ExecutionStrategy() { dataFetcherExceptionHandler = params -> handleDataFetchingException( params.getExecutionContext(), params.getFieldDefinition(), params.getArgumentValues(), params.getPath(), params.getException() ); }
Source:
<code>public static boolean existsTable(final String dbFileAbsolutePath, final RelationKey relationKey) throws IOException, SQLiteException { boolean exists = false; SQLiteConnection sqliteConnection = null; SQLiteStatement statement = null; try { final File f = new File(dbFileAbsolutePath); if (!f.getParentFile().exists()) { f.getParentFile().mkdirs(); } sqliteConnection = new SQLiteConnection(f); sqliteConnection.open(true); statement = <START> sqliteConnection.prepare("SELECT * FROM sqlite_master WHERE type='table' AND name=" <END> + relationKey.toString(MyriaConstants.STORAGE_SYSTEM_SQLITE)); if (statement.step()) { return true; } } finally { if (statement != null) { statement.dispose(); } if (sqliteConnection != null) { sqliteConnection.dispose(); } } return exists; }</code><technical_language>need quote table name a string literal, a quoted identifier</technical_language>

Target:
public static boolean existsTable(final String dbFileAbsolutePath, final RelationKey relationKey) throws IOException, SQLiteException { boolean exists = false; SQLiteConnection sqliteConnection = null; SQLiteStatement statement = null; try { final File f = new File(dbFileAbsolutePath); if (!f.getParentFile().exists()) { f.getParentFile().mkdirs(); } sqliteConnection = new SQLiteConnection(f); sqliteConnection.open(true); statement = sqliteConnection.prepare("SELECT * FROM sqlite_master WHERE type='table' AND name=?"); statement.bind(1, relationKey.toString()); if (statement.step()) { return true; } } finally { if (statement != null) { statement.dispose(); } if (sqliteConnection != null) { sqliteConnection.dispose(); } } return exists; }
Source:
<code>public void save() { for (int i = 0; i < size; i++) { <START> cfg.setValue(PlayerBackpack.backpacks + id + ".contents." + i, inventory.getItem(i)); <END> } }</code><technical_language>PlayerBackpack is redundant here, need class in</technical_language>

Target:
public void save() { for (int i = 0; i < size; i++) { cfg.setValue(CONFIG_PREFIX + id + ".contents." + i, inventory.getItem(i)); } }
Source:
<code>private <V> Map<Long, V> executeLocalOperation(final RangeKeyOperation<Long, V> operation, final Map<Integer, List<Pair<Long, Long>>> blockToSubKeyRangesMap) { if (blockToSubKeyRangesMap.isEmpty()) { return Collections.emptyMap(); } final Map<Long, V> outputData; final Iterator<Map.Entry<Integer, List<Pair<Long, Long>>>> blockToSubKeyRangesIterator = blockToSubKeyRangesMap.entrySet().iterator(); if (blockToSubKeyRangesIterator.hasNext()) { final Map.Entry<Integer, List<Pair<Long, Long>>> blockToSubKeyRanges = blockToSubKeyRangesIterator.next(); final int blockId = blockToSubKeyRanges.getKey(); <START> final Lock readLock = router.resolveEvalWithLock(blockId).getValue(); <END> try { final Block<V> block = blocks.get(blockId); final List<Pair<Long, Long>> subKeyRanges = blockToSubKeyRanges.getValue(); outputData = block.executeSubOperation(operation, subKeyRanges); } finally { readLock.unlock(); } } else { return Collections.emptyMap(); } while (blockToSubKeyRangesIterator.hasNext()) { final Map<Long, V> partialOutput; final Map.Entry<Integer, List<Pair<Long, Long>>> blockToSubKeyRanges = blockToSubKeyRangesIterator.next(); final int blockId = blockToSubKeyRanges.getKey(); final Lock readLock = router.resolveEvalWithLock(blockId).getValue(); try { final Block<V> block = blocks.get(blockId); final List<Pair<Long, Long>> subKeyRanges = blockToSubKeyRanges.getValue(); partialOutput = block.executeSubOperation(operation, subKeyRanges); } finally { readLock.unlock(); } outputData.putAll(partialOutput); } return outputData; }</code><technical_language>extract L490 - L498 a method, is duplicated in L508-L516</technical_language>

Target:
private <V> Map<Long, V> executeLocalOperation(final RangeKeyOperation<Long, V> operation, final Map<Integer, List<Pair<Long, Long>>> blockToSubKeyRangesMap) { if (blockToSubKeyRangesMap.isEmpty()) { return Collections.emptyMap(); } final Map<Long, V> outputData; final Iterator<Map.Entry<Integer, List<Pair<Long, Long>>>> blockToSubKeyRangesIterator = blockToSubKeyRangesMap.entrySet().iterator(); if (blockToSubKeyRangesIterator.hasNext()) { final Map.Entry<Integer, List<Pair<Long, Long>>> blockToSubKeyRanges = blockToSubKeyRangesIterator.next(); final int blockId = blockToSubKeyRanges.getKey(); final List<Pair<Long, Long>> subKeyRanges = blockToSubKeyRanges.getValue(); outputData = executeLocalSubOperation(operation, blockId, subKeyRanges); } else { return Collections.emptyMap(); } while (blockToSubKeyRangesIterator.hasNext()) { final Map<Long, V> partialOutput; final Map.Entry<Integer, List<Pair<Long, Long>>> blockToSubKeyRanges = blockToSubKeyRangesIterator.next(); final int blockId = blockToSubKeyRanges.getKey(); final List<Pair<Long, Long>> subKeyRanges = blockToSubKeyRanges.getValue(); partialOutput = executeLocalSubOperation(operation, blockId, subKeyRanges); outputData.putAll(partialOutput); } return outputData; }
Source:
<code>protected List<RefNode> getRefNodes(RevCommit commit, Repository repo, String... refPrefixes) { List<Ref> availableBranches = new ArrayList<Ref>(); List<RefNode> nodes = new ArrayList<RefNode>(); try { Map<String, Ref> branches = new HashMap<String, Ref>(); <START> for (String refPrefix : refPrefixes) { <END> branches.putAll(repo.getRefDatabase().getRefs(refPrefix)); } for (Ref branch : branches.values()) { if (branch.getLeaf().getObjectId().equals(commit.getId())) availableBranches.add(branch); } RepositoryNode repoNode = new RepositoryNode(null, repo); for (Ref ref : availableBranches) nodes.add(new RefNode(repoNode, repo, ref)); } catch (IOException e) { } return nodes; }</code><technical_language>style nit: braces single line blocks</technical_language>

Target:
protected List<RefNode> getRefNodes(RevCommit commit, Repository repo, String... refPrefixes) { List<Ref> availableBranches = new ArrayList<Ref>(); List<RefNode> nodes = new ArrayList<RefNode>(); try { Map<String, Ref> branches = new HashMap<String, Ref>(); for (String refPrefix : refPrefixes) branches.putAll(repo.getRefDatabase().getRefs(refPrefix)); for (Ref branch : branches.values()) { if (branch.getLeaf().getObjectId().equals(commit.getId())) availableBranches.add(branch); } RepositoryNode repoNode = new RepositoryNode(null, repo); for (Ref ref : availableBranches) nodes.add(new RefNode(repoNode, repo, ref)); } catch (IOException e) { } return nodes; }
Source:
<code>public List<DocumentReference> loadBacklinks(DocumentReference documentReference, boolean bTransaction, XWikiContext inputxcontext) throws XWikiException { XWikiContext context = getExecutionXContext(inputxcontext, true); Set<DocumentReference> backlinkReferences = new HashSet<DocumentReference>(); try { if (bTransaction) { checkHibernate(context); bTransaction = beginTransaction(false, context); } Session session = getSession(context); Query query = session <START> .createQuery("select backlink.fullName from XWikiLink as backlink where backlink.id.link = :backlink" <END> + " or backlink.id.link = :backlinkwithwiki"); query.setString("backlink", this.localEntityReferenceSerializer.serialize(documentReference)); query.setString("backlinkwithwiki", this.defaultEntityReferenceSerializer.serialize(documentReference)); @SuppressWarnings("unchecked") List<String> backlinkNames = query.list(); for (String backlinkName : backlinkNames) { backlinkReferences.add(this.currentMixedDocumentReferenceResolver.resolve(backlinkName)); } if (bTransaction) { endTransaction(context, false, false); } } catch (Exception e) { throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_BACKLINKS, "Exception while loading backlinks", e); } finally { try { if (bTransaction) { endTransaction(context, false, false); } } catch (Exception e) { } restoreExecutionXContext(); } return new ArrayList<DocumentReference>(backlinkReferences); }</code><technical_language>wondering if backlink.id.link in (:backlink, :backlinkwithwiki) for performances conditions</technical_language>

Target:
public List<DocumentReference> loadBacklinks(DocumentReference documentReference, boolean bTransaction, XWikiContext inputxcontext) throws XWikiException { XWikiContext context = getExecutionXContext(inputxcontext, true); Set<DocumentReference> backlinkReferences = new HashSet<DocumentReference>(); try { if (bTransaction) { checkHibernate(context); bTransaction = beginTransaction(false, context); } Session session = getSession(context); Query query = session .createQuery("select backlink.fullName from XWikiLink as backlink where backlink.id.link = :backlink"); query.setString("backlink", this.compactWikiEntityReferenceSerializer.serialize(documentReference)); @SuppressWarnings("unchecked") List<String> backlinkNames = query.list(); for (String backlinkName : backlinkNames) { DocumentReference backlinkreference = this.currentMixedDocumentReferenceResolver.resolve(backlinkName); backlinkReferences.add(backlinkreference); } } catch (Exception e) { throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_BACKLINKS, "Exception while loading backlinks", e); } finally { try { if (bTransaction) { endTransaction(context, false, false); } } catch (Exception e) { } restoreExecutionXContext(); } return new ArrayList<DocumentReference>(backlinkReferences); }
Source:
<code>public void setInitJobContent(String jobContent) { try { this.jobContentAsByteArray = ByteCompressionUtils.compress(jobContent.getBytes()); } catch (Exception e) { LOGGER.error(e.getMessage(), e); <START> this.jobContentAsByteArray = null; <END> } }</code><technical_language>EMPTY object instead of null</technical_language>

Target:
public void setInitJobContent(String jobContent) { try { this.jobContentAsByteArray = ByteCompressionUtils.compress(jobContent.getBytes()); } catch (Exception e) { LOGGER.error(e.getMessage(), e); this.jobContentAsByteArray = new byte[0]; } }
Source:
<code>private void addLocalScopes(APIIdentifier apiIdentifier, int tenantId, Set<URITemplate> uriTemplates) throws APIManagementException { String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId); Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(tenantDomain); Set<Scope> scopesToRegister = getScopesToRegisterFromURITemplates(apiIdentifier, tenantId, uriTemplates); scopesDAO.addScopes(scopesToRegister, tenantId); for (Scope scope : scopesToRegister) { for (Map.Entry<String, KeyManagerDto> keyManagerDtoEntry : tenantKeyManagers.entrySet()) { KeyManager keyManager = keyManagerDtoEntry.getValue().getKeyManager(); if (keyManager != null) { String scopeKey = scope.getKey(); <START> try{ <END> if (!keyManager.isScopeExists(scopeKey)) { keyManager.registerScope(scope); } else { if (log.isDebugEnabled()) { log.debug("Scope: " + scopeKey + " already registered in KM. Skipping registering scope."); } } }catch (APIManagementException e){ log.error("Error while registering Scope " + scopeKey + "in KeyManager " + keyManagerDtoEntry.getKey(), e); } } } } }</code><technical_language>formatting issue</technical_language>

Target:
private void addLocalScopes(APIIdentifier apiIdentifier, int tenantId, Set<URITemplate> uriTemplates) throws APIManagementException { String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId); Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(tenantDomain); Set<Scope> scopesToRegister = getScopesToRegisterFromURITemplates(apiIdentifier, tenantId, uriTemplates); for (Scope scope : scopesToRegister) { for (Map.Entry<String, KeyManagerDto> keyManagerDtoEntry : tenantKeyManagers.entrySet()) { KeyManager keyManager = keyManagerDtoEntry.getValue().getKeyManager(); if (keyManager != null) { String scopeKey = scope.getKey(); try { if (!keyManager.isScopeExists(scopeKey)) { keyManager.registerScope(scope); } else { if (log.isDebugEnabled()) { log.debug("Scope: " + scopeKey + " already registered in KM. Skipping registering scope."); } } } catch (APIManagementException e) { log.error("Error while registering Scope " + scopeKey + "in Key Manager " + keyManagerDtoEntry.getKey(), e); } } } } addScopes(scopesToRegister, tenantId); }
Source:
<code>public static GridSqlQuery selectForInsertOrMerge(GridSqlColumn[] cols, List<GridSqlElement[]> rows, GridSqlQuery subQry, GridH2RowDescriptor desc) { if (!F.isEmpty(rows)) { assert !F.isEmpty(cols); GridSqlSelect sel = new GridSqlSelect(); GridSqlFunction from = new GridSqlFunction(GridSqlFunctionType.TABLE); sel.from(from); GridSqlArray[] args = new GridSqlArray[cols.length]; for (int i = 0; i < cols.length; i++) { GridSqlArray arr = new GridSqlArray(rows.size()); String colName = cols[i].columnName(); GridSqlAlias alias = new GridSqlAlias(colName, arr); alias.resultType(cols[i].resultType()); from.addChild(alias); args[i] = arr; GridSqlColumn newCol = new GridSqlColumn(null, from, null,"TABLE", colName); newCol.resultType(cols[i].resultType()); sel.addColumn(newCol, true); } for (GridSqlElement[] row : rows) { assert cols.length == row.length; for (int i = 0; i < row.length; i++) args[i].addChild(row[i]); } <START> sel.getSQL(); <END> return sel; } else { assert subQry != null; return subQry; } }</code><technical_language>this removed</technical_language>

Target:
public static GridSqlQuery selectForInsertOrMerge(GridSqlColumn[] cols, List<GridSqlElement[]> rows, GridSqlQuery subQry, GridH2RowDescriptor desc) { if (!F.isEmpty(rows)) { assert !F.isEmpty(cols); GridSqlSelect sel = new GridSqlSelect(); GridSqlFunction from = new GridSqlFunction(GridSqlFunctionType.TABLE); sel.from(from); GridSqlArray[] args = new GridSqlArray[cols.length]; for (int i = 0; i < cols.length; i++) { GridSqlArray arr = new GridSqlArray(rows.size()); String colName = cols[i].columnName(); GridSqlAlias alias = new GridSqlAlias(colName, arr); alias.resultType(cols[i].resultType()); from.addChild(alias); args[i] = arr; GridSqlColumn newCol = new GridSqlColumn(null, from, null,"TABLE", colName); newCol.resultType(cols[i].resultType()); sel.addColumn(newCol, true); } for (GridSqlElement[] row : rows) { assert cols.length == row.length; for (int i = 0; i < row.length; i++) args[i].addChild(row[i]); } return sel; } else { assert subQry != null; return subQry; } }
Source:
<code>public static JsonNode readJsonNodeFromResource(final String resourcePath) throws IOException { final ObjectMapper mapper = new ObjectMapper(); <START> try(final InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath)) { <END> return mapper.readTree(new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8.name())); } }</code><technical_language>cool :+1: this Java 7 sugar</technical_language>

Target:
public static JsonNode readJsonNodeFromResource(final String resourcePath) throws IOException { try(final InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath)) { return MAPPER.readTree(new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8.name())); } }
Source:
<code>public String execute() throws Exception { ActionContext nestedContext = ActionContext.getContext(); <START> ActionContext.bound(invocation.getInvocationContext()); <END> String retCode = null; try { retCode = invocation.invoke(); } finally { if (cleanupContext) { ActionContext.bound(nestedContext); } } return retCode; }</code><technical_language>bound() "better-named" method call here, involves operations (a set a get). this method read/use return of bound(), setContext() is a choice (more efficient anyway) ? If return of bound() assigned a local variable compared invocation.getInvocationContext() (to confirm context bound expected ThreadLocal) a scenario. additional method a similar naming convention: public static void bind(ActionContext actionContext) { ActionContext.setContext(actionContext); } a compromise (named attempt bind, provide a return confirm bound expected)</technical_language>

Target:
public String execute() throws Exception { ActionContext nestedContext = ActionContext.getContext(); ActionContext.bind(invocation.getInvocationContext()); String retCode = null; try { retCode = invocation.invoke(); } finally { if (cleanupContext) { ActionContext.bind(nestedContext); } } return retCode; }
Source:
<code>private List<Unit> addMustMoveWith( final List<Unit> best, final Map<Unit, Collection<Unit>> dependentUnits) { final MustMoveWithDetails mustMoveWithDetails = MoveValidator.getMustMoveWith( route.getStart(), route.getStart().getUnits(), dependentUnits, data, player); final List<Unit> bestWithDependents = new ArrayList<>(best); for (final Unit u : best) { if (mustMoveWithDetails.getMustMoveWith().containsKey(u)) { final Collection<Unit> mustMoveWith = mustMoveWithDetails.getMustMoveWith().get(u); if (mustMoveWith != null) { for (final Unit m : mustMoveWith) { <START> if (!bestWithDependents.contains(m)) { <END> bestWithDependents.addAll(mustMoveWith); } } } } } return bestWithDependents; }</code><technical_language>Avoid deeply nested control flow statements</technical_language>

Target:
private List<Unit> addMustMoveWith( final List<Unit> best, final Map<Unit, Collection<Unit>> dependentUnits) { final MustMoveWithDetails mustMoveWithDetails = MoveValidator.getMustMoveWith(route.getStart(), dependentUnits, player); final List<Unit> bestWithDependents = new ArrayList<>(best); for (final Unit u : best) { final Collection<Unit> mustMoveWith = mustMoveWithDetails.getMustMoveWithForUnit(u); for (final Unit m : mustMoveWith) { if (!bestWithDependents.contains(m)) { bestWithDependents.addAll(mustMoveWith); } } } return bestWithDependents; }
Source:
<code><START> public String getRawSignature() { <END> List<Type> inputTypes = new ArrayList<>(); TypeTuple typeTuple = getInputTypes(); for (int i = 0; i < typeTuple.size(); i++) { if (i == 0 && this.isStatic()) { continue; } Type type = typeTuple.get(i); if (type.isGeneric()) { type = type.getRawtype(); } inputTypes.add(type); } String methodName = declaringType.getRawtype().toString() + (this.isMethodCall() ? "." + super.getName() : ""); return methodName + "(" + UtilMDE.join(inputTypes, ",") + ")"; }</code><technical_language>getRawSignature is called frequently. caching result</technical_language>

Target:
public RawSignature getRawSignature() { if (!this.isConstructorCall() && !this.isMethodCall()) { return null; } if (rawSignature == null) { Package classPackage = this.declaringType.getPackage(); String packageName = (classPackage != null) ? classPackage.getName() : ""; String classname = this.getDeclaringType().getRawtype().getUnqualifiedName(); String name = this.getUnqualifiedName().equals("<init>") ? classname : this.getUnqualifiedName(); Class<?>[] parameterTypes = this.isMethodCall() ? ((MethodCall) getOperation()).getMethod().getParameterTypes() : ((ConstructorCall) getOperation()).getConstructor().getParameterTypes(); rawSignature = new RawSignature(packageName, classname, name, parameterTypes); } return rawSignature; }
Source:
<code>public void requestPhoneSignIn() { study.setShortName("AppName"); String cacheKey = TestConstants.PHONE.getNumber() + ":api:phoneSignInRequest"; when(accountDao.getAccount(SIGN_IN_WITH_PHONE.getAccountId())).thenReturn(account); when(service.getPhoneToken()).thenReturn("123456"); service.requestPhoneSignIn(SIGN_IN_REQUEST_WITH_PHONE); verify(cacheProvider).getString(cacheKey); verify(cacheProvider).setString(eq(cacheKey), stringCaptor.capture(), eq(300)); verify(notificationsService).sendSMSMessage(eq(study.getStudyIdentifier()), eq(TestConstants.PHONE), stringCaptor.capture()); assertEquals("123456", stringCaptor.getAllValues().get(0)); <START> assertEquals("Enter 123-456 to sign in to AppName", stringCaptor.getAllValues().get(1)); <END> }</code><technical_language>I recommend ArgumentCaptors for verify() checks. This way, name meaningful, accidentally break adding another of stringCaptor.capture() in between. Alternatively, string is, eq() match string exactly</technical_language>

Target:
public void requestPhoneSignIn() { study.setShortName("AppName"); String cacheKey = TestConstants.PHONE.getNumber() + ":api:phoneSignInRequest"; when(accountDao.getAccount(SIGN_IN_WITH_PHONE.getAccountId())).thenReturn(account); when(service.getPhoneToken()).thenReturn("123456"); service.requestPhoneSignIn(SIGN_IN_REQUEST_WITH_PHONE); verify(cacheProvider).getString(cacheKey); verify(cacheProvider).setString(cacheKey, "123456", 300); verify(notificationsService).sendSMSMessage(study.getStudyIdentifier(), TestConstants.PHONE, "Enter 123-456 to sign in to AppName"); }
Source:
<code>public HttpRequestBase buildRequest(MMSUtils.HttpRequestType type, File sendData, ContentType contentType, Project project) throws IOException, URISyntaxException { if(uriBuilder != null) { URI requestDest = uriBuilder.build(); final HttpRequestBase request; if (type == MMSUtils.HttpRequestType.GET && sendData != null) { throw new IOException("GETs with body are not supported"); } switch (type) { case DELETE: request = new HttpDeleteWithBody(requestDest); break; case GET: default: request = new HttpGet(requestDest); break; case POST: request = new HttpPost(requestDest); break; case PUT: request = new HttpPut(requestDest); break; } request.addHeader("Authorization", "Bearer " + TicketUtils.getTicket(project)); <START> request.addHeader("Content-Type", "application/json"); END> request.addHeader("charset", (contentType != null ? contentType.getCharset() : Consts.UTF_8).displayName()); if (sendData != null) { if (contentType != null) { request.addHeader("Content-Type", contentType.getMimeType()); } HttpEntity reqEntity = new FileEntity(sendData, contentType); ((HttpEntityEnclosingRequest) request).setEntity(reqEntity); } return request; } return null; }</code><technical_language>I avoid hard-coding application/json default contentType in this way. alternative this a method overload defaults contentType ContentType.APPLICATION_JSON. A cursory analysis of usages of buildRequest show of explicitly ContentType.APPLICATION_JSON while a leave null. I exclusively explicit implicit a method overload</technical_language>

Target:
public HttpRequestBase buildRequest(MMSUtils.HttpRequestType type, File sendData, ContentType contentType, Project project) throws IOException, URISyntaxException { if(uriBuilder != null) { URI requestDest = uriBuilder.build(); final HttpRequestBase request; if (type == GET && sendData != null) { throw new IOException("GETs with body are not supported"); } switch (type) { case DELETE: request = new HttpDeleteWithBody(requestDest); break; case GET: default: request = new HttpGet(requestDest); break; case POST: request = new HttpPost(requestDest); break; case PUT: request = new HttpPut(requestDest); break; } request.addHeader("Authorization", "Bearer " + TicketUtils.getTicket(project)); request.addHeader("charset", (contentType != null ? contentType.getCharset() : Consts.UTF_8).displayName()); if (sendData != null) { if (contentType != null) { request.addHeader(HTTP.CONTENT_TYPE, contentType.getMimeType()); } FileEntity reqEntity = new FileEntity(sendData, contentType); reqEntity.setChunked(true); ((HttpEntityEnclosingRequest) request).setEntity(reqEntity); } return request; } return null; }
Source:
<code>public List<Contentlet> getRelated(final String variableName) { if (this.relatedIds.containsKey(variableName)) { return this.relatedIds.get(variableName).stream().map(identifier -> { try { return this.contentletAPI.findContentletByIdentifierAnyLanguage(identifier); } catch (DotDataException | DotSecurityException e) { <START> throw new DotStateException(e); <END> } }).collect(Collectors.toList()); } else { try { com.dotcms.contenttype.model.field.Field field = APILocator.getContentTypeFieldAPI() .byContentTypeIdAndVar(getContentTypeId(), variableName); final List<Contentlet> relatedList = this.contentletAPI .getRelatedContent(this, RelationshipUtil .getRelationshipFromField(field, getContentType().variable()), this.userAPI.getSystemUser(), false); if (UtilMethods.isSet(relatedList)) { this.relatedIds.put(variableName, relatedList.stream().map(contentlet -> contentlet.getIdentifier()) .collect( Collectors.toList())); return relatedList; } } catch (DotDataException e) { Logger.warn(this, "No field found with this variable name " + variableName, e); throw new DotStateException(e); } catch (DotSecurityException e) { throw new DotStateException(e); } } return Collections.emptyList(); }</code><technical_language>need add 'variableName' in exception message for logging support purposes</technical_language>

Target:
public List<Contentlet> getRelated(final String variableName) { if (this.relatedIds.containsKey(variableName)) { return this.relatedIds.get(variableName).stream().map(identifier -> { try { return this.contentletAPI.findContentletByIdentifierAnyLanguage(identifier); } catch (DotDataException | DotSecurityException e) { Logger.warn(this, "No field found with this variable name " + variableName, e); throw new DotStateException(e); } }).collect(Collectors.toList()); } else { try { com.dotcms.contenttype.model.field.Field field = APILocator.getContentTypeFieldAPI() .byContentTypeIdAndVar(getContentTypeId(), variableName); final List<Contentlet> relatedList = this.contentletAPI .getRelatedContent(this, RelationshipUtil .getRelationshipFromField(field, getContentType().variable()), this.userAPI.getSystemUser(), false); if (UtilMethods.isSet(relatedList)) { this.relatedIds.put(variableName, relatedList.stream().map(contentlet -> contentlet.getIdentifier()) .collect( CollectionsUtils.toImmutableList())); return relatedList; } } catch (DotDataException | DotSecurityException e) { Logger.warn(this, "No field found with this variable name " + variableName, e); throw new DotStateException(e); } } return Collections.emptyList(); }
Source:
<code>public boolean contains( long[] value ) { <START> assert value.length == width : "all elements must have the same size"; <END> int slot = slotFor( value ); int result; do { result = table.checkSlot( slot, value ); slot = (slot + 1) & table.tableMask; } while ( result == CONTINUE_PROBING ); return result == VALUE_FOUND; }</code><technical_language>assert is valid too</technical_language>

Target:
public boolean contains( long[] value ) { assert validValue( value ); int slot = slotFor( value ); int result; do { result = table.checkSlot( slot, value ); slot = (slot + 1) & table.tableMask; } while ( result == CONTINUE_PROBING ); return result == VALUE_FOUND; }
Source:
<code>public AbstractValidationProblem(SourceInfo sourceInfo, ASTNode node) { this.sourceInfo = sourceInfo; this.sourceStart = node.getStartPosition(); <START> this.sourceEnd = node.getStartPosition() + node.getLength(); <END> this.lineNumber = sourceInfo.getSourceLineNumber(getSourceEnd()); }</code><technical_language>Do -1 is required here</technical_language>

Target:
public AbstractValidationProblem(SourceInfo sourceInfo, ASTNode node) { this.sourceInfo = sourceInfo; ASTNode nodeToMark = getNodeToMark(node); this.sourceStart = nodeToMark.getStartPosition(); this.sourceEnd = nodeToMark.getStartPosition() + nodeToMark.getLength(); this.lineNumber = sourceInfo.getSourceLineNumber(getSourceEnd()); }
Source:
<code>public BasicInvocationStage visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable { if (streamSummaryContainer.isEnabled() && ctx.isOriginLocal()) { <START> streamSummaryContainer.addGet(command.getKey(), false); <END> } return invokeNext(ctx, command); }</code><technical_language>isRemote(command.getKey()) instead of false</technical_language>

Target:
public BasicInvocationStage visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable { if (streamSummaryContainer.isEnabled() && ctx.isOriginLocal()) { streamSummaryContainer.addGet(command.getKey(), isRemote(command.getKey())); } return invokeNext(ctx, command); }
Source:
<code>private void loadCheProjects() { projectServiceClient.getProjects(false).then(new Operation<List<ProjectDescriptor>>() { @Override public void apply(List<ProjectDescriptor> result) throws OperationException { cheProjects = FluentIterable.from(result).transform( new com.google.common.base.Function<ProjectDescriptor, String>() { @Override public String apply(ProjectDescriptor input) { return input.getName(); } <START> }).toList(); <END> } }); }</code><technical_language>I cheProjects = new ArraysList<>(); // cheProjects.clear(); Collections.emptyList(); for init this variable for (ProjectDescriptor project : result) { cheProjects.add(project.getName()); } is here. WDYT</technical_language>

Target:
private void loadCheProjects() { projectServiceClient.getProjects(false).then(new Operation<List<ProjectDescriptor>>() { @Override public void apply(List<ProjectDescriptor> result) throws OperationException { cheProjects.clear(); for (ProjectDescriptor project : result) { cheProjects.add(project.getName()); } } }); }
Source:
<code>private PageTitle makeTitleFrom(@NonNull ReadingListPageDiskRow row) { <START> ReadingListPageRow pageRow = row.dat(); <END> if (pageRow == null) { return null; } String namespace = pageRow.namespace().toString(); return new PageTitle(namespace, pageRow.title(), pageRow.site()); }</code><technical_language>case row.dat() is null is page marked for deletion. model row is deleted readinglistpage table disk row is marked DELETED. file deleted in this case :| I picturing able pageRow.key() in this circumstance uniquely identify page for deletion disk. Is this possible? line 52 is handling this case</technical_language>

Target:
private PageTitle makeTitleFrom(@NonNull ReadingListPageDiskRow row) { ReadingListPageRow pageRow = row.dat(); if (pageRow == null) { return null; } String namespace = pageRow.namespace().toLegacyString(); return new PageTitle(namespace, pageRow.title(), pageRow.site()); }
Source:
<code>public int getLockPriority() { <START> return getContextValue("lockPriority") == null ? DEFAULT_TASK_PRIORITY : Integer.parseInt(getContextValue("lockPriority").toString()); <END> }</code><technical_language>key strings public static final String in this class</technical_language>

Target:
public int getLockPriority() { return getLockPriority(DEFAULT_TASK_PRIORITY); }
Source:
<code>public void approve(String ip, String name, boolean approve) { AgentInfo agentInfoInDB = agentManagerRepository.findByIpAndName(ip, name); if (agentInfoInDB != null) { agentInfoInDB.setApproved(approve); } else { agentInfoInDB = new AgentInfo(); agentInfoInDB.setIp(ip); agentInfoInDB.setName(name); agentInfoInDB.setApproved(approve); <START> agentManagerRepository.save(agentInfoInDB); <END> } agentManagerRepository.flush(); AgentInfo agentInfo = agentInfoStore.getAgentInfo(createAgentKey(ip, name)); agentInfo.setApproved(approve); agentInfoStore.updateAgentInfo(agentInfo.getAgentKey(), agentInfo); }</code><technical_language>I hope lines a separate method</technical_language>

Target:
public void approve(String ip, String name, boolean approve) { AgentInfo agentInfoInDB = agentManagerRepository.findByIpAndName(ip, name); if (agentInfoInDB != null) { agentInfoInDB.setApproved(approve); } else { agentInfoInDB = new AgentInfo(); agentInfoInDB.setIp(ip); agentInfoInDB.setName(name); agentInfoInDB.setApproved(approve); agentManagerRepository.save(agentInfoInDB); } agentManagerRepository.flush(); updateApproveInStore(ip, name, approve); }
Source:
<code>public static ResultSpec convertToResultSpec(final VisualizationObject visualizationObject, final VisualizationClass visualizationClass) throws Exception { if (!visualizationObject.getVisualizationClassUri().equals(visualizationClass.getUri())) { <START> throw new Exception("VisualizationClass URI does not match the VisualizationObject URI, " <END> + "you're trying to create ResultSpec for incompatible objects"); } List<SortItem> sorts = getSorting(visualizationObject); List<Dimension> dimensions = getDimensions(visualizationObject, visualizationClass.getVisualizationType()); return new ResultSpec(dimensions, sorts); }</code><technical_language>nicer some specific exception type instead</technical_language>

Target:
public static ResultSpec convertToResultSpec(final VisualizationObject visualizationObject, final VisualizationClass visualizationClass) { notNull(visualizationObject, "visualizationObject"); notNull(visualizationClass, "visualizationClass"); isTrue(visualizationObject.getVisualizationClassUri().equals(visualizationClass.getUri()), "visualizationClass URI does not match the URI within visualizationObject, " + "you're trying to create ResultSpec for incompatible objects"); List<SortItem> sorts = getSorting(visualizationObject); List<Dimension> dimensions = getDimensions(visualizationObject, visualizationClass.getVisualizationType()); return new ResultSpec(dimensions, sorts); }
Source:
<code><START> private Subject buildUnixSubject(int uid, int gid, int[] gids) { <END> final Subject unixSubject = new Subject(); final Set<Principal> principals = unixSubject.getPrincipals(); principals.add(new UnixNumericUserPrincipal(uid)); principals.add(new UnixNumericGroupPrincipal(gid, true)); for (int gidElem : gids) { principals.add(new UnixNumericGroupPrincipal(gidElem, false)); } return unixSubject; }</code><technical_language>this static</technical_language>

Target:
private static Subject buildUnixSubject(int uid, int gid, int[] gids) { final Subject unixSubject = new Subject(); final Set<Principal> principals = unixSubject.getPrincipals(); principals.add(new UnixNumericUserPrincipal(uid)); principals.add(new UnixNumericGroupPrincipal(gid, true)); for (int gidElem : gids) { principals.add(new UnixNumericGroupPrincipal(gidElem, false)); } return unixSubject; }
Source:
<code>private boolean filterByMimeType( Set<MimeType> mimeTypes, Map<String, Object> serviceProperties, MimeType userMimeType) { Set<String> baseTypes = mimeTypes.stream().map(MimeType::getBaseType).collect(Collectors.toSet()); String userIdValue = userMimeType.getParameter(Constants.SERVICE_ID); String userBaseType = userMimeType.getBaseType(); String serviceId = getServiceId(serviceProperties); <START> return CollectionUtils.isNotEmpty(mimeTypes) <END> && baseTypes.contains(userBaseType) && (userIdValue == null || StringUtils.equals(userIdValue, serviceId)); }</code><technical_language>Is isNotEmpty() check necessary? If mimeTypes is empty baseTypes contains() check fail</technical_language>

Target:
private boolean filterByMimeType( Set<MimeType> mimeTypes, Map<String, Object> serviceProperties, MimeType userMimeType) { Set<String> baseTypes = mimeTypes.stream().map(MimeType::getBaseType).collect(Collectors.toSet()); String userIdValue = userMimeType.getParameter(Constants.SERVICE_ID); String userBaseType = userMimeType.getBaseType(); String serviceId = getServiceId(serviceProperties); return baseTypes.contains(userBaseType) && (userIdValue == null || StringUtils.equals(userIdValue, serviceId)); }
Source:
<code>public void should_exclude_virtual_keyspaces_from_token_map() { <START> if (ccmRule.getDseVersion().isPresent()) { <END> Version dseVersion = ccmRule.getDseVersion().get(); if (dseVersion.compareTo(DSE_MIN_VIRTUAL_TABLES) < 0) { throw new AssumptionViolatedException("DSE 6.0 does not support virtual tables"); } } Metadata metadata = sessionRule.session().getMetadata(); Map<CqlIdentifier, ? extends KeyspaceMetadata> keyspaces = metadata.getKeyspaces(); assertThat(keyspaces) .containsKey(CqlIdentifier.fromCql("system_views")) .containsKey(CqlIdentifier.fromCql("system_virtual_schema")); TokenMap tokenMap = metadata.getTokenMap().orElseThrow(AssertionError::new); ByteBuffer partitionKey = Bytes.fromHexString("0x00"); assertThat(tokenMap.getReplicas("system_views", partitionKey)).isEmpty(); assertThat(tokenMap.getReplicas("system_virtual_schema", partitionKey)).isEmpty(); assertThat(tokenMap.getReplicas(sessionRule.keyspace(), partitionKey)).isNotEmpty(); }</code><technical_language>Nit: this logic is repeated above, factorize it</technical_language>

Target:
public void should_exclude_virtual_keyspaces_from_token_map() { skipIfDse60(); Metadata metadata = sessionRule.session().getMetadata(); Map<CqlIdentifier, ? extends KeyspaceMetadata> keyspaces = metadata.getKeyspaces(); assertThat(keyspaces) .containsKey(CqlIdentifier.fromCql("system_views")) .containsKey(CqlIdentifier.fromCql("system_virtual_schema")); TokenMap tokenMap = metadata.getTokenMap().orElseThrow(AssertionError::new); ByteBuffer partitionKey = Bytes.fromHexString("0x00"); assertThat(tokenMap.getReplicas("system_views", partitionKey)).isEmpty(); assertThat(tokenMap.getReplicas("system_virtual_schema", partitionKey)).isEmpty(); assertThat(tokenMap.getReplicas(sessionRule.keyspace(), partitionKey)).isNotEmpty(); }
Source:
<code>public GDPRSymmetricKey(String secret, String algorithm) throws Exception { Preconditions.checkArgument(secret.length() == 32, "Secret must be exactly 32 characters"); this.secret = secret; this.algorithm = algorithm; <START> this.secretKey = new SecretKeySpec( <END> secret.substring(0, OzoneConsts.GDPR_RANDOM_SECRET_LENGTH) .getBytes(OzoneConsts.GDPR_CHARSET), algorithm); this.cipher = Cipher.getInstance(algorithm); }</code><technical_language>is secret.substring(0, OzoneConsts.GDPR_RANDOM_SECRET_LENGTH)? checking start of method for 32 characters length. replace below. this.secretKey = new SecretKeySpec( secret.getBytes(OzoneConsts.GDPR_CHARSET), algorithm);</technical_language>

Target:
public GDPRSymmetricKey(String secret, String algorithm) throws Exception { Preconditions.checkArgument(secret.length() == 32, "Secret must be exactly 32 characters"); this.secret = secret; this.algorithm = algorithm; this.secretKey = new SecretKeySpec( secret.getBytes(OzoneConsts.GDPR_CHARSET), algorithm); this.cipher = Cipher.getInstance(algorithm); }
Source:
<code>public Iterator<T> iterator() { if (state == State.INFLATED) { <START> return Collections.unmodifiableSet(inflatedSet).iterator(); <END> } return new ImmutableHybridIterator(); }</code><technical_language>I tell, this immutable set is constructed builder additions, case in set inflated -> this line executed. throw illegal state exception instead</technical_language>

Target:
public Iterator<T> iterator() { if (state == State.INFLATED) { throw new IllegalStateException("Set is immutable and can not be inflated."); } return new ImmutableHybridIterator(); }
Source:
<code>public boolean allObjUids(String typeName, InputObjectState foundInstances, int matchState) throws ObjectStoreException { if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger.trace("SlotStore.allObjUids(" + typeName + ", " + matchState + ")"); } SlotStoreKey key = new SlotStoreKey(null, typeName, matchState); SlotStoreKey[] matchingKeys = store.getMatchingKeys(key); OutputObjectState buffer = new OutputObjectState(); try { <START> if (matchingKeys != null) { <END> for (SlotStoreKey matchingKey : matchingKeys) { if (matchingKey != null) { UidHelper.packInto(matchingKey.getUid(), buffer); } } } UidHelper.packInto(Uid.nullUid(), buffer); } catch (IOException e) { throw new ObjectStoreException(e); } foundInstances.setBuffer(buffer.buffer()); return true; }</code><technical_language>Superfluous test for null matchingKeys null SlotStoreAdaptor#getMatchingKeys(key) returns a valid array</technical_language>

Target:
public boolean allObjUids(String typeName, InputObjectState foundInstances, int matchState) throws ObjectStoreException { if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger.trace("SlotStore.allObjUids(" + typeName + ", " + matchState + ")"); } SlotStoreKey key = new SlotStoreKey(null, typeName, matchState); SlotStoreKey[] matchingKeys = store.getMatchingKeys(key); OutputObjectState buffer = new OutputObjectState(); try { for (SlotStoreKey matchingKey : matchingKeys) { UidHelper.packInto(matchingKey.getUid(), buffer); } UidHelper.packInto(Uid.nullUid(), buffer); } catch (IOException e) { throw new ObjectStoreException(e); } foundInstances.setBuffer(buffer.buffer()); return true; }