auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { <START> if (newVersion <= oldVersion) { <END> Timber.w("Can't downgrade from version %d to version %d", oldVersion, newVersion); return; } if (oldVersion < 2) { db.execSQL("DROP TABLE IF EXISTS " + TranslationsTable.TABLE_NAME); db.execSQL(CREATE_TRANSLATIONS_TABLE); } }</code><technical_language>strictly speaking, needed this a framework bug</technical_language>

Target:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion < 2) { final String BACKUP_TABLE = TranslationsTable.TABLE_NAME + "_backup"; db.execSQL(TranslationsTable.getCreateTableSql(BACKUP_TABLE)); db.execSQL("INSERT INTO " + BACKUP_TABLE + " (" + TranslationsTable.ID + ", " + TranslationsTable.NAME + ", " + TranslationsTable.TRANSLATOR + ", " + TranslationsTable.FILENAME + ", " + TranslationsTable.URL + ", " + TranslationsTable.VERSION + ")" + "SELECT " + TranslationsTable.ID + ", " + TranslationsTable.NAME + ", " + TranslationsTable.TRANSLATOR + ", " + TranslationsTable.FILENAME + ", " + TranslationsTable.URL + ", " + TranslationsTable.VERSION + " FROM " + TranslationsTable.TABLE_NAME + ";"); db.execSQL("DROP TABLE " + TranslationsTable.TABLE_NAME); db.execSQL("ALTER TABLE " + BACKUP_TABLE + " RENAME TO " + TranslationsTable.TABLE_NAME); } }
Source:
<code>public Response<AppendBlobItem> createWithResponse(AppendBlobCreateOptions options, Duration timeout, Context context) { return StorageImplUtils.blockWithOptionalTimeout(appendBlobAsyncClient. <START> createWithResponse(options, context), options == null ? null : timeout); <END> }</code><technical_language>This timeout</technical_language>

Target:
public Response<AppendBlobItem> createWithResponse(AppendBlobCreateOptions options, Duration timeout, Context context) { return StorageImplUtils.blockWithOptionalTimeout(appendBlobAsyncClient. createWithResponse(options, context), timeout); }
Source:
<code>protected String callValidateSession(String sessionID) { try { String data = String.format(SESSION_DATA_FORMAT, URLEncoder.encode(sessionID, "UTF-8")); HttpURLConnection servletConnection = createURLConnection(); if (servletConnection == null) { logger.error("Unable to create servlet connection."); return null; } DataOutputStream output = new DataOutputStream(servletConnection.getOutputStream()); output.writeBytes(data); output.flush(); <START> output.close(); <END> if (servletConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { logger.error("ValidateSession servlet returned " + servletConnection.getResponseCode()); return null; } InputStream inputStream = servletConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; inputLine = reader.readLine(); return inputLine; } catch (MalformedURLException e) { e.printStackTrace(); logger.error(e); return null; } catch (IOException e) { e.printStackTrace(); logger.error(e); return null; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); logger.error(e); return null; } catch (CertificateException e) { e.printStackTrace(); logger.error(e); return null; } catch (KeyStoreException e) { e.printStackTrace(); logger.error(e); return null; } catch (KeyManagementException e) { e.printStackTrace(); logger.error(e); return null; } }</code><technical_language>I suggest put close in finally block</technical_language>

Target:
protected String callValidateSession(String sessionID) { DataOutputStream output = null; try { String data = String.format(SESSION_DATA_FORMAT, URLEncoder.encode(sessionID, "UTF-8")); HttpURLConnection servletConnection = createURLConnection(); if (servletConnection == null) { logger.error("Unable to create servlet connection."); return null; } output = new DataOutputStream(servletConnection.getOutputStream()); output.writeBytes(data); output.flush(); output.close(); if (servletConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { logger.error("ValidateSession servlet returned " + servletConnection.getResponseCode()); return null; } InputStream inputStream = servletConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; inputLine = reader.readLine(); return inputLine; } catch (Exception ex) { logger.error(ex); } finally { try { if (output != null) output.close(); } catch (IOException ex) { logger.error(ex); } } return null; }
Source:
<code><START> private void readLinesLoop(Pattern success, Pattern failure, <END> BufferedReader reader) throws IOException { StringBuilder output = new StringBuilder(); output.append(String.format("Webpack build failed with errors:%n")); Consumer<String> info = s -> getLogger().debug(GREEN, s); Consumer<String> error = s -> getLogger().error(RED, s); Consumer<String> warn = s -> getLogger().debug(YELLOW, s); Consumer<String> log = info; for (String line; ((line = reader.readLine()) != null);) { String cleanLine = line .replaceAll("\u001b\\[[;\\d]*m", "") .replaceAll("\\?babel-target=[\\w\\d]+", ""); log = line.contains("WARNING") ? warn : line.contains("ERROR") ? error : log; log.accept(cleanLine); if(line.contains("ERROR")) { output.append(cleanLine).append(System.lineSeparator()); } boolean succeed = success.matcher(line).find(); boolean failed = failure.matcher(line).find(); if (succeed || failed) { log.accept(succeed ? SUCCEED_MSG : FAILED_MSG); failedOutput = failed ? output.toString() : null; output = new StringBuilder(); log = info; doNotify(); } } }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Refactor this method reduce Cognitive Complexity 17 15 allowed. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
private void readLinesLoop(Pattern success, Pattern failure, BufferedReader reader) throws IOException { StringBuilder output = getOutputBuilder(); Consumer<String> info = s -> getLogger().debug(GREEN, s); Consumer<String> error = s -> getLogger().error(RED, s); Consumer<String> warn = s -> getLogger().debug(YELLOW, s); Consumer<String> log = info; for (String line; ((line = reader.readLine()) != null);) { String cleanLine = line .replaceAll("\u001b\\[[;\\d]*m", "") .replaceAll("\\?babel-target=[\\w\\d]+", ""); log = line.contains("WARNING") ? warn : line.contains("ERROR") ? error : log; log.accept(cleanLine); if(line.contains("ERROR")) { output.append(cleanLine).append(System.lineSeparator()); } boolean succeed = success.matcher(line).find(); boolean failed = failure.matcher(line).find(); if (succeed || failed) { log.accept(succeed ? SUCCEED_MSG : FAILED_MSG); failedOutput = failed ? output.toString() : null; output = getOutputBuilder(); log = info; doNotify(); } } }
Source:
<code>protected RoleDTO initSourceObject() { RoleDTO source = new RoleDTO(); List<UserDTO> users = new ArrayList<>(); List<PermissionBlueprintDTO> permissions = new ArrayList<>(); for (int i = 0; i < 5; ++i) { UserDTO user = (UserDTO) this.userDTOTranslatorTest.initSourceObject(); user.setId("test-user-" + i); PermissionBlueprintDTO permission = (PermissionBlueprintDTO) this.permDTOTranslatorTest.initSourceObject(); permission.setId("test-perm-" + i); users.add(user); permissions.add(permission); } source.id("test-role-id") .name("test-role-name") .users(users) .permissions(permissions) <START> .created(new Date().toInstant().atOffset(ZoneOffset.UTC)) .updated(new Date().toInstant().atOffset(ZoneOffset.UTC)); <END> return source; }</code><technical_language>need create a new Date object transform OffsetDateTime. OffsetDateTime.now()</technical_language>

Target:
protected RoleDTO initSourceObject() { RoleDTO source = new RoleDTO(); Set<UserDTO> users = new HashSet<>(); List<PermissionBlueprintDTO> permissions = new ArrayList<>(); for (int i = 0; i < 5; ++i) { UserDTO user = (UserDTO) this.userDTOTranslatorTest.initSourceObject(); user.setUsername("user_username" + i); PermissionBlueprintDTO permission = (PermissionBlueprintDTO) this.permDTOTranslatorTest.initSourceObject(); permission.setId("test-perm-" + i); users.add(user); permissions.add(permission); } source.id("test-role-id") .name("test-role-name") .users(users) .permissions(permissions) .created(OffsetDateTime.now()) .updated(OffsetDateTime.now()); return source; }
Source:
<code>public CustomProcessorInfo addCustomProcessorInfo (CustomProcessorInfo customProcessorInfo, InputStream jarFile, InputStream imageFile) throws IOException { try { uploadFileToStorage(jarFile, customProcessorInfo.getJarFileName()); uploadFileToStorage(imageFile, customProcessorInfo.getImageFileName()); TopologyComponentDefinition topologyComponentDefinition = customProcessorInfo.toTopologyComponent(); topologyComponentDefinition.setId(this.dao.nextId(TopologyComponentDefinition.NAME_SPACE)); this.dao.add(topologyComponentDefinition); } catch (StorageException|IOException e) { LOG.error(String.format("Unexpected exception thrown while adding custom processor info %s", customProcessorInfo.getName())); throw e; } finally { try { deleteFileFromStorage(customProcessorInfo.getJarFileName()); <START> deleteFileFromStorage(customProcessorInfo.getJarFileName()); <END> } catch (IOException e) { LOG.error(String.format("Unexpected exception thrown while cleaning up custom processor info %s", customProcessorInfo.getName())); throw e; } } return customProcessorInfo; }</code><technical_language>getImageFileName here</technical_language>

Target:
public CustomProcessorInfo addCustomProcessorInfo (CustomProcessorInfo customProcessorInfo, InputStream jarFile, InputStream imageFile) throws IOException { try { uploadFileToStorage(jarFile, customProcessorInfo.getJarFileName()); uploadFileToStorage(imageFile, customProcessorInfo.getImageFileName()); TopologyComponentDefinition topologyComponentDefinition = customProcessorInfo.toTopologyComponent(); topologyComponentDefinition.setId(this.dao.nextId(TopologyComponentDefinition.NAME_SPACE)); this.dao.add(topologyComponentDefinition); } catch (StorageException|IOException e) { LOG.error("Unexpected exception thrown while adding custom processor info %s", customProcessorInfo.getName()); throw e; } finally { try { deleteFileFromStorage(customProcessorInfo.getJarFileName()); deleteFileFromStorage(customProcessorInfo.getImageFileName()); } catch (IOException e) { LOG.error("Unexpected exception thrown while cleaning up custom processor info %s", customProcessorInfo.getName()); throw e; } } return customProcessorInfo; }
Source:
<code>public void testUnattributedOutcomeSuccess() throws Exception { service.setSuccess(true); sessionManager.initSessionFromCache(); controller.sendOutcomeEvent(OUTCOME_NAME); threadAndTaskWait(); new Thread(new Runnable() { @Override public void run() { <START> handler.setOutcomes(repository.getSavedOutcomeEvents()); <END> } }, "OS_GET_SAVED_OUTCOMES_SUCCESS").start(); threadAndTaskWait(); assertEquals(0, outcomeEvents.size()); assertEquals("{\"id\":\"testing\",\"sources\":{},\"device_type\":1}", service.getLastJsonObjectSent()); }</code><technical_language>run this thread</technical_language>

Target:
public void testUnattributedOutcomeSuccess() throws Exception { service.setSuccess(true); sessionManager.initSessionFromCache(); controller.sendOutcomeEvent(OUTCOME_NAME); threadAndTaskWait(); handler.setOutcomes(repository.getSavedOutcomeEvents()); threadAndTaskWait(); assertEquals(0, outcomeEvents.size()); assertEquals("{\"id\":\"testing\",\"sources\":{},\"device_type\":1}", service.getLastJsonObjectSent()); }
Source:
<code>public String graphData( Map<String, Object> model, @RequestParam(value = "id", defaultValue = "") String id, @RequestParam(value = "uri", defaultValue = "") String uri, @RequestParam(value = "min_edges", required = false, defaultValue = "1") String minEdges ) { if (Strings.isNullOrEmpty(uri) && Strings.isNullOrEmpty(id)) { throw new IllegalArgumentException("Must specify at least one of 'uri' or 'id'"); } int minimumEdgeCount = Integer.parseInt(minEdges); model.put("id", id); model.put("uri", uri); model.put("min_edges", minimumEdgeCount); <START> String uriFromId = getUriFromId(id).get(); <END> LookupEntry subj = Iterables.getOnlyElement( lookupStore.entriesForCanonicalUris(ImmutableList.of(uri, uriFromId)), null ); if (subj != null) { Iterable<LookupEntry> equivs = lookupStore.entriesForCanonicalUris( subj.equivalents() .stream() .map(LookupRef.TO_URI::apply) .collect(Collectors.toList())); List<SimpleModel> nodes = Lists.newLinkedList(); for (LookupEntry equiv : equivs) { if (edgeCount(equiv) >= minimumEdgeCount) { SimpleModel nodeModel = modelNode(equiv); if (equiv.uri().equals(uri)) { nodeModel.put("fixed", true); } nodes.add(nodeModel); } } model.put("content", new SimpleModelList(nodes)); } return "equivalence.graph"; }</code><technical_language>returning Optional immediately checking present</technical_language>

Target:
public String graphData( Map<String, Object> model, @RequestParam(value = "id", defaultValue = "") String id, @RequestParam(value = "uri", defaultValue = "") String uri, @RequestParam(value = "min_edges", required = false, defaultValue = "1") String minEdges ) { if (Strings.isNullOrEmpty(uri) && Strings.isNullOrEmpty(id)) { throw new IllegalArgumentException("Must specify at least one of 'uri' or 'id'"); } int minimumEdgeCount = Integer.parseInt(minEdges); model.put("id", id); model.put("uri", uri); model.put("min_edges", minimumEdgeCount); String uriFromId = ""; if (getUriFromId(id).isPresent()) { uriFromId = getUriFromId(id).get(); } LookupEntry subj = Iterables.getOnlyElement( lookupStore.entriesForCanonicalUris(ImmutableList.of(uri, uriFromId)), null ); if (subj != null) { Iterable<LookupEntry> equivs = lookupStore.entriesForCanonicalUris( subj.equivalents() .stream() .map(LookupRef.TO_URI::apply) .collect(Collectors.toList())); List<SimpleModel> nodes = Lists.newLinkedList(); for (LookupEntry equiv : equivs) { if (edgeCount(equiv) >= minimumEdgeCount) { SimpleModel nodeModel = modelNode(equiv); if (equiv.uri().equals(uri)) { nodeModel.put("fixed", true); } nodes.add(nodeModel); } } model.put("content", new SimpleModelList(nodes)); } return "equivalence.graph"; }
Source:
<code><START> private synchronized boolean performCheck(Nameable entity, Predicate<IAuthorizationPlugin> predicate) { <END> lock.readLock().lock(); try { return stack.isAllowed(entity, predicate); } finally { lock.readLock().unlock(); } }</code><technical_language>synchronized present</technical_language>

Target:
private boolean performCheck(Nameable entity, Predicate<IAuthorizationPlugin> predicate) { lock.readLock().lock(); try { return stack.isAllowed(entity, predicate); } finally { lock.readLock().unlock(); } }
Source:
<code>protected Node visitShowStats(ShowStats node, Void context) { checkState(queryExplainer.isPresent(), "Query explainer must be provided for SHOW STATS SELECT"); if (node.getRelation() instanceof TableSubquery) { QuerySpecification specification = (QuerySpecification) ((TableSubquery) node.getRelation()).getQuery().getQueryBody(); Plan plan = queryExplainer.get().getLogicalPlan(session, new Query(Optional.empty(), specification, Optional.empty(), Optional.empty()), parameters); <START> validateShowStats(node, plan); <END> Table table = (Table) specification.getFrom().get(); Constraint<ColumnHandle> constraint = getConstraint(specification, plan); return rewriteShowStats(node, table, constraint); } else if (node.getRelation() instanceof Table) { Table table = (Table) node.getRelation(); return rewriteShowStats(node, table, Constraint.alwaysTrue()); } else { throw new IllegalArgumentException("Expected either TableSubquery or Table as relation"); } }</code><technical_language>pull here? do this check in getConstraint, change validate need extract plan</technical_language>

Target:
protected Node visitShowStats(ShowStats node, Void context) { checkState(queryExplainer.isPresent(), "Query explainer must be provided for SHOW STATS SELECT"); if (node.getRelation() instanceof TableSubquery) { Query query = ((TableSubquery) node.getRelation()).getQuery(); QuerySpecification specification = (QuerySpecification) query.getQueryBody(); Plan plan = queryExplainer.get().getLogicalPlan(session, new Query(Optional.empty(), specification, Optional.empty(), Optional.empty()), parameters, warningCollector); validateShowStatsSubquery(node, query, specification, plan); Table table = (Table) specification.getFrom().get(); Constraint<ColumnHandle> constraint = getConstraint(plan); return rewriteShowStats(node, table, constraint); } else if (node.getRelation() instanceof Table) { Table table = (Table) node.getRelation(); return rewriteShowStats(node, table, Constraint.alwaysTrue()); } else { throw new IllegalArgumentException("Expected either TableSubquery or Table as relation"); } }
Source:
<code>private void updateCommand(Class<?> handlerType, Object[] elements, IEnabledTarget[] actions) { boolean hasMultipleWindowServices = hasMultipleWindowServices(); <START> if (!hasMultipleWindowServices) { <END> Job.getJobManager().cancel(handlerType); } if (elements.length == 1) { Object element = elements[0]; IDebugCommandHandler handler = getHandler(element, handlerType); if (handler != null) { UpdateActionsRequest request = new UpdateActionsRequest(elements, actions); handler.canExecute(request); return; } } else { Map<IDebugCommandHandler, List<Object>> map = collate(elements, handlerType); if (map != null) { ActionsUpdater updater = new ActionsUpdater(actions, map.size()); for (Entry<IDebugCommandHandler, List<Object>> entry : map.entrySet()) { UpdateHandlerRequest request = new UpdateHandlerRequest(entry.getValue().toArray(), updater); entry.getKey().canExecute(request); } return; } } for (IEnabledTarget action : actions) { action.setEnabled(false); } }</code><technical_language>A detail is fault bothered change set is consequence a null handlerType. happen cancel _any_ job in this case</technical_language>

Target:
private void updateCommand(Class<?> handlerType, Object[] elements, IEnabledTarget[] actions) { cancelHandlerEnablementUpdateJobs(handlerType); if (elements.length == 1) { Object element = elements[0]; IDebugCommandHandler handler = getHandler(element, handlerType); if (handler != null) { UpdateActionsRequest request = new UpdateActionsRequest(elements, actions); handler.canExecute(request); return; } } else { Map<IDebugCommandHandler, List<Object>> map = collate(elements, handlerType); if (map != null) { ActionsUpdater updater = new ActionsUpdater(actions, map.size()); for (Entry<IDebugCommandHandler, List<Object>> entry : map.entrySet()) { UpdateHandlerRequest request = new UpdateHandlerRequest(entry.getValue().toArray(), updater); entry.getKey().canExecute(request); } return; } } for (IEnabledTarget action : actions) { action.setEnabled(false); } }
Source:
<code>private ReplLoadOpType getLoadTableType(Table table, boolean isBootstrapDuringInc) throws InvalidOperationException, HiveException { if (table == null) { return ReplLoadOpType.LOAD_NEW; } <START> if (isBootstrapDuringInc && AcidUtils.isTransactionalTable(table)) { <END> LOG.info("Transactional table " + table.getTableName() + " will be replaced"); return ReplLoadOpType.LOAD_REPLACE; } if (ReplUtils.replCkptStatus(table.getDbName(), table.getParameters(), context.dumpDirectory)) { return ReplLoadOpType.LOAD_SKIP; } return ReplLoadOpType.LOAD_REPLACE; }</code><technical_language>I think, this check done for external tables. replace table in case of isBootstrapDuringInc</technical_language>

Target:
private ReplLoadOpType getLoadTableType(Table table, boolean isBootstrapDuringInc) throws InvalidOperationException, HiveException { if (table == null) { return ReplLoadOpType.LOAD_NEW; } if (isBootstrapDuringInc) { LOG.info("Table " + table.getTableName() + " will be replaced as bootstrap is requested during incremental load"); return ReplLoadOpType.LOAD_REPLACE; } if (ReplUtils.replCkptStatus(table.getDbName(), table.getParameters(), context.dumpDirectory)) { return ReplLoadOpType.LOAD_SKIP; } return ReplLoadOpType.LOAD_REPLACE; }
Source:
<code>public void received( final Object o ) { <START> if ( o instanceof Initialize ) { <END> init( (Initialize) o ); } else if ( o instanceof RequestStatus ) { requestStatus(); } else if ( o instanceof RemoveRule ) { getUpdateManager().removeRule( ( (RemoveRule) o ).getDeletedRow() ); } else if ( o instanceof Update ) { try { getUpdateManager().update( ( (Update) o ).getModel(), ( (Update) o ).getCoordinates() ); } catch ( final UpdateException e ) { poster.post( new WebWorkerException( e.getMessage() ) ); } } else if ( o instanceof DeleteColumns ) { getUpdateManager().deleteColumns( ( (DeleteColumns) o ).getFirstColumnIndex(), ( (DeleteColumns) o ).getNumberOfColumns() ); } else if ( o instanceof MakeRule ) { makeRule( (MakeRule) o ); } else if ( o instanceof NewColumn ) { newColumn( (NewColumn) o ); } }</code><technical_language>Nice extensible want add new commands ;-) I guess commands pretty static; add, delete, update etc.. live it</technical_language>

Target:
public void received( final Object o ) { if ( o instanceof Initialize ) { init( (Initialize) o ); } else if ( o instanceof RequestStatus ) { requestStatus(); } else if ( o instanceof RemoveRule ) { removeRule( (RemoveRule) o ); } else if ( o instanceof Update ) { update( (Update) o ); } else if ( o instanceof DeleteColumns ) { deleteColumns( (DeleteColumns) o ); } else if ( o instanceof MakeRule ) { makeRule( (MakeRule) o ); } else if ( o instanceof NewColumn ) { newColumn( (NewColumn) o ); } }
Source:
<code>private void buildSwitchStatement(SwitchStatementTree switchStatementTree) { Block switchSuccessor = currentBlock; currentBlock = createBlock(); currentBlock.terminator = switchStatementTree; switches.addLast(currentBlock); build(switchStatementTree.expression()); currentBlock = createBlock(switchSuccessor); breakTargets.addLast(switchSuccessor); <START> boolean defaultCaseMet = false; <END> if (!switchStatementTree.cases().isEmpty()) { CaseGroupTree firstCase = switchStatementTree.cases().get(0); for (CaseGroupTree caseGroupTree : Lists.reverse(switchStatementTree.cases())) { build(caseGroupTree.body()); for (CaseLabelTree caseLabel : caseGroupTree.labels()) { if ("default".equals(caseLabel.caseOrDefaultKeyword().text())) { defaultCaseMet = true; } } switches.getLast().addSuccessor(currentBlock); if (!caseGroupTree.equals(firstCase)) { currentBlock = createBlock(currentBlock); } } } breakTargets.removeLast(); currentBlock = switches.removeLast(); if (!defaultCaseMet) { currentBlock.addSuccessor(switchSuccessor); } }</code><technical_language>I rename : hasDefault hasDefaultCase</technical_language>

Target:
private void buildSwitchStatement(SwitchStatementTree switchStatementTree) { Block switchSuccessor = currentBlock; currentBlock = createBlock(); currentBlock.terminator = switchStatementTree; switches.addLast(currentBlock); build(switchStatementTree.expression()); currentBlock = createBlock(switchSuccessor); breakTargets.addLast(switchSuccessor); boolean hasDefaultCase = false; if (!switchStatementTree.cases().isEmpty()) { CaseGroupTree firstCase = switchStatementTree.cases().get(0); for (CaseGroupTree caseGroupTree : Lists.reverse(switchStatementTree.cases())) { build(caseGroupTree.body()); if (!hasDefaultCase) { for (CaseLabelTree caseLabel : caseGroupTree.labels()) { if ("default".equals(caseLabel.caseOrDefaultKeyword().text())) { hasDefaultCase = true; break; } } } switches.getLast().addSuccessor(currentBlock); if (!caseGroupTree.equals(firstCase)) { currentBlock = createBlock(currentBlock); } } } breakTargets.removeLast(); currentBlock = switches.removeLast(); if (!hasDefaultCase) { currentBlock.addSuccessor(switchSuccessor); } }
Source:
<code>private List<ItemDefinition> setItemDefinitionsNamespace(final List<ItemDefinition> itemDefinitions, final String namespace) { return itemDefinitions .stream() <START> .peek(itemDefinition -> setItemDefinitionNamespace(itemDefinition, namespace)) <END> .collect(Collectors.toList()); }</code><technical_language>Reading [this](<LINK_0> I map instead of peek , I miss something</technical_language>

Target:
private List<ItemDefinition> setItemDefinitionsNamespace(final List<ItemDefinition> itemDefinitions, final String namespace) { return itemDefinitions .stream() .map(itemDefinition -> setItemDefinitionNamespace(itemDefinition, namespace)) .collect(Collectors.toList()); }
Source:
<code>public ExecutionEngineJNI( final int clusterIndex, final long siteId, final int partitionId, final int hostId, final String hostname, final int drClusterId, final int defaultDrBufferSize, final int tempTableMemory, final HashinatorConfig hashinatorConfig, final boolean createDrReplicatedStream) { super(siteId, partitionId); LOG.trace("Creating Execution Engine on clusterIndex=" + clusterIndex + ", site_id = " + siteId + "..."); pointer = nativeCreate(System.getProperty("java.vm.vendor") .toLowerCase().contains("sun microsystems")); nativeSetLogLevels(pointer, EELoggers.getLogLevels()); int errorCode = nativeInitialize( pointer, clusterIndex, siteId, partitionId, hostId, getStringBytes(hostname), drClusterId, defaultDrBufferSize, tempTableMemory * 1024 * 1024, createDrReplicatedStream, EE_COMPACTION_THRESHOLD); checkErrorCode(errorCode); setupPsetBuffer(smallBufferSize); setupPerFragmentStatsBuffer(smallBufferSize); <START> setupUDFBuffer(2 * 1024 * 1024); <END> updateEEBufferPointers(); updateHashinator(hashinatorConfig); }</code><technical_language>This magic number needs a named constant somewhere</technical_language>

Target:
public ExecutionEngineJNI( final int clusterIndex, final long siteId, final int partitionId, final int hostId, final String hostname, final int drClusterId, final int defaultDrBufferSize, final int tempTableMemory, final HashinatorConfig hashinatorConfig, final boolean createDrReplicatedStream) { super(siteId, partitionId); LOG.trace("Creating Execution Engine on clusterIndex=" + clusterIndex + ", site_id = " + siteId + "..."); pointer = nativeCreate(System.getProperty("java.vm.vendor") .toLowerCase().contains("sun microsystems")); nativeSetLogLevels(pointer, EELoggers.getLogLevels()); int errorCode = nativeInitialize( pointer, clusterIndex, siteId, partitionId, hostId, getStringBytes(hostname), drClusterId, defaultDrBufferSize, tempTableMemory * 1024 * 1024, createDrReplicatedStream, EE_COMPACTION_THRESHOLD); checkErrorCode(errorCode); setupPsetBuffer(smallBufferSize); setupPerFragmentStatsBuffer(smallBufferSize); setupUDFBuffer(smallBufferSize); updateEEBufferPointers(); updateHashinator(hashinatorConfig); }
Source:
<code>public void onCreate() { super.onCreate(); HandlerThread thread = new HandlerThread("ServiceStartArguments", android.os.Process.THREAD_PRIORITY_BACKGROUND); thread.start(); Looper serviceLooper = thread.getLooper(); mServiceHandler = getHandler(serviceLooper); Replicator[] replicators = getReplicators(getApplicationContext()); if (replicators != null && replicators.length > 0) { if (mReplicationPolicyManager == null) { mReplicationPolicyManager = new ReplicationPolicyManager() { @Override public void start() { } @Override public void stop() { } }; } mReplicationPolicyManager.addReplicators(replicators); mReplicationPolicyManager.setReplicationsCompletedListener(this); <START> mReplicationPolicyManager.start(); <END> } else { throw new RuntimeException( "No replications setup. Please return Replicators from getReplicators()"); } }</code><technical_language>explain this conditionless policy manager is created, interacts setReplicationPolicyManager below? (e.g., setReplicationPolicyManager call stop existing policy manager re-assigning?)</technical_language>

Target:
public void onCreate() { super.onCreate(); HandlerThread thread = new HandlerThread("ServiceStartArguments", android.os.Process.THREAD_PRIORITY_BACKGROUND); thread.start(); Looper serviceLooper = thread.getLooper(); mServiceHandler = getHandler(serviceLooper); Replicator[] replicators = getReplicators(getApplicationContext()); if (replicators != null && replicators.length > 0) { if (mReplicationPolicyManager == null) { mReplicationPolicyManager = new ReplicationPolicyManager(); } mReplicationPolicyManager.addReplicators(replicators); mReplicationPolicyManager.setReplicationsCompletedListener(this); } else { throw new RuntimeException( "No replications setup. Please return Replicators from getReplicators()"); } }
Source:
<code>public String getCanonicalName(ApiMethodArg argument) throws MojoExecutionException { final Class<?> type = argument.getType(); if (type.isPrimitive()) { return getCanonicalName(ClassUtils.primitiveToWrapper(type)); } String canonicalName = getCanonicalName(type); final String typeArgs = argument.getTypeArgs(); if (typeArgs != null) { StringBuilder parameterizedType = new StringBuilder(canonicalName); parameterizedType.append('<'); final String[] argTypes = typeArgs.split(","); boolean ignore = false; final int nTypes = argTypes.length; int i = 0; for (String argType : argTypes) { try { parameterizedType.append(getCanonicalName(getProjectClassLoader().loadClass(argType))); } catch (ClassNotFoundException e) { try { if (log.isDebugEnabled()) { log.debug("Could not load " + argType + ", trying to load java.lang." + argType); } parameterizedType.append( getCanonicalName(getProjectClassLoader().loadClass("java.lang." + argType))); } catch (ClassNotFoundException e1) { <START> if (argType.trim().length() > 1) { <END> log.warn("Ignoring type parameters <" + typeArgs + "> for argument " + argument.getName() + ", unable to load parametric type argument " + argType, e1); ignore = true; } else { parameterizedType.append("?"); } } } if (ignore) { break; } else if (++i < nTypes) { parameterizedType.append(","); } } if (!ignore) { parameterizedType.append('>'); canonicalName = parameterizedType.toString(); } } return canonicalName; }</code><technical_language>@manonthegithub sure, try implement more elegant solution, cast (T) catch ClassCastException</technical_language>

Target:
public String getCanonicalName(ApiMethodArg argument) throws MojoExecutionException { final Class<?> type = argument.getType(); if (type.isPrimitive()) { return getCanonicalName(ClassUtils.primitiveToWrapper(type)); } String canonicalName = getCanonicalName(type); final String typeArgs = argument.getTypeArgs(); if (typeArgs != null) { StringBuilder parameterizedType = new StringBuilder(canonicalName); parameterizedType.append('<'); final String[] argTypes = typeArgs.split(","); final int nTypes = argTypes.length; int i = 0; for (String argType : argTypes) { try { parameterizedType.append(getCanonicalName(getProjectClassLoader().loadClass(argType))); } catch (ClassNotFoundException e) { try { if (log.isDebugEnabled()) { log.debug("Could not load " + argType + ", trying to load java.lang." + argType); } parameterizedType.append( getCanonicalName(getProjectClassLoader().loadClass("java.lang." + argType))); } catch (ClassNotFoundException e1) { parameterizedType.append("?"); if (argType.trim().length() > 1) { log.warn("Ignoring type parameters <" + typeArgs + "> for argument " + argument.getName() + ", unable to load parametric type argument " + argType, e1); } } } if (++i < nTypes) { parameterizedType.append(","); } } parameterizedType.append('>'); canonicalName = parameterizedType.toString(); } return canonicalName; }
Source:
<code>private static void assertObjectsAreDistinct(GetBlobOptions a, GetBlobOptions b) { assertThat("GetBlobOptions should not be equal.", a, not(b)); <START> assertThat("GetBlobOptions hashcodes should not be equal", a.hashCode(), not(b.hashCode())); <END> assertThat("GetBlobOptions toString should not be equal", a.toString(), not(b.toString())); }</code><technical_language>hashcode equal if objects - this test is correct lead spurious failures</technical_language>

Target:
private static void assertObjectsAreDistinct(GetBlobOptions a, GetBlobOptions b) { assertThat("GetBlobOptions should not be equal.", a, not(b)); assertThat("GetBlobOptions toString should not be equal", a.toString(), not(b.toString())); }
Source:
<code>private InputStream getManagedFile(Run<?, ?> run, String fileName) throws UnsupportedEncodingException { InputStream stream = null; Plugin plugin = Jenkins.get().getPlugin("config-file-provider"); if (plugin != null) { Config config = null; <START> assert getProviderClass() != null; <END> List<Config> configs = ConfigFiles.getConfigsInContext(run.getParent().getParent(), getProviderClass()); for (Config c : configs) { if (c.name.equalsIgnoreCase(fileName)) { config = c; break; } } if (config != null) { stream = new ByteArrayInputStream(config.content.getBytes("UTF-8")); } } return stream; }</code><technical_language>this work for cases? .getParent().getParent()? if is folder nesting, work in case</technical_language>

Target:
private InputStream getManagedFile(Run<?, ?> run, String fileName) throws UnsupportedEncodingException { InputStream stream = null; Plugin plugin = Jenkins.get().getPlugin("config-file-provider"); if (plugin != null) { Config config = null; List<Config> configs = ConfigFiles.getConfigsInContext(run.getParent().getParent(), getProviderClass()); for (Config c : configs) { if (c.name.equalsIgnoreCase(fileName)) { config = c; break; } } if (config != null) { stream = new ByteArrayInputStream(config.content.getBytes("UTF-8")); } } return stream; }
Source:
<code>public void create() { if (exists()) { return; } final CreateIndexRequestBuilder req = client().admin().indices().prepareCreate(name); final Multimap<String, Map<String, Object>> esMappings = HashMultimap.create(); for (DocumentMapping mapping : mappings.getMappings()) { final String type = mapping.typeAsString(); Map<String, Object> typeMapping = ImmutableMap.of(type, ImmutableMap.builder() .put("_all", ImmutableMap.of("enabled", false)) .putAll(toProperties(mapping)) .build() ); esMappings.put(type, typeMapping); } for (String type : esMappings.keySet()) { <START> final Map<String, Object> typeMapping = esMappings.get(type).stream().sorted((m1, m2) -> -1 * Ints.compare(m1.toString().length(), m2.toString().length())).findFirst().get(); <END> req.addMapping(type, typeMapping); } try { final Map<String, Object> indexSettings = createSettings(); log.info("Configuring '{}' index with settings: {}", name, indexSettings); req.setSettings(indexSettings); } catch (IOException e) { throw new IndexException("Couldn't prepare settings for index " + name, e); } CreateIndexResponse response = req.get(); checkState(response.isAcknowledged(), "Failed to create index %s", name); waitForYellowHealth(); }</code><technical_language>this part do? Shorter mappings win longer ones</technical_language>

Target:
public void create() { if (exists()) { waitForYellowHealth(); return; } final CreateIndexRequestBuilder req = client().admin().indices().prepareCreate(name); final Multimap<String, Map<String, Object>> esMappings = HashMultimap.create(); for (DocumentMapping mapping : mappings.getMappings()) { final String type = mapping.typeAsString(); Map<String, Object> typeMapping = ImmutableMap.of(type, ImmutableMap.builder() .put("_all", ImmutableMap.of("enabled", false)) .putAll(toProperties(mapping)) .build() ); esMappings.put(type, typeMapping); } for (String type : esMappings.keySet()) { final Map<String, Object> typeMapping = esMappings.get(type).stream().sorted((m1, m2) -> -1 * Ints.compare(m1.toString().length(), m2.toString().length())).findFirst().get(); req.addMapping(type, typeMapping); } try { final Map<String, Object> indexSettings = createSettings(); log.info("Configuring '{}' index with settings: {}", name, indexSettings); req.setSettings(indexSettings); } catch (IOException e) { throw new IndexException("Couldn't prepare settings for index " + name, e); } CreateIndexResponse response = req.get(); checkState(response.isAcknowledged(), "Failed to create index %s", name); waitForYellowHealth(); }
Source:
<code>public Object getCustomParam(String name) { <START> return (customParams!=null)?customParams.get(name):null; <END> }</code><technical_language>check customParams if checked in setCustomParams method</technical_language>

Target:
public Object getCustomParam(String name) { return customParams.get(name); }
Source:
<code>public static String getSisSectionIDChunk(HttpServletRequest request) { String courseId = getLTICustomParam(request, LTI_PARAM_CANVAS_COURSE_ID); if(courseId==null){ <START> M_log.warn("Course id could not be found for making a SIS Section Id"); <END> long epoch = System.currentTimeMillis(); courseId = String.valueOf(epoch); } return "ccmS" + courseId + "-"; }</code><technical_language>move warning message line 317, change text "Course id for making a SIS Section Id. current timestamp for id: <courseId value>"</technical_language>

Target:
public static String getSisSectionIDChunk(HttpServletRequest request) { String courseId = getLTICustomParam(request, LTI_PARAM_CANVAS_COURSE_ID); if(courseId==null){ long epoch = System.currentTimeMillis(); courseId = String.valueOf(epoch); M_log.warn("Course id could not be found for making a SIS Section Id. Used current timestamp for course id:"); } return "ccmS" + courseId + "-"; }
Source:
<code><START> public Promise<CLIOutputResponse> copy(Path project, Path source, Path destination, String comment, Credentials credentials) { <END> final CopyRequest request = dtoFactory.createDto(CopyRequest.class) .withProjectPath(project.toString()) .withSource(source.toString()) .withDestination(destination.toString()) .withComment(comment) .withUsername(credentials.getUsername()) .withPassword(credentials.getPassword()); return asyncRequestFactory.createPostRequest(getBaseUrl() + "/copy", request) .loader(loader) .send(dtoUnmarshallerFactory.newUnmarshaller(CLIOutputResponse.class)); }</code><technical_language><LINK_0> mark credentials Nullable this implementation support null value. get NPE</technical_language>

Target:
public Promise<CLIOutputResponse> copy(Path project, Path source, Path destination, String comment, Credentials credentials) { final CopyRequest request = dtoFactory.createDto(CopyRequest.class) .withProjectPath(project.toString()) .withSource(source.toString()) .withDestination(destination.toString()) .withComment(comment); if (credentials != null) { request.setUsername(credentials.getUsername()); request.setPassword(credentials.getPassword()); } return asyncRequestFactory.createPostRequest(getBaseUrl() + "/copy", request) .loader(loader) .send(dtoUnmarshallerFactory.newUnmarshaller(CLIOutputResponse.class)); }
Source:
<code>void onContactsStatusRequestedFromServer(final Map<String, ContactStatus> contactsStatus) { if (updateContactStatus(contactsStatus)) { final Set<ContactDataComplete> contacts = createFullContactDataSet(); mState = State.INITIALIZED; <START> notifyFullContactsListeners(contacts); <END> } else { onError(); } }</code><technical_language>notifyFullContactsListeners(createFullContactDataSet());</technical_language>

Target:
void onContactsStatusRequestedFromServer(final Map<String, ContactStatus> contactsStatus) { if (updateContactStatus(contactsStatus)) { mState = State.INITIALIZED; notifyFullContactsListeners(createFullContactDataSet(), Error.NONE); } else { onError(Error.NO_INTERNET_CONNECTION); } }
Source:
<code>static byte[] getRid(byte[] oscoreOption) { if (oscoreOption.length == 0) { <START> oscoreOption = new byte[] { 0x00 }; <END> } byte flagByte = oscoreOption[0]; int n = flagByte & 0x07; int k = flagByte & 0x08; int h = flagByte & 0x10; byte[] kid = null; int index = 1; index += n; if (h != 0) { int s = oscoreOption[index]; index += s + 1; } if (k != 0) { kid = Arrays.copyOfRange(oscoreOption, index, oscoreOption.length); } return kid; }</code><technical_language>For this case return null, or</technical_language>

Target:
static byte[] getRid(byte[] oscoreOption) { if (oscoreOption.length == 0) { return null; } byte flagByte = oscoreOption[0]; int n = flagByte & 0x07; int k = flagByte & 0x08; int h = flagByte & 0x10; byte[] kid = null; int index = 1; index += n; if (h != 0) { int s = oscoreOption[index]; index += s + 1; } if (k != 0) { kid = Arrays.copyOfRange(oscoreOption, index, oscoreOption.length); } return kid; }
Source:
<code>public Range getSearchRangeOnSingleValue(Object value) { if (Date.class.isAssignableFrom(dataType)) { Date center = (Date) value; Calendar cal = Calendar.getInstance(); cal.setTime(center); cal.setTimeInMillis(cal.getTimeInMillis() - before.longValue()); Date min = cal.getTime(); cal.setTime(center); cal.setTimeInMillis(cal.getTimeInMillis() + after.longValue()); Date max = cal.getTime(); return new DateRange(min, max); } else { <START> throw new IllegalArgumentException("Unsupported value type " + dataType); <END> } }</code><technical_language>Unnecessary else</technical_language>

Target:
public Range getSearchRangeOnSingleValue(Object value) { if (Date.class.isAssignableFrom(dataType)) { Date center = (Date) value; Calendar cal = Calendar.getInstance(); cal.setTime(center); cal.setTimeInMillis(cal.getTimeInMillis() - before.longValue()); Date min = cal.getTime(); cal.setTime(center); cal.setTimeInMillis(cal.getTimeInMillis() + after.longValue()); Date max = cal.getTime(); return new DateRange(min, max); } throw new IllegalArgumentException("Unsupported value type " + dataType); }
Source:
<code>public static short computeDuplicateScore(final SAMRecord record, final ScoringStrategy scoringStrategy, final boolean assumeMateCigar) { Short storedScore = (Short) record.getTransientAttribute(Attr.DuplicateScore); if (storedScore == null) { short score = 0; switch (scoringStrategy) { case SUM_OF_BASE_QUALITIES: score += getSumOfBaseQualities(record); break; case TOTAL_MAPPED_REFERENCE_LENGTH: if (!record.getReadUnmappedFlag()) { score += record.getCigar().getReferenceLength(); } if (assumeMateCigar && record.getReadPairedFlag() && !record.getMateUnmappedFlag()) { score += SAMUtils.getMateCigar(record).getReferenceLength(); } break; case RANDOM: <START> score += (short) Math.sqrt(record.getReadName().hashCode()); <END> } storedScore = score; record.setTransientAttribute(Attr.DuplicateScore, storedScore); } return storedScore; }</code><technical_language>murmur3 hash in htsjdk, agreed for other parts of code is default String.hashCode implementation, murmur3 instead</technical_language>

Target:
public static short computeDuplicateScore(final SAMRecord record, final ScoringStrategy scoringStrategy, final boolean assumeMateCigar) { Short storedScore = (Short) record.getTransientAttribute(Attr.DuplicateScore); if (storedScore == null) { short score = 0; switch (scoringStrategy) { case SUM_OF_BASE_QUALITIES: score += getSumOfBaseQualities(record); break; case TOTAL_MAPPED_REFERENCE_LENGTH: if (!record.getReadUnmappedFlag()) { score += record.getCigar().getReferenceLength(); } if (assumeMateCigar && record.getReadPairedFlag() && !record.getMateUnmappedFlag()) { score += SAMUtils.getMateCigar(record).getReferenceLength(); } break; case RANDOM: score += (short) (hasher.hashUnencodedChars(record.getReadName()) >> 16); } storedScore = score; record.setTransientAttribute(Attr.DuplicateScore, storedScore); } return storedScore; }
Source:
<code>public void start() throws Exception { if (transport == null) <START> throw new IllegalStateException("CacheViewManager only works in clustered cachesb"); <END> self = transport.getAddress(); running = true; ThreadFactory tfViewInstaller = new ThreadFactory() { private volatile AtomicInteger count = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "CacheViewInstaller-" + count.incrementAndGet() + "," + self); } }; cacheViewInstallerExecutor = Executors.newCachedThreadPool(tfViewInstaller); viewTriggerThread = new ViewTriggerThread(); cacheManagerNotifier.addListener(listener); handleNewView(transport.getMembers(), false, true); }</code><technical_language>a "cachesb" ? ;)</technical_language>

Target:
public void start() throws Exception { if (transport == null) throw new ConfigurationException("CacheViewManager only works in clustered caches"); self = transport.getAddress(); running = true; ThreadFactory tfViewInstaller = new ThreadFactory() { private volatile AtomicInteger count = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "CacheViewInstaller-" + count.incrementAndGet() + "," + self); } }; cacheViewInstallerExecutor = Executors.newCachedThreadPool(tfViewInstaller); viewTriggerThread = new ViewTriggerThread(); cacheManagerNotifier.addListener(listener); handleNewView(transport.getMembers(), false, true); }
Source:
<code><START> private String extractImageId(ServerInfo serverInfo) { <END> String imageId = serverInfo.getMeta().get("image_id"); if (imageId == null) { ServerDrive serverBootDrive = null; for (ServerDrive serverDrive : serverInfo.getDrives()) { if (serverDrive.getBootOrder() > 0 && (serverBootDrive == null || serverDrive.getBootOrder() < serverBootDrive.getBootOrder())) { serverBootDrive = serverDrive; } } if (serverBootDrive != null) { imageId = serverBootDrive.getDriveUuid(); } } return imageId; }</code><technical_language>[minor] static</technical_language>

Target:
private static String extractImageId(ServerInfo serverInfo) { String imageId = serverInfo.getMeta().get("image_id"); if (imageId == null) { ServerDrive serverBootDrive = null; for (ServerDrive serverDrive : serverInfo.getDrives()) { if (serverDrive.getBootOrder() != null && (serverBootDrive == null || serverDrive.getBootOrder() < serverBootDrive.getBootOrder())) { serverBootDrive = serverDrive; } } if (serverBootDrive != null) { imageId = serverBootDrive.getDriveUuid(); } } return imageId; }
Source:
<code>private double getConsumerMetricValue(Consumer<?, ?> consumer, String clientId, String metricName) { Map<String, String> tags = new HashMap<>(2); tags.put("client-id", clientId); MetricName name = new MetricName(metricName, "lnkd", "", tags); <START> return Optional.ofNullable(consumer).map(c -> c.metrics().get(name)).map(Metric::value).orElse(0.0); <END> }</code><technical_language>I consumer null guard prior calling getConsumerMetricValue(). suppliers/lambdas bound consumer param</technical_language>

Target:
private double getConsumerMetricValue(Consumer<?, ?> consumer, String clientId, String metricName) { Map<String, String> tags = new HashMap<>(2); tags.put("client-id", clientId); MetricName name = new MetricName(metricName, "lnkd", "", tags); Metric metric = consumer.metrics().get(name); return (metric != null && metric.metricValue() instanceof Double) ? (Double) metric.metricValue() : 0.0; }
Source:
<code>private static void executeDeleteQueryWithLikeOperator(Connection conn, String query, int tenantId) throws Exception { PreparedStatement ps = null; <START> try { <END> ps = conn.prepareStatement(query); String param = "%/" + String.valueOf(tenantId) + "/%"; ps.setNString(1, param); ps.executeUpdate(); } catch (SQLException e) { String errMsg = "Error executing query " + query + " for tenant: " + tenantId; log.error(errMsg, e); throw new Exception(errMsg, e); } finally { if (ps != null) { ps.close(); } } }</code><technical_language>try resource</technical_language>

Target:
private static void executeDeleteQueryWithLikeOperator(Connection conn, String query, int tenantId) throws SQLException { try (PreparedStatement ps = conn.prepareStatement(query)) { String param = "%/cloud-services/" + String.valueOf(tenantId) + "/%"; ps.setNString(1, param); ps.executeUpdate(); if (log.isDebugEnabled()) { log.debug("Deletion query : " + query + "executed for tenant :" + tenantId); } } catch (SQLException e) { String errMsg = "Error executing query " + query + " for tenant: " + tenantId; throw new SQLException(errMsg, e); } }
Source:
<code>public ImmutableMap<String, Long> collectWrongEpochs() { Map<String, Long> wrongEpochs = new HashMap<>(); clusterState.forEach((server, state) -> { try { <START> state.get(timeout, TimeUnit.MILLISECONDS); <END> } catch (Exception e) { if (e.getCause() instanceof WrongEpochException) { wrongEpochs.put(server, ((WrongEpochException) e.getCause()).getCorrectEpoch()); } } }); return ImmutableMap.copyOf(wrongEpochs); }</code><technical_language>Please remove this duplicate code aggregate lists in a single place. difficult understand code. scenario: RPC timeout of 5 seconds. In this code, method timeout differently: First, collect node states timeout in 2 seconds. collect wrong epoch exceptions future completed returned a wrongEpochException</technical_language>

Target:
public ImmutableMap<String, Long> collectWrongEpochs() { Map<String, Long> wrongEpochs = new HashMap<>(); clusterState.forEach((server, state) -> { try { state.get(); } catch (Exception e) { if (e.getCause() instanceof WrongEpochException) { wrongEpochs.put(server, ((WrongEpochException) e.getCause()).getCorrectEpoch()); } } }); return ImmutableMap.copyOf(wrongEpochs); }