auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void toJSON(OutputWriter jsonOutputWriter, GoDashboardPipeline model, Username username) { String usernameString = username.getUsername().toString(); jsonOutputWriter .addLinks(linksWriter -> addLinks(linksWriter, model)) .add("name", model.name().toString()) .add("last_updated_timestamp", model.getLastUpdatedTimeStamp()) .add("locked", model.model().getLatestPipelineInstance().isCurrentlyLocked()) <START> .addChild("pause_info", getPauseInfoNEW(model)) <END> .add("can_operate", model.isPipelineOperator(usernameString)) .add("can_administer", model.canBeAdministeredBy(usernameString)) .add("can_unlock", model.canBeOperatedBy(usernameString)) .add("can_pause", model.canBeOperatedBy(usernameString)) .addChild("origin", getOrigin(model.getOrigin())); if (model.getTrackingTool().isPresent()) { TrackingTool trackingTool = model.getTrackingTool().get(); jsonOutputWriter.addChild("tracking_tool", childWriter -> { childWriter .add("regex", trackingTool.getRegex()) .add("link", trackingTool.getLink()); }); } jsonOutputWriter.addChild("_embedded", childWriter -> { childWriter.addChildList("instances", writeInstances(model)); }); }</code><technical_language>Rename method getPauseInfo</technical_language>

Target:
public static void toJSON(OutputWriter jsonOutputWriter, GoDashboardPipeline model, Username username) { String usernameString = username.getUsername().toString(); jsonOutputWriter .addLinks(linksWriter -> addLinks(linksWriter, model)) .add("name", model.name().toString()) .add("last_updated_timestamp", model.getLastUpdatedTimeStamp()) .add("locked", model.model().getLatestPipelineInstance().isCurrentlyLocked()) .addChild("pause_info", getPauseInfoNEW(model)) .add("can_operate", model.isPipelineOperator(usernameString)) .add("can_administer", model.canBeAdministeredBy(usernameString)) .add("can_unlock", model.canBeOperatedBy(usernameString)) .add("can_pause", model.canBeOperatedBy(usernameString)) .add("from_config_repo", !model.getOrigin().isLocal()); if (model.getTrackingTool().isPresent()) { TrackingTool trackingTool = model.getTrackingTool().get(); jsonOutputWriter.addChild("tracking_tool", childWriter -> { childWriter .add("regex", trackingTool.getRegex()) .add("link", trackingTool.getLink()); }); } jsonOutputWriter.addChild("_embedded", childWriter -> { childWriter.addChildList("instances", writeInstances(model)); }); }
Source:
<code>public void doGet(HttpServletRequest request,HttpServletResponse response){ M_log.debug("doGet: Called"); try { <START> if(request.getServletPath().equals("/manager")){ <END> canvasRestApiCall(request, response); } else{ M_log.info("NOT MANAGER"); doRequest(request, response); } }catch(Exception e) { M_log.error("GET request has some exceptions",e); } }</code><technical_language>"/manager" a constant</technical_language>

Target:
public void doGet(HttpServletRequest request,HttpServletResponse response){ M_log.debug("doGet: Called"); try { if(request.getServletPath().equals(MANAGER_SERVLET_NAME)){ canvasRestApiCall(request, response); } else{ M_log.info("NOT MANAGER"); doRequest(request, response); } }catch(Exception e) { M_log.error("GET request has some exceptions",e); } }
Source:
<code>private static File generateDefaultConfigFile(String workingDir) { checkArgument(workingDir != null, "working directory should not be null."); final File jaasConfFile; try { Path path = Paths.get(workingDir); if (Files.notExists(Paths.get(workingDir))) { <START> Path parent = path.getParent().toRealPath(); Path resolvedPath = Paths.get(parent.toString(), path.getFileName().toString()); path = Files.createDirectories(resolvedPath); <END> } Path jaasConfPath = Files.createTempFile(path, "jaas-", ".conf"); try (InputStream resourceStream = JaasModule.class.getClassLoader().getResourceAsStream(JAAS_CONF_RESOURCE_NAME)) { Files.copy(resourceStream, jaasConfPath, StandardCopyOption.REPLACE_EXISTING); } jaasConfFile = new File(workingDir, jaasConfPath.getFileName().toString()); jaasConfFile.deleteOnExit(); } catch (IOException e) { throw new RuntimeException("unable to generate a JAAS configuration file", e); } return jaasConfFile; }</code><technical_language>This logic tested a symbolic link</technical_language>

Target:
private static File generateDefaultConfigFile(String workingDir) { checkArgument(workingDir != null, "working directory should not be null."); final File jaasConfFile; try { Path path = Paths.get(workingDir); if (Files.notExists(path)) { Path parent = path.getParent().toRealPath(); Path resolvedPath = Paths.get(parent.toString(), path.getFileName().toString()); path = Files.createDirectories(resolvedPath); } Path jaasConfPath = Files.createTempFile(path, "jaas-", ".conf"); try (InputStream resourceStream = JaasModule.class.getClassLoader().getResourceAsStream(JAAS_CONF_RESOURCE_NAME)) { Files.copy(resourceStream, jaasConfPath, StandardCopyOption.REPLACE_EXISTING); } jaasConfFile = new File(workingDir, jaasConfPath.getFileName().toString()); jaasConfFile.deleteOnExit(); } catch (IOException e) { throw new RuntimeException("unable to generate a JAAS configuration file", e); } return jaasConfFile; }
Source:
<code>private List<Map<String, Object>> dedupeAndMergeLocations(Content episode, List<Map<String, Object>> existingLocations) { ImmutableSet<Location> locations = episode.getManifestedAs().stream() .filter(encoding -> encoding != null) .flatMap(encoding -> encoding.getAvailableAt().stream()) .filter(location -> location != null) .filter(location -> location.getPolicy() != null) .collect(MoreCollectors.toImmutableSet()); List<Map<String, Object>> nonNullExistingLocations = existingLocations != null ? existingLocations : ImmutableList.of(); Predicate<Policy> filter = createLocationNotPresentFilter( fromEsLocations(nonNullExistingLocations) ); <START> ImmutableList<Map<String, Object>> newLocations = locations.stream() <END> .filter(location -> filter.apply(location.getPolicy())) .map(location -> newLocationPolicyToMap(location.getPolicy())) .collect(MoreCollectors.toImmutableList()); return ImmutableList.<Map<String, Object>>builder() .addAll(nonNullExistingLocations) .addAll(newLocations) .build(); }</code><technical_language>I a bit confused fix. This commit message is describing</technical_language>

Target:
private List<Map<String, Object>> dedupeAndMergeLocations(Content episode, List<Map<String, Object>> existingLocations) { ImmutableSet<Location> locations = episode.getManifestedAs().stream() .filter(encoding -> encoding != null) .flatMap(encoding -> encoding.getAvailableAt().stream()) .filter(location -> location != null) .filter(location -> location.getPolicy() != null) .collect(MoreCollectors.toImmutableSet()); List<Map<String, Object>> nonNullExistingLocations = existingLocations != null ? existingLocations : ImmutableList.of(); Predicate<Policy> filter = createLocationNotPresentFilter( fromEsLocations(nonNullExistingLocations) ); ImmutableList<Map<String, Object>> newLocations = locations.stream() .filter(location -> filter.apply(location.getPolicy())) .map(EsLocation::toMap) .collect(MoreCollectors.toImmutableList()); return ImmutableList.<Map<String, Object>>builder() .addAll(nonNullExistingLocations) .addAll(newLocations) .build(); }
Source:
<code>public static AccrualOnDefaultFormula of(String uniqueName) { ArgChecker.notNull(uniqueName, "uniqueName"); <START> return valueOf(uniqueName.replace('-', '_').toUpperCase(Locale.ENGLISH)); <END> }</code><technical_language>Code String str = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, uniqueName); if (str.endsWith("I_S_D_A")) { str = "ORIGINAL_ISDA"; } return valueOf(str)</technical_language>

Target:
public static AccrualOnDefaultFormula of(String uniqueName) { ArgChecker.notNull(uniqueName, "uniqueName"); String str = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, uniqueName); if (str.endsWith("I_S_D_A")) { str = "ORIGINAL_ISDA"; } return valueOf(str); }
Source:
<code>public static String getFirstReachableAddress(ComputeServiceContext context, NodeMetadata node) { SshClient client; try { client = context.utils().sshForNode().apply(node); } catch (Exception e) { <START> throw new IllegalStateException("Unable to connect SshClient to "+node+"; check that the node is accessible and that the SSH key exists and is correctly configured, including any passphrase defined", e); <END> } return client.getHostAddress(); }</code><technical_language>This swallow interrupts etc? Exceptions.propagateIfFatal() first</technical_language>

Target:
public static String getFirstReachableAddress(ComputeServiceContext context, NodeMetadata node) { SshClient client; try { client = context.utils().sshForNode().apply(node); } catch (Exception e) { Exceptions.propagateIfFatal(e); throw new IllegalStateException("Unable to connect SshClient to "+node+"; check that the node is accessible and that the SSH key exists and is correctly configured, including any passphrase defined", e); } return client.getHostAddress(); }
Source:
<code>protected void assertNoRetryContextAfterScopeExecutions(int expectedExecutions) throws MuleException { final CoreEvent testEvent = eventBuilder(muleContext).message(of("queso")).build(); try { untilSuccessful.process(testEvent); <START> fail(); <END> } catch (Exception e) { MessagingException messagingException = (MessagingException) e; Map<String, Object> retryCtxContainer = ((InternalEvent) messagingException.getEvent()).getInternalParameter(RETRY_CTX_INTERNAL_PARAMETER_KEY); assertThat(retryCtxContainer.isEmpty(), is(true)); assertThat(targetMessageProcessor.eventCount, is(expectedExecutions)); } }</code><technical_language>add a message failure</technical_language>

Target:
protected void assertNoRetryContextAfterScopeExecutions(int expectedExecutions) throws MuleException { final CoreEvent testEvent = eventBuilder(muleContext).message(of("queso")).build(); try { untilSuccessful.process(testEvent); fail("An exhaustion error was expected from an until successful scope"); } catch (Exception e) { MessagingException messagingException = (MessagingException) e; Map<String, Object> retryCtxContainer = ((InternalEvent) messagingException.getEvent()).getInternalParameter(RETRY_CTX_INTERNAL_PARAMETER_KEY); assertThat(retryCtxContainer.isEmpty(), is(true)); assertThat(targetMessageProcessor.eventCount, is(expectedExecutions)); } }
Source:
<code>public void showAllImages(boolean enabled) { if(!enabled) { this.viewer.addFilter(hideDanglingImagesFilter); this.viewer.addFilter(hideIntermediateImagesFilter); <START> this.form.setText(DVMessages.getFormattedString( <END> connection.getName(), Integer.toString(connection.getContainers().size()))); } else { this.viewer.removeFilter(hideDanglingImagesFilter); this.viewer.removeFilter(hideIntermediateImagesFilter); this.form.setText(DVMessages.getFormattedString( connection.getName(), Integer.toString(connection.getContainers().size()))); } refreshViewTitle(); }</code><technical_language>this work. a message id</technical_language>

Target:
public void showAllImages(boolean enabled) { if(!enabled) { this.viewer.addFilter(hideDanglingImagesFilter); this.viewer.addFilter(hideIntermediateImagesFilter); } else { final List<ViewerFilter> filters = new ArrayList<>( Arrays.asList(this.viewer.getFilters())); for (Iterator<ViewerFilter> iterator = filters.iterator(); iterator .hasNext();) { ViewerFilter viewerFilter = iterator.next(); if (viewerFilter.equals(hideDanglingImagesFilter) || viewerFilter.equals(hideIntermediateImagesFilter)) { iterator.remove(); } } this.viewer.setFilters(filters.toArray(new ViewerFilter[0])); } refreshViewTitle(); }
Source:
<code>public static ResultHolder[] applyConstraintsToSpecifics(HaxeMethodModel model, ResultHolder[] specifics) { if (nonNull(model.getGenericParams())) { <START> List<HaxeGenericParamModel> genericParams = model.getGenericParams(); <END> if (genericParams != null) { Map<String, ResultHolder> nameAndConstraints = getGenericTypeParametersByName(genericParams); for (int i = 0; i < specifics.length; i++) { String name = specifics[i].getClassType().getClassName(); boolean nameFound = genericParams.stream().anyMatch(m -> m.getName().equals(name)); if (nameFound) { if (nameAndConstraints.containsKey(name)) { specifics[i] = nameAndConstraints.get(name); if (specifics[i].getClassType().isEnumValueClass()) { ResultHolder dynamicType = SpecificTypeReference.getDynamic(model.getMethodPsi()).createHolder(); specifics[i] = wrapType(dynamicType, specifics[i].getElementContext(), true).createHolder(); } continue; } specifics[i] = SpecificTypeReference.getDynamic(model.getMethodPsi()).createHolder(); } } } } return specifics; }</code><technical_language>Again: Capture, test. getGenericParams is expensive</technical_language>

Target:
public static ResultHolder[] applyConstraintsToSpecifics(HaxeMethodModel model, ResultHolder[] specifics) { List<HaxeGenericParamModel> genericParams = model.getGenericParams(); if (nonNull(genericParams)) { Map<String, ResultHolder> nameAndConstraints = getGenericTypeParametersByName(genericParams); for (int i = 0; i < specifics.length; i++) { String name = specifics[i].getClassType().getClassName(); boolean nameFound = genericParams.stream().anyMatch(m -> m.getName().equals(name)); if (nameFound) { if (nameAndConstraints.containsKey(name)) { specifics[i] = nameAndConstraints.get(name); if (specifics[i].getClassType().isEnumValueClass()) { ResultHolder dynamicType = SpecificTypeReference.getDynamic(model.getMethodPsi()).createHolder(); specifics[i] = wrapType(dynamicType, specifics[i].getElementContext(), true).createHolder(); } continue; } specifics[i] = SpecificTypeReference.getDynamic(model.getMethodPsi()).createHolder(); } } } return specifics; }
Source:
<code>public void startExport(Process process) throws DAOException, DataException, IOException { boolean exported = process.isExported(); process.setExported(true); ServiceManager.getProcessService().save(process); boolean exportSucessfull = startExport(process, (URI) null); if (exportSucessfull) { if (Objects.nonNull(process.getParent())) { startExport(process.getParent()); } } else { process.setExported(exported); } <START> ServiceManager.getProcessService().save(process); <END> }</code><technical_language>Is a reason save process, process flagis changed again? I this save is neccessary export failed exportflag changed back. is neccessary if flag changed. This counts for save. if process is exported, save is needed</technical_language>

Target:
public void startExport(Process process) throws DataException { boolean wasNotAlreadyExported = !process.isExported(); if (wasNotAlreadyExported) { process.setExported(true); ServiceManager.getProcessService().save(process); } boolean exportSucessfull = startExport(process, (URI) null); if (exportSucessfull) { if (Objects.nonNull(process.getParent())) { startExport(process.getParent()); } } else if (wasNotAlreadyExported) { process.setExported(false); ServiceManager.getProcessService().save(process); } }
Source:
<code>public boolean isPublished() { Instant now = Instant.now(); Instant publishTime = this.resultsVisibleFromTime; if (publishTime.equals(Const.TIME_REPRESENTS_FOLLOW_VISIBLE)) { return isVisible(); } else if (publishTime.equals(Const.TIME_REPRESENTS_LATER)) { return false; } else if (publishTime.equals(Const.TIME_REPRESENTS_NEVER)) { return false; } else if (publishTime.equals(Const.TIME_REPRESENTS_NOW)) { return true; } else { <START> return now.isAfter(publishTime) || now.equals(publishTime); <END> } }</code><technical_language>early returns instead for if/elses</technical_language>

Target:
public boolean isPublished() { Instant publishTime = this.resultsVisibleFromTime; if (publishTime.equals(Const.TIME_REPRESENTS_FOLLOW_VISIBLE)) { return isVisible(); } if (publishTime.equals(Const.TIME_REPRESENTS_LATER) || publishTime.equals(Const.TIME_REPRESENTS_NEVER)) { return false; } if (publishTime.equals(Const.TIME_REPRESENTS_NOW)) { return true; } Instant now = Instant.now(); return now.isAfter(publishTime) || now.equals(publishTime); }
Source:
<code>private List<Long> collectResumingTasksForResumeFailedMode(long attemptId) { List<ArchivedTask> tasks = sm .getSessionStore(getSiteId()) .getTasksOfAttempt(attemptId); List<Long> groupRetryErrorTaskIds = tasks.stream() .filter(task -> task.getState() == TaskStateCode.GROUP_ERROR && task.getStateParams().has("retry_count")) .map(task -> task.getId()) .collect(Collectors.toList()); List<Long> successTasks = tasks.stream() <START> .filter(task -> !groupRetryErrorTaskIds.contains(task.getParentId().orNull())) <END> .filter(task -> !task.getFullName().contains("^sub")) .filter(task -> task.getState() == TaskStateCode.SUCCESS) .map(task -> { if (!task.getParentId().isPresent()) { throw new IllegalArgumentException("Resuming successfully completed attempts is not supported"); } return task.getId(); }) .collect(Collectors.toList()); return ImmutableList.copyOf(successTasks); }</code><technical_language>in case, want add task parent in successTasks, right</technical_language>

Target:
private List<Long> collectResumingTasksForResumeFailedMode(long attemptId) { List<ArchivedTask> tasks = sm .getSessionStore(getSiteId()) .getTasksOfAttempt(attemptId); List<Long> groupRetryErrorTaskIds = tasks.stream() .filter(task -> task.getState() == TaskStateCode.GROUP_ERROR && task.getStateParams().has("retry_count")) .map(task -> task.getId()) .collect(Collectors.toList()); List<Long> successTasks = tasks.stream() .filter(task -> !task.getFullName().contains("^sub")) .filter(task -> task.getState() == TaskStateCode.SUCCESS) .filter(task -> { if (!task.getParentId().isPresent()) { throw new IllegalArgumentException("Resuming successfully completed attempts is not supported"); } return !groupRetryErrorTaskIds.contains(task.getParentId().get()); }) .map(StoredTask::getId) .collect(Collectors.toList()); return ImmutableList.copyOf(successTasks); }
Source:
<code>private void setTimeInterval(Criteria c, Calendar fromTime, Calendar toTime) { Calendar from = fromTime; if (from == null) { from = Calendar.getInstance(); from.setTimeInMillis(0); } Calendar to = toTime; if (to == null) { to = Calendar.getInstance(); <START> to.setTimeInMillis(System.currentTimeMillis()); <END> } if (to.after(from)) { c.add(Restrictions.between(TIME_FIELD_NAME, from, to)); } }</code><technical_language>Calendar.getInstace returns instance set "now", this call is useless (and in other places call setTimeInMillis(System.currentTimeMillis()))</technical_language>

Target:
private void setTimeInterval(Criteria c, Calendar fromTime, Calendar toTime) { if (fromTime != null && toTime != null) { c.add(Restrictions.between(TIME_FIELD_NAME, fromTime, toTime)); } else if (fromTime != null) { c.add(Restrictions.ge(TIME_FIELD_NAME, fromTime)); } else if (toTime != null) { c.add(Restrictions.le(TIME_FIELD_NAME, toTime)); } }
Source:
<code>private static boolean isSTDistance(RowExpression expression, FunctionManager functionManager) { <START> if (expression instanceof CallExpression) { <END> return functionManager.getFunctionMetadata(((CallExpression) expression).getFunctionHandle()).getName().equals(ST_DISTANCE); } return false; }</code><technical_language>return (expression instanceof CallExpression) && functionManager.getFunctionMetadata(..</technical_language>

Target:
private static boolean isSTDistance(RowExpression expression, FunctionManager functionManager) { return expression instanceof CallExpression && functionManager.getFunctionMetadata(((CallExpression) expression).getFunctionHandle()).getName().equals(ST_DISTANCE); }
Source:
<code>public List searchContentlets(String[] structureInodes, List<String> fields, List<String> categories, boolean showDeleted, boolean filterSystemHost, boolean filterUnpublish, boolean filterLocked, int page, int perPage,String orderBy, String modDateFrom, String modDateTo) throws DotStateException, DotDataException, DotSecurityException { <START> String structureInodesJoined = String.join(",", structureInodes); <END> return searchContentlets(structureInodesJoined, fields, categories, showDeleted, filterSystemHost, filterUnpublish, filterLocked, page, perPage, orderBy, modDateFrom, modDateTo); }</code><technical_language>replace StringUtils.COMMA</technical_language>

Target:
public List searchContentlets(String[] structureInodes, List<String> fields, List<String> categories, boolean showDeleted, boolean filterSystemHost, boolean filterUnpublish, boolean filterLocked, int page, int perPage,String orderBy, String modDateFrom, String modDateTo) throws DotStateException, DotDataException, DotSecurityException { String structureInodesJoined = String.join(CONTENT_TYPES_INODE_SEPARATOR, structureInodes); return searchContentlets(structureInodesJoined, fields, categories, showDeleted, filterSystemHost, filterUnpublish, filterLocked, page, perPage, orderBy, modDateFrom, modDateTo); }
Source:
<code>private void saveVmDevicesToDb() { <START> updateAllInTransaction(vmDeviceToSave.values(), getDbFacade().getVmDeviceDAO()); <END> if (!removedDeviceIds.isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() { @Override public Void runInTransaction() { getDbFacade().getVmDeviceDAO().removeAll(removedDeviceIds); return null; } }); } if (!newVmDevices.isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() { @Override public Void runInTransaction() { getDbFacade().getVmDeviceDAO().saveAll(newVmDevices); return null; } }); } }</code><technical_language>problem os sort is solved here, vmDeviceToSave.values() - order is unpredictable, sort device here</technical_language>

Target:
private void saveVmDevicesToDb() { List<VmDevice> list = new ArrayList<VmDevice>(vmDeviceToSave.values()); Collections.sort(list); updateAllInTransaction("UpdateVmDeviceRuntimeInfo", list, getDbFacade().getVmDeviceDAO()); if (!removedDeviceIds.isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() { @Override public Void runInTransaction() { getDbFacade().getVmDeviceDAO().removeAll(removedDeviceIds); return null; } }); } if (!newVmDevices.isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() { @Override public Void runInTransaction() { getDbFacade().getVmDeviceDAO().saveAll(newVmDevices); return null; } }); } }
Source:
<code>public void allFieldsOfVariantShouldBeConverted(){ String chromosome = "12"; int start = 3; int end = 4; String reference = "A"; String alternate = "T"; Variant variant = buildVariant(chromosome, start, end, reference, alternate, fileId, studyId); variantToMongoDbObjectConverter = new VariantToMongoDbObjectConverter(false, false, true, <START> includeSrc); <END> conversionService.addConverter(variantToMongoDbObjectConverter); DBObject dbObject = conversionService.convert(variant, DBObject.class); assertNotNull(dbObject); BasicDBObject addToSet = (BasicDBObject) dbObject.get("$addToSet"); BasicDBObject files = (BasicDBObject) addToSet.get("files"); assertTrue(fileId.equals(files.get("fid"))); assertTrue(studyId.equals(files.get("sid"))); BasicDBObject setOnInsert = (BasicDBObject) dbObject.get("$setOnInsert"); assertTrue(String.format("%s_%s_%s_%s", chromosome, start, reference, alternate).equals(setOnInsert.get("_id"))); assertTrue(chromosome.equals(setOnInsert.get("chr"))); assertEquals(start, setOnInsert.get("start")); assertEquals(end, setOnInsert.get("end")); assertTrue(reference.equals(setOnInsert.get("ref"))); assertTrue(alternate.equals(setOnInsert.get("alt"))); }</code><technical_language>I this fit in 120 characters (same for lines 89-90)</technical_language>

Target:
public void allFieldsOfVariantShouldBeConverted() { String chromosome = "12"; int start = 3; int end = 4; String reference = "A"; String alternate = "T"; Variant variant = buildVariant(chromosome, start, end, reference, alternate, fileId, studyId); variantToMongoDbObjectConverter = new VariantToMongoDbObjectConverter(false, false, true, includeSrc); conversionService.addConverter(variantToMongoDbObjectConverter); DBObject dbObject = conversionService.convert(variant, DBObject.class); assertNotNull(dbObject); BasicDBObject addToSet = (BasicDBObject) dbObject.get("$addToSet"); BasicDBObject files = (BasicDBObject) addToSet.get("files"); assertEquals(fileId, files.get("fid")); assertEquals(studyId, files.get("sid")); BasicDBObject setOnInsert = (BasicDBObject) dbObject.get("$setOnInsert"); assertEquals(String.format("%s_%s_%s_%s", chromosome, start, reference, alternate), setOnInsert.get("_id")); assertEquals(chromosome, setOnInsert.get("chr")); assertEquals(start, setOnInsert.get("start")); assertEquals(end, setOnInsert.get("end")); assertEquals(reference, setOnInsert.get("ref")); assertEquals(alternate, setOnInsert.get("alt")); }
Source:
<code>public static Properties getDatasourceProperties() { String propertiesNotFoundMessage = "Unable to load datasource properties [" + DATASOURCE_PROPERTIES + "]"; boolean propertiesNotFound = false; System.setProperty("h2.lobInDatabase", "true"); InputStream propsInputStream = PersistenceUtil.class.getResourceAsStream(DATASOURCE_PROPERTIES); <START> assert propsInputStream != null : propertiesNotFoundMessage; <END> Properties props = new Properties(); if (propsInputStream != null) { try { props.load(propsInputStream); } catch (IOException ioe) { propertiesNotFound = true; logger.warn("Unable to find properties, using default H2 properties: " + ioe.getMessage()); ioe.printStackTrace(); } } else { propertiesNotFound = true; } String password = props.getProperty("password"); if ("${maven.jdbc.password}".equals(password) || propertiesNotFound) { props = getDefaultProperties(); } return props; }</code><technical_language>Please change like: if (propsInputStream == null) { throw new IllegalStateException(propertiesNotFoundMessage); } remove completely please. problem is java asserts need enabled a command line argument, active default</technical_language>

Target:
public static Properties getDatasourceProperties() { String propertiesNotFoundMessage = "Unable to load datasource properties [" + DATASOURCE_PROPERTIES + "]"; boolean propertiesNotFound = false; System.setProperty("h2.lobInDatabase", "true"); InputStream propsInputStream = PersistenceUtil.class.getResourceAsStream(DATASOURCE_PROPERTIES); if (propsInputStream == null) { throw new IllegalStateException(propertiesNotFoundMessage); } Properties props = new Properties(); try { props.load(propsInputStream); } catch (IOException ioe) { propertiesNotFound = true; logger.warn("Unable to find properties, using default H2 properties: " + ioe.getMessage()); ioe.printStackTrace(); } String password = props.getProperty("password"); if ("${maven.jdbc.password}".equals(password) || propertiesNotFound) { props = getDefaultProperties(); } return props; }
Source:
<code>public synchronized void setInstanceStatus(InstanceStatus status) { InstanceStatus prev = instanceInfo.setStatus(status); if (prev != null) { for (StatusChangeListener listener : listeners.values()) { <START> listener.notify(new StatusChangeEvent(prev, status)); <END> } } }</code><technical_language>Handle errors listener invocation</technical_language>

Target:
public synchronized void setInstanceStatus(InstanceStatus status) { InstanceStatus prev = instanceInfo.setStatus(status); if (prev != null) { for (StatusChangeListener listener : listeners.values()) { try { listener.notify(new StatusChangeEvent(prev, status)); } catch (Exception e) { logger.warn("failed to notify listener: {}", listener.getId(), e); } } } }
Source:
<code>protected Image addParents(Image image) { image.setStorageDomain(new StorageDomain()); <START> image.getStorageDomain().setId(storageDomainId.toString()); <END> return image; }</code><technical_language>create domain first, set params, apply image, nitpicking ;-)</technical_language>

Target:
protected Image addParents(Image image) { StorageDomain sd = new StorageDomain(); sd.setId(storageDomainId.toString()); image.setStorageDomain(sd); return super.addParents(image); }
Source:
<code>public void activateHoverHelp(final Control control) { control.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseHover(MouseEvent event) { if ((event.stateMask & SWT.BUTTON_MASK) != 0) { return; } Point pt = new Point(event.x, event.y); Control timeGraphControl = (Control) event.widget; Point ptInDisplay = control.toDisplay(event.x, event.y); fInitialDeadzone = new Rectangle(ptInDisplay.x - MOUSE_DEADZONE, ptInDisplay.y - MOUSE_DEADZONE, 2 * MOUSE_DEADZONE, 2 * MOUSE_DEADZONE); createTooltipShell(timeGraphControl.getShell()); for (Control child : fTipComposite.getChildren()) { child.dispose(); } fill(control, event, pt); if (fTipComposite.getChildren().length == 0) { return; } fTipShell.pack(); Point tipPosition = control.toDisplay(pt); setHoverLocation(fTipShell, tipPosition); fTipShell.setVisible(true); Display display = Display.getDefault(); display.addFilter(SWT.MouseMove, fListener); <START> display.addFilter(SWT.FocusOut, fListener); <END> } }); }</code><technical_language>If Eclipse application focus, get a tool tip hovering time graph. clicking tool tip shell, Eclipse gain focus, while tool tip focus OS point of view, Eclipse point of view. clicking another application, is SWT.FocusOut event in Eclipse, tool tip shell remains top. solution give focus tool tip is created (or is entered?) I if this disrupt user... keyboard shortcuts time graph longer work). I suggest is dispose MouseExit. need happen soon exit shell bounds offset (in case MouseExit of Eclipse application. FocusOut MouseExit if Alt-Tab another application</technical_language>

Target:
public void activateHoverHelp(final Control control) { control.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseHover(MouseEvent event) { if ((event.stateMask & SWT.BUTTON_MASK) != 0) { return; } Point pt = new Point(event.x, event.y); Control timeGraphControl = (Control) event.widget; Point ptInDisplay = control.toDisplay(event.x, event.y); fInitialDeadzone = new Rectangle(ptInDisplay.x - MOUSE_DEADZONE, ptInDisplay.y - MOUSE_DEADZONE, 2 * MOUSE_DEADZONE, 2 * MOUSE_DEADZONE); createTooltipShell(timeGraphControl.getShell()); for (Control child : fTipComposite.getChildren()) { child.dispose(); } fill(control, event, pt); if (fTipComposite.getChildren().length == 0) { return; } fTipShell.pack(); Point tipPosition = control.toDisplay(pt); setHoverLocation(fTipShell, tipPosition); fTipShell.setVisible(true); Display display = Display.getDefault(); display.addFilter(SWT.MouseMove, fListener); display.addFilter(SWT.FocusOut, fFocusLostListener); } }); }
Source:
<code>private void asyncInstall(License newLicense, UpdateCenter updateCenter) { try { Set<String> editionPluginKeys = newLicense.getPluginKeys(); Map<String, PluginInfo> pluginInfosByKeys = pluginRepository.getPluginInfosByKeys(); Set<String> pluginsToRemove = pluginsToRemove(editionPluginKeys, pluginInfosByKeys.values()); Set<String> pluginsToInstall = pluginsToInstall(editionPluginKeys, pluginInfosByKeys.keySet()); editionPluginDownloader.downloadEditionPlugins(pluginsToInstall, updateCenter); uninstallPlugins(pluginsToRemove); editionManagementState.automaticInstallReady(); } catch (Throwable t) { LOG.error("Failed to install edition with plugins {}", newLicense.getEditionKey(), newLicense.getPluginKeys(), t); editionManagementState.installFailed(t.getMessage()); <START> } finally { <END> semaphore.release(); } }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Catch Exception instead of Throwable. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
private void asyncInstall(License newLicense, UpdateCenter updateCenter) { try { Set<String> editionPluginKeys = newLicense.getPluginKeys(); Map<String, PluginInfo> pluginInfosByKeys = pluginRepository.getPluginInfosByKeys(); Set<String> pluginsToRemove = pluginsToRemove(editionPluginKeys, pluginInfosByKeys.values()); Set<String> pluginsToInstall = pluginsToInstall(editionPluginKeys, pluginInfosByKeys.keySet()); LOG.info("Installing edition '{}', download: {}, remove: {}", newLicense.getEditionKey(), pluginsToInstall, pluginsToRemove); editionPluginDownloader.downloadEditionPlugins(pluginsToInstall, updateCenter); uninstallPlugins(pluginsToRemove); editionManagementState.automaticInstallReady(); } catch (Throwable t) { LOG.error("Failed to install edition with plugins {}", newLicense.getEditionKey(), newLicense.getPluginKeys(), t); editionManagementState.installFailed(t.getMessage()); } finally { semaphore.release(); } }
Source:
<code>public String toString() { <START> return Objects.toStringHelper(this).add("public=", publicPort). <END> add("private=", target+":"+privatePort).toString(); }</code><technical_language>This give "public=="+publicPort. need include "=" yourself</technical_language>

Target:
public String toString() { return Objects.toStringHelper(this).add("public=", publicPort). add("private", target+":"+privatePort).toString(); }
Source:
<code><START> public Set<OperatorSpec> getAllOperatorSpecs() { <END> Collection<InputStreamInternal> inputStreams = inStreams.values(); Set<OperatorSpec> operatorSpecs = new HashSet<>(); for (InputStreamInternal stream : inputStreams) { doGetOperatorSpecs((MessageStreamImpl) stream, operatorSpecs); } return operatorSpecs; }</code><technical_language>public Collection<OperatorSpec></technical_language>

Target:
public Collection<OperatorSpec> getAllOperatorSpecs() { Collection<InputStreamInternal> inputStreams = inStreams.values(); Set<OperatorSpec> operatorSpecs = new HashSet<>(); for (InputStreamInternal stream : inputStreams) { doGetOperatorSpecs((MessageStreamImpl) stream, operatorSpecs); } return operatorSpecs; }
Source:
<code>@Override public E remove() { lock.lock(); try { if (queue.isEmpty()) { throw new NoSuchElementException(); } E peek = queue.peek(); queue.remove(); return peek; } catch (IOException e) { QueueFile.<Error>getSneakyThrowable(e); <START> return null; <END> } finally { lock.unlock(); } }</code><technical_language>throws QueueFile.<Error>getSneakyThrowable(e);</technical_language>

Target:
@Override public E remove() { lock.lock(); try { if (queue.isEmpty()) { throw new NoSuchElementException(); } E peek = queue.peek(); queue.remove(); return peek; } catch (IOException e) { throw QueueFile.<Error>getSneakyThrowable(e); } finally { lock.unlock(); } }
Source:
<code>public void testEncode() { FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(); try { ReferencedEnvelope env = new ReferencedEnvelope( Double.valueOf(48.81752162), Double.valueOf(48.81915540), Double.valueOf(-3.47568429), Double.valueOf(-3.47261370), CRS.decode("EPSG:4326")); Filter bboxFilter = ff.bbox(ff.property("geom"), env); Encoder encoder = new Encoder(createConfiguration()); String encodedFilter = encoder.encodeAsString(bboxFilter, FES.Filter); Assert.assertTrue( encodedFilter.contains("<fes:ValueReference>geom</fes:ValueReference>")); Assert.assertTrue( encodedFilter.contains( "<gml:Envelope srsDimension=\"2\" srsName=\"urn:ogc:def:crs:EPSG::4326\">")); Assert.assertTrue( encodedFilter.contains( "<gml:lowerCorner>48.817522 -3.475684</gml:lowerCorner>")); Assert.assertTrue( encodedFilter.contains( "<gml:upperCorner>48.819155 -3.472614</gml:upperCorner>")); <START> } catch (MismatchedDimensionException e) { <END> Assert.fail(e.getMessage()); } catch (NoSuchAuthorityCodeException e) { Assert.fail(e.getMessage()); } catch (FactoryException e) { Assert.fail(e.getMessage()); } catch (IOException e) { Assert.fail(e.getMessage()); } }</code><technical_language>Letting simply throw exception is easier get test fail, details including a stack trace, while this reports error message</technical_language>

Target:
public void testEncode() throws Exception { FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(); ReferencedEnvelope env = new ReferencedEnvelope( Double.valueOf(48.81752162), Double.valueOf(48.81915540), Double.valueOf(-3.47568429), Double.valueOf(-3.47261370), CRS.decode("EPSG:4326")); Filter bboxFilter = ff.bbox(ff.property("geom"), env); Encoder encoder = new Encoder(createConfiguration()); String encodedFilter = encoder.encodeAsString(bboxFilter, FES.Filter); Assert.assertTrue(encodedFilter.contains("<fes:ValueReference>geom</fes:ValueReference>")); Assert.assertTrue( encodedFilter.contains( "<gml:Envelope srsDimension=\"2\" srsName=\"urn:ogc:def:crs:EPSG::4326\">")); Assert.assertTrue( encodedFilter.contains("<gml:lowerCorner>48.817522 -3.475684</gml:lowerCorner>")); Assert.assertTrue( encodedFilter.contains("<gml:upperCorner>48.819155 -3.472614</gml:upperCorner>")); }
Source:
<code>public void testListJobs() throws Exception { <START> InspectGcsFile.inspectGcsFile(PROJECT_ID, <END> GCS_PATH, PUB_SUB_TOPIC_ID, PUB_SUB_SUBSCRIPTION_ID); JobsList.listJobs(PROJECT_ID, "state=DONE", "INSPECT_JOB"); String output = bout.toString(); Matcher matcher = JOB_ID_PATTERN.matcher(bout.toString()); assertTrue("List must contain results.", matcher.find()); }</code><technical_language>If a job, is a setUp function creates runs first. Or, alternatively test pass if jobs found</technical_language>

Target:
public void testListJobs() throws Exception { JobsList.listJobs(PROJECT_ID); String output = bout.toString(); assertThat(output, CoreMatchers.containsString("DLP jobs found:")); }
Source:
<code>public SecurityContext createSecurityContext(WithMockOidcUser withUser) { String userId = StringUtils.hasLength(withUser.name()) ? withUser .name() : withUser.value(); if (userId == null) { throw new IllegalArgumentException(withUser + " cannot have null userId on both userId and value properties"); } List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : withUser.authorities()) { <START> grantedAuthorities.add(new SimpleGrantedAuthority(authority)); <END> } OidcUser principal = new DefaultOidcUser(grantedAuthorities, new OidcIdTokenFactory(userId, withUser.clientId(), withUser.nameTokenClaim()).build(), withUser.nameTokenClaim()); Authentication authentication = new OAuth2AuthenticationToken( principal, principal.getAuthorities(), withUser.clientId()); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authentication); return context; }</code><technical_language>align this OidcUser OidcUserService creates, I [an OidcUserAuthority added](<LINK_0></technical_language>

Target:
public SecurityContext createSecurityContext(WithMockOidcUser withUser) { String userId = StringUtils.hasLength(withUser.name()) ? withUser .name() : withUser.value(); if (userId == null) { Assert.notNull(userId, "@WithMockOidcUser cannot have null name on both name and value properties"); } Set<GrantedAuthority> grantedAuthorities = new HashSet<>(); for (String authority : withUser.authorities()) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } if (grantedAuthorities.isEmpty()) { for (String scope : withUser.scopes()) { Assert.isTrue(!scope.startsWith("SCOPE_"), "scopes cannot start with SCOPE_ got " + scope); grantedAuthorities.add(new SimpleGrantedAuthority("SCOPE_" + scope)); } } grantedAuthorities.add(new OidcUserAuthority(getOidcTokenForUser(userId))); OidcUser principal = new DefaultOidcUser(grantedAuthorities, getOidcTokenForUser(userId)); Authentication authentication = new OAuth2AuthenticationToken( principal, principal.getAuthorities(), "client-id"); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authentication); return context; }
Source:
<code>public void write(JsonGenerator jg, DocumentModel enriched) throws IOException { Collection<String> subtypes = enriched.getDocumentType().getAllowedSubtypes(); jg.writeFieldName(NAME); jg.writeStartArray(); for (String subtype : subtypes) { jg.writeStartObject(); <START> jg.writeStringField("id", subtype); <END> jg.writeEndObject(); } jg.writeEndArray(); }</code><technical_language>this called type instead of id? a client test for this enricher, I miss it</technical_language>

Target:
public void write(JsonGenerator jg, DocumentModel enriched) throws IOException { Collection<String> subtypes = enriched.getDocumentType().getAllowedSubtypes(); jg.writeFieldName(NAME); jg.writeStartArray(); for (String subtype : subtypes) { jg.writeStartObject(); jg.writeStringField("type", subtype); jg.writeEndObject(); } jg.writeEndArray(); }
Source:
<code><START> public DrawingData(final double dar, final double drawingWidth, final double drawingHeight, <END> final DrawingDataDescriptor placementOption) { this.dar = dar; this.drawingWidth = drawingWidth; this.drawingHeight = drawingHeight; this.plaOpt = placementOption; calcAreaAspectRatioScaleMeasure(); }</code><technical_language>Call other constructor (line 86) default values for unused members here</technical_language>

Target:
public DrawingData(final double dar, final double drawingWidth, final double drawingHeight, final DrawingDataDescriptor placementOption) { this(dar, drawingWidth, drawingHeight, placementOption, 0.0, 0.0); }
Source:
<code><START> public static Object deserializeState(final ByteBuffer byteBuffer) throws IOException, ClassNotFoundException { <END> final byte[] bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){ try(ObjectInputStream o = new ObjectInputStream(b)){ return o.readObject(); } } }</code><technical_language>public</technical_language>

Target:
private static Object deserializeState(final ByteBuffer byteBuffer) throws RuntimeException { final byte[] bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); try { try (final ByteArrayInputStream b = new ByteArrayInputStream(bytes)) { try (final ObjectInputStream o = new ObjectInputStream(b)) { return o.readObject(); } } } catch (final Exception e) { LOG.log(Level.SEVERE, "An exception occured while deserializing the state."); e.printStackTrace(); throw new RuntimeException("Error while deserializing the operator state."); } }
Source:
<code>public void setup() { <START> filterBuilder = mock(FilterBuilder.class, RETURNS_DEEP_STUBS); <END> when(workspaceMetacardFilter.filter(any())).thenReturn(true); workspaceServiceImpl = new WorkspaceServiceImpl( catalogFramework, workspaceTransformer, workspaceQueryBuilder, securityService, persistentStore, filterBuilder); workspaceServiceImpl.setMaxSubscriptions(100); }</code><technical_language>configure this @Mock annotation: @Mock(answer = RETURNS_DEEP_STUBS)</technical_language>

Target:
public void setup() { when(workspaceMetacardFilter.filter(any())).thenReturn(true); workspaceServiceImpl = new WorkspaceServiceImpl( catalogFramework, workspaceTransformer, workspaceQueryBuilder, securityService, persistentStore, filterBuilder); workspaceServiceImpl.setMaxSubscriptions(100); }
Source:
<code>private void show(final String graphUuid, final DomainObject domainObject) { final String domainObjectUUID = domainObject.getDomainObjectUUID(); final String domainObjectName = translationService.getTranslation(domainObject.getDomainObjectNameTranslationKey()); final Diagram<?, ?> diagram = formSessionHandler.getDiagram(); <START> final Path diagramPath = diagram.getMetadata().getPath(); <END> final RenderMode renderMode = formSessionHandler.getSession() instanceof EditorSession ? RenderMode.EDIT_MODE : RenderMode.READ_ONLY_MODE; formsContainer.render(graphUuid, domainObjectUUID, domainObject, diagramPath, (fieldName, newValue) -> { try { formSessionHandler.executeUpdateDomainObjectProperty(domainObject, fieldName, newValue); } catch (final Exception ex) { log(Level.SEVERE, "Something wrong happened refreshing the DomainObject '" + domainObject + "' for field '" + fieldName + "': " + ex.getCause()); } }, renderMode); propertiesOpenedEvent.fire(new FormPropertiesOpened(formSessionHandler.getSession(), domainObjectUUID, domainObjectName)); }</code><technical_language>kie-wb-common-stunner-extensions/kie-wb-common-stunner-forms/kie-wb-common-stunner-forms-client/src/main/java/org/kie/workbench/common/stunner/forms/client/widgets/FormPropertiesWidget.java:187: error: NULL_DER$ object diagram assigned line 186 null is dereferenced line 187. 185. final String domainObjectName = translationService.getTranslation(domainObject.getDomainObjectNameTranslationKey()); 186. final Diagram<?, ?> diagram = formSessionHandler.getDiagram(); 187. > final Path diagramPath = diagram.getMetadata().getPath(); 188. final RenderMode renderMode = formSessionHandler.getSession() instanceof EditorSession ? RenderMode.EDIT_MODE : RenderMode.READ_ONLY_MODE; 189</technical_language>

Target:
private void show(final String graphUuid, final DomainObject domainObject) { final String domainObjectUUID = domainObject.getDomainObjectUUID(); final String domainObjectName = translationService.getTranslation(domainObject.getDomainObjectNameTranslationKey()); final Diagram<?, ?> diagram = formSessionHandler.getDiagram(); if (Objects.isNull(diagram)) { return; } final Metadata metadata = diagram.getMetadata(); if (Objects.isNull(metadata)) { return; } final Path diagramPath = metadata.getPath(); final RenderMode renderMode = formSessionHandler.getSession() instanceof EditorSession ? RenderMode.EDIT_MODE : RenderMode.READ_ONLY_MODE; formsContainer.render(graphUuid, domainObjectUUID, domainObject, diagramPath, (fieldName, newValue) -> { try { formSessionHandler.executeUpdateDomainObjectProperty(domainObject, fieldName, newValue); } catch (final Exception ex) { log(Level.SEVERE, "Something wrong happened refreshing the DomainObject '" + domainObject + "' for field '" + fieldName + "': " + ex.getCause()); } }, renderMode); propertiesOpenedEvent.fire(new FormPropertiesOpened(formSessionHandler.getSession(), domainObjectUUID, domainObjectName)); }
Source:
<code>public void initWithHosts(Map<Host, HostConnectionPool<CL>> hPools) { List<HostToken> allHostTokens = tokenSupplier.getTokens(hPools.keySet()); Map<HostToken, HostConnectionPool<CL>> tokenPoolMap = new HashMap<HostToken, HostConnectionPool<CL>>(); for (HostToken hToken : allHostTokens) { hostTokens.put(hToken.getHost(), hToken); tokenPoolMap.put(hToken, hPools.get(hToken.getHost())); } Map<HostToken, HostConnectionPool<CL>> localPools = getHostPoolsForRack(tokenPoolMap, localRack); localSelector.initWithHosts(localPools); if (localSelector.isTokenAware()) { replicationFactor.set(calculateReplicationFactorForDC(allHostTokens, cpConfig.getLocalDataCenter())); } Set<String> remoteRacks = new HashSet<String>(); for (Host host : hPools.keySet()) { String rack = host.getRack(); if(localRack == null && rack != null) { remoteRacks.add(rack); } <START> else if (localRack != null && !localRack.isEmpty() && rack != null && !rack.isEmpty() && !localRack.equals(rack)) { <END> remoteRacks.add(rack); } } for (String rack : remoteRacks) { Map<HostToken, HostConnectionPool<CL>> dcPools = getHostPoolsForRack(tokenPoolMap, rack); HostSelectionStrategy<CL> remoteSelector = selectorFactory.vendPoolSelectionStrategy(); remoteSelector.initWithHosts(dcPools); remoteRackSelectors.put(rack, remoteSelector); } remoteDCNames.swapWithList(remoteRackSelectors.keySet()); topology.set(createTokenPoolTopology(allHostTokens)); }</code><technical_language>removing 'localrack != null' check in L372? get behavior in if condition</technical_language>

Target:
public void initWithHosts(Map<Host, HostConnectionPool<CL>> hPools) { List<HostToken> allHostTokens = tokenSupplier.getTokens(hPools.keySet()); Map<HostToken, HostConnectionPool<CL>> tokenPoolMap = new HashMap<HostToken, HostConnectionPool<CL>>(); for (HostToken hToken : allHostTokens) { hostTokens.put(hToken.getHost(), hToken); tokenPoolMap.put(hToken, hPools.get(hToken.getHost())); } Map<HostToken, HostConnectionPool<CL>> localPools = getHostPoolsForRack(tokenPoolMap, localRack); localSelector.initWithHosts(localPools); if (localSelector.isTokenAware()) { replicationFactor.set(calculateReplicationFactorForDC(allHostTokens, cpConfig.getLocalDataCenter())); } Set<String> remoteRacks = hPools.keySet().stream().map(h -> h.getRack()).filter(rack -> rack != null && !rack.equals(localRack)).collect(Collectors.toSet()); for (String rack : remoteRacks) { Map<HostToken, HostConnectionPool<CL>> dcPools = getHostPoolsForRack(tokenPoolMap, rack); HostSelectionStrategy<CL> remoteSelector = selectorFactory.vendPoolSelectionStrategy(); remoteSelector.initWithHosts(dcPools); remoteRackSelectors.put(rack, remoteSelector); } remoteDCNames.swapWithList(remoteRackSelectors.keySet()); topology.set(createTokenPoolTopology(allHostTokens)); }