auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public SentryClient createSentryClient(Dsn dsn) { if (!checkPermission(Manifest.permission.INTERNET)) { Log.e(TAG, Manifest.permission.INTERNET + " is required to connect to the Sentry server," + " please add it to your AndroidManifest.xml"); } Log.d(TAG, "Sentry init with ctx='" + ctx.toString() + "' and dsn='" + dsn + "'"); String protocol = dsn.getProtocol(); if (!(protocol.equalsIgnoreCase("http") || protocol.equalsIgnoreCase("https"))) { throw new IllegalArgumentException("Only 'http' or 'https' connections are supported in" + " Sentry Android, but received: " + protocol); } <START> if ("false".equalsIgnoreCase(dsn.getOptions().get(DefaultSentryClientFactory.ASYNC_OPTION))) { <END> throw new IllegalArgumentException("Sentry Android cannot use synchronous connections, remove '" + DefaultSentryClientFactory.ASYNC_OPTION + "=false' from your DSN."); } SentryClient sentryClient = super.createSentryClient(dsn); sentryClient.addBuilderHelper(new AndroidEventBuilderHelper(ctx)); SentryUncaughtExceptionHandler.setup(); return sentryClient; }</code><technical_language>I this introduced this conditional reads a weird constant left side</technical_language>

Target:
public SentryClient createSentryClient(Dsn dsn) { if (!checkPermission(Manifest.permission.INTERNET)) { Log.e(TAG, Manifest.permission.INTERNET + " is required to connect to the Sentry server," + " please add it to your AndroidManifest.xml"); } Log.d(TAG, "Sentry init with ctx='" + ctx.toString() + "' and dsn='" + dsn + "'"); String protocol = dsn.getProtocol(); if (!(protocol.equalsIgnoreCase("http") || protocol.equalsIgnoreCase("https"))) { throw new IllegalArgumentException("Only 'http' or 'https' connections are supported in" + " Sentry Android, but received: " + protocol); } String async = dsn.getOptions().get(DefaultSentryClientFactory.ASYNC_OPTION); if (async != null && async.equalsIgnoreCase("false")) { throw new IllegalArgumentException("Sentry Android cannot use synchronous connections, remove '" + DefaultSentryClientFactory.ASYNC_OPTION + "=false' from your DSN."); } SentryClient sentryClient = super.createSentryClient(dsn); sentryClient.addBuilderHelper(new AndroidEventBuilderHelper(ctx)); SentryUncaughtExceptionHandler.setup(); return sentryClient; }
Source:
<code>public Map<String, Serializable> getStringSerializableMap(SchedulingService service, TaskTerminationData taskToTerminate) throws IOException, ClassNotFoundException { Map<String, Serializable> variables = new HashMap<>(); RunningTaskData taskData = taskToTerminate.taskData; TaskResultImpl taskResult = taskToTerminate.taskResult; InternalJob internalJob = taskToTerminate.internalJob; if (!taskToTerminate.normalTermination || taskResult == null) { List<InternalTask> iDependences = taskData.getTask().getIDependences(); if (iDependences != null) { List<TaskId> parentIds = new ArrayList<>(iDependences.size()); for (int i = 0; i < iDependences.size(); i++) { parentIds.add(iDependences.get(i).getId()); } Map<TaskId, TaskResult> taskResults = service.getInfrastructure().getDBManager() .loadTasksResults( taskData.getTask().getJobId(), parentIds); for (TaskResult currentTaskResult : taskResults.values()) { <START> if (currentTaskResult.getPropagatedVariables() != null) { <END> variables.putAll(SerializationUtil.deserializeVariableMap(currentTaskResult.getPropagatedVariables())); } } } else { if(internalJob!=null) variables.putAll(internalJob.getVariables()); } variables.put(SchedulerVars.PA_TASK_SUCCESS.toString(),Boolean.toString(false)); } else if (taskResult.hadException()) { variables = SerializationUtil.deserializeVariableMap(taskResult.getPropagatedVariables()); variables.put(SchedulerVars.PA_TASK_SUCCESS.toString(),Boolean.toString(false)); } else { variables = SerializationUtil.deserializeVariableMap(taskResult.getPropagatedVariables()); variables.put(SchedulerVars.PA_TASK_SUCCESS.toString(), Boolean.toString(true)); } return variables; }</code><technical_language>is a bit long complex this method. refactor a bit</technical_language>

Target:
public Map<String, Serializable> getStringSerializableMap(SchedulingService service, TaskTerminationData taskToTerminate) throws Exception { Map<String, Serializable> variables = new HashMap<>(); RunningTaskData taskData = taskToTerminate.taskData; TaskResultImpl taskResult = taskToTerminate.taskResult; InternalJob internalJob = taskToTerminate.internalJob; if (!taskToTerminate.normalTermination || taskResult == null) { List<InternalTask> iDependences = taskData.getTask().getIDependences(); if (iDependences != null) { List<TaskId> parentIds = new ArrayList<>(iDependences.size()); for (int i = 0; i < iDependences.size(); i++) { parentIds.add(iDependences.get(i).getId()); } Map<TaskId, TaskResult> taskResults = service.getInfrastructure().getDBManager() .loadTasksResults( taskData.getTask().getJobId(), parentIds); getResultsFromListOfTaskResults(variables, taskResults); } else { if(internalJob!=null) variables.putAll(internalJob.getVariables()); } variables.put(SchedulerVars.PA_TASK_SUCCESS.toString(),Boolean.toString(false)); } else if (taskResult.hadException()) { variables = fillMapWithTaskResult(taskResult,false); } else { variables = fillMapWithTaskResult(taskResult,true); } return variables; }
Source:
<code>public boolean allTypes(InputObjectState foundTypes) throws ObjectStoreException { if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger.trace("SlotStore.allTypes()"); } String[] knownTypes = store.getKnownTypes(); Set<String> typeSet = new HashSet<>(); if (knownTypes == null || knownTypes.length == 0) { return true; } OutputObjectState buffer = new OutputObjectState(); try { for (String typeName : knownTypes) { if (typeName == null) { continue; } <START> if (typeName.startsWith("/")) { <END> typeName = typeName.substring(1); } if (typeName.contains("/")) { String value = ""; String[] parents = typeName.split("/"); for (String parent : parents) { if (parent.length() == 0) { continue; } if (value.length() > 0) { value = value + "/"; } value = value + parent; if (!typeSet.contains(value)) { typeSet.add(value); buffer.packString(value); } } } else { buffer.packString(typeName); } } buffer.packString(""); } catch (IOException e) { throw new ObjectStoreException(e); } foundTypes.setBuffer(buffer.buffer()); return true; }</code><technical_language>I asking more java.nio.files.Path split type name instead of hand rolled complex parsing. if prefer complex version fine maintain for ;)</technical_language>

Target:
public boolean allTypes(InputObjectState foundTypes) throws ObjectStoreException { if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger.trace("SlotStore.allTypes()"); } String[] knownTypes = store.getKnownTypes(); Set<String> typeSet = new HashSet<>(); if (knownTypes == null || knownTypes.length == 0) { return true; } OutputObjectState buffer = new OutputObjectState(); try { for (String typeName : knownTypes) { if (typeName.startsWith("/")) { typeName = typeName.substring(1); } if (typeName.contains("/")) { String value = ""; String[] parents = typeName.split("/"); for (String parent : parents) { if (parent.length() == 0) { continue; } if (value.length() > 0) { value = value + "/"; } value = value + parent; if (!typeSet.contains(value)) { typeSet.add(value); buffer.packString(value); } } } else { buffer.packString(typeName); } } buffer.packString(""); } catch (IOException e) { throw new ObjectStoreException(e); } foundTypes.setBuffer(buffer.buffer()); return true; }
Source:
<code>public static void getPropertyValues(Object obj, Set<String> properties, Map<String, String> values) { try { PropertyDescriptor[] pds = Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors(); int hitCount = 0; for (PropertyDescriptor pd : pds) { <START> String propertyName = pd.getName().toLowerCase(); <END> if (properties.contains(propertyName) && !values.containsKey(propertyName)) { Object value = null; hitCount++; try { value = pd.getReadMethod().invoke(obj); String stringValue = value != null ? value.toString() : null; values.put(propertyName, stringValue); } catch (Exception e) { log.warn("Unable to get value of property: " + pd.getDisplayName() + " for class " + obj.getClass().getName()); } if (hitCount == properties.size()) { break; } } } } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>if propertyName is contains in values, a hitCount increased</technical_language>

Target:
public static void getPropertyValues(Object obj, Set<String> properties, Map<String, String> values) { try { PropertyDescriptor[] pds = Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors(); int hitCount = 0; hitCount = values.size(); for (PropertyDescriptor pd : pds) { String propertyName = pd.getName().toLowerCase(); if (properties.contains(propertyName) && !values.containsKey(propertyName)) { Object value = null; hitCount++; try { value = pd.getReadMethod().invoke(obj); String stringValue = value != null ? value.toString() : null; values.put(propertyName, stringValue); } catch (Exception e) { log.warn("Unable to get value of property: " + pd.getDisplayName() + " for class " + obj.getClass().getName()); } if (hitCount == properties.size()) { break; } } } } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public PagedResources<ScheduleInfoResource> list( PagedResourcesAssembler<ScheduleInfo> assembler) { List<ScheduleInfo> result = this.schedulerService.list(); <START> Pageable pageable = new PageRequest(0, result.size()); <END> Page<ScheduleInfo> page = new PageImpl<>(result, pageable, result.size()); return assembler.toResource(page, taskAssembler); }</code><technical_language>This enforce pageable content size based result. I this client; otherwise, client implementations (ex: web UI) able request desired page</technical_language>

Target:
public PagedResources<ScheduleInfoResource> list( PagedResourcesAssembler<ScheduleInfo> assembler) { List<ScheduleInfo> result = this.schedulerService.list(); int resultSize = result.size(); Pageable pageable = new PageRequest(0, (resultSize == 0) ? resultSize = 1 : resultSize); Page<ScheduleInfo> page = new PageImpl<>(result, pageable, result.size()); return assembler.toResource(page, taskAssembler); }
Source:
<code>private void showPurchasesOrDeleteSiteDialog(JSONObject response, final Blog currentBlog) { <START> try { <END> JSONArray purchases = response.getJSONArray(PURCHASE_ORIGINAL_RESPONSE_KEY); if (hasActivePurchases(purchases)) { showPurchasesDialog(currentBlog); } else { showDeleteSiteDialog(); } } catch (JSONException e) { AppLog.e(AppLog.T.API, e.toString()); } }</code><technical_language>I a question for benefit here, I hope mind. Is chance response null here? Is worth check here? Note: I wrap head NPEs missing in PRs, understand it</technical_language>

Target:
private void showPurchasesOrDeleteSiteDialog(JSONObject response, final Blog currentBlog) { try { JSONArray purchases = response.getJSONArray(PURCHASE_ORIGINAL_RESPONSE_KEY); if (hasActivePurchases(purchases)) { showPurchasesDialog(currentBlog); } else { showDeleteSiteDialog(); } } catch (JSONException e) { AppLog.e(AppLog.T.API, "Error occurred while trying to delete site: " + e.toString()); } }
Source:
<code>public static void start() { loggingDir = new File(Constants.RESOURCES_DIR + Constants.LOGGER_DIR); if (loggingDir.exists() == false) { loggingDir.mkdir(); } try { Date currentDate = new Date(); SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM.dd-hh-mm-ss"); String desiredFileName = "Session-" + simpleFormat.format(currentDate) + ".log"; <START> loggingFile = new File(Constants.RESOURCES_DIR + Constants.LOGGER_DIR + desiredFileName); <END> BufferedWriter buffWriter = new BufferedWriter(new FileWriter(loggingFile)); buffWriter.write("SCRUMBLEDORE LOGGING FILE"); buffWriter.close(); } catch (IOException e) { System.out.println(e); } }</code><technical_language>code this line try statement's block? <layout</technical_language>

Target:
public static void start() { loggingDir = new File(Constants.RESOURCES_DIR + Constants.LOGGER_DIR); if (loggingDir.exists() == false) { loggingDir.mkdir(); } try { Date currentDate = new Date(); SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM.dd-hh-mm-ss"); String desiredFileName = "Session-" + simpleFormat.format(currentDate) + ".log"; loggingFile = new File(Constants.RESOURCES_DIR + Constants.LOGGER_DIR + desiredFileName); BufferedWriter buffWriter = new BufferedWriter(new FileWriter(loggingFile)); buffWriter.write("SCRUMBLEDORE LOGGING FILE"); buffWriter.close(); } catch (IOException e) { System.out.println(e); } started = true; }
Source:
<code>private static boolean isFixedLength(int typeID) { <START> int varLengthBit = typeID & FLAG_UNKNOWN_SIZE; <END> return varLengthBit == 0; }</code><technical_language>minor return (typeID & FLAG_UNKNOWN_SIZE) == 0; instead</technical_language>

Target:
private static boolean isFixedLength(int typeID) { return (typeID & FLAG_UNKNOWN_SIZE) == 0; }
Source:
<code>public CheckEditPartResized(SWTBotGefEditPart editPartBot) { <START> this.graphicalEditPart = (GraphicalEditPart) editPartBot.part(); this.initialSize = graphicalEditPart.getFigure().getBounds().getSize().getCopy(); <END> }</code><technical_language>replace by: this((GraphicalEditPart) editPartBot.part());</technical_language>

Target:
public CheckEditPartResized(SWTBotGefEditPart editPartBot) { this((GraphicalEditPart) editPartBot.part()); }
Source:
<code>public List<ObjectId> lookUp(final String partialId) { Preconditions.checkNotNull(partialId); byte[] raw = ObjectId.toRaw(partialId); List<ObjectId> baseResults = lookUpInternal(raw); if (partialId.length() % 2 != 0) { Iterator<ObjectId> listIterator = baseResults.iterator(); while (listIterator.hasNext()) { ObjectId result = listIterator.next(); <START> if (!result.toString().contains(partialId)) { <END> listIterator.remove(); } } } return baseResults; }</code><technical_language>this startsWith instead of contains</technical_language>

Target:
public List<ObjectId> lookUp(final String partialId) { Preconditions.checkNotNull(partialId); byte[] raw = ObjectId.toRaw(partialId); List<ObjectId> baseResults = lookUpInternal(raw); if (partialId.length() % 2 != 0) { Iterator<ObjectId> listIterator = baseResults.iterator(); while (listIterator.hasNext()) { ObjectId result = listIterator.next(); if (!result.toString().startsWith(partialId)) { listIterator.remove(); } } } return baseResults; }
Source:
<code>public void initialize() { Map<String, String> properties = editProperties(); if (!super.configure()) { return; } if (getThing().getStatus() == ThingStatus.OFFLINE) { return; } sensors.add(new DS18x20(sensorIds.get(0), this)); if (!properties.containsKey(PROPERTY_MODELID)) { scheduler.execute(() -> { updateSensorProperties(); }); <START> return; <END> } else { scheduler.execute(() -> { configureThingChannels(); }); return; } }</code><technical_language>useless</technical_language>

Target:
public void initialize() { Map<String, String> properties = editProperties(); if (!super.configure()) { return; } if (getThing().getStatus() == ThingStatus.OFFLINE) { return; } sensors.add(new DS18x20(sensorIds.get(0), this)); if (!properties.containsKey(PROPERTY_MODELID)) { scheduler.execute(() -> { updateSensorProperties(); }); } else { scheduler.execute(() -> { configureThingChannels(); }); } }
Source:
<code>SweepOutcomeMetrics() { Arrays.stream(SweepOutcome.values()).forEach(outcome -> <START> metricsManager.registerMetric(BackgroundSweeperImpl.class, outcome.name(), () -> getCount(outcome)) <END> ); }</code><technical_language>metric is measured 30s: 1. a DISABLED time t(when service starts) <-- measure find null 2. Config changes t+25s sweep is enabled, NOTHING_TO_SWEEP 3. measure metrics t+30s find DISABLED=0 NOTHING_TO_SWEEP=1. This is kind of bad, lose a datapoint for DISABLED. I separate lastOutcome for enum values check lastOutcome. reset lastOutComes time a measurement is made, reset done in lambda passed for metric</technical_language>

Target:
SweepOutcomeMetrics() { Arrays.stream(SweepOutcome.values()).forEach(outcome -> metricsManager.registerMetric(BackgroundSweeperImpl.class, outcome.name(), () -> getOutcomeCount(outcome)) ); reservoir = new SlidingTimeWindowReservoir(60L, TimeUnit.SECONDS); }
Source:
<code>public DigipostClientMock() { URI host = URI.create("http://localhost:" + PORT); <START> HttpClientBuilder httpClientBuilder = DigipostHttpClientFactory.createBuilder(DigipostHttpClientSettings.DEFAULT.timeouts(DEFAULT_TIMEOUTS_MS.all(0))); <END> apiService = new ApiServiceImpl(httpClientBuilder, PORT, null, host, null); apiService.buildApacheHttpClientBuilder(); client = new DigipostClient(newBuilder().build(), "digipostmock-url", 1, new Signer() { @Override public byte[] sign(String dataToSign) { return new byte[0]; } }, apiService); }</code><technical_language>rage4:</technical_language>

Target:
public DigipostClientMock() { this(UnaryOperator.identity()); }
Source:
<code>protected void beforeInvocation() throws Exception { <START> ActionContext.bound(invocation.getInvocationContext()); <END> }</code><technical_language>candidate for bind() if method is created</technical_language>

Target:
protected void beforeInvocation() throws Exception { ActionContext.bind(invocation.getInvocationContext()); }
Source:
<code>public MovePath addStep(final MoveStepType type) { BulldozerMovePath mp = (BulldozerMovePath) super.addStep(type); IHex hex = mp.getGame().getBoard().getHex(mp.getFinalCoords()); <START> int hexWaterDepth = (hex != null) && hex.containsTerrain(Terrains.WATER) ? <END> hex.depth() : Integer.MIN_VALUE; if (!mp.isMoveLegal() && !mp.isJumping()) { int levelingCost = calculateLevelingCost(mp.getFinalCoords(), getEntity()); if(levelingCost > CANNOT_LEVEL) { coordLevelingCosts.put(mp.getFinalCoords(), levelingCost); coordsToLevel.add(mp.getFinalCoords()); } if(hexWaterDepth > 0) { MovementType mType = MovementType.getMovementType(mp.getEntity()); if(mType == MovementType.Walker || mType == MovementType.WheeledAmphi || mType == MovementType.TrackedAmphi) { additionalCosts.put(mp.getFinalCoords(), 1); } } } if (mp.isJumping()) { if ((hex != null) && !hex.containsTerrain(Terrains.BRIDGE)) { if (hexWaterDepth == 1) { additionalCosts.put(mp.getFinalCoords(), mp.getCachedEntityState().getJumpMP() - mp.getCachedEntityState().getTorsoJumpJets()); } else if (hexWaterDepth > 1) { additionalCosts.put(mp.getFinalCoords(), mp.getCachedEntityState().getJumpMP()); } } } return mp; }</code><technical_language>suggestion int hexWaterDepth = ((hex != null) && hex.containsTerrain(Terrains.WATER))</technical_language>

Target:
public MovePath addStep(final MoveStepType type) { BulldozerMovePath mp = (BulldozerMovePath) super.addStep(type); IHex hex = mp.getGame().getBoard().getHex(mp.getFinalCoords()); int hexWaterDepth = ((hex != null) && hex.containsTerrain(Terrains.WATER)) ? hex.depth() : Integer.MIN_VALUE; if (!mp.isMoveLegal() && !mp.isJumping()) { int levelingCost = calculateLevelingCost(mp.getFinalCoords(), getEntity()); if(levelingCost > CANNOT_LEVEL) { coordLevelingCosts.put(mp.getFinalCoords(), levelingCost); coordsToLevel.add(mp.getFinalCoords()); } if(hexWaterDepth > 0) { MovementType mType = MovementType.getMovementType(mp.getEntity()); if(mType == MovementType.Walker || mType == MovementType.WheeledAmphi || mType == MovementType.TrackedAmphi) { additionalCosts.put(mp.getFinalCoords(), 1); } } } if (mp.isJumping()) { if ((hex != null) && !hex.containsTerrain(Terrains.BRIDGE)) { if (hexWaterDepth == 1) { additionalCosts.put(mp.getFinalCoords(), mp.getCachedEntityState().getJumpMP() - mp.getCachedEntityState().getTorsoJumpJets()); } else if (hexWaterDepth > 1) { additionalCosts.put(mp.getFinalCoords(), mp.getCachedEntityState().getJumpMP()); } } } return mp; }
Source:
<code>public void testGetApiMetaDataWithTokenCredentialsAuth() { KeystoneApi api = requestsSendResponses( keystoneAuthWithTokenAndTenantName, responseWithKeystoneAccess, HttpRequest.builder().method("GET").endpoint(endpoint + "/v2.0/"). addHeader("Accept", APPLICATION_JSON).build(), HttpResponse.builder().statusCode(200). payload(payloadFromResourceWithContentType("/raxVersion.json", APPLICATION_JSON)).build()); ApiMetadata metadata = api.getApiMetadata(); <START> assertEquals(metadata, new ParseRackspaceApiMetadataTest().expected()); <END> }</code><technical_language>I suggest ParseAccessTest class here</technical_language>

Target:
public void testGetApiMetaDataWithTokenCredentialsAuth() { ParseRackspaceApiMetadataTest test = new ParseRackspaceApiMetadataTest(); KeystoneApi api = requestsSendResponses( keystoneAuthWithTokenAndTenantName, responseWithKeystoneAccess, HttpRequest.builder().method("GET").endpoint(endpoint + "/v2.0/"). addHeader("Accept", APPLICATION_JSON).build(), HttpResponse.builder().statusCode(200). payload(payloadFromResourceWithContentType(test.resource(), APPLICATION_JSON)).build()); ApiMetadata metadata = api.getApiMetadata(); assertEquals(metadata, test.expected()); }
Source:
<code>Connection createConnection() throws AmqpException; String getHost(); int getPort(); String getVirtualHost(); String getUsername(); void addConnectionListener(ConnectionListener listener); boolean removeConnectionListener(ConnectionListener listener); void clearConnectionListeners(); <START> default Connection createPublisherConnection() throws AmqpException { <END> return createConnection(); }</code><technical_language>I need this get direct access publisherCF delegate in producers</technical_language>

Target:
Connection createConnection() throws AmqpException; String getHost(); int getPort(); String getVirtualHost(); String getUsername(); void addConnectionListener(ConnectionListener listener); boolean removeConnectionListener(ConnectionListener listener); void clearConnectionListeners(); default @Nullable ConnectionFactory getPublisherConnectionFactory() { return null; }
Source:
<code>private String getAuthorizationHeader(String clientId, String clientSecret) { if(clientId == null || clientSecret == null) { <START> logger.debug("Null Client ID or Client Secret detected. Endpoint that requires authentication will reject request with 401 error."); <END> } String creds = String.format("%s:%s", clientId, clientSecret); try { return "Basic " + new String(Base64.encode(creds.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Could not convert String"); } }</code><technical_language>DEBUG is a bit of a weak signal, think, this is fail</technical_language>

Target:
private String getAuthorizationHeader(String clientId, String clientSecret) { if(clientId == null || clientSecret == null) { logger.warn("Null Client ID or Client Secret detected. Endpoint that requires authentication will reject request with 401 error."); } String creds = String.format("%s:%s", clientId, clientSecret); try { return "Basic " + new String(Base64.encode(creds.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Could not convert String"); } }
Source:
<code>private void resetVmAttributes(VmDynamic vm) { vm.setMigratingToVds(null); vm.getGraphicsInfos().clear(); vm.setGuestCurrentUserName(null); vm.setConsoleCurrentUserName(null); vm.setConsoleUserId(null); <START> vm.setClientIp(""); <END> vm.setIp(null); vm.setFqdn(null); vm.setCpuName(null); vm.setEmulatedMachine(null); vm.setVolatileRun(false); vm.setGuestAgentNicsHash(0); }</code><technical_language>Good, if other places set null. I fix comparison</technical_language>

Target:
private void resetVmAttributes(VmDynamic vm) { vm.setMigratingToVds(null); vm.getGraphicsInfos().clear(); vm.setGuestCurrentUserName(null); vm.setConsoleCurrentUserName(null); vm.setConsoleUserId(null); vm.setClientIp(null); vm.setIp(null); vm.setFqdn(null); vm.setCpuName(null); vm.setEmulatedMachine(null); vm.setVolatileRun(false); vm.setGuestAgentNicsHash(0); }
Source:
<code>public void setUp() throws Exception { when(translationService.format(GuidedDecisionTableErraiConstants.MetaDataColumnPage_MetadataNameEmpty)) .thenReturn("empty"); when(translationService.format(GuidedDecisionTableErraiConstants.MetaDataColumnPage_ThatColumnNameIsAlreadyInUsePleasePickAnother)) .thenReturn("alreadyUsed"); when(translationService.format(GuidedDecisionTableErraiConstants.MetaDataColumnPage_IsNotValidIdentifier)) .thenReturn("isNotValid"); <START> when(validationServiceCaller.call(any())).thenReturn(validationService); <END> }</code><technical_language>CallerMock (in uberfire-testing-utils) is better/easier. do validationServiceCaller = new CallerMock(validationService); test need RemoteCallback captor</technical_language>

Target:
public void setUp() throws Exception { when(translationService.format(GuidedDecisionTableErraiConstants.MetaDataColumnPage_MetadataNameEmpty)) .thenReturn("empty"); when(translationService.format(GuidedDecisionTableErraiConstants.MetaDataColumnPage_ThatColumnNameIsAlreadyInUsePleasePickAnother)) .thenReturn("alreadyUsed"); when(translationService.format(GuidedDecisionTableErraiConstants.MetaDataColumnPage_IsNotValidIdentifier)) .thenReturn("isNotValid"); validationServiceCaller = new CallerMock<>(validationService); page.validationService = validationServiceCaller; when(validationService.evaluateJavaIdentifiers(any())).thenReturn(validationResult); }
Source:
<code>void createOrEditFileComment() { if (!Gerrit.isSignedIn()) { <START> Gerrit.doSignIn(parent.getToken()); <END> } if (boxes.isEmpty()) { CommentInfo info = CommentInfo.createFile( path, side, null, null); addFileComment(parent.addDraftBox(info)); } else { CommentBox box = boxes.get(boxes.size() - 1); if (box instanceof DraftBox) { ((DraftBox) box).setEdit(true); } else { addFileComment(((PublishedBox) box).addReplyBox()); } } }</code><technical_language>return this</technical_language>

Target:
void createOrEditFileComment() { if (!Gerrit.isSignedIn()) { Gerrit.doSignIn(parent.getToken()); return; } if (boxes.isEmpty()) { CommentInfo info = CommentInfo.createFile( path, side, null, null); addFileComment(parent.addDraftBox(info)); } else { CommentBox box = boxes.get(boxes.size() - 1); if (box instanceof DraftBox) { ((DraftBox) box).setEdit(true); } else { addFileComment(((PublishedBox) box).addReplyBox()); } } }
Source:
<code>private boolean matchesNamespace(final String namespace) { <START> return namespaces.stream().anyMatch(ns -> ns.equals(namespace)); <END> }</code><technical_language>Objects.equals() please</technical_language>

Target:
private boolean matchesNamespace(final String namespace) { return namespaces.stream().anyMatch(ns -> Objects.equals(ns, namespace)); }
Source:
<code>protected void executeQueryCommand() { try { VDSReturnValue returnValue = getBackendResourceManager().RunVdsCommand(VDSCommandType.GetGlusterVolumeAdvancedDetails, new GlusterVolumeAdvancedDetailsVDSParameters(getUpServerId(), getParameters().getClusterId(), getParameters().getVolumeName(), getParameters().getBrickName(), getParameters().detailsRequired())); getQueryReturnValue().setReturnValue(returnValue.getReturnValue()); <START> } catch (Exception e) { <END> throw new RuntimeException(e); } }</code><technical_language>point of catching exception throwing again, in catch block? is need wrap a RuntimeException, is thrown getUpServerId() is a RuntimeException</technical_language>

Target:
protected void executeQueryCommand() { VDSReturnValue returnValue = getBackendResourceManager().RunVdsCommand(VDSCommandType.GetGlusterVolumeAdvancedDetails, new GlusterVolumeAdvancedDetailsVDSParameters(getUpServerId(getParameters().getClusterId()), getParameters().getClusterId(), getParameters().getVolumeName(), getParameters().getBrickName(), getParameters().detailsRequired())); getQueryReturnValue().setReturnValue(returnValue.getReturnValue()); }
Source:
<code>public EList<Widget> renderWidget(Widget w, StringBuilder sb) throws RenderException { String snippet = getSnippet("list"); snippet = snippet.replaceAll("%label%", getLabel(w)); String rowSnippet = getSnippet("list_row"); String state = itemUIRegistry.getState(w).toString(); String[] rowContents = state.split(((List) w).getSeparator()); StringBuilder rowSB = new StringBuilder(); for(String row : rowContents) { rowSB.append(StringUtils.replace(rowSnippet, "%title%", row)); } snippet = StringUtils.replace(snippet, "%rows%", rowSB.toString()); String style = ""; String color = itemUIRegistry.getLabelColor(w); if(color != null) <START> style = "color:"+ color; <END> snippet = StringUtils.replace(snippet, "%labelstyle%", style); style = ""; color = itemUIRegistry.getValueColor(w); if(color != null) style = "color:"+ color; snippet = StringUtils.replace(snippet, "%valuestyle%", style); sb.append(snippet); return null; }</code><technical_language>curly braces please</technical_language>

Target:
public EList<Widget> renderWidget(Widget w, StringBuilder sb) throws RenderException { String snippet = getSnippet("list"); snippet = snippet.replaceAll("%label%", getLabel(w)); String rowSnippet = getSnippet("list_row"); String state = itemUIRegistry.getState(w).toString(); String[] rowContents = state.split(((List) w).getSeparator()); StringBuilder rowSB = new StringBuilder(); for(String row : rowContents) { rowSB.append(StringUtils.replace(rowSnippet, "%title%", row)); } snippet = StringUtils.replace(snippet, "%rows%", rowSB.toString()); snippet = processColor(w, snippet); sb.append(snippet); return null; }
Source:
<code>public void testRunScenarioDependentImportsAndFactData() throws Exception { <START> final ArrayList<Fixture> fixtures = new ArrayList<Fixture>(); <END> final Imports imports = new Imports() {{ addImport(new Import("java.sql.ClientInfoStatus")); addImport(new Import("Integer")); addImport(new Import("org.kie.Person")); }}; final Map<String, ModelField[]> modelFields = new HashMap<String, ModelField[]>() {{ put("java.sql.ClientInfoStatus", new ModelField[]{modelField("java.sql.JDBCType")}); put("org.kie.Person", new ModelField[]{modelField("org.kie.Address")}); put("org.kie.Address", new ModelField[]{modelField("org.kie.City"), modelField("org.kie.Street")}); }}; when(scenario.getFixtures()).thenReturn(fixtures); when(dataModelService.getDataModel(path)).thenReturn(modelOracle); when(modelOracle.getProjectModelFields()).thenReturn(modelFields); when(scenario.getImports()).thenReturn(imports); testEditorService.runScenario("userName", path, scenario); assertEquals(7, scenario.getImports().getImports().size()); }</code><technical_language>DRY, diamond operator. (Also line 325.)</technical_language>

Target:
public void testRunScenarioDependentImportsAndFactData() throws Exception { final ArrayList<Fixture> fixtures = new ArrayList<>(); final Imports imports = new Imports() {{ addImport(new Import("java.sql.ClientInfoStatus")); addImport(new Import("Integer")); addImport(new Import("org.kie.Person")); }}; final Map<String, ModelField[]> modelFields = new HashMap() {{ put("java.sql.ClientInfoStatus", toModelFields("java.sql.JDBCType")); put("org.kie.Person", toModelFields("org.kie.Address")); put("org.kie.Address", toModelFields("org.kie.City", "org.kie.Street")); }}; final int usedDataTypesCount = 7; when(scenario.getFixtures()).thenReturn(fixtures); when(dataModelService.getDataModel(path)).thenReturn(modelOracle); when(modelOracle.getProjectModelFields()).thenReturn(modelFields); when(scenario.getImports()).thenReturn(imports); testEditorService.runScenario("userName", path, scenario); assertEquals(usedDataTypesCount, scenario.getImports().getImports().size()); }
Source:
<code>public void testDefaultLoggerClosesItStreams() throws Exception { final Checker checker = new Checker(); try (CloseAndFlushTestByteArrayOutputStream testInfoOutputStream = <START> new CloseAndFlushTestByteArrayOutputStream(); <END> CloseAndFlushTestByteArrayOutputStream testErrorOutputStream = new CloseAndFlushTestByteArrayOutputStream()) { checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); checker.addListener(new DefaultLogger(testInfoOutputStream, OutputStreamOptions.CLOSE, testErrorOutputStream, OutputStreamOptions.CLOSE)); final File tmpFile = temporaryFolder.newFile("file.java"); final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; verify(checker, tmpFile.getPath(), expected); assertEquals("Close count was not expected", 1, testInfoOutputStream.getCloseCount()); assertEquals("Flush count was not expected", 3, testInfoOutputStream.getFlushCount()); assertEquals("Close count was not expected", 1, testErrorOutputStream.getCloseCount()); assertEquals("Flush count was not expected", 1, testErrorOutputStream.getFlushCount()); } }</code><technical_language>this done in separate issue? ctor for DefaultLogger is affected this PR</technical_language>

Target:
public void testDefaultLoggerClosesItStreams() throws Exception { final Checker checker = new Checker(); try (CloseAndFlushTestByteArrayOutputStream testInfoOutputStream = new CloseAndFlushTestByteArrayOutputStream(); CloseAndFlushTestByteArrayOutputStream testErrorOutputStream = new CloseAndFlushTestByteArrayOutputStream()) { checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); checker.addListener(new DefaultLogger(testInfoOutputStream, true, testErrorOutputStream, true)); final File tmpFile = temporaryFolder.newFile("file.java"); final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; verify(checker, tmpFile.getPath(), expected); assertEquals("Close count was not expected", 1, testInfoOutputStream.getCloseCount()); assertEquals("Flush count was not expected", 3, testInfoOutputStream.getFlushCount()); assertEquals("Close count was not expected", 1, testErrorOutputStream.getCloseCount()); assertEquals("Flush count was not expected", 1, testErrorOutputStream.getFlushCount()); } }
Source:
<code>private QueryContext createQueryContext(Session session) { QueryContext newQueryContext = new QueryContext(context.getConf(), session); String tajoTest = System.getProperty(CommonTestingUtil.TAJO_TEST_KEY); if (tajoTest != null && tajoTest.equalsIgnoreCase(CommonTestingUtil.TAJO_TEST_TRUE)) { newQueryContext.putAll(CommonTestingUtil.getSessionVarsForTest()); } <START> synchronized (session) { <END> if (session.getQueryCache() == null) { session.setQueryCache(CacheBuilder.newBuilder() .maximumSize(200) .expireAfterAccess(1, TimeUnit.HOURS) .build(new CacheLoader<String, Expr>() { public Expr load(String sql) throws SQLSyntaxError { return analyzer.parse(sql); } }) ); } } return newQueryContext; }</code><technical_language>Please remove redundant synchronized block</technical_language>

Target:
private QueryContext createQueryContext(Session session) { QueryContext newQueryContext = new QueryContext(context.getConf(), session); String tajoTest = System.getProperty(CommonTestingUtil.TAJO_TEST_KEY); if (tajoTest != null && tajoTest.equalsIgnoreCase(CommonTestingUtil.TAJO_TEST_TRUE)) { newQueryContext.putAll(CommonTestingUtil.getSessionVarsForTest()); } int queryCacheSize = context.getConf().getIntVar(TajoConf.ConfVars.QUERY_SESSION_QUERY_CACHE_SIZE); if (queryCacheSize > 0 && session.getQueryCache() == null) { Weigher<String, Expr> weighByLength = new Weigher<String, Expr>() { public int weigh(String key, Expr expr) { return key.length(); } }; LoadingCache<String, Expr> cache = CacheBuilder.newBuilder() .maximumWeight(queryCacheSize * 1024) .weigher(weighByLength) .expireAfterAccess(1, TimeUnit.HOURS) .build(new CacheLoader<String, Expr>() { public Expr load(String sql) throws SQLSyntaxError { return analyzer.parse(sql); } }); session.setQueryCache(cache); } return newQueryContext; }
Source:
<code>public void addField(@NonNull String name, @NonNull IDeclaration declaration) { if (Arrays.asList(fFieldNames).contains(name)) { <START> return; <END> } @NonNull IDeclaration[] fields = Arrays.copyOf(fFields, fFields.length + 1); fields[fFields.length] = declaration; fFields = fields; @NonNull String[] names = Arrays.copyOf(fFieldNames, fFieldNames.length + 1); names[fFieldNames.length] = name; fFieldNames = names; fMaxAlign = Math.max(fMaxAlign, declaration.getAlignment()); }</code><technical_language>a log message here? Activator.logWarning("Fields exist.");</technical_language>

Target:
public void addField(@NonNull String name, @NonNull IDeclaration declaration) { if (Arrays.asList(fFieldNames).contains(name)) { Activator.log(IStatus.WARNING, "Struct already contains a field named " + name); return; } @NonNull IDeclaration[] fields = Arrays.copyOf(fFields, fFields.length + 1); fields[fFields.length] = declaration; fFields = fields; @NonNull String[] names = Arrays.copyOf(fFieldNames, fFieldNames.length + 1); names[fFieldNames.length] = name; fFieldNames = names; fMaxAlign = Math.max(fMaxAlign, declaration.getAlignment()); }
Source:
<code>public void writeData(ObjectDataOutput out) throws IOException { IOUtil.writeObject(out, key); IOUtil.writeObject(out, value); out.writeLong(cost); out.writeLong(creationTime); out.writeLong(expirationTime); out.writeLong(hits); out.writeLong(lastAccessTime); out.writeLong(lastStoredTime); out.writeLong(lastUpdateTime); out.writeLong(version); out.writeLong(ttl); <START> out.writeLong(maxIdle); <END> }</code><technical_language>RU compatibility</technical_language>

Target:
public void writeData(ObjectDataOutput out) throws IOException { IOUtil.writeObject(out, key); IOUtil.writeObject(out, value); out.writeLong(cost); out.writeLong(creationTime); out.writeLong(expirationTime); out.writeLong(hits); out.writeLong(lastAccessTime); out.writeLong(lastStoredTime); out.writeLong(lastUpdateTime); out.writeLong(version); out.writeLong(ttl); if (out.getVersion().isGreaterOrEqual(V3_11)) { out.writeLong(maxIdle); } }
Source:
<code>public void setUp() throws Exception { dockerHostAddress = ElasticSearchRestDataContextIT.determineHostName(); <START> externalClient = new RestHighLevelClient(RestClient.builder(new HttpHost(dockerHostAddress, 9200))); <END> externalClient.indices().create(new CreateIndexRequest(INDEX_NAME), RequestOptions.DEFAULT); final PutMappingRequest putMappingRequest = new PutMappingRequest(INDEX_NAME); putMappingRequest .source(ElasticSearchUtils .getMappingSource(new MutableTable(DEFAULT_TABLE_NAME, TableType.TABLE, new MutableSchema( INDEX_NAME), new MutableColumn("name", ColumnType.STRING), new MutableColumn("age", ColumnType.INTEGER)))); externalClient.indices().putMapping(putMappingRequest, RequestOptions.DEFAULT); factory = new ElasticSearchRestDataContextFactory(); }</code><technical_language>9200 is multiple locations in this module. A constant nice</technical_language>

Target:
public void setUp() throws Exception { dockerHostAddress = ElasticSearchRestDataContextIT.determineHostName(); externalClient = new RestHighLevelClient(RestClient .builder(new HttpHost(dockerHostAddress, ElasticSearchRestDataContextIT.DEFAULT_REST_CLIENT_PORT))); externalClient.indices().create(new CreateIndexRequest(INDEX_NAME), RequestOptions.DEFAULT); final MutableTable table = new MutableTable(DEFAULT_TABLE_NAME, TableType.TABLE, new MutableSchema(INDEX_NAME), new MutableColumn("name", ColumnType.STRING), new MutableColumn("age", ColumnType.INTEGER)); final PutMappingRequest putMappingRequest = new PutMappingRequest(INDEX_NAME) .source(ElasticSearchUtils.getMappingSource(table)); externalClient.indices().putMapping(putMappingRequest, RequestOptions.DEFAULT); factory = new ElasticSearchRestDataContextFactory(); properties = new DataContextPropertiesImpl(); properties .put(DataContextPropertiesImpl.PROPERTY_URL, "http://" + dockerHostAddress + ":" + ElasticSearchRestDataContextIT.DEFAULT_REST_CLIENT_PORT); properties.put(DataContextPropertiesImpl.PROPERTY_DATABASE, INDEX_NAME); }
Source:
<code>private void initEnumValues() { if ( enumValues == null ) { Class<Enum<?>> returnedClass = coreEnumType.returnedClass(); <START> this.enumValues = returnedClass.getEnumConstants(); <END> if ( enumValues == null ) { throw new NullPointerException( "Failed to init enumValues" ); } } }</code><technical_language>I a difference 2 codes. is OK me</technical_language>

Target:
private void initEnumValues() { if ( enumValues == null ) { Class<? extends Enum<?>> returnedClass = coreEnumType.returnedClass(); this.enumValues = returnedClass.getEnumConstants(); if ( enumValues == null ) { throw new NullPointerException( "Failed to init enumValues" ); } } }
Source:
<code>private void scheduleRefreshAccessToken(long expireDateInMs) { <START> long refreshAfter = expireDateInMs - System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(10); <END> if (refreshAfter < 0) { RealmLog.debug("Expires time already reached for the access token, refreshing now"); refreshAccessToken(); } else { RealmLog.debug("Scheduling an access_token refresh in " + (refreshAfter) + " milliseconds"); if (refreshTokenTask != null) { refreshTokenTask.cancel(); } ScheduledFuture<?> task = REFRESH_TOKENS_EXECUTOR.schedule(new Runnable() { @Override public void run() { refreshAccessToken(); } }, refreshAfter, TimeUnit.MILLISECONDS); refreshTokenTask = new RealmAsyncTaskImpl(task, REFRESH_TOKENS_EXECUTOR); } }</code><technical_language>10 a constant</technical_language>

Target:
private void scheduleRefreshAccessToken(long expireDateInMs) { long refreshAfter = expireDateInMs - System.currentTimeMillis() - REFRESH_MARGIN_DELAY; if (refreshAfter < 0) { RealmLog.debug("Expires time already reached for the access token, refreshing now"); refreshAccessToken(); } else { RealmLog.debug("Scheduling an access_token refresh in " + (refreshAfter) + " milliseconds"); if (refreshTokenTask != null) { refreshTokenTask.cancel(); } ScheduledFuture<?> task = REFRESH_TOKENS_EXECUTOR.schedule(new Runnable() { @Override public void run() { refreshAccessToken(); } }, refreshAfter, TimeUnit.MILLISECONDS); refreshTokenTask = new RealmAsyncTaskImpl(task, REFRESH_TOKENS_EXECUTOR); } }
Source:
<code>public void performRequestDetailLineValidation(ConcurRequestExtractRequestDetailFileLine detailFileLine, List<String> uniqueRequestIdsInFile) { if (requestDetailFileLineIsCashAdvance(detailFileLine)) { boolean lineValidationPassed = true; lineValidationPassed = requestedCashAdvanceHasNotBeenClonedInFile(detailFileLine, uniqueRequestIdsInFile); LOG.info("requestedCashAdvanceHasNotBeenClonedInFile = " + lineValidationPassed); lineValidationPassed &= requestedCashAdvanceHasNotBeenUsedInExpenseReport(detailFileLine); LOG.info("requestedCashAdvanceHasNotBeenUsedInExpenseReport = " + lineValidationPassed); lineValidationPassed &= requestedCashAdvanceIsNotBeingDuplicated(detailFileLine); LOG.info("requestedCashAdvanceIsNotBeingDuplicated = " + lineValidationPassed); lineValidationPassed &= requestedCashAdvanceAccountingInformationIsValid(detailFileLine); <START> LOG.info("requestedCashAdvanceAccountingInformationIsValid = " + lineValidationPassed); <END> detailFileLine.getValidationResult().setValidCashAdvanceLine(lineValidationPassed); LOG.info("performRequestDetailLineValidation: Detail File Line validation : " + ((lineValidationPassed) ? "PASSED" : ("FAILED" + KFSConstants.NEWLINE + detailFileLine.toString()))); } }</code><technical_language>log statements include function name</technical_language>

Target:
public void performRequestDetailLineValidation(ConcurRequestExtractRequestDetailFileLine detailFileLine, List<String> uniqueRequestIdsInFile) { if (requestDetailFileLineIsCashAdvance(detailFileLine)) { boolean lineValidationPassed = true; lineValidationPassed = requestedCashAdvanceHasNotBeenClonedInFile(detailFileLine, uniqueRequestIdsInFile); LOG.info("performRequestDetailLineValidation: requestedCashAdvanceHasNotBeenClonedInFile = " + lineValidationPassed); lineValidationPassed &= requestedCashAdvanceHasNotBeenUsedInExpenseReport(detailFileLine); LOG.info("performRequestDetailLineValidation: requestedCashAdvanceHasNotBeenUsedInExpenseReport = " + lineValidationPassed); lineValidationPassed &= requestedCashAdvanceIsNotBeingDuplicated(detailFileLine); LOG.info("performRequestDetailLineValidation: requestedCashAdvanceIsNotBeingDuplicated = " + lineValidationPassed); lineValidationPassed &= requestedCashAdvanceAccountingInformationIsValid(detailFileLine); LOG.info("performRequestDetailLineValidation: requestedCashAdvanceAccountingInformationIsValid = " + lineValidationPassed); detailFileLine.getValidationResult().setValidCashAdvanceLine(lineValidationPassed); LOG.info("performRequestDetailLineValidation: Detail File Line validation : " + ((lineValidationPassed) ? "PASSED" : ("FAILED" + KFSConstants.NEWLINE + detailFileLine.toString()))); } }
Source:
<code>public static VarSimToolNamespace fromName(final String name) { if (name != null) { for (final VarSimToolNamespace varSimTool : values()) { if (varSimTool == Unknown) { continue; } <START> if (varSimTool.toolName.equals(name) || varSimTool.name().equalsIgnoreCase(name)) { <END> return varSimTool; } } } return Unknown; }</code><technical_language>This is trivial, retain varSimTool.name().equalsIgnoreCase(name)</technical_language>

Target:
public static VarSimToolNamespace fromName(final String name) { if (name != null) { for (final VarSimToolNamespace varSimTool : values()) { if (varSimTool == Unknown) { continue; } if (varSimTool.command.equals(name) || varSimTool.name().equalsIgnoreCase(name)) { return varSimTool; } if (varSimTool.commandAliases != null) { for (final String commandAlias : varSimTool.commandAliases) { if (commandAlias.equalsIgnoreCase(name)) { return varSimTool; } } } } } return Unknown; }
Source:
<code>private void fetchRequests(RequestRegistrationCallback<GetOperation> requestRegistrationCallback) { Iterator<ReplicaId> replicaIterator = operationTracker.getReplicaIterator(); while (replicaIterator.hasNext()) { ReplicaId replicaId = replicaIterator.next(); String hostname = replicaId.getDataNodeId().getHostname(); Port port = replicaId.getDataNodeId().getPortToConnectTo(); GetRequest getRequest = createGetRequest(blobId, getOperationFlag(), GetOptions.None); RequestInfo request = new RequestInfo(hostname, port, getRequest); int correlationId = getRequest.getCorrelationId(); correlationIdToGetRequestInfo.put(correlationId, new GetRequestInfo(replicaId, time.milliseconds())); requestRegistrationCallback.registerRequestToSend(this, request); replicaIterator.remove(); <START> if (RouterUtils.isRemoteReplica(routerConfig, replicaId)) { <END> routerMetrics.crossColoRequestCount.inc(); } routerMetrics.getDataNodeBasedMetrics(replicaId.getDataNodeId()).getBlobInfoRequestRate.mark(); } }</code><technical_language>Need a log.trace, in DeleteOperation</technical_language>

Target:
private void fetchRequests(RequestRegistrationCallback<GetOperation> requestRegistrationCallback) { Iterator<ReplicaId> replicaIterator = operationTracker.getReplicaIterator(); while (replicaIterator.hasNext()) { ReplicaId replicaId = replicaIterator.next(); String hostname = replicaId.getDataNodeId().getHostname(); Port port = replicaId.getDataNodeId().getPortToConnectTo(); GetRequest getRequest = createGetRequest(blobId, getOperationFlag(), GetOptions.None); RequestInfo request = new RequestInfo(hostname, port, getRequest); int correlationId = getRequest.getCorrelationId(); correlationIdToGetRequestInfo.put(correlationId, new GetRequestInfo(replicaId, time.milliseconds())); requestRegistrationCallback.registerRequestToSend(this, request); replicaIterator.remove(); if (RouterUtils.isRemoteReplica(routerConfig, replicaId)) { logger.trace("Making request to a remote replica in", replicaId.getDataNodeId().getDatacenterName()); routerMetrics.crossColoRequestCount.inc(); } routerMetrics.getDataNodeBasedMetrics(replicaId.getDataNodeId()).getBlobInfoRequestRate.mark(); } }