auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void storeStartingMachine( Pod createdPod, ObjectMeta toCreateMeta, Map<String, InternalMachineConfig> machineConfigs, KubernetesServerResolver serverResolver) throws InfrastructureException { final String workspaceId = getContext().getIdentity().getWorkspaceId(); for (Container container : createdPod.getSpec().getContainers()) { String machineName = Names.machineName(toCreateMeta, container); LOG.debug("Creating machine '{}' in workspace '{}'", machineName, workspaceId); Optional<InternalMachineConfig> machineConfigOpt = Optional .ofNullable(machineConfigs.get(machineName)); if (!machineConfigOpt.isPresent()) { LOG.error( "Workspace '{}' start failed. Machine with name '{}' requested but not found in configs map. Present machines are: {}.", workspaceId, machineName, String.join(",", machineConfigs.keySet())); throw new InfrastructureException(format( "Unable to start workspace '%s' due to internal error. Case will be investigated.", workspaceId)): } machines.put( getContext().getIdentity(), new KubernetesMachineImpl( workspaceId, machineName, createdPod.getMetadata().getName(), container.getName(), MachineStatus.STARTING, machineConfigOpt.get().getAttributes(), serverResolver.resolve(machineName))); eventPublisher.sendStartingEvent(machineName, getContext().getIdentity()); } }

Target:
private void storeStartingMachine( Pod createdPod, ObjectMeta toCreateMeta, Map<String, InternalMachineConfig> machineConfigs, KubernetesServerResolver serverResolver) throws InfrastructureException { final String workspaceId = getContext().getIdentity().getWorkspaceId(); for (Container container : createdPod.getSpec().getContainers()) { String machineName = Names.machineName(toCreateMeta, container); LOG.debug("Creating machine '{}' in workspace '{}'", machineName, workspaceId); InternalMachineConfig machineConfig = Optional.ofNullable(machineConfigs.get(machineName)) .orElseThrow( () -> { LOG.error( "Workspace '{}' start failed. Machine with name '{}' requested but not found in configs map. Present machines are: {}.", workspaceId, machineName, String.join(",", machineConfigs.keySet())); return new InfrastructureException( format( "Unable to start the workspace '%s' due to an internal inconsistency while composing the workspace runtime." + "Please report a bug. If possible, include the details from Che devfile and server log in bug report (your admin can help with that)", workspaceId)); }); machines.put( getContext().getIdentity(), new KubernetesMachineImpl( workspaceId, machineName, createdPod.getMetadata().getName(), container.getName(), MachineStatus.STARTING, machineConfig.getAttributes(), serverResolver.resolve(machineName))); eventPublisher.sendStartingEvent(machineName, getContext().getIdentity()); } }
Source:
protected void executeCommand() { updateOvfStoreContent(); int missingDiskCount = Config.<Integer> getValue(ConfigValues.StorageDomainOvfStoreCount) - ovfDiskCount; if (missingDiskCount > 0) { Backend.getInstance().runInternalAction(VdcActionType.CreateOvfStoresForStorageDomain, new CreateOvfStoresForStorageDomainCommandParameters(getParameters().getStoragePoolId(), getParameters().getStorageDomainId(), missingDiskCount)); } setSucceeded(true); }

Target:
protected void executeCommand() { updateOvfStoreContent(); int missingDiskCount = Config.<Integer> getValue(ConfigValues.StorageDomainOvfStoreCount) - ovfDiskCount; if (missingDiskCount > 0) { getBackend().runInternalAction(VdcActionType.CreateOvfStoresForStorageDomain, new CreateOvfStoresForStorageDomainCommandParameters(getParameters().getStoragePoolId(), getParameters().getStorageDomainId(), missingDiskCount)); } setSucceeded(true); }
Source:
public boolean addMetadataStoreRealm(String namespace, String realm) { synchronized (this) { if (!_routingDataWriterMap.containsKey(namespace)) { throw new NoSuchElementException( "Failed to add metadata store realm: Namespace " + namespace + " is not found!"); } boolean result = _routingDataWriterMap.get(namespace).addMetadataStoreRealm(realm); refreshRoutingData(namespace); return result; } }

Target:
public boolean addMetadataStoreRealm(String namespace, String realm) { if (!_routingDataWriterMap.containsKey(namespace)) { throw new NoSuchElementException( "Failed to add metadata store realm: Namespace " + namespace + " is not found!"); } synchronized (this) { boolean result = _routingDataWriterMap.get(namespace).addMetadataStoreRealm(realm); refreshRoutingData(namespace); return result; } }
Source:
public void groupBy(StructuredRecord record, Emitter<String> emitter) throws Exception { if (record.get(keyField) == null) { if (!record.getSchema().getField(keyField).getSchema().isNullable()) { throw new IllegalArgumentException("null value found for non-nullable field " + keyField); } return; } emitter.emit((String) record.get(keyField)); }

Target:
public void groupBy(StructuredRecord record, Emitter<String> emitter) throws Exception { if (record.get(keyField) == null) { if (record.getSchema().getField(keyField) == null) { throw new IllegalArgumentException( String.format("Keyfield '%s' does not exist in input schema %s", keyField, record.getSchema())); } return; } if (record.get(nameField) == null && record.getSchema().getField(nameField) == null) { throw new IllegalArgumentException( String.format("Namefield '%s' does not exist in input schema %s", nameField, record.getSchema())); } if (record.get(valueField) == null && record.getSchema().getField(valueField) == null) { throw new IllegalArgumentException( String.format("Valuefield '%s' does not exist in input schema %s", valueField, record.getSchema())); } emitter.emit((String) record.get(keyField)); }
Source:
public void exceedLimitTest() throws Exception { MarkableInputStream in = new MarkableInputStream(new ByteArrayInputStream( "ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes(Charset.forName("US-ASCII"))),true); assertThat(readBytes(in, 3)).isEqualTo("ABC"); long posA = in.savePosition(7); assertThat(readBytes(in, 4)).isEqualTo("DEFG"); in.mark(5); assertThat(readBytes(in, 4)).isEqualTo("HIJK"); in.reset(); assertThat(readBytes(in, 3)).isEqualTo("HIJ"); in.reset(posA); assertThat(readBytes(in, 7)).isEqualTo("DEFGHIJ"); in.reset(); assertThat(readBytes(in, 6)).isEqualTo("HIJKLM"); try { in.reset(); assertThat(readBytes(in, 2)).isEqualTo("HI"); } catch (IOException notexpected) { fail(); } try { in.reset(posA); assertThat(readBytes(in, 2)).isEqualTo("DE"); } catch (IOException notexpected) { fail(); } }

Target:
public void exceedLimitTest() throws Exception { MarkableInputStream in = new MarkableInputStream(new ByteArrayInputStream( "ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes(Charset.forName("US-ASCII")))); in.allowMarksToExpire(false); assertThat(readBytes(in, 3)).isEqualTo("ABC"); long posA = in.savePosition(7); assertThat(readBytes(in, 4)).isEqualTo("DEFG"); in.mark(5); assertThat(readBytes(in, 4)).isEqualTo("HIJK"); in.reset(); assertThat(readBytes(in, 3)).isEqualTo("HIJ"); in.reset(posA); assertThat(readBytes(in, 7)).isEqualTo("DEFGHIJ"); in.reset(); assertThat(readBytes(in, 6)).isEqualTo("HIJKLM"); in.reset(); assertThat(readBytes(in, 2)).isEqualTo("HI"); in.reset(posA); assertThat(readBytes(in, 2)).isEqualTo("DE"); }
Source:
public SearchEngine(String identifier, InputStream in) throws IOException, XmlPullParserException { this.identifier = identifier; try { final XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); parser.setInput(in, null); parser.nextTag(); readSearchPlugin(parser); } finally { in.close(); } }

Target:
public SearchEngine(String identifier, InputStream in) throws IOException, XmlPullParserException { this.identifier = identifier; final XmlPullParser parser = Xml.newPullParser(); parser.setInput(in, null); parser.nextTag(); readSearchPlugin(parser); }
Source:
public static FunctionHandle getFlippedFunctionHandle(CallExpression callExpression, FunctionManager functionManager) { FunctionMetadata callExpressionMetadata = functionManager.getFunctionMetadata(callExpression.getFunctionHandle()); checkArgument(callExpressionMetadata.getOperatorType().isPresent()); OperatorType operatorType = flip(callExpressionMetadata.getOperatorType().get()); FunctionHandle functionHandle = functionManager.resolveOperator( operatorType, swapPair(fromTypes(callExpression.getArguments().stream().map(RowExpression::getType).collect(toImmutableList())))); return functionHandle; }

Target:
public static FunctionHandle getFlippedFunctionHandle(CallExpression callExpression, FunctionManager functionManager) { FunctionMetadata callExpressionMetadata = functionManager.getFunctionMetadata(callExpression.getFunctionHandle()); checkArgument(callExpressionMetadata.getOperatorType().isPresent()); OperatorType operatorType = flip(callExpressionMetadata.getOperatorType().get()); List<TypeSignatureProvider> typeProviderList = fromTypes(callExpression.getArguments().stream().map(RowExpression::getType).collect(toImmutableList())); checkArgument(typeProviderList.size() == 2, "Expected there to be only two arguments in type provider"); return functionManager.resolveOperator( operatorType, ImmutableList.of(typeProviderList.get(1), typeProviderList.get(0))); }
Source:
public void initialise(String otherStatus, T value, Duration retryAfterDuration) { PollResponse<String> inProgressPollResponse = new PollResponse<>(PollResponse.OperationStatus.fromString("CUSTOM_OTHER_STATUS"), "my custom response", Duration.ofMillis(5000)); END: com.azure.core.util.polling.pollresponse.custom.status.retryAfter }

Target:
public void initialise(String otherStatus, T value, Duration retryAfterDuration) { PollResponse<String> inProgressPollResponse = new PollResponse<>(OperationStatus.fromString("CUSTOM_OTHER_STATUS"), "my custom response", Duration.ofMillis(5000)); END: com.azure.core.util.polling.pollresponse.custom.status.retryAfter }
Source:
public static synchronized Log getLog(Class clazz) { String logTag = clazz.getSimpleName(); if (logTag.length() > 23) { android.util.Log.w(TAG, "Truncating log tag length as it exceed 23, the limit imposed by android on certain API Levels"); logTag =logTag.substring(0, 23); } return getLog(logTag); }

Target:
public static synchronized Log getLog(Class clazz) { return getLog(getTruncatedLogTag(clazz.getSimpleName())); }
Source:
public Set<String> getAppliesToProfiles() { return myAppliesToProfiles; }

Target:
public Set<String> getAppliesToProfiles() { return Collections.unmodifiableSet(myAppliesToProfiles); }
Source:
public Module jacksonUserDeserializerModule() { return new SimpleModule("userDeserializerModule", new Version(1, 0, 0, null, "org.osiam", "scim-schema")) .addDeserializer(User.class, new UserDeserializer(User.SCHEMA)); }

Target:
public Module jacksonUserDeserializerModule() { return new SimpleModule("userDeserializerModule", new Version(1, 0, 0, null, "org.osiam", "osiam")) .addDeserializer(User.class, new UserDeserializer(User.SCHEMA)); }
Source:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { BigDecimal finalResult = BigDecimal.ZERO; for(int i=0; i<children.size(); i++) { if (!children.get(i).evaluate(tuple, ptr)) { return false; } if (ptr.getLength() == 0) { return true; } BigDecimal value; PDataType type = children.get(i).getDataType(); ColumnModifier columnModifier = children.get(i).getColumnModifier(); if(type == PDataType.TIMESTAMP) { Timestamp timestamp = (Timestamp)PDataType.TIMESTAMP.toObject(ptr, columnModifier); long millisPart = timestamp.getTime(); BigDecimal nanosPart = BigDecimal.valueOf((timestamp.getNanos() % QueryConstants.MILLIS_TO_NANOS_CONVERTOR)/QueryConstants.MILLIS_TO_NANOS_CONVERTOR); value = BigDecimal.valueOf(millisPart).add(nanosPart); } else if (type.isCoercibleTo(PDataType.DECIMAL)) { value = (((BigDecimal)PDataType.DECIMAL.toObject(ptr, columnModifier)).multiply(QueryConstants.BD_MILLIS_IN_DAY)).setScale(6, RoundingMode.HALF_UP); } else if (type.isCoercibleTo(PDataType.DOUBLE)) { value = ((BigDecimal.valueOf(type.getCodec().decodeDouble(ptr, columnModifier))).multiply(QueryConstants.BD_MILLIS_IN_DAY)).setScale(6, RoundingMode.HALF_UP); } else { value = BigDecimal.valueOf(type.getCodec().decodeLong(ptr, columnModifier)); } finalResult = finalResult.add(value); } Timestamp ts = DateUtil.getTimestamp(finalResult.longValue(), ((finalResult.remainder(BigDecimal.ONE).multiply(BigDecimal.valueOf(QueryConstants.MILLIS_TO_NANOS_CONVERTOR))).intValue())); byte[] resultPtr = new byte[getDataType().getByteSize()]; PDataType.TIMESTAMP.toBytes(ts, resultPtr, 0); ptr.set(resultPtr); return true; }

Target:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { BigDecimal finalResult = BigDecimal.ZERO; for(int i=0; i<children.size(); i++) { if (!children.get(i).evaluate(tuple, ptr)) { return false; } if (ptr.getLength() == 0) { return true; } BigDecimal value; PDataType type = children.get(i).getDataType(); ColumnModifier columnModifier = children.get(i).getColumnModifier(); if(type == PDataType.TIMESTAMP) { value = (BigDecimal)(PDataType.DECIMAL.toObject(ptr, PDataType.TIMESTAMP, columnModifier)); } else if (type.isCoercibleTo(PDataType.DECIMAL)) { value = (((BigDecimal)PDataType.DECIMAL.toObject(ptr, columnModifier)).multiply(QueryConstants.BD_MILLIS_IN_DAY)).setScale(6, RoundingMode.HALF_UP); } else if (type.isCoercibleTo(PDataType.DOUBLE)) { value = ((BigDecimal.valueOf(type.getCodec().decodeDouble(ptr, columnModifier))).multiply(QueryConstants.BD_MILLIS_IN_DAY)).setScale(6, RoundingMode.HALF_UP); } else { value = BigDecimal.valueOf(type.getCodec().decodeLong(ptr, columnModifier)); } finalResult = finalResult.add(value); } Timestamp ts = DateUtil.getTimestamp(finalResult); byte[] resultPtr = new byte[getDataType().getByteSize()]; PDataType.TIMESTAMP.toBytes(ts, resultPtr, 0); ptr.set(resultPtr); return true; }
Source:
private void createSmallBam(final File outputFile) { final SAMFileWriterFactory factory = new SAMFileWriterFactory(); factory.setCreateIndex(true); factory.setCreateMd5File(true); final SAMFileHeader header = new SAMFileHeader(); header.setSortOrder(SAMFileHeader.SortOrder.coordinate); header.addSequence(new SAMSequenceRecord("chr1", 123)); final SAMFileWriter writer = factory.makeBAMWriter(header, false, outputFile); fillSmallBam(writer); writer.close(); }

Target:
private void createSmallBam(final File outputFile) { final SAMFileWriterFactory factory = new SAMFileWriterFactory(); factory.setCreateIndex(true); factory.setCreateMd5File(true); final SAMFileHeader header = new SAMFileHeader(); header.setSortOrder(SAMFileHeader.SortOrder.coordinate); header.addSequence(new SAMSequenceRecord("chr1", 123)); try (final SAMFileWriter writer = factory.makeBAMWriter(header, false, outputFile)) { fillSmallBam(writer); } }
Source:
public JsonNode toJsonNode(Object json) throws Exception { if (json instanceof String) { return this.objectMapper.readTree((String) json); } else if (json instanceof byte[]) { return this.objectMapper.readTree((byte[]) json); } else if (json instanceof File) { return this.objectMapper.readTree((File) json); } else if (json instanceof URL) { return this.objectMapper.readTree((URL) json); } else if (json instanceof InputStream) { return this.objectMapper.readTree((InputStream) json); } else if (json instanceof Reader) { return this.objectMapper.readTree((Reader) json); } else { return this.objectMapper.valueToTree(json); } }

Target:
public JsonNode toJsonNode(Object json) throws Exception { try { if (json instanceof String) { return this.objectMapper.readTree((String) json); } else if (json instanceof byte[]) { return this.objectMapper.readTree((byte[]) json); } else if (json instanceof File) { return this.objectMapper.readTree((File) json); } else if (json instanceof URL) { return this.objectMapper.readTree((URL) json); } else if (json instanceof InputStream) { return this.objectMapper.readTree((InputStream) json); } else if (json instanceof Reader) { return this.objectMapper.readTree((Reader) json); } } catch (JsonParseException e) { if (!(json instanceof String) && !(json instanceof byte[])) { throw e; } } return this.objectMapper.valueToTree(json); }
Source:
public void render(Context context, T value, SafeHtmlBuilder sb) { cellImage.getElement().setAttribute("name", CELL_IMAGE_NAME); sb.appendHtmlConstant("<div>" + cellImage.toString() + "</div>"); }

Target:
public void render(Context context, T value, SafeHtmlBuilder sb) { image = this.column.getImage(value); image.getElement().setAttribute("name", CELL_IMAGE_NAME); sb.append(template.openContainerTag()); sb.appendHtmlConstant(image.toString()); sb.append(template.closeContainerTag()); }
Source:
public void deleteComment(CoreSession session, String commentId) throws CommentNotFoundException, CommentSecurityException { IdRef commentRef = new IdRef(commentId); if (!CoreInstance.doPrivileged(session, s -> {return s.exists(commentRef);})) { throw new CommentNotFoundException("The comment " + commentId + " does not exist."); } NuxeoPrincipal principal = session.getPrincipal(); CoreInstance.doPrivileged(session, s -> { DocumentModel comment = s.getDocument(commentRef); String parentId = (String) comment.getPropertyValue(COMMENT_PARENT_ID); DocumentRef ancestorRef = getTopLevelCommentAncestor(s, commentRef); if (s.exists(ancestorRef) && !principal.isAdministrator() && !comment.getPropertyValue(COMMENT_AUTHOR).equals(principal.getName()) && !s.hasPermission(principal, ancestorRef, SecurityConstants.EVERYTHING)) { throw new CommentSecurityException( "The user " + principal.getName() + " can not delete comments of document " + parentId); } comment.detach(true); s.removeDocument(commentRef); notifyEvent(s, comment, CommentEvents.COMMENT_REMOVED); }); }

Target:
public void deleteComment(CoreSession session, String commentId) throws CommentNotFoundException, CommentSecurityException { IdRef commentRef = new IdRef(commentId); if (!CoreInstance.doPrivileged(session, s -> {return s.exists(commentRef);})) { throw new CommentNotFoundException("The comment " + commentId + " does not exist."); } NuxeoPrincipal principal = session.getPrincipal(); CoreInstance.doPrivileged(session, s -> { DocumentModel comment = s.getDocument(commentRef); String parentId = (String) comment.getPropertyValue(COMMENT_PARENT_ID); DocumentRef ancestorRef = getTopLevelCommentAncestor(s, commentRef); if (s.exists(ancestorRef) && !principal.isAdministrator() && !comment.getPropertyValue(COMMENT_AUTHOR).equals(principal.getName()) && !s.hasPermission(principal, ancestorRef, SecurityConstants.EVERYTHING)) { throw new CommentSecurityException( "The user " + principal.getName() + " can not delete comments of document " + parentId); } comment.detach(true); s.removeDocument(commentRef); notifyEvent(s, CommentEvents.COMMENT_REMOVED, comment); }); }
Source:
public ClearResponse send(DistributedMember recipient, PartitionedRegion region) throws ForceReattemptException { Set recipients = Collections.singleton(recipient); ClearResponse clearResponse = new ClearResponse(region.getSystem(), recipients); initMessage(region, recipients, clearResponse); if (logger.isDebugEnabled()) { logger.debug("ClearPRMessage.send: recipient is {}, msg is {}", recipient, this); } Set<InternalDistributedMember> failures = region.getDistributionManager().putOutgoing(this); if (failures != null && failures.size() > 0) { throw new ForceReattemptException("Failed sending <" + this + ">"); } return clearResponse; }

Target:
public ClearResponse send(DistributedMember recipient, PartitionedRegion region) throws ForceReattemptException { Set<InternalDistributedMember> recipients = Collections.singleton((InternalDistributedMember) recipient); ClearResponse clearResponse = new ClearResponse(region.getSystem(), recipients); initMessage(region, recipients, clearResponse); if (logger.isDebugEnabled()) { logger.debug("ClearPRMessage.send: recipient is {}, msg is {}", recipient, this); } Set<InternalDistributedMember> failures = region.getDistributionManager().putOutgoing(this); if (failures != null && failures.size() > 0) { throw new ForceReattemptException("Failed sending <" + this + "> due to " + failures); } return clearResponse; }
Source:
public boolean prepare() throws Exception { if (!prepared) { prepared = true; super.prepare(); ProjectLauncher launcher = getProjectLauncher(); if (port > 0) { launcher.getRunProperties() .put(TESTER_PORT, "" + port); if (host != null) launcher.getRunProperties() .put(TESTER_HOST, "" + host); } launcher.getRunProperties() .put(TESTER_UNRESOLVED, getProject().getProperty(Constants.TESTUNRESOLVED, "true")); launcher.getRunProperties() .put(TESTER_DIR, getReportDir().getAbsolutePath()); launcher.getRunProperties() .put(TESTER_CONTINUOUS, "" + getContinuous()); if (getProject().is(Constants.RUNTRACE)) launcher.getRunProperties() .put(TESTER_TRACE, "true"); Collection<String> testnames = getTests(); if (testnames.size() > 0) { launcher.getRunProperties() .put(TESTER_NAMES, Processor.join(testnames.stream() .map(ProjectTesterImpl::maybeQuote) .collect(Collectors.toList()))); } launcher.addRunBundle(me.getFile() .getAbsolutePath()); launcher.prepare(); } return true; }

Target:
public boolean prepare() throws Exception { if (!prepared) { prepared = true; super.prepare(); ProjectLauncher launcher = getProjectLauncher(); if (port > 0) { launcher.getRunProperties() .put(TESTER_PORT, "" + port); if (host != null) launcher.getRunProperties() .put(TESTER_HOST, "" + host); } launcher.getRunProperties() .put(TESTER_UNRESOLVED, getProject().getProperty(Constants.TESTUNRESOLVED, "true")); launcher.getRunProperties() .put(TESTER_DIR, getReportDir().getAbsolutePath()); launcher.getRunProperties() .put(TESTER_CONTINUOUS, "" + getContinuous()); if (getProject().is(Constants.RUNTRACE)) launcher.getRunProperties() .put(TESTER_TRACE, "true"); Collection<String> testnames = getTests(); if (testnames.size() > 0) { launcher.getRunProperties() .put(TESTER_NAMES, testnames.stream() .map(ProjectTesterImpl::maybeQuote) .collect(Collectors.joining(","))); } launcher.addRunBundle(me.getFile() .getAbsolutePath()); launcher.prepare(); } return true; }
Source:
public long[] getFinalTallies(String platform, String intervals[]) { try (Jedis jedis = jedisPool.getWriteResource()) { long tallies[] = new long[intervals.length]; for (int i = 0; i < intervals.length; i++) { tallies[i] = Long.valueOf(jedis.get(tallyKey(platform, intervals[i]))); } return tallies; } }

Target:
public long[] getFinalTallies(String platform, String intervals[]) { try (Jedis jedis = jedisPool.getReadResource()) { long tallies[] = new long[intervals.length]; for (int i = 0; i < intervals.length; i++) { tallies[i] = Long.valueOf(jedis.get(tallyKey(platform, intervals[i]))); } return tallies; } }
Source:
public TaskSelectionDialog(Shell parent, boolean multi) { super(parent, multi); this.taskActivationHistory = TasksUiPlugin.getTaskActivityManager().getTaskActivationHistory(); this.history = new LinkedHashSet<AbstractTask>(taskActivationHistory.getPreviousTasks()); this.itemsComparator = new TaskHistoryItemsComparator(new ArrayList<AbstractTask>(history)); this.needsCreateTask = true; this.labelProvider = new TaskElementLabelProvider(false); this.showCompletedTasksAction = new ShowCompletedTasksAction(); setSelectionHistory(new TaskSelectionHistory()); setListLabelProvider(labelProvider); setDetailsLabelProvider(new TaskDetailLabelProvider()); setSeparatorLabel(TaskListView.LABEL_VIEW + Messages.TaskSelectionDialog__matches); IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); ISelection selection = window.getSelectionService().getSelection(); if (selection instanceof ITextSelection) { String text = ((ITextSelection) selection).getText(); Strings.nullToEmpty(text); int n = text.indexOf('\n'); if (n > -1) { text = text.substring(0, n); } setInitialPattern(text); } windowWorkingSet = window.getActivePage().getAggregateWorkingSet(); selectedWorkingSet = windowWorkingSet; PlatformUI.getWorkbench().getWorkingSetManager().addPropertyChangeListener(workingSetListener); }

Target:
public TaskSelectionDialog(Shell parent, boolean multi) { super(parent, multi); this.taskActivationHistory = TasksUiPlugin.getTaskActivityManager().getTaskActivationHistory(); this.history = new LinkedHashSet<AbstractTask>(taskActivationHistory.getPreviousTasks()); this.itemsComparator = new TaskHistoryItemsComparator(new ArrayList<AbstractTask>(history)); this.needsCreateTask = true; this.labelProvider = new TaskElementLabelProvider(false); this.showCompletedTasksAction = new ShowCompletedTasksAction(); setSelectionHistory(new TaskSelectionHistory()); setListLabelProvider(labelProvider); setDetailsLabelProvider(new TaskDetailLabelProvider()); setSeparatorLabel(TaskListView.LABEL_VIEW + Messages.TaskSelectionDialog__matches); IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); ISelection selection = window.getSelectionService().getSelection(); if (selection instanceof ITextSelection) { String text = ((ITextSelection) selection).getText(); text = Strings.nullToEmpty(text); int n = text.indexOf('\n'); if (n > -1) { text = text.substring(0, n); } setInitialPattern(text); } windowWorkingSet = window.getActivePage().getAggregateWorkingSet(); selectedWorkingSet = windowWorkingSet; PlatformUI.getWorkbench().getWorkingSetManager().addPropertyChangeListener(workingSetListener); }
Source:
public void initFailureTest() throws Exception { alloc = constructAllocator(); alloc.initializePool(Collections.singletonList(new DiskSpaceRequirements(50, 2, 0))); verifyPoolState(new ExpectedState().add(50, 2)); File fileSizeDir = new File(reserveFileDir, DiskSpaceAllocator.generateFileSizeDirName(50)); alloc = constructAllocator(); assertTrue("Could not make non-writable", fileSizeDir.setWritable(false)); try { alloc.initializePool(Collections.emptyList()); fail("Expected StoreException"); } catch (StoreException e) { assertEquals("Wrong error code", StoreErrorCodes.Initialization_Error, e.getErrorCode()); } finally { assertTrue("Could not make writable again", fileSizeDir.setWritable(true)); } alloc = constructAllocator(); assertTrue("Could not make non-writable", fileSizeDir.setWritable(false)); try { alloc.initializePool(Collections.singletonList(new DiskSpaceRequirements(50, 1, 0))); fail("Expected StoreException"); } catch (StoreException e) { assertEquals("Wrong error code", StoreErrorCodes.Initialization_Error, e.getErrorCode()); } finally { assertTrue("Could not make writable again", fileSizeDir.setWritable(true)); } }

Target:
public void initFailureTest() throws Exception { alloc = constructAllocator(); alloc.initializePool(Collections.singletonList(new DiskSpaceRequirements(50, 2, 0))); verifyPoolState(new ExpectedState().add(50, 2)); runInitFailureTest(reserveFileDir, false); File fileSizeDir = new File(reserveFileDir, DiskSpaceAllocator.generateFileSizeDirName(50)); runInitFailureTest(fileSizeDir, false, new DiskSpaceRequirements(50, 1, 0)); runInitFailureTest(reserveFileDir, true); }
Source:
public ExtendedUser(final ByteBuf buffer) throws InvalidPacketException { this.src_charset = new Charset(buffer); this.src_user = new Opaque(buffer, Optional.empty(), buffer1 -> Opaque.parseBytes(buffer1)); this.dst_charset = new Charset(buffer); this.dst_user = new Opaque(buffer, Optional.empty(), buffer1 -> Opaque.parseBytes(buffer1)); }

Target:
public ExtendedUser(final ByteBuf buffer) throws InvalidPacketException { this.src_charset = new Charset(buffer); this.src_user = new Opaque(buffer, Optional.empty(), Opaque::parseBytes); this.dst_charset = new Charset(buffer); this.dst_user = new Opaque(buffer, Optional.empty(), Opaque::parseBytes); }
Source:
public Guid getEntityGuid(Object entity) { if (entity instanceof BusinessEntity) { return getEntityGuid((BusinessEntity<? extends Guid>) entity); } if (entity instanceof VmPool) { return ((VmPool) entity).getVmPoolId(); } else if (entity instanceof DbUser) { return ((DbUser) entity).getId(); } else if (entity instanceof DbGroup) { return ((DbGroup) entity).getId(); } else { return Guid.Empty; } }

Target:
public Guid getEntityGuid(Object entity) { if (entity instanceof BusinessEntity) { Object id = getEntityGuid((BusinessEntity<? extends Guid>) entity); if (id instanceof Guid) { return (Guid) id; } } if (entity instanceof VmPool) { return ((VmPool) entity).getVmPoolId(); } else if (entity instanceof DbUser) { return ((DbUser) entity).getId(); } else if (entity instanceof DbGroup) { return ((DbGroup) entity).getId(); } else { return Guid.Empty; } }
Source:
private void attachRemoteDebugger(IServer server, int localDebugPort, IProgressMonitor monitor) throws CoreException { monitor.subTask("Attaching remote debugger"); OpenShiftDebugUtils debugUtils = OpenShiftDebugUtils.get(); ILaunchConfiguration debuggerLaunchConfig = debugUtils.getRemoteDebuggerLaunchConfiguration(server); ILaunchConfigurationWorkingCopy workingCopy; if (debuggerLaunchConfig == null) { workingCopy = debugUtils.createRemoteDebuggerLaunchConfiguration(server); } else { if (debugUtils.isRunning(debuggerLaunchConfig, localDebugPort)) { return; } workingCopy = debuggerLaunchConfig.getWorkingCopy(); } IProject project = OpenShiftServerUtils.getDeployProject(server); debugUtils.setupRemoteDebuggerLaunchConfiguration(workingCopy, project, localDebugPort); debuggerLaunchConfig = workingCopy.doSave(); long elapsed = 0; long increment = 1_000; long maxWait = 60_000; boolean launched = false; monitor.subTask("Waiting for remote debug port availability"); while(!launched && elapsed < maxWait) { try { debuggerLaunchConfig.launch("debug", new NullProgressMonitor()); launched = true; } catch (Exception e) { if (monitor.isCanceled()) { break; } try { Thread.sleep(increment); elapsed+=increment; } catch (InterruptedException ie) { } } } if (!launched){ throw toCoreException("Unable to start a remote debugger to localhost:"+localDebugPort); } monitor.worked(10); }

Target:
private void attachRemoteDebugger(IServer server, int localDebugPort, IProgressMonitor monitor) throws CoreException { monitor.subTask("Attaching remote debugger"); OpenShiftDebugUtils debugUtils = OpenShiftDebugUtils.get(); ILaunchConfiguration debuggerLaunchConfig = debugUtils.getRemoteDebuggerLaunchConfiguration(server); ILaunchConfigurationWorkingCopy workingCopy; if (debuggerLaunchConfig == null) { workingCopy = debugUtils.createRemoteDebuggerLaunchConfiguration(server); } else { if (debugUtils.isRunning(debuggerLaunchConfig, localDebugPort)) { return; } workingCopy = debuggerLaunchConfig.getWorkingCopy(); } IProject project = OpenShiftServerUtils.getDeployProject(server); debugUtils.setupRemoteDebuggerLaunchConfiguration(workingCopy, project, localDebugPort); debuggerLaunchConfig = workingCopy.doSave(); long elapsed = 0; long increment = 1_000; long maxWait = 60_000; boolean launched = false; monitor.subTask("Waiting for remote debug port availability"); while(!launched && elapsed < maxWait) { try { debuggerLaunchConfig.launch(DEBUG_MODE, new NullProgressMonitor()); launched = true; } catch (Exception e) { if (monitor.isCanceled()) { break; } try { Thread.sleep(increment); elapsed+=increment; } catch (InterruptedException ie) { } } } if (!launched){ throw toCoreException("Unable to start a remote debugger to localhost:"+localDebugPort); } monitor.worked(10); }
Source:
public boolean readProtobuf(ProtobufWritable<M> message) throws Exception { return readNext(message); }

Target:
public boolean readProtobuf(ProtobufWritable<M> message) throws IOException { return readNext(message); }
Source:
public User formBackingObject(WebRequest request, @RequestParam(required = false, value = "person_id") Integer personId) { String userId = request.getParameter("userId"); User u = null; try { u = Context.getUserService().getUser(Integer.valueOf(userId)); } catch (Exception ex) { log.debug ("Error while getting user",ex); } if (u == null) { u = new User(); } if (personId != null) { u.setPerson(Context.getPersonService().getPerson(personId)); } else if (u.getPerson() == null) { Person p = new Person(); p.addName(new PersonName()); u.setPerson(p); } return u; }

Target:
public User formBackingObject(WebRequest request, @RequestParam(required = false, value = "person_id") Integer personId) { String userId = request.getParameter("userId"); User u = null; try { u = Context.getUserService().getUser(Integer.valueOf(userId)); } catch (Exception ex) { log.error ("Error while getting user", ex); } if (u == null) { u = new User(); } if (personId != null) { u.setPerson(Context.getPersonService().getPerson(personId)); } else if (u.getPerson() == null) { Person p = new Person(); p.addName(new PersonName()); u.setPerson(p); } return u; }
Source:
public SourceOperatorStreamTask(Environment env) throws Exception { super(env); this.isExternallyInducedSource = false; }

Target:
public SourceOperatorStreamTask(Environment env) throws Exception { super(env); }
Source:
public void testInessentialChildrenFailureDoesNotAbortSecondaryOrFailPrimary() { Task<String> t1 = monitorableTask(null, "1", new FailCallable()); TaskTags.markInessential(t1); Task<String> t = Tasks.<String>builder().dynamic(true) .body(monitorableJob("main")) .add(t1).add(monitorableTask("2")).build(); ec.submit(t); releaseMonitorableJob("1"); waitForMessage("1"); Assert.assertFalse(t.blockUntilEnded(TINY_TIME)); releaseMonitorableJob("2"); Assert.assertFalse(t.blockUntilEnded(TINY_TIME)); releaseMonitorableJob("main"); Assert.assertTrue(t.blockUntilEnded(TIMEOUT)); Assert.assertEquals(messages, MutableList.of("1", "2", "main")); Assert.assertTrue(stopwatch.elapsed(TimeUnit.MILLISECONDS) < TIMEOUT.toMilliseconds(), "took too long: "+stopwatch); Assert.assertFalse(t.isError()); Assert.assertTrue(t1.isError()); }

Target:
public void testInessentialChildrenFailureDoesNotAbortSecondaryOrFailPrimary() { Task<String> t1 = monitorableTask(null, "1", new FailCallable()); TaskTags.markInessential(t1); Task<String> t = Tasks.<String>builder().dynamic(true) .body(monitorableJob("main")) .add(t1).add(monitorableTask("2")).build(); ec.submit(t); releaseMonitorableJob("1"); waitForMessage("1"); Assert.assertFalse(t.blockUntilEnded(TINY_TIME)); releaseMonitorableJob("2"); waitForMessage("2"); Assert.assertFalse(t.blockUntilEnded(TINY_TIME)); releaseMonitorableJob("main"); Assert.assertTrue(t.blockUntilEnded(TIMEOUT)); Assert.assertEquals(messages, MutableList.of("1", "2", "main")); Assert.assertTrue(stopwatch.elapsed(TimeUnit.MILLISECONDS) < TIMEOUT.toMilliseconds(), "took too long: "+stopwatch); Assert.assertFalse(t.isError()); Assert.assertTrue(t1.isError()); }
Source:
private void checkNotAlreadyRegistered(Class<? extends Message> stateClass) { RepositoryAccess alreadyRegistered = repositories.get(stateClass); if (alreadyRegistered != null) { throw newIllegalStateException( "A repository for the state class %s already registered: %s", stateClass.getName(), alreadyRegistered); } }

Target:
private void checkNotAlreadyRegistered(Class<? extends Message> stateClass) { RepositoryAccess alreadyRegistered = repositories.get(stateClass); if (alreadyRegistered != null) { throw newIllegalStateException( "A repository for the state class %s already registered: `%s`.", stateClass.getName(), alreadyRegistered ); } }
Source:
public Action onApplicationHeartbeat(final int libraryId, final int aeronSessionId) { final LiveLibraryInfo library = idToLibrary.get(libraryId); if (library != null) { final long timeInMs = clock.time(); DebugLogger.log( APPLICATION_HEARTBEAT, "Received Heartbeat from library %d at timeInMs %d%n", libraryId, timeInMs); library.onHeartbeat(timeInMs); return CONTINUE; } return ABORT; }

Target:
public Action onApplicationHeartbeat(final int libraryId, final int aeronSessionId) { final LiveLibraryInfo library = idToLibrary.get(libraryId); if (library != null) { final long timeInMs = clock.time(); DebugLogger.log( APPLICATION_HEARTBEAT, "Received Heartbeat from library %d at timeInMs %d%n", libraryId, timeInMs); library.onHeartbeat(timeInMs); return null; } return CONTINUE; }
Source:
public HermesClient build() { if (retryCondition == null) { retryCondition = new HermesClientBasicRetryCondition(); } return new HermesClient(sender, uri, retries, retryCondition); }

Target:
public HermesClient build() { return new HermesClient(sender, uri, retries, retryCondition); }
Source:
public void testPurgeTxnLogWhenRecentSnapshotsAreAllInvalid() throws Exception { tmpDir = ClientBase.createTmpDir(); File dataDir = new File(tmpDir, "dataDir"); File dataLogDir = new File(tmpDir, "dataLogDir"); File dataDirVersion2 = new File(dataDir, "version-2"); dataDirVersion2.mkdirs(); File dataLogDirVersion2 = new File(dataLogDir, "version-2"); dataLogDirVersion2.mkdirs(); int totalFiles = 10; int numberOfSnapFilesToKeep = 3; for (int i = 0; i < totalFiles; i++) { File logFile = new File(dataLogDirVersion2, "log." + Long.toHexString(i)); logFile.createNewFile(); File snapFile = new File(dataDirVersion2, "snapshot." + Long.toHexString(i)); snapFile.createNewFile(); if (i < (totalFiles - numberOfSnapFilesToKeep)) { makeValidSnapshot(snapFile); } else { makeInvalidSnapshot(snapFile); } } String[] args = new String[]{dataLogDir.getAbsolutePath(), dataDir.getAbsolutePath(), "-n", Integer.toString(numberOfSnapFilesToKeep)}; PurgeTxnLog.main(args); assertEquals(numberOfSnapFilesToKeep + numberOfSnapFilesToKeep, dataDirVersion2.listFiles().length); assertEquals(numberOfSnapFilesToKeep + numberOfSnapFilesToKeep, dataLogDirVersion2.listFiles().length); ClientBase.recursiveDelete(tmpDir); }

Target:
public void testPurgeTxnLogWhenRecentSnapshotsAreAllInvalid() throws Exception { File dataDir = new File(tmpDir, "dataDir"); File dataLogDir = new File(tmpDir, "dataLogDir"); File dataDirVersion2 = new File(dataDir, "version-2"); dataDirVersion2.mkdirs(); File dataLogDirVersion2 = new File(dataLogDir, "version-2"); dataLogDirVersion2.mkdirs(); int totalFiles = 10; int numberOfSnapFilesToKeep = 3; for (int i = 0; i < totalFiles; i++) { File logFile = new File(dataLogDirVersion2, "log." + Long.toHexString(i)); logFile.createNewFile(); File snapFile = new File(dataDirVersion2, "snapshot." + Long.toHexString(i)); snapFile.createNewFile(); if (i < (totalFiles - numberOfSnapFilesToKeep)) { makeValidSnapshot(snapFile); } else { makeInvalidSnapshot(snapFile); } } String[] args = new String[]{dataLogDir.getAbsolutePath(), dataDir.getAbsolutePath(), "-n", Integer.toString(numberOfSnapFilesToKeep)}; PurgeTxnLog.main(args); assertEquals(numberOfSnapFilesToKeep + numberOfSnapFilesToKeep, dataDirVersion2.listFiles().length); assertEquals(numberOfSnapFilesToKeep + numberOfSnapFilesToKeep, dataLogDirVersion2.listFiles().length); }
Source:
public static String manageDouble(Double d) { if (d == (long) (double) d) { return String.format("%d", (long) (double) d); } else { return String.format("%s", d); } }

Target:
public static String manageDouble(Double d) { Objects.requireNonNull(d); long longValue = d.longValue(); if (d == longValue) { return String.format("%d", longValue); } else { return String.format("%s", d); } }
Source:
public synchronized void start(LeaderContender contender) { assert(!getStartFuture().isDone()); this.contender = contender; if (hasLeadership) { CompletableFuture.runAsync(() -> contender.grantLeadership(issuedLeaderSessionId), leaderElectorExecutor); } startFuture.complete(null); }

Target:
public synchronized void start(LeaderContender contender) { assert(!getStartFuture().isDone()); this.contender = contender; if (hasLeadership) { contender.grantLeadership(issuedLeaderSessionId); } startFuture.complete(null); }
Source:
public static boolean allow(String input, IPet pet) { YAMLConfig config = ConfigOptions.instance.getConfig(); String nameToCheck = ChatColor.stripColor(input); ConfigurationSection cs = config.getConfigurationSection("petNames"); if (cs != null) { for (String key : cs.getKeys(false)) { if (key.equalsIgnoreCase(nameToCheck)) { String value = config.getString("petNames." + key); return pet.getOwner().hasPermission("echopet.pet.name.override") || !(value.equalsIgnoreCase("deny") || value.equalsIgnoreCase("false")); } } } if (config.getBoolean("petNamesRegexMatching")) { ConfigurationSection csRegex = config.getConfigurationSection("petNamesRegex"); if (csRegex != null) { for (String key : csRegex.getKeys(false)) { if (key.matches(nameToCheck)) { String value = config.getString("petNames." + key); return pet.getOwner().hasPermission("echopet.pet.name.override") || !(value.equalsIgnoreCase("deny") || value.equalsIgnoreCase("false")); } } } } return true; }

Target:
public static boolean allow(String input, IPet pet) { YAMLConfig config = ConfigOptions.instance.getConfig(); String nameToCheck = ChatColor.stripColor(input); ConfigurationSection cs = config.getConfigurationSection("petNames"); if (cs != null) { for (String key : cs.getKeys(false)) { if (key.equalsIgnoreCase(nameToCheck)) { String value = config.getString("petNames." + key); return pet.getOwner().hasPermission("echopet.pet.name.override") || !(value.equalsIgnoreCase("deny") || value.equalsIgnoreCase("false")); } } } if (config.getBoolean("petNamesRegexMatching")) { List<Map<String, String>> csRegex = (List<Map<String, String>>) config.get("petNamesRegex"); if (!csRegex.isEmpty()) { for (Map<String, String> regexMap : csRegex) { for (Map.Entry<String, String> entry : regexMap.entrySet()) { if (nameToCheck.matches(entry.getKey())) { return pet.getOwner().hasPermission("echopet.pet.name.override") || !(entry.getValue().equalsIgnoreCase("deny") || entry.getValue().equalsIgnoreCase("false")); } } } } } return true; }
Source:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 3) { throw new IllegalArgumentException("function 'if' needs 3 argument"); } ExprEval x = args.get(0).eval(bindings); return x.asBoolean() ? args.get(1).eval(bindings) : args.get(2).eval(bindings); }

Target:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 3) { throw new IAE("function 'if' needs 3 arguments"); } ExprEval x = args.get(0).eval(bindings); return x.asBoolean() ? args.get(1).eval(bindings) : args.get(2).eval(bindings); }
Source:
public void encodeLink(String link, HierarchicalStreamWriter writer) { String path = request.getRequestURI(); if (path.contains("script")) { try { link = URLDecoder.decode(link, "UTF-8"); encodeAlternateAtomLinkNoExt(link, writer); writer.addAttribute("type", getMediaType()); writer.endNode(); } catch (UnsupportedEncodingException e) { } } else { encodeAlternateAtomLink(link, writer); } }

Target:
public void encodeLink(String link, HierarchicalStreamWriter writer) { if (checkPath(request)) { try { link = URLDecoder.decode(link, "UTF-8"); encodeAlternateAtomLinkNoExt(link, writer); writer.addAttribute("type", getMediaType()); writer.endNode(); } catch (UnsupportedEncodingException e) { } } else { encodeAlternateAtomLink(link, writer); } }
Source:
private static boolean testValue(Type type, Object value, TupleDomainFilter filter) { if (value == null) { return filter.testNull(); } if (filter == IS_NULL) { return false; } if (filter == IS_NOT_NULL) { return true; } if (type == BOOLEAN) { return filter.testBoolean((Boolean) value); } if (type == TINYINT || type == BIGINT || type == INTEGER || type == SMALLINT) { return filter.testLong(((Number) value).longValue()); } if (type == REAL) { return filter.testFloat(((Number) value).floatValue()); } if (type == DOUBLE) { return filter.testDouble((double) value); } if (type == DATE) { return filter.testLong(((SqlDate) value).getDays()); } if (type == TIMESTAMP) { return filter.testLong(((SqlTimestamp) value).getMillisUtc()); } if (type instanceof DecimalType) { DecimalType decimalType = (DecimalType) type; SqlDecimal decimal = (SqlDecimal) value; if (decimalType.isShort()) { return filter.testLong(decimal.toBigDecimal().unscaledValue().longValue()); } else { Slice s = Decimals.encodeScaledValue(decimal.toBigDecimal()); return filter.testDecimal(s.getLong(0), s.getLong(Long.BYTES)); } } fail("Unsupported type: " + type); return false; }

Target:
private static boolean testValue(Type type, Object value, TupleDomainFilter filter) { if (value == null) { return filter.testNull(); } if (filter == IS_NULL) { return false; } if (filter == IS_NOT_NULL) { return true; } if (type == BOOLEAN) { return filter.testBoolean((Boolean) value); } if (type == TINYINT || type == BIGINT || type == INTEGER || type == SMALLINT) { return filter.testLong(((Number) value).longValue()); } if (type == REAL) { return filter.testFloat(((Number) value).floatValue()); } if (type == DOUBLE) { return filter.testDouble((double) value); } if (type == DATE) { return filter.testLong(((SqlDate) value).getDays()); } if (type == TIMESTAMP) { return filter.testLong(((SqlTimestamp) value).getMillisUtc()); } if (type instanceof DecimalType) { DecimalType decimalType = (DecimalType) type; BigDecimal bigDecimal = ((SqlDecimal) value).toBigDecimal(); if (decimalType.isShort()) { return filter.testLong(bigDecimal.unscaledValue().longValue()); } else { Slice encodedDecimal = Decimals.encodeScaledValue(bigDecimal); return filter.testDecimal(encodedDecimal.getLong(0), encodedDecimal.getLong(Long.BYTES)); } } fail("Unsupported type: " + type); return false; }
Source:
public String getInternalLinkRedirectTitleWithIndex(int index) { wait.forElementVisible(internalLink.get(index)); scrollToElement(internalLink.get(index)); return internalLink.get(index).getAttribute("href"); }

Target:
public String getInternalLinkRedirectTitleWithIndex(int index) { return getLinkRedirectTitle(internalLinks.get(index)); }
Source:
private void initialize() throws Exception { for (DcZkInfo dcZkInfo : dcToDcZkInfo.values()) { logger.info("Initializing cluster information from {}", dcZkInfo.zkConnectStr); HelixAdmin admin = dcZkInfo.helixManager.getClusterManagmentTool(); for (String instanceName : admin.getInstancesInCluster(clusterName)) { logger.info("Adding node and its disks and replicas", instanceName); InstanceConfig instanceConfig = admin.getInstanceConfig(clusterName, instanceName); AmbryDataNode datanode = new AmbryDataNode(dcZkInfo.dcName, clusterMapConfig, instanceConfig.getHostName(), Integer.valueOf(instanceConfig.getPort()), getRackId(instanceConfig), getSslPortStr(instanceConfig)); initializeDisksAndReplicasOnNode(datanode, instanceConfig); instanceNameToAmbryDataNode.put(instanceName, datanode); dcZkInfo.clusterChangeListener.allInstances.add(instanceName); } } for (Set<AmbryDisk> disks : ambryDataNodeToAmbryDisks.values()) { for (AmbryDisk disk : disks) { clusterWideRawCapacityBytes += disk.getRawCapacityInBytes(); } } for (Set<AmbryReplica> partitionReplicas : ambryPartitionToAmbryReplicas.values()) { long replicaCapacity = partitionReplicas.iterator().next().getCapacityInBytes(); clusterWideAllocatedRawCapacityBytes += replicaCapacity * partitionReplicas.size(); clusterWiseAllocatedUsableCapacityBytes += replicaCapacity; } }

Target:
private void initialize() throws Exception { for (DcZkInfo dcZkInfo : dcToDcZkInfo.values()) { logger.info("Initializing cluster information from {}", dcZkInfo.zkConnectStr); HelixAdmin admin = dcZkInfo.helixManager.getClusterManagmentTool(); for (String instanceName : admin.getInstancesInCluster(clusterName)) { logger.info("Adding node and its disks and replicas", instanceName); InstanceConfig instanceConfig = admin.getInstanceConfig(clusterName, instanceName); AmbryDataNode datanode = new AmbryDataNode(dcZkInfo.dcName, clusterMapConfig, instanceConfig.getHostName(), Integer.valueOf(instanceConfig.getPort()), getRackId(instanceConfig), getSslPortStr(instanceConfig)); initializeDisksAndReplicasOnNode(datanode, instanceConfig); instanceNameToAmbryDataNode.put(instanceName, datanode); dcZkInfo.clusterChangeListener.allInstances.add(instanceName); } logger.info("Initialized cluster information from {}", dcZkInfo.zkConnectStr); } for (Set<AmbryDisk> disks : ambryDataNodeToAmbryDisks.values()) { for (AmbryDisk disk : disks) { clusterWideRawCapacityBytes += disk.getRawCapacityInBytes(); } } for (Set<AmbryReplica> partitionReplicas : ambryPartitionToAmbryReplicas.values()) { long replicaCapacity = partitionReplicas.iterator().next().getCapacityInBytes(); clusterWideAllocatedRawCapacityBytes += replicaCapacity * partitionReplicas.size(); clusterWiseAllocatedUsableCapacityBytes += replicaCapacity; } }
Source:
public Collection<Object> getComponentsToRegister() { return Collections.<Object>singletonList(this.receiver); }

Target:
public Collection<Object> getComponentsToRegister() { return this.componentsToRegister; }