auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void populateMileage(CuDisbursementVoucherDocument dvDocument, DisbursementVoucherNonEmployeeTravelXml nonEmployeeTravel) { dvDocument.getDvNonEmployeeTravel().setDisbVchrAutoRoundTripCode(convertStringToBoolean(nonEmployeeTravel.getRoundTripCode())); dvDocument.getDvNonEmployeeTravel().setDvPersonalCarMileageAmount(nonEmployeeTravel.getPersonalCarMileageAmount().intValue()); KualiDecimal caluclatedMilageAmount = disbursementVoucherTravelService.calculateMileageAmount(dvDocument.getDvNonEmployeeTravel().getDvPersonalCarMileageAmount(), dvDocument.getDvNonEmployeeTravel().getDvPerdiemStartDttmStamp()); dvDocument.getDvNonEmployeeTravel().setDisbVchrMileageCalculatedAmt(caluclatedMilageAmount); if (ObjectUtils.isNotNull(nonEmployeeTravel.getPersonalCarAmount())) { dvDocument.getDvNonEmployeeTravel().setDisbVchrPersonalCarAmount(nonEmployeeTravel.getPersonalCarAmount()); } else { dvDocument.getDvNonEmployeeTravel().setDisbVchrPersonalCarAmount(caluclatedMilageAmount); } }

Target:
protected void populateMileage(CuDisbursementVoucherDocument dvDocument, DisbursementVoucherNonEmployeeTravelXml nonEmployeeTravel) { dvDocument.getDvNonEmployeeTravel().setDisbVchrAutoRoundTripCode(convertStringToBoolean(nonEmployeeTravel.getRoundTripCode())); dvDocument.getDvNonEmployeeTravel().setDvPersonalCarMileageAmount(nonEmployeeTravel.getPersonalCarMileageAmount().intValue()); KualiDecimal calculatedMileageAmount = disbursementVoucherTravelService.calculateMileageAmount(dvDocument.getDvNonEmployeeTravel().getDvPersonalCarMileageAmount(), dvDocument.getDvNonEmployeeTravel().getDvPerdiemStartDttmStamp()); dvDocument.getDvNonEmployeeTravel().setDisbVchrMileageCalculatedAmt(calculatedMileageAmount); if (ObjectUtils.isNotNull(nonEmployeeTravel.getPersonalCarAmount())) { dvDocument.getDvNonEmployeeTravel().setDisbVchrPersonalCarAmount(nonEmployeeTravel.getPersonalCarAmount()); } else { dvDocument.getDvNonEmployeeTravel().setDisbVchrPersonalCarAmount(calculatedMileageAmount); } }
Source:
public List<Partition> subPartitions(boolean refresh) { try { List<Partition> partitions; if (!refresh) { partitions = partitionInfoCache.getIfPresent(tableName); if (partitions != null) { return partitions; } } List<HRegionLocation> tableLocations = ((ClusterConnection) connection).locateRegions(tableName, !refresh, false); if (outdated(tableLocations)) { tableLocations = ((ClusterConnection) connection).locateRegions(tableName, refresh, false); } partitions = new ArrayList<>(tableLocations.size()); for (HRegionLocation location : tableLocations){ if (location.getServerName() == null) { continue; } HRegionInfo regionInfo = location.getRegionInfo(); partitions.add(new RangedClientPartition(this, regionInfo, new RLServer(location))); } partitionInfoCache.put(tableName, partitions); return partitions; } catch (IOException e) { throw new RuntimeException(e); } }

Target:
public List<Partition> subPartitions(boolean refresh) { try { List<Partition> partitions; if (!refresh) { partitions = partitionInfoCache.getIfPresent(tableName); if (partitions != null) { return partitions; } } List<HRegionLocation> tableLocations = ((ClusterConnection) connection).locateRegions(tableName, !refresh, false); if (outdated(tableLocations)) { tableLocations = ((ClusterConnection) connection).locateRegions(tableName, false, false); } partitions = new ArrayList<>(tableLocations.size()); for (HRegionLocation location : tableLocations){ if (location.getServerName() == null) { continue; } HRegionInfo regionInfo = location.getRegionInfo(); partitions.add(new RangedClientPartition(this, regionInfo, new RLServer(location))); } partitionInfoCache.put(tableName, partitions); return partitions; } catch (IOException e) { throw new RuntimeException(e); } }
Source:
private void createTopic(final String topic, final int partitionsNum, final int replicaFactor, final long retentionMs, final long rotationMs) throws TopicCreationException { try { doWithZkUtils(zkUtils -> { final Properties topicConfig = new Properties(); topicConfig.setProperty("retention.ms", Long.toString(retentionMs)); topicConfig.setProperty("segment.ms", Long.toString(rotationMs)); AdminUtils.createTopic(zkUtils, topic, partitionsNum, replicaFactor, topicConfig, RackAwareMode.Enforced$.MODULE$); }); } catch (final TopicExistsException e) { throw new TopicCreationException("Topic with name " + topic + " already exists (or wasn't completely removed yet)", e); } catch (final Exception e) { throw new TopicCreationException("Unable to create topic " + topic, e); } }

Target:
private void createTopic(final String topic, final int partitionsNum, final int replicaFactor, final long retentionMs, final long rotationMs) throws TopicCreationException { try { doWithZkUtils(zkUtils -> { final Properties topicConfig = new Properties(); topicConfig.setProperty("retention.ms", Long.toString(retentionMs)); topicConfig.setProperty("segment.ms", Long.toString(rotationMs)); AdminUtils.createTopic(zkUtils, topic, partitionsNum, replicaFactor, topicConfig, RackAwareMode.Enforced$.MODULE$); }); } catch (final TopicExistsException e) { throw new TopicCreationException("Topic with name " + topic + " already exists (or wasn't completely removed yet)", e); } catch (final Exception e) { throw new TopicCreationException("Unable to create topic " + topic, e); } final long timeoutMillis = TimeUnit.SECONDS.toMillis(5); final Boolean allowsConsumption = Retryer.executeWithRetry(() -> { try (Consumer<byte[], byte[]> consumer = kafkaFactory.getConsumer()) { return null != consumer.partitionsFor(topic); } }, new RetryForSpecifiedTimeStrategy<Boolean>(timeoutMillis) .withWaitBetweenEachTry(100L) .withResultsThatForceRetry(Boolean.FALSE)); if (!Boolean.TRUE.equals(allowsConsumption)) { throw new TopicCreationException("Failed to confirm topic creation within " + timeoutMillis + " millis"); } }
Source:
public static String ingest(String data, String mimeType) { return given() .body(data) .header("Content-Type", mimeType) .expect() .statusCode(201) .when() .post(REST_PATH.getUrl()) .getHeader("id"); }

Target:
public static String ingest(String data, String mimeType) { return given() .body(data) .header(HttpHeaders.CONTENT_TYPE, mimeType) .expect() .statusCode(HttpStatus.SC_CREATED) .when() .post(REST_PATH.getUrl()) .getHeader("id"); }
Source:
public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof NameHolder)) { return false; } final NameHolder name = (NameHolder) o; return value != null ? value.equals(name.value) : name.value == null; }

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof NameHolder)) { return false; } final NameHolder name = (NameHolder) o; return Objects.equals(value, name.value); }
Source:
void fragmentAndReassembleData() { System.out.println("original"); ByteBuf frame = PayloadFrameFlyweight.encodeNextComplete(allocator, 2, DefaultPayload.create(data)); System.out.println(FrameUtil.toString(frame)); Publisher<ByteBuf> fragments = FrameFragmenter.fragmentFrame( allocator, 64, frame, FrameHeaderFlyweight.frameType(frame), false); FrameReassembler reassembler = new FrameReassembler(allocator); ByteBuf assembled = Flux.from(fragments) .doOnNext(byteBuf -> System.out.println(FrameUtil.toString(byteBuf))) .handle(reassembler::reassembleFrame) .blockLast(); System.out.println("assembled"); String s = FrameUtil.toString(assembled); System.out.println(s); Assert.assertEquals( FrameHeaderFlyweight.frameType(frame), FrameHeaderFlyweight.frameType(assembled)); Assert.assertEquals(frame.readableBytes(), assembled.readableBytes()); Assert.assertEquals(PayloadFrameFlyweight.data(frame), PayloadFrameFlyweight.data(assembled)); }

Target:
void fragmentAndReassembleData() { ByteBuf frame = PayloadFrameFlyweight.encodeNextComplete(allocator, 2, DefaultPayload.create(data)); System.out.println(FrameUtil.toString(frame)); Publisher<ByteBuf> fragments = FrameFragmenter.fragmentFrame( allocator, 64, frame, FrameHeaderFlyweight.frameType(frame), false); FrameReassembler reassembler = new FrameReassembler(allocator); ByteBuf assembled = Flux.from(fragments) .doOnNext(byteBuf -> System.out.println(FrameUtil.toString(byteBuf))) .handle(reassembler::reassembleFrame) .blockLast(); System.out.println("assembled"); String s = FrameUtil.toString(assembled); System.out.println(s); Assert.assertEquals( FrameHeaderFlyweight.frameType(frame), FrameHeaderFlyweight.frameType(assembled)); Assert.assertEquals(frame.readableBytes(), assembled.readableBytes()); Assert.assertEquals(PayloadFrameFlyweight.data(frame), PayloadFrameFlyweight.data(assembled)); }
Source:
public Optional<AttributeValidationReport> validate(Attribute attribute) { if (attribute == null || CollectionUtils.isEmpty(validators)) { return Optional.empty(); } List<Serializable> serializables = attribute.getValues(); List<Optional<AttributeValidationReport>> resultValidationReportList = new ArrayList<>(); for (Serializable serializable : serializables) { List<Optional<AttributeValidationReport>> validationReportList = validateAttributeSerializable(attribute.getName(), serializable); if (validationReportList.size() == validators.size()) { resultValidationReportList.addAll(validationReportList); } } return generateValidationReports(resultValidationReportList); }

Target:
public Optional<AttributeValidationReport> validate(Attribute attribute) { if (attribute == null || CollectionUtils.isEmpty(validators)) { return Optional.empty(); } List<Serializable> attributeValues = attribute.getValues(); List<AttributeValidationReport> resultValidationReportList = new ArrayList<>(); for (Serializable serializable : attributeValues) { List<AttributeValidationReport> validationReportList = validateAttributeSerializable(attribute.getName(), serializable); if (validationReportList.size() == validators.size()) { resultValidationReportList.addAll(validationReportList); } } return generateValidationReports(resultValidationReportList); }
Source:
public void setEnabled(Object evaluationContext) { if (evaluationContext instanceof IEvaluationContext) { IEvaluationContext ctx = (IEvaluationContext) evaluationContext; Object selection = getSelection(ctx); if (selection instanceof ISelection) { Repository repo = extractRepository((ISelection) selection, getActiveEditorInput(ctx)); if (repo != null) { boolean enabled = isEnabledForState(repo, repo.getRepositoryState()); setBaseEnabled(enabled); } else setBaseEnabled(false); return; } } setBaseEnabled(true); }

Target:
public void setEnabled(Object evaluationContext) { if (evaluationContext instanceof IEvaluationContext) { IEvaluationContext ctx = (IEvaluationContext) evaluationContext; Object selection = getSelection(ctx); if (selection instanceof ISelection) { Repository repo = getRepository((ISelection) selection, getActiveEditorInput(ctx)); if (repo != null) { boolean enabled = isEnabledForState(repo, repo.getRepositoryState()); setBaseEnabled(enabled); } else setBaseEnabled(false); return; } } setBaseEnabled(true); }
Source:
public boolean add(long pageId) { assert pageId != 0L; if (size >= MAX_SIZE) return false; int stripeIdx = (int)pageId & (STRIPES_COUNT - 1); synchronized (stripeLocks[stripeIdx]) { if (size >= MAX_SIZE) return false; GridLongList stripe = stripes[stripeIdx]; if (stripe == null) stripes[stripeIdx] = stripe = new GridLongList(MAX_SIZE / STRIPES_COUNT); if (stripe.size() >= MAX_SIZE / STRIPES_COUNT) return false; else { stripe.add(pageId); sizeUpdater.incrementAndGet(this); return true; } } }

Target:
public boolean add(long pageId) { assert pageId != 0L; if (size >= MAX_SIZE) return false; int stripeIdx = (int)pageId & (STRIPES_COUNT - 1); synchronized (stripeLocks[stripeIdx]) { GridLongList stripe = stripes[stripeIdx]; if (stripe == null) stripes[stripeIdx] = stripe = new GridLongList(MAX_SIZE / STRIPES_COUNT); if (stripe.size() >= MAX_SIZE / STRIPES_COUNT) return false; else { stripe.add(pageId); sizeUpdater.incrementAndGet(this); return true; } } }
Source:
protected void replaceAttributeExpressionWithValue(final StringBuilder container, final String attributeName, final String value) { final Pattern patternWithAttributeName = Pattern.compile("\\[" + ATTRIBUTE_KEY + "." + attributeName + "\\]"); final Matcher matcher = patternWithAttributeName.matcher(container.toString()); while (matcher.find()) { container.replace(matcher.start(), matcher.end(), value); } }

Target:
protected void replaceAttributeExpressionWithValue(final StringBuilder container, final String attributeName, final String value) { final String key = "[" + ATTRIBUTE_KEY + "." + attributeName + "]"; int start = container.indexOf(key, 0); while (start > -1) { int end = start + key.length(); int nextSearchStart = start + value.length(); container.replace(start, end, value); start = container.indexOf(key, nextSearchStart); } }
Source:
private void calculateSuffix() { try { fValue = getLiteral(); switch (fKind) { case lk_float_constant: case lk_integer_constant: { int offset = (fValue[0] == '.' ? afterDecimalPoint(0) : integerLiteral()); if (offset == 0) { fHasNumericalSuffix = true; } else { fSuffix = CharArrayUtils.subarray(fValue, offset, -1); switch (new String(fSuffix).toLowerCase()) { case "u": case "f": case "l": case "ul": case "lu": case "ll": case "ull": case "llu": fHasNumericalSuffix = true; break; } if (!fHasNumericalSuffix) { fValue = CharArrayUtils.subarray(fValue, 0, offset); } } } break; case lk_string_literal: { final int offset = CharArrayUtils.lastIndexOf('"', fValue, CharArrayUtils.indexOf('"', fValue) + 1); if (offset > 0) { fSuffix = CharArrayUtils.subarray(fValue, offset + 1, -1); fValue = CharArrayUtils.subarray(fValue, 0, fValue.length - fSuffix.length); } } break; case lk_char_constant: { final int offset = CharArrayUtils.lastIndexOf('\'', fValue, CharArrayUtils.indexOf('\'', fValue) + 1); if (offset > 0) { fSuffix = CharArrayUtils.subarray(fValue, offset + 1, -1); fValue = CharArrayUtils.subarray(fValue, 0, fValue.length - fSuffix.length); } } break; } } catch (ArrayIndexOutOfBoundsException e) { } }

Target:
private void calculateSuffix() { try { fValue = getRawValue(); int offset = 0; switch (fKind) { case lk_float_constant: case lk_integer_constant: offset = (fValue[0] == '.' ? afterDecimalPoint(0) : integerLiteral()); break; case lk_string_literal: offset = CharArrayUtils.lastIndexOf('"', fValue, CharArrayUtils.indexOf('"', fValue) + 1) + 1; break; case lk_char_constant: offset = CharArrayUtils.lastIndexOf('\'', fValue, CharArrayUtils.indexOf('\'', fValue) + 1) + 1; break; } if (offset > 0) { fSuffix = CharArrayUtils.subarray(fValue, offset, -1); fValue = CharArrayUtils.subarray(fValue, 0, fValue.length - fSuffix.length); } } catch (ArrayIndexOutOfBoundsException e) { } }
Source:
public boolean processReconfig(QuorumVerifier qv, Long suggestedLeaderId, Long zxid, boolean restartLE) { InetSocketAddress oldClientAddr = getClientAddress(); boolean isReconfigEnabled = QuorumPeerConfig.isReconfigEnabled(); QuorumVerifier prevQV = setQuorumVerifier(qv, isReconfigEnabled); if (!isReconfigEnabled) { return false; } initConfigInZKDatabase(); if (prevQV.getVersion() < qv.getVersion() && !prevQV.equals(qv)) { Map<Long, QuorumServer> newMembers = qv.getAllMembers(); updateRemotePeerMXBeans(newMembers); if (restartLE) restartLeaderElection(prevQV, qv); QuorumServer myNewQS = newMembers.get(getId()); if (myNewQS != null && myNewQS.clientAddr != null && !myNewQS.clientAddr.equals(oldClientAddr)) { cnxnFactory.reconfigure(myNewQS.clientAddr); updateThreadName(); } boolean roleChange = updateLearnerType(qv); boolean leaderChange = false; if (suggestedLeaderId != null) { leaderChange = updateVote(suggestedLeaderId, zxid); } else { long currentLeaderId = getCurrentVote().getId(); QuorumServer myleaderInCurQV = prevQV.getVotingMembers().get(currentLeaderId); QuorumServer myleaderInNewQV = qv.getVotingMembers().get(currentLeaderId); leaderChange = (myleaderInCurQV == null || myleaderInCurQV.addr == null || myleaderInNewQV == null || !myleaderInCurQV.addr.equals(myleaderInNewQV.addr)); reconfigFlagClear(); } if (roleChange || leaderChange) { return true; } } return false; }

Target:
public boolean processReconfig(QuorumVerifier qv, Long suggestedLeaderId, Long zxid, boolean restartLE) { if (!QuorumPeerConfig.isReconfigEnabled()) { LOG.debug("Reconfig feature is disabled, skip reconfig processing."); return false; } InetSocketAddress oldClientAddr = getClientAddress(); QuorumVerifier prevQV = setQuorumVerifier(qv, true); initConfigInZKDatabase(); if (prevQV.getVersion() < qv.getVersion() && !prevQV.equals(qv)) { Map<Long, QuorumServer> newMembers = qv.getAllMembers(); updateRemotePeerMXBeans(newMembers); if (restartLE) restartLeaderElection(prevQV, qv); QuorumServer myNewQS = newMembers.get(getId()); if (myNewQS != null && myNewQS.clientAddr != null && !myNewQS.clientAddr.equals(oldClientAddr)) { cnxnFactory.reconfigure(myNewQS.clientAddr); updateThreadName(); } boolean roleChange = updateLearnerType(qv); boolean leaderChange = false; if (suggestedLeaderId != null) { leaderChange = updateVote(suggestedLeaderId, zxid); } else { long currentLeaderId = getCurrentVote().getId(); QuorumServer myleaderInCurQV = prevQV.getVotingMembers().get(currentLeaderId); QuorumServer myleaderInNewQV = qv.getVotingMembers().get(currentLeaderId); leaderChange = (myleaderInCurQV == null || myleaderInCurQV.addr == null || myleaderInNewQV == null || !myleaderInCurQV.addr.equals(myleaderInNewQV.addr)); reconfigFlagClear(); } if (roleChange || leaderChange) { return true; } } return false; }
Source:
public void processMessageShouldNotSendFirmwareFileRequestWhenFirmwareFileAvailable() throws JMSException { final String firmwareIdentification = "unavailable"; final ObjectMessage message = new ObjectMessageBuilder().withObject(firmwareIdentification).build(); when(this.firmwareService.isFirmwareFileAvailable(firmwareIdentification)).thenReturn(true); this.processor.processMessage(message); verify(this.osgpRequestMessageSender, times(0)).send(any(RequestMessage.class), any(String.class), any(MessageMetadata.class)); }

Target:
public void processMessageShouldNotSendFirmwareFileRequestWhenFirmwareFileAvailable() throws JMSException { final String firmwareIdentification = "unavailable"; final ObjectMessage message = new ObjectMessageBuilder().withObject(firmwareIdentification).build(); when(this.firmwareService.isFirmwareFileAvailable(firmwareIdentification)).thenReturn(true); this.processor.processMessage(message); verify(this.osgpRequestMessageSender, never()).send(any(RequestMessage.class), any(String.class), any(MessageMetadata.class)); }
Source:
public void start(BundleContext context) throws Exception { super.start(context); setDefault(this); TmfAnalysisManager.initializeModuleSources(); }

Target:
public void start(BundleContext context) throws Exception { super.start(context); setDefault(this); }
Source:
public synchronized boolean record(final String chrom, final int pos) { this.lastChrom = chrom; this.lastPos = pos; if (this.lastStartTime == -1) this.lastStartTime = System.currentTimeMillis(); if (++this.processed % this.n == 0) { log(chrom, pos); return true; } else { return false; } }

Target:
public synchronized boolean record(final String chrom, final int pos) { this.lastChrom = chrom; this.lastPos = pos; if (this.lastStartTime == -1) { this.lastStartTime = System.currentTimeMillis(); } if (++this.processed % this.n == 0) { record(); return true; } else { return false; } }
Source:
public CassandraDataSegmentPusher( CassandraDataSegmentConfig config, ObjectMapper jsonMapper) { this.config = config; this.jsonMapper = jsonMapper; this.astyanaxContext = new AstyanaxContext.Builder() .forCluster(CLUSTER_NAME) .forKeyspace(config.getKeyspace()) .withAstyanaxConfiguration(new AstyanaxConfigurationImpl().setDiscoveryType(NodeDiscoveryType.NONE)) .withConnectionPoolConfiguration( new ConnectionPoolConfigurationImpl("MyConnectionPool").setMaxConnsPerHost(10) .setSeeds(config.getHost())).withConnectionPoolMonitor(new CountingConnectionPoolMonitor()) .buildKeyspace(ThriftFamilyFactory.getInstance()); this.astyanaxContext.start(); this.keyspace = this.astyanaxContext.getEntity(); descriptorStorage = new ColumnFamily<String, String>(DESCRIPTOR_TABLE_NAME, StringSerializer.get(), StringSerializer.get()); indexStorage = new CassandraChunkedStorageProvider(keyspace, INDEX_TABLE_NAME); }

Target:
public CassandraDataSegmentPusher( CassandraDataSegmentConfig config, ObjectMapper jsonMapper) { super(config); this.jsonMapper=jsonMapper; }
Source:
private void initialize() throws Exception { for (DcZkInfo dcZkInfo : dcToDcZkInfo.values()) { HelixAdmin admin = dcZkInfo.helixManager.getClusterManagmentTool(); for (String instanceName : admin.getInstancesInCluster(clusterName)) { InstanceConfig instanceConfig = admin.getInstanceConfig(clusterName, instanceName); AmbryDataNode datanode = new AmbryDataNode(dcZkInfo.dcName, clusterMapConfig, instanceConfig.getHostName(), instanceConfig.getPort(), getRackIdStr(instanceConfig), getSslPortStr(instanceConfig)); initializeDisksAndReplicasOnNode(datanode, instanceConfig); instanceNameToDataNodeIdMap.put(instanceName, datanode); dcZkInfo.clusterChangeListener.allInstances.add(instanceName); } } for (Set<AmbryDisk> disks : dataNodeIdToDiskIds.values()) { for (AmbryDisk disk : disks) { clusterWideRawCapacityBytes += disk.getRawCapacityInBytes(); } } for (Map.Entry<AmbryPartition, Set<AmbryReplica>> partitionInfo : partitionIdToReplicaIds.entrySet()) { long replicaCapacity = partitionInfo.getValue().iterator().next().getCapacityInBytes(); clusterWideAllocatedRawCapacityBytes += replicaCapacity * partitionInfo.getValue().size(); clusterWiseAllocatedUsableCapacityBytes += replicaCapacity; } }

Target:
private void initialize() throws Exception { for (DcZkInfo dcZkInfo : dcToDcZkInfo.values()) { HelixAdmin admin = dcZkInfo.helixManager.getClusterManagmentTool(); for (String instanceName : admin.getInstancesInCluster(clusterName)) { 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; } }
Source:
static void validateEmail( final String email ) throws ResourceException { if ( !EMAIL_PATTERN.matcher( email ).matches() ) { throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "Invalid e-mail address: " + email ); } }

Target:
static void validateEmail( final String email ) throws ResourceException { if ( StringUtils.isEmpty( email ) ) { throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "E-mail address cannot be empty" ); } if ( !EMAIL_PATTERN.matcher( email ).matches() ) { throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "Invalid e-mail address: " + email ); } }
Source:
public final Observable<T> takeLast(final int count) { return lift(new OperatorTakeLast(count)); }

Target:
public final Observable<T> takeLast(final int count) { return lift(new OperatorTakeLast<T>(count)); }
Source:
private synchronized void renderQueues() { Platform.runLater(() -> { List<MatchmakingQueue> queues = Collections.synchronizedList(teamMatchmakingService.getMatchmakingQueues()); synchronized (queues) { queueBox.getChildren().clear(); queues.sort(Comparator.comparing(MatchmakingQueue::getQueueId)); queues.forEach(queue -> { MatchmakingQueueItemController controller = uiService.loadFxml("theme/play/teammatchmaking/matchmaking_queue_card.fxml"); controller.setQueue(queue); queueBox.getChildren().add(controller.getRoot()); }); } }); }

Target:
private void renderQueues() { Platform.runLater(() -> { List<MatchmakingQueue> queues = Collections.synchronizedList(teamMatchmakingService.getMatchmakingQueues()); synchronized (queues) { queueBox.getChildren().clear(); queues.sort(Comparator.comparing(MatchmakingQueue::getQueueId)); queues.forEach(queue -> { MatchmakingQueueItemController controller = uiService.loadFxml("theme/play/teammatchmaking/matchmaking_queue_card.fxml"); controller.setQueue(queue); queueBox.getChildren().add(controller.getRoot()); }); } }); }
Source:
@Override public void onMatch(RelOptRuleCall call) { IgniteProject rel = call.rel(0); RelNode input = call.rel(1); RelOptCluster cluster = rel.getCluster(); RelMetadataQuery mq = cluster.getMetadataQuery(); RelTraitSet traits = rel.getTraitSet() .replace(IgniteDistributions.project(mq, input, rel.getProjects())); if (call.getPlanner().getRelTraitDefs().contains(RelCollationTraitDef.INSTANCE)) { List<RelCollation> projCollations = RelMdCollation.project(mq, input, rel.getProjects()); if (!F.isEmpty(projCollations)) traits = traits.replace(projCollations.get(0)); } RuleUtils.transformTo(call, new IgniteProject(cluster, traits, input, rel.getProjects(), rel.getRowType())); }

Target:
@Override public void onMatch(RelOptRuleCall call) { IgniteProject rel = call.rel(0); RelNode input = call.rel(1); RelOptCluster cluster = rel.getCluster(); RelMetadataQuery mq = cluster.getMetadataQuery(); RelTraitSet traits = rel.getTraitSet() .replace(IgniteDistributions.project(mq, input, rel.getProjects())); List<RelCollation> projCollations = RelMdCollation.project(mq, input, rel.getProjects()); if (!F.isEmpty(projCollations)) traits = traits.replace(projCollations.get(0)); RuleUtils.transformTo(call, new IgniteProject(cluster, traits, input, rel.getProjects(), rel.getRowType())); }
Source:
public boolean trySetBytes(long bytes) { boolean result = delegate.trySetBytes(bytes); if (peakMemory.isPresent()) { peakMemory.get().accumulateAndGet(delegate.getBytes(), Math::max); } return result; }

Target:
public boolean trySetBytes(long bytes) { return delegate.trySetBytes(bytes); }
Source:
public long deleteHorizonMs() { return -1L; }

Target:
public long deleteHorizonMs() { return RecordBatch.NO_TIMESTAMP; }
Source:
public FSDataOutputStream openHdfsOutputFile(Path path, boolean useLocal, boolean allowOveride) throws IOException { short repCount = (short) HadoopLogsConfigs.getReplicationCount(); long blockSize = (long) HadoopLogsConfigs.getHdfsBlockSize() * 1048576L; if (useLocal) { return localFileSystem.create(path, allowOveride, bufferSize, repCount, blockSize); } else { return remoteFileSystem.create(path, allowOveride, bufferSize, repCount, blockSize); } }

Target:
public FSDataOutputStream openHdfsOutputFile(Path path, boolean useLocal, boolean allowOveride) throws IOException { short repCount = (short) HadoopLogsConfigs.getReplicationCount(); long blockSize = (long) HadoopLogsConfigs.getHdfsBlockSize() * 1024L*1024L; if (useLocal) { return localFileSystem.create(path, allowOveride, bufferSize, repCount, blockSize); } else { return remoteFileSystem.create(path, allowOveride, bufferSize, repCount, blockSize); } }
Source:
public HiveMetastoreClientFactory( Optional<SSLContext> sslContext, Optional<HostAndPort> socksProxy, Duration timeout, HiveMetastoreAuthentication metastoreAuthentication) { this.sslContext = sslContext; this.socksProxy = requireNonNull(socksProxy, "socksProxy is null"); this.timeoutMillis = toIntExact(timeout.toMillis()); this.metastoreAuthentication = requireNonNull(metastoreAuthentication, "metastoreAuthentication is null"); }

Target:
public HiveMetastoreClientFactory( Optional<SSLContext> sslContext, Optional<HostAndPort> socksProxy, Duration timeout, HiveMetastoreAuthentication metastoreAuthentication) { this.sslContext = requireNonNull(sslContext, "sslContext is null"); this.socksProxy = requireNonNull(socksProxy, "socksProxy is null"); this.timeoutMillis = toIntExact(timeout.toMillis()); this.metastoreAuthentication = requireNonNull(metastoreAuthentication, "metastoreAuthentication is null"); }
Source:
public ITmfTrace openMinimalTrace(String projectName, String traceName, Boolean isExperiment) { return null; }

Target:
public ITmfTrace openMinimalTrace(String projectName, String traceName, Boolean isExperiment) throws FileNotFoundException { Map<String, Object> parameters = new HashMap<>(); parameters.put("name", traceName); String filePath = getFile(projectName, traceName, isExperiment).getLocation().getPath(); parameters.put("uri", filePath); QueryParameters query = new QueryParameters(parameters, Collections.emptyList()); TraceManagerService traceManager = new TraceManagerService(); Response response = traceManager.putTrace(query); Object traceObject = response.getEntity(); if (traceObject instanceof ITmfTrace) { return (ITmfTrace) traceObject; } throw new FileNotFoundException(); }
Source:
void addModuleCompletions(ModuleService moduleService) { if (this.moduleService == moduleService) { return; } sorted = false; this.moduleService = moduleService; ArrayList<Completion> list = new ArrayList<Completion>(); for (ModuleInfo info : moduleService.getModules()) { if(info.getMenuPath().getLeaf() != null) { String name = info.getMenuPath().getLeaf().getName().trim(); String headline = "run(\"" + name +"\")"; String description = "<b>" + headline + "</b><p>" + "<a href=\"<LINK_0>" + name.replace(" ", "%20") + "\">Search imagej wiki for help</a>"; list.add(makeListEntry(this, headline, null, description)); } } addCompletions(list); }

Target:
void addModuleCompletions(ModuleService moduleService) { if (this.moduleService == moduleService) { return; } sorted = false; this.moduleService = moduleService; ArrayList<Completion> completions = new ArrayList<>(); for (ModuleInfo info : moduleService.getModules()) { if(info.getMenuPath().getLeaf() != null) { String name = info.getMenuPath().getLeaf().getName().trim(); String headline = "run(\"" + name +"\")"; String description = "<b>" + headline + "</b><p>" + "<a href=\"<LINK_0>" + name.replace(" ", "%20") + "\">Search imagej wiki for help</a>"; completions.add(makeListEntry(this, headline, null, description)); } } addCompletions(completions); }
Source:
public byte[] serialize() { ByteBuffer buffer = ByteBuffer.allocate(9); buffer.put(TYPE_DOUBLE); buffer.putDouble(value); return buffer.array(); }

Target:
public byte[] serialize() { ByteBuffer buffer = ByteBuffer.allocate(Byte.BYTES + Double.BYTES); buffer.put(getType().getByte()); buffer.putDouble(value); return buffer.array(); }
Source:
public static String createUniqueText() { return String.format(UNIQUE_TEXT_FORMAT, System.nanoTime()); }

Target:
public static String createUniqueText() { return String.format(UNIQUE_TEXT_FORMAT, System.currentTimeMillis()); }
Source:
default Optional<String> getGroupId() { Optional<String> standalone = getAttribute(getClass().getClassLoader(), "Engine-GroupID-" + getId()); if (standalone.isPresent()) { return standalone; } return Optional.empty(); }

Target:
default Optional<String> getGroupId() { return Optional.empty(); }
Source:
protected VersionInfo fetchVersionInfoFromResponse(Map<String, String> responseAsMap) throws ParseException { return new VersionInfo.Builder().withBuildDate(responseAsMap.get(VersionInfo.VersionKeys.BUILD_DATE)) .withGitCommit(responseAsMap.get(VersionInfo.VersionKeys.GIT_COMMIT)) .withGitVersion(responseAsMap.get(VersionInfo.VersionKeys.GIT_VERSION)) .withMajor(responseAsMap.get(VersionInfo.VersionKeys.MAJOR)) .withMinor(responseAsMap.get(VersionInfo.VersionKeys.MINOR)) .withGitTreeState(responseAsMap.get(VersionInfo.VersionKeys.GIT_TREE_STATE)) .withPlatform(responseAsMap.get(VersionInfo.VersionKeys.PLATFORM)) .withGoVersion(responseAsMap.get(VersionInfo.VersionKeys.GO_VERSION)) .withCompiler(responseAsMap.get(VersionInfo.VersionKeys.COMPILER)) .build(); }

Target:
protected static VersionInfo fetchVersionInfoFromResponse(Map<String, String> responseAsMap) throws ParseException { return new VersionInfo.Builder().withBuildDate(responseAsMap.get(VersionInfo.VersionKeys.BUILD_DATE)) .withGitCommit(responseAsMap.get(VersionInfo.VersionKeys.GIT_COMMIT)) .withGitVersion(responseAsMap.get(VersionInfo.VersionKeys.GIT_VERSION)) .withMajor(responseAsMap.get(VersionInfo.VersionKeys.MAJOR)) .withMinor(responseAsMap.get(VersionInfo.VersionKeys.MINOR)) .withGitTreeState(responseAsMap.get(VersionInfo.VersionKeys.GIT_TREE_STATE)) .withPlatform(responseAsMap.get(VersionInfo.VersionKeys.PLATFORM)) .withGoVersion(responseAsMap.get(VersionInfo.VersionKeys.GO_VERSION)) .withCompiler(responseAsMap.get(VersionInfo.VersionKeys.COMPILER)) .build(); }
Source:
private static InetAddress getPrivateIpAddress(DatabaseInstance instance) { Preconditions.checkNotNull(instance, "instance is null"); List<IpMapping> ipMappingList = instance.getIpAddresses(); if (ipMappingList == null || ipMappingList.size() == 0) { throw new IllegalArgumentException("No network interfaces found for database instance '" + instance.getName() + "'."); } else { try { return InetAddress.getByName(ipMappingList.get(0).getIpAddress()); } catch (UnknownHostException e) { throw new IllegalArgumentException("Invalid IPv4 address", e); } } }

Target:
private static InetAddress getPrivateIpAddress(DatabaseInstance instance) { Preconditions.checkNotNull(instance, "instance is null"); List<IpMapping> ipMappingList = instance.getIpAddresses(); if (ipMappingList == null || ipMappingList.isEmpty()) { throw new IllegalArgumentException("No network interfaces found for database instance '" + instance.getName() + "'."); } else { try { return InetAddress.getByName(ipMappingList.get(0).getIpAddress()); } catch (UnknownHostException e) { throw new IllegalArgumentException("Invalid IPv4 address", e); } } }
Source:
public ActionResult execute() { String searchKey = getNonNullRequestParamValue(Const.ParamsNames.SEARCH_KEY); List<StudentAttributes> students; List<StudentData> studentDataList = new ArrayList<>(); if (userInfo.isAdmin) { students = logic.searchStudentsInWholeSystem(searchKey).studentList; } else { List<InstructorAttributes> instructors = logic.getInstructorsForGoogleId(userInfo.id); students = logic.searchStudents(searchKey, instructors).studentList; } for (StudentAttributes s : students) { courseIds.add(s.getCourse()); StudentData studentData = new StudentData(s); if (userInfo.isAdmin) { studentData.setKey(StringHelper.encrypt(s.getKey())); } studentDataList.add(studentData); } StudentsData studentsData = new StudentsData(); studentsData.setStudents(studentDataList); populateCourseIdToInstituteMap(); studentsData.getStudents().forEach((StudentData student) -> { student.setInstitute(courseIdToInstituteMap.get(student.getCourseId())); }); studentsData.getStudents().forEach(StudentData::hideLastName); if (userInfo.isInstructor) { studentsData.getStudents().forEach(StudentData::hideInformationForInstructor); } return new JsonResult(studentsData); }

Target:
public ActionResult execute() { String searchKey = getNonNullRequestParamValue(Const.ParamsNames.SEARCH_KEY); List<StudentAttributes> students; List<StudentData> studentDataList = new ArrayList<>(); if (userInfo.isAdmin) { students = logic.searchStudentsInWholeSystem(searchKey).studentList; } else { List<InstructorAttributes> instructors = logic.getInstructorsForGoogleId(userInfo.id); students = logic.searchStudents(searchKey, instructors).studentList; } for (StudentAttributes s : students) { StudentData studentData = new StudentData(s); if (userInfo.isAdmin) { studentData.addAdditionalInformationForAdminSearch( StringHelper.encrypt(s.getKey()), getInstituteFromCourseId(s.getCourse())); } else { studentData.hideInformationForInstructor(); } studentData.hideLastName(); studentDataList.add(studentData); } StudentsData studentsData = new StudentsData(); studentsData.setStudents(studentDataList); return new JsonResult(studentsData); }
Source:
public void testFindAll() throws Throwable { String p = "<p>Find all instances of find on the page and highlight them.</p>"; mWebView.loadData("<html><body>" + p + "</body></html>", "text/html", "UTF-8"); waitForLoadComplete(mWebView, TEST_TIMEOUT); runTestOnUiThread(new Runnable() { public void run() { assertEquals(2, mWebView.findAll("find")); } }); }

Target:
public void testFindAll() throws Throwable { getActivity().runOnUiThread(new Runnable() { public void run() { String p = "<p>Find all instances of find on the page and highlight them.</p>"; mWebView.loadData("<html><body>" + p +"</body></html>", "text/html", "UTF-8"); } }); waitForLoadComplete(mWebView, TEST_TIMEOUT); runTestOnUiThread(new Runnable() { public void run() { assertEquals(2, mWebView.findAll("find")); } }); }
Source:
private static ITmfTrace openAndInitializeTrace(IFile file, String location, String name, String typeID) throws TmfTraceException, InstantiationException, IllegalAccessException, FileNotFoundException, TmfTraceImportException { List<TraceTypeHelper> traceTypes = TmfTraceType.selectTraceType(location, typeID); if (traceTypes.isEmpty()) { throw new FileNotFoundException(); } TraceTypeHelper helper = traceTypes.get(0); ITmfTrace trace = helper.getTraceClass().newInstance(); trace.initTrace(file, location, ITmfEvent.class, name, typeID); return trace; }

Target:
private static ITmfTrace openAndInitializeTrace(IFile file, String location, String name, String typeID) throws TmfTraceException, InstantiationException, IllegalAccessException, FileNotFoundException, TmfTraceImportException { List<TraceTypeHelper> traceTypes = TmfTraceType.selectTraceType(location, typeID); if (traceTypes.isEmpty()) { throw new FileNotFoundException("No trace type could not be found"); } TraceTypeHelper helper = traceTypes.get(0); ITmfTrace trace = helper.getTraceClass().newInstance(); trace.initTrace(file, location, ITmfEvent.class, name, typeID); return trace; }
Source:
public void testNoSelfSuppression() { try { try (TestAsyncWriter t = new TestAsyncWriter()) { for (int i = 0; i < 1000; i++) { t.write(i); } Assert.fail("Expected exception"); } } catch (Exception e) { Assert.assertFalse(e.getMessage().contains("Self-suppression")); Assert.assertTrue(e instanceof MyException); } }

Target:
public void testNoSelfSuppression() { try (TestAsyncWriter t = new TestAsyncWriter()) { try { t.write(1); t.write(2); t.write(3); Assert.fail("Expected exception"); } catch (MyException e) { Assert.assertEquals(1, e.item.intValue()); } try { t.write(4); Assert.fail("Expected exception"); } catch (RuntimeIOException e) { } } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_template_printer); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { showErrorDialog(Localization.get("print.not.supported")); } Bundle data = getIntent().getExtras(); if (data == null) { showErrorDialog(Localization.get("no.print.data")); } this.outputPath = CommCareApplication._().getTempFilePath() + ".html"; String path = data.getString("cc:print_template_reference"); if (path != null) { try { path = ReferenceManager._().DeriveReference(path).getLocalURI(); preparePrintDoc(path); } catch (InvalidReferenceException e) { showErrorDialog(Localization.get("template.invalid")); } } else { SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences(); path = prefs.getString(CommCarePreferences.PRINT_DOC_LOCATION, ""); if ("".equals(path)) { showErrorDialog(Localization.get("missing.template.file")); } else { preparePrintDoc(path); } } }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_template_printer); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { showErrorDialog(Localization.get("print.not.supported")); return; } Bundle data = getIntent().getExtras(); if (data == null) { showErrorDialog(Localization.get("no.print.data")); return; } this.outputPath = CommCareApplication._().getTempFilePath() + ".html"; String path = data.getString("cc:print_template_reference"); if (path != null) { try { path = ReferenceManager._().DeriveReference(path).getLocalURI(); preparePrintDoc(path); } catch (InvalidReferenceException e) { showErrorDialog(Localization.get("template.invalid")); } } else { SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences(); path = prefs.getString(CommCarePreferences.PRINT_DOC_LOCATION, ""); if ("".equals(path)) { showErrorDialog(Localization.get("missing.template.file")); } else { preparePrintDoc(path); } } }
Source:
RtPullComments(final Request req, final Pull pull) { this.entry = req; this.owner = pull; this.request = this.entry.uri() .path("/repos") .path(pull.repo().coordinates().user()) .path(pull.repo().coordinates().repo()) .path("/pulls") .path("" + pull.number()) .path("/comments") .back(); }

Target:
RtPullComments(final Request req, final Pull pull) { this.entry = req; this.owner = pull; this.request = this.entry.uri() .path("/repos") .path(pull.repo().coordinates().user()) .path(pull.repo().coordinates().repo()) .path("/pulls") .path(Integer.toString(pull.number())) .path("/comments") .back(); }
Source:
private void close(final boolean clean) { if (state() == State.CREATED) { transitionTo(State.CLOSING); } else { if (state() == State.RUNNING) { if (clean) { commit(); } transitionTo(State.CLOSING); } if (state() == State.CLOSING) { executeAndMaybeSwallow(clean, () -> { StateManagerUtil.closeStateManager(log, logPrefix, clean, false, stateMgr, stateDirectory, TaskType.STANDBY); }, "state manager close"); } else { throw new IllegalStateException("Illegal state " + state() + " while closing standby task " + id); } } closeTaskSensor.record(); transitionTo(State.CLOSED); }

Target:
private void close(final boolean clean) { if (state() == State.CREATED) { transitionTo(State.CLOSING); } else { if (state() == State.RUNNING) { if (clean) { commit(); } transitionTo(State.CLOSING); } if (state() == State.CLOSING) { executeAndMaybeSwallow(clean, () -> { StateManagerUtil.closeStateManager(log, logPrefix, clean, false, stateMgr, stateDirectory, TaskType.STANDBY); }, "state manager close", log); } else { throw new IllegalStateException("Illegal state " + state() + " while closing standby task " + id); } } closeTaskSensor.record(); transitionTo(State.CLOSED); }
Source:
public void init() { get( "/forms/query", (req, res) -> util.getMetacardsByFilter(QUERY_TEMPLATE_TAG) .values() .stream() .map(Result::getMetacard) .filter(Objects::nonNull) .map(transformer::toFormTemplate) .filter(Objects::nonNull) .collect(Collectors.toList()), MAPPER::toJson); get( "/forms/result", (req, res) -> util.getMetacardsByFilter(ATTRIBUTE_GROUP_TAG) .values() .stream() .map(Result::getMetacard) .filter(Objects::nonNull) .map(transformer::toFieldFilter) .filter(Objects::nonNull) .collect(Collectors.toList()), MAPPER::toJson); get( "/forms/sharing", (req, res) -> { String currentUser = SubjectUtils.getEmailAddress(SecurityUtils.getSubject()); return util.getMetacardsByFilter(QUERY_TEMPLATE_TAG) .entrySet() .stream() .map(Map.Entry::getValue) .map(Result::getMetacard) .filter( metacard -> metacard.getAttribute(SecurityAttributes.ACCESS_INDIVIDUALS) != null) .filter( metacard -> metacard .getAttribute(SecurityAttributes.ACCESS_INDIVIDUALS) .getValues() .contains(currentUser)) .map(transformer::toFormTemplate) .filter(Objects::nonNull) .collect(Collectors.toList()); }, util::getJson); }

Target:
public void init() { get( "/forms/query", (req, res) -> util.getMetacardsByFilter(QUERY_TEMPLATE_TAG) .values() .stream() .map(Result::getMetacard) .filter(Objects::nonNull) .map(transformer::toFormTemplate) .filter(Objects::nonNull) .collect(Collectors.toList()), MAPPER::toJson); get( "/forms/result", (req, res) -> util.getMetacardsByFilter(ATTRIBUTE_GROUP_TAG) .values() .stream() .map(Result::getMetacard) .filter(Objects::nonNull) .map(transformer::toFieldFilter) .filter(Objects::nonNull) .collect(Collectors.toList()), MAPPER::toJson); delete( "/forms/:id", APPLICATION_JSON, (req, res) -> { String id = req.params(":id"); DeleteResponse deleteResponse = catalogFramework.delete(new DeleteRequestImpl(id)); if (!deleteResponse.getProcessingErrors().isEmpty()) { res.status(500); LOGGER.debug("Failed to Delete Form {}", id); return ImmutableMap.of("message", "Failed to delete."); } return ImmutableMap.of("message", "Successfully deleted."); }, util::getJson); }
Source:
private static void fillRepresentations(Contract contract, Section section, ApiDeclaration apiDeclaration, Map<String, List<String>> subtypes, List<String> declaredTypes) { Representation representation; for (Entry<String, ModelDeclaration> modelEntry : apiDeclaration .getModels().entrySet()) { ModelDeclaration model = modelEntry.getValue(); if (model.getSubTypes() != null && !model.getSubTypes().isEmpty()) { subtypes.put(model.getId(), model.getSubTypes()); } if (!declaredTypes.contains(modelEntry.getKey())) { declaredTypes.add(modelEntry.getKey()); representation = toRepresentation(model, modelEntry.getKey()); representation.addSections(Arrays.asList(section.getName())); contract.getRepresentations().add(representation); LOGGER.log(Level.FINE, "Representation " + modelEntry.getKey() + " added."); } } }

Target:
private static void fillRepresentations(Contract contract, Section section, ApiDeclaration apiDeclaration, Map<String, List<String>> subtypes, List<String> declaredTypes) { Representation representation; for (Entry<String, ModelDeclaration> modelEntry : apiDeclaration .getModels().entrySet()) { ModelDeclaration model = modelEntry.getValue(); if (model.getSubTypes() != null && !model.getSubTypes().isEmpty()) { subtypes.put(model.getId(), model.getSubTypes()); } if (!declaredTypes.contains(modelEntry.getKey())) { declaredTypes.add(modelEntry.getKey()); representation = toRepresentation(model, modelEntry.getKey()); representation.addSection(section.getName()); contract.getRepresentations().add(representation); LOGGER.log(Level.FINE, "Representation " + modelEntry.getKey() + " added."); } } }
Source:
public Change createChange(IProgressMonitor pm) throws CoreException { pm.beginTask("", 1); try { if (fFieldName.length() == 0) { fFieldName= getInitialFieldName(); } ASTRewrite rewrite= ASTRewrite.create(fCompilationUnitNode.getAST()); if (fInitializeIn == INITIALIZE_IN_METHOD && tempHasInitializer()) addLocalDeclarationSplit(rewrite); else addLocalDeclarationRemoval(rewrite); if (fInitializeIn == INITIALIZE_IN_CONSTRUCTOR) addInitializersToConstructors(rewrite); addTempRenames(rewrite); addFieldDeclaration(rewrite); CompilationUnitChange result= new CompilationUnitChange(RefactoringCoreMessages.PromoteTempToFieldRefactoring_name, fCu); result.setDescriptor(new RefactoringChangeDescriptor(getRefactoringDescriptor())); TextEdit resultingEdits; Map<String, String> formatter= (this.fFormatterOptions == null) ? fCu.getJavaProject().getOptions(true) : this.fFormatterOptions; try { resultingEdits= rewrite.rewriteAST(new Document(fCu.getSource()), formatter); } catch (JavaModelException e) { resultingEdits= rewrite.rewriteAST(); } TextChangeCompatibility.addTextEdit(result, RefactoringCoreMessages.PromoteTempToFieldRefactoring_editName, resultingEdits); return result; } finally { pm.done(); } }

Target:
public Change createChange(IProgressMonitor pm) throws CoreException { pm.beginTask("", 1); try { if (fFieldName.length() == 0) { fFieldName= getInitialFieldName(); } ASTRewrite rewrite= ASTRewrite.create(fCompilationUnitNode.getAST()); if (fInitializeIn == INITIALIZE_IN_METHOD && tempHasInitializer()) addLocalDeclarationSplit(rewrite); else addLocalDeclarationRemoval(rewrite); if (fInitializeIn == INITIALIZE_IN_CONSTRUCTOR) addInitializersToConstructors(rewrite); addTempRenames(rewrite); addFieldDeclaration(rewrite); CompilationUnitChange result= new CompilationUnitChange(RefactoringCoreMessages.PromoteTempToFieldRefactoring_name, fCu); result.setDescriptor(new RefactoringChangeDescriptor(getRefactoringDescriptor())); TextEdit resultingEdits; if (fFormatterOptions == null) { resultingEdits= rewrite.rewriteAST(); } else { resultingEdits= rewrite.rewriteAST(new Document(fCu.getSource()), fFormatterOptions); } TextChangeCompatibility.addTextEdit(result, RefactoringCoreMessages.PromoteTempToFieldRefactoring_editName, resultingEdits); return result; } finally { pm.done(); } }