auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testPutNodeReferenceObjectType() { for (Storage storage : TestConfig.STORAGES_TO_TEST_AGAINST) { storage.createNode().put(Mods.NAME, storage.createLeaf("Wilhelm Busch", "de")); } }

Target:
public void testPutNodeReferenceObjectType() { for (Storage storage : TestConfig.STORAGES_TO_TEST_AGAINST) { storage.createNode().put(MODS_NAME, storage.createLeaf("Wilhelm Busch", "de")); } }
Source:
private void onHistoryAdded() { if (fullHistSize.incrementAndGet() > MAX_HIST_SIZE) { Iterator<HistoryAffinityAssignment> it = affCache.values().iterator(); int rmvCnt = MAX_HIST_SIZE / 2; Collection<AffinityTopologyVersion> topVerRmv = new HashSet<>(rmvCnt); while (it.hasNext() && rmvCnt > 0) { AffinityAssignment aff0 = it.next(); it.remove(); rmvCnt--; fullHistSize.decrementAndGet(); topVerRmv.add(aff0.topologyVersion()); } ctx.affinity().removeCachedAffinity(topVerRmv); } }

Target:
private void onHistoryAdded() { if (fullHistSize.incrementAndGet() > MAX_HIST_SIZE) { Iterator<HistoryAffinityAssignment> it = affCache.values().iterator(); int rmvCnt = MAX_HIST_SIZE / 2; AffinityTopologyVersion topVerRmv = null; while (it.hasNext() && rmvCnt > 0) { AffinityAssignment aff0 = it.next(); it.remove(); rmvCnt--; fullHistSize.decrementAndGet(); topVerRmv = aff0.topologyVersion(); } topVerRmv = it.hasNext() ? it.next().topologyVersion() : topVerRmv; ctx.affinity().removeCachedAffinity(topVerRmv); } }
Source:
public void filter(ContainerRequestContext requestContext) throws IOException { String path = Optional.ofNullable(uriInfo) .flatMap(info -> Optional.ofNullable(info.getMatchedModelResource())) .flatMap(resource -> Optional.ofNullable(resource.getPath())) .orElse("(unknown)"); String operation = requestContext.getMethod() + " " + path; String traceId = requestContext.getHeaderString(TraceHttpHeaders.TRACE_ID); String spanId = requestContext.getHeaderString(TraceHttpHeaders.SPAN_ID); if (Strings.isNullOrEmpty(traceId)) { Tracer.initTrace(Optional.empty(), Tracers.randomId()); Tracer.startSpan(operation, SpanType.SERVER_INCOMING); } else { Tracer.initTrace(hasSampledHeader(requestContext), traceId); if (spanId == null) { Tracer.startSpan(operation, SpanType.SERVER_INCOMING); } else { Tracer.startSpan(operation, spanId, SpanType.SERVER_INCOMING); } } requestContext.setProperty("com.palantir.remoting3.traceId", Tracer.getTraceId()); }

Target:
public void filter(ContainerRequestContext requestContext) throws IOException { String path = Optional.ofNullable(uriInfo) .map(ExtendedUriInfo::getMatchedModelResource) .map(Resource::getPath) .orElse("(unknown)"); String operation = requestContext.getMethod() + " " + path; String traceId = requestContext.getHeaderString(TraceHttpHeaders.TRACE_ID); String spanId = requestContext.getHeaderString(TraceHttpHeaders.SPAN_ID); if (Strings.isNullOrEmpty(traceId)) { Tracer.initTrace(Optional.empty(), Tracers.randomId()); Tracer.startSpan(operation, SpanType.SERVER_INCOMING); } else { Tracer.initTrace(hasSampledHeader(requestContext), traceId); if (spanId == null) { Tracer.startSpan(operation, SpanType.SERVER_INCOMING); } else { Tracer.startSpan(operation, spanId, SpanType.SERVER_INCOMING); } } requestContext.setProperty("com.palantir.remoting3.traceId", Tracer.getTraceId()); }
Source:
public void onDisconnect(IClient client) { try{ KalturaEntryIdKey entryIdKey = null; WMSProperties properties = client.getProperties(); synchronized (properties) { entryIdKey = (KalturaEntryIdKey) properties.getProperty(Constants.KALTURA_ENTRY_DATA_PERSISTENCY_KEY); } KalturaLiveEntry liveEntry = (KalturaLiveEntry) KalturaStreamsDataPersistence.getEntry(entryIdKey, Constants.CLIENT_PROPERTY_KALTURA_LIVE_ENTRY, String.valueOf(client.getClientId())); logger.info("Entry removed [" + liveEntry.id + "]"); } catch (Exception e){ logger.info("Error" + e.getMessage()); } }

Target:
public void onDisconnect(IClient client) { try{ WMSProperties properties = client.getProperties(); String entryId = Utils.getEntryIdFromClient(client); synchronized (properties) { properties.setProperty(Constants.KALTURA_ENTRY_DATA_PERSISTENCY_KEY, null); } logger.info("Entry removed [" + entryId + "]"); } catch (Exception e){ logger.info("Error" + e.getMessage()); } }
Source:
public boolean close(int waitForShutdownTimeoutMs) throws InterruptedException { close(); if (waitForShutdownTimeoutMs > 0) { return testableWaitForShutdown(waitForShutdownTimeoutMs); } return false; }

Target:
public boolean close(int waitForShutdownTimeoutMs) throws InterruptedException { close(); return testableWaitForShutdown(waitForShutdownTimeoutMs); }
Source:
protected void executeQueryCommand() { List<ExtensionProxy> extensions = getExtensionsManager().getExtensionsByService(Authz.class.getName()); List<String> names = new ArrayList<>(extensions.size()); for (ExtensionProxy extension : extensions) { names.add(AuthzUtils.getName(extension)); } if (getParameters().getFilterInternalDomain()) { names.remove(INTERNAL); } sort(names); getQueryReturnValue().setReturnValue(names); }

Target:
protected void executeQueryCommand() { List<ExtensionProxy> extensions = getExtensionsManager().getExtensionsByService(Authz.class.getName()); List<String> names = new ArrayList<>(extensions.size()); for (ExtensionProxy extension : extensions) { names.add(AuthzUtils.getName(extension)); } sort(names); getQueryReturnValue().setReturnValue(names); }
Source:
public double ticsCalc(int pixelDistance, RectangleWrap field, double deltaRange) { double noTicks = field.height / pixelDistance; double delta = (deltaRange) / noTicks, dec = Math.floor(Math.log(delta) / Math.log(10)); double magn = Math.pow(10, dec), norm = delta / magn; double size; if (norm < 1.5) { size = 1; } else if (norm < 3) { size = 2; if (norm > 2.25) { size = 2.5; } } else if (norm < 7.5) { size = 5; } else { size = 10; } size *= magn; Timber.d("ChartBuilder ticksCalc : pixelDistance: %d, ticks: %,.2f, deltaRange: %,.2f, height: %d", pixelDistance, size, deltaRange, field.height); return size; }

Target:
public double ticsCalc(int pixelDistance, RectangleWrap field, double deltaRange) { double numTicks = field.height / pixelDistance; double delta = deltaRange / numTicks; double dec = Math.floor(Math.log(delta) / Math.log(10)); double magn = Math.pow(10, dec); double norm = delta / magn; double size; if (norm < 1.5) { size = 1; } else if (norm < 3) { size = 2; if (norm > 2.25) { size = 2.5; } } else if (norm < 7.5) { size = 5; } else { size = 10; } size *= magn; Timber.d("ChartBuilder ticksCalc : pixelDistance: %d, ticks: %,.2f, deltaRange: %,.2f, height: %d", pixelDistance, size, deltaRange, field.height); return size; }
Source:
} else if (TARGET_NAME.equals(KuraConstants.Reliagate_20_25.getTargetName())) { baseGpio = -1; try { baseGpio = getBaseGpio(); } catch (KuraException e) { logger.warn("BaseGpio fetch failed!", e); } if (baseGpio != -1) { String gpioIndex = Integer.toString(baseGpio + 30); String gpioPath = BASE_GPIO_PATH + gpioIndex; String gpioDirectionPath = gpioPath + GPIO_DIRECTION_SUFFIX_PATH; try { exportGpio(gpioIndex, gpioPath); setGpioDirection(gpioDirectionPath, GPIO_DIRECTION); } catch (IOException e) { logger.warn(FAILED_INITIALIZE_GPIO_MSG, gpioIndex, e); } gpioIndex = Integer.toString(baseGpio + 23); gpioPath = BASE_GPIO_PATH + gpioIndex; gpioDirectionPath = gpioPath + GPIO_DIRECTION_SUFFIX_PATH; try { exportGpio(gpioIndex, gpioPath); setGpioDirection(gpioDirectionPath, GPIO_DIRECTION); } catch (IOException e) { logger.warn(FAILED_INITIALIZE_GPIO_MSG, gpioIndex, e); } gpioIndex = Integer.toString(baseGpio + 35); gpioPath = BASE_GPIO_PATH + gpioIndex; gpioDirectionPath = gpioPath + GPIO_DIRECTION_SUFFIX_PATH; try { exportGpio(gpioIndex, gpioPath); setGpioDirection(gpioDirectionPath, GPIO_DIRECTION); } catch (IOException e) { logger.warn(FAILED_INITIALIZE_GPIO_MSG, gpioIndex, e); } } }

Target:
} else if (TARGET_NAME.equals(KuraConstants.Reliagate_20_25.getTargetName())) { baseGpio = -1; try { baseGpio = getBaseGpio(); } catch (KuraException e) { logger.warn("BaseGpio fetch failed!", e); } if (baseGpio != -1) { exportGpio(30); exportGpio(23); exportGpio(35); } }
Source:
protected Map<String, ServerImpl> getServersWithFilledPorts(final String externalHostame, final String internalHostname, final Map<String, List<PortBinding>> exposedPorts) { final HashMap<String, ServerImpl> servers = new LinkedHashMap<>(); for (Map.Entry<String, List<PortBinding>> portEntry : exposedPorts.entrySet()) { String portProtocol = portEntry.getKey(); String externalPort = portEntry.getValue().get(0).getHostPort(); servers.put(portProtocol, new ServerImpl(null, null, externalHostame + ":" + externalPort, null, externalPort, new ServerPropertiesImpl(null, internalHostname + ":" + externalPort, null))); } return servers; }

Target:
protected Map<String, ServerImpl> getServersWithFilledPorts(final String externalHostame, final String internalHostname, final Map<String, List<PortBinding>> exposedPorts) { final HashMap<String, ServerImpl> servers = new LinkedHashMap<>(); for (Map.Entry<String, List<PortBinding>> portEntry : exposedPorts.entrySet()) { String portProtocol = portEntry.getKey(); String externalPort = portEntry.getValue().get(0).getHostPort(); servers.put(portProtocol, new ServerImpl(null, null, externalHostame + ":" + externalPort, null, new ServerPropertiesImpl(null, internalHostname + ":" + externalPort, null))); } return servers; }
Source:
protected ITmfTreeViewerEntry updateElements(long start, long end, boolean isSelection) { ITmfTrace trace = getTrace(); if (isSelection || (start == end) || trace == null) { return null; } UstMemoryUsageDataProvider provider = DataProviderManager.getInstance().getDataProvider(trace, UstMemoryUsageDataProvider.ID, UstMemoryUsageDataProvider.class); if (provider == null) { return null; } TmfModelResponse<@NonNull List<@NonNull MemoryUsageTreeModel>> response = provider.fetchTree(new TimeQueryFilter(start, end, 2), null); List<@NonNull MemoryUsageTreeModel> model = response.getModel(); if (model == null) { return null; } Map<Long, TmfTreeViewerEntry> map = new HashMap<>(); TmfTreeViewerEntry root = new TmfTreeViewerEntry(""); map.put(-1L, root); for (MemoryUsageTreeModel m : model) { MemoryUsageEntry entry = new MemoryUsageEntry(m); map.put(m.getId(), entry); TmfTreeViewerEntry parent = map.get(m.getParentId()); if (parent != null) { parent.addChild(entry); } } return root; }

Target:
protected ITmfTreeViewerEntry updateElements(long start, long end, boolean isSelection) { ITmfTrace trace = getTrace(); if (isSelection || (start == end) || trace == null) { return null; } ITmfTreeXYDataProvider<@NonNull MemoryUsageTreeModel> provider = DataProviderManager.getInstance().getDataProvider(trace, UstMemoryUsageDataProvider.ID, ITmfTreeXYDataProvider.class); if (provider == null) { return null; } TmfModelResponse<@NonNull List<@NonNull MemoryUsageTreeModel>> response = provider.fetchTree(new TimeQueryFilter(start, end, 2), null); List<@NonNull MemoryUsageTreeModel> model = response.getModel(); if (model == null) { return null; } Map<Long, TmfTreeViewerEntry> map = new HashMap<>(); TmfTreeViewerEntry root = new TmfTreeViewerEntry(""); map.put(-1L, root); for (MemoryUsageTreeModel m : model) { MemoryUsageEntry entry = new MemoryUsageEntry(m); map.put(m.getId(), entry); TmfTreeViewerEntry parent = map.get(m.getParentId()); if (parent != null) { parent.addChild(entry); } } return root; }
Source:
private void handleStandbyContainerStop(String standbyContainerID, String resourceID, String preferredHost, ContainerAllocator containerAllocator, Duration preferredHostRetryDelay) { Optional<StandbyContainerManager.FailoverMetadata> failoverMetadata = this.checkIfUsedForFailover(resourceID); if (failoverMetadata.isPresent()) { String activeContainerID = failoverMetadata.get().activeContainerID; String standbyContainerHostname = failoverMetadata.get().getStandbyContainerHostname(resourceID); log.info("Requesting resource for active container on host {}, and backup container on any host", activeContainerID, standbyContainerHostname, standbyContainerID); SamzaResourceRequest resourceRequestForActive = containerAllocator.getResourceRequestWithDelay(activeContainerID, standbyContainerHostname, preferredHostRetryDelay); failoverMetadata.get().recordResourceRequest(resourceRequestForActive); containerAllocator.issueResourceRequest(resourceRequestForActive); containerAllocator.requestResource(standbyContainerID, ResourceRequestState.ANY_HOST, faultDomainManager.getAllowedFaultDomainsForSchedulingContainer(standbyContainerHostname)); } else { log.info("Issuing request for standby container on host {}, since this is not for a failover", standbyContainerID, preferredHost); containerAllocator.requestResourceWithDelay(standbyContainerID, preferredHost, preferredHostRetryDelay); } }

Target:
private void handleStandbyContainerStop(String standbyContainerID, String resourceID, String preferredHost, ContainerAllocator containerAllocator, Duration preferredHostRetryDelay) { Optional<StandbyContainerManager.FailoverMetadata> failoverMetadata = this.checkIfUsedForFailover(resourceID); if (failoverMetadata.isPresent()) { String activeContainerID = failoverMetadata.get().activeContainerID; String standbyContainerHostname = failoverMetadata.get().getStandbyContainerHostname(resourceID); log.info("Requesting resource for active container on host {}, and backup container on any host", activeContainerID, standbyContainerHostname, standbyContainerID); SamzaResourceRequest resourceRequestForActive = containerAllocator.getResourceRequestWithDelay(activeContainerID, standbyContainerHostname, preferredHostRetryDelay); failoverMetadata.get().recordResourceRequest(resourceRequestForActive); containerAllocator.issueResourceRequest(resourceRequestForActive); requestResource(containerAllocator, standbyContainerID, ResourceRequestState.ANY_HOST, Duration.ZERO, standbyContainerHostname); } else { log.info("Issuing request for standby container on host {}, since this is not for a failover", standbyContainerID, preferredHost); String activeContainerHost = getActiveContainerHost(standbyContainerID) .orElse(null); requestResource(containerAllocator, standbyContainerID, preferredHost, preferredHostRetryDelay, activeContainerHost); } }
Source:
private void writeObject(ObjectOutputStream oos) throws IOException { Channel target = getChannelForSerialization(); if(channel!=target) { throw new IllegalStateException("Can't send a remote FilePath to a different remote channel"); } oos.defaultWriteObject(); oos.writeBoolean(channel==null); }

Target:
private void writeObject(ObjectOutputStream oos) throws IOException { Channel target = getChannelForSerialization(); if (channel != null && channel != target) { throw new IllegalStateException("Can't send a remote FilePath to a different remote channel (current=" + channel + ", target=" + target + ")"); } oos.defaultWriteObject(); oos.writeBoolean(channel==null); }
Source:
private List<String> getAvailableContainerIds() { try { CuratorFramework client = zkConnection.getClient(); return client.getChildren().forPath(Paths.CONTAINERS); } catch (Exception e) { throw ZooKeeperUtils.wrapThrowable(e); } }

Target:
private List<String> getAvailableContainerIds() { try { return zkConnection.getClient().getChildren().forPath(Paths.CONTAINERS); } catch (Exception e) { throw ZooKeeperUtils.wrapThrowable(e); } }
Source:
public void testPreDestroySuppressedExceptionHandling() throws Exception { Injector injector = Guice.createInjector( Stage.PRODUCTION, new LifeCycleModule(), binder -> { binder.bind(DependentInstance.class).in(Scopes.SINGLETON); binder.bind(DestroyExceptionInstance.class).in(Scopes.SINGLETON); }); LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); assertEquals(stateLog, ImmutableList.of("postDependentInstance")); try { lifeCycleManager.stopWithoutFailureLogging(); fail("Expected exception to be thrown"); } catch (LifeCycleStopException e) { assertEquals(e.getSuppressed().length, 2, "Expected two suppressed exceptions"); Set<String> suppressedMessages = Arrays.stream(e.getSuppressed()) .map(Throwable::getMessage) .collect(Collectors.toSet()); assertEquals(ImmutableSet.copyOf(suppressedMessages), ImmutableSet.of("preDestroyExceptionOne", "preDestroyExceptionTwo")); } catch (Exception e) { fail("Expected LifeCycleStopException to be thrown, found: " + e.getClass()); } assertEquals(ImmutableSet.copyOf(stateLog), ImmutableSet.of( "postDependentInstance", "preDestroyExceptionOne", "preDestroyExceptionTwo", "preDependentInstance")); }

Target:
public void testPreDestroySuppressedExceptionHandling() { Injector injector = Guice.createInjector( Stage.PRODUCTION, new LifeCycleModule(), binder -> { binder.bind(DependentInstance.class).in(Scopes.SINGLETON); binder.bind(DestroyExceptionInstance.class).in(Scopes.SINGLETON); }); LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); assertEquals(stateLog, ImmutableList.of("postDependentInstance")); try { lifeCycleManager.stopWithoutFailureLogging(); fail("Expected exception to be thrown"); } catch (LifeCycleStopException e) { assertEquals(e.getSuppressed().length, 2, "Expected two suppressed exceptions"); Set<String> suppressedMessages = Arrays.stream(e.getSuppressed()) .map(Throwable::getMessage) .collect(Collectors.toSet()); assertEquals(ImmutableSet.copyOf(suppressedMessages), ImmutableSet.of("preDestroyExceptionOne", "preDestroyExceptionTwo")); } assertEquals(ImmutableSet.copyOf(stateLog), ImmutableSet.of( "postDependentInstance", "preDestroyExceptionOne", "preDestroyExceptionTwo", "preDependentInstance")); }
Source:
public synchronized void clear() { this.store.clear(); this.storeKeys.clear(); }

Target:
public void clear() { synchronized (store) { this.store.clear(); this.storeKeys.clear(); } }
Source:
List<DateRange> findDates(WMS wms, CoverageInfo coverage, List<Object> times) throws IOException { TreeSet<Date> availableDates = new TreeSet<Date>(); final boolean isRange = times.get(0) instanceof DateRange; for (Object time : times) { TreeSet<Object> foundTimes = wms.queryCoverageTimes( coverage, getAsRange(time, isRange), Query.DEFAULT_MAX); foundTimes .stream() .sequential() .forEach( d -> { Date date = (Date) d; if (!availableDates.contains(date)) { availableDates.add(date); } }); } return availableDates .stream() .map(date -> new DateRange(date, date)) .collect(Collectors.toList()); }

Target:
List<DateRange> findDates(WMS wms, CoverageInfo coverage, List<Object> times) throws IOException { TreeSet<Date> availableDates = wms.queryCoverageNearestMatchTimes(coverage, times); return availableDates .stream() .map(date -> new DateRange(date, date)) .collect(Collectors.toList()); }
Source:
public int getCount() { return (int) getValue(countStr); }

Target:
public long getCount() { return getValue(countStr); }
Source:
protected abstract void setUnregisteredEntityAndImages(String ovfData) throws OvfReaderException; @Override protected boolean validate() { if (!validate(entityExists())) { return false; } StorageDomainValidator validator = new StorageDomainValidator(getStorageDomain()); if (!validate(validator.isDomainExistAndActive())) { return false; } if (getStorageDomain().getStorageDomainType() != StorageDomainType.Data) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_TYPE_ILLEGAL); } return true; }

Target:
protected abstract void setUnregisteredEntityAndImages(String ovfData) throws OvfReaderException; protected abstract boolean isUnregisteredEntityExists(); protected abstract EngineMessage getEntityNotExistsMessage(); protected abstract EngineMessage getRemoveAction(); public RemoveUnregisteredEntityCommand(T parameters, CommandContext cmdContext) { super(parameters, cmdContext); setStorageDomainId(parameters.getStorageDomainId()); }
Source:
public static String toAlleleString(final int copyNumberState) { return "<" + String.valueOf(copyNumberState) + ">"; }

Target:
private static String toAlleleString(final int copyNumberState) { return "<" + String.valueOf(copyNumberState) + ">"; }
Source:
private List<File> generateFindTileMetricsExpected(Path baseDir, List<Integer> populatedCycleDirs, boolean baseMetricsFile) { List<File> expected = new ArrayList<>(); if (baseMetricsFile) { expected.add(new File( baseDir .resolve(TileMetricsUtil.INTEROP_SUBDIRECTORY_NAME) .resolve(TileMetricsUtil.TILE_METRICS_OUT_FILE_NAME).toUri()) ); } if (populatedCycleDirs.size() > 0) { Path baseOpDir = getBaseOpDir(baseDir); populatedCycleDirs.stream().sorted(Comparator.reverseOrder()).forEach(i -> expected.add(new File( baseOpDir .resolve("C" + i + ".1") .resolve(TileMetricsUtil.TILE_METRICS_OUT_FILE_NAME) .toUri() )) ); } return expected; }

Target:
private List<File> generateFindTileMetricsExpected(Path baseDir, List<Integer> populatedCycleDirs, boolean baseMetricsFile) { List<File> expected = new ArrayList<>(); if (baseMetricsFile) { expected.add( baseDir .resolve(TileMetricsUtil.INTEROP_SUBDIRECTORY_NAME) .resolve(TileMetricsUtil.TILE_METRICS_OUT_FILE_NAME).toFile() ); } if (populatedCycleDirs.size() > 0) { Path baseOpDir = getBaseOpDir(baseDir); populatedCycleDirs.stream().sorted(Comparator.reverseOrder()).forEach(i -> expected.add( baseOpDir .resolve("C" + i + ".1") .resolve(TileMetricsUtil.TILE_METRICS_OUT_FILE_NAME) .toFile() ) ); } return expected; }
Source:
public void testCompareEqualNames(final SAMRecord record1, final SAMRecord record2, final int sign) throws Exception { final int comparisonResult = COMPARATOR.compare(record1, record2); switch (sign) { case -1: Assert.assertTrue(comparisonResult < 0); break; case 0: Assert.assertEquals(comparisonResult, 0); break; case 1: Assert.assertTrue(comparisonResult > 0); break; default: throw new IllegalArgumentException("Invalid sign: " + sign); } }

Target:
public void testCompareEqualNames(final SAMRecord record1, final SAMRecord record2, final int sign) throws Exception { final int comparisonResult = COMPARATOR.compare(record1, record2); Assert.assertEquals(Integer.signum(comparisonResult),sign); }
Source:
public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { alias.email(combinedEmails(alias, email)); res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". Not verified yet.", email ) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); try { alias.email(combinedEmails(alias, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; }

Target:
public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { alias.email(email); res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; }
Source:
public void testArrayConcat() { ImmutableList.Builder<Integer> expectedArray = ImmutableList.builder(); IntStream.range(0, 253).forEach(i -> expectedArray.add(1)); assertFunction("CONCAT(" + Joiner.on(", ").join(nCopies(253, "array[1]")) + ")", new ArrayType(INTEGER), expectedArray.build()); assertNotSupported( "CONCAT(" + Joiner.on(", ").join(nCopies(254, "array[1]")) + ")", "Too many arguments for vararg function"); }

Target:
public void testArrayConcat() { assertFunction("CONCAT(" + Joiner.on(", ").join(nCopies(253, "array[1]")) + ")", new ArrayType(INTEGER), nCopies(253, 1)); assertNotSupported( "CONCAT(" + Joiner.on(", ").join(nCopies(254, "array[1]")) + ")", "Too many arguments for vararg function"); }
Source:
public <T extends DistributedObject> T getDistributedObject(@Nonnull String serviceName, @Nonnull String name, boolean remote) { return (T) proxyManager.getOrCreateProxy(serviceName, name, remote); }

Target:
private <T extends DistributedObject> T getDistributedObject(@Nonnull String serviceName, @Nonnull String name, boolean remote) { if (remote) { return (T) proxyManager.getOrCreateProxy(serviceName, name); } return (T) proxyManager.getOrCreateLocalProxy(serviceName, name); }
Source:
public double rate( PricingEnvironment env, OvernightCompoundedRateObservation observation, LocalDate startDate, LocalDate endDate) { ObservationDetails details = new ObservationDetails(env, observation); return details.calculateRate(); }

Target:
public double rate( PricingEnvironment env, OvernightCompoundedRateObservation observation, LocalDate startDate, LocalDate endDate) { return new ObservationDetails(env, observation).calculateRate(); }
Source:
public void createFeaturesSuccessiveTokensTest() throws IOException { final String[] testSentence = new String[] {"he", "went", "with", "you", "in", "town"}; ResourceAsStreamFactory stream = new ResourceAsStreamFactory( getClass(), "/opennlp/tools/formats/brown-cluster.txt"); BrownCluster brownCluster = new BrownCluster(stream.createInputStream()); AdaptiveFeatureGenerator generator = new BrownBigramFeatureGenerator(brownCluster); List<String> features = new ArrayList<>(); generator.createFeatures(features, testSentence, 3, null); Assert.assertEquals(3, features.size()); Assert.assertTrue(features.contains("pbrowncluster,browncluster=0101,0010")); Assert.assertTrue(features.contains("pbrowncluster,browncluster=01010,00101")); Assert.assertTrue(features.contains("browncluster,nbrowncluster=0010,0000")); }

Target:
public void createFeaturesSuccessiveTokensTest() throws IOException { final String[] testSentence = new String[] {"he", "went", "with", "you", "in", "town"}; List<String> features = new ArrayList<>(); generator.createFeatures(features, testSentence, 3, null); Assert.assertEquals(3, features.size()); Assert.assertTrue(features.contains("pbrowncluster,browncluster=0101,0010")); Assert.assertTrue(features.contains("pbrowncluster,browncluster=01010,00101")); Assert.assertTrue(features.contains("browncluster,nbrowncluster=0010,0000")); }
Source:
public void clientValidated(ClientDescriptor clientDescriptor) { if (managementRegistry != null) { LOGGER.trace("clientValidated({})", clientDescriptor); ClusterTierClientStateBinding clientStateBinding = new ClusterTierClientStateBinding(clientDescriptor, new ClusterTierClientState(storeIdentifier, true)); managementRegistry.unregister(clientStateBinding); managementRegistry.registerAndRefresh(clientStateBinding); managementRegistry.pushServerEntityNotification(clientStateBinding, EHCACHE_SERVER_STORE_ATTACHED.name()); } }

Target:
public void clientValidated(ClientDescriptor clientDescriptor) { if (managementRegistry != null) { LOGGER.trace("clientValidated({})", clientDescriptor); ClusterTierClientStateBinding clientStateBinding = new ClusterTierClientStateBinding(clientDescriptor, new ClusterTierClientState(storeIdentifier, true)); managementRegistry.unregister(clientStateBinding); managementRegistry.registerAndRefresh(clientStateBinding).thenRun(() -> managementRegistry.pushServerEntityNotification(clientStateBinding, EHCACHE_SERVER_STORE_ATTACHED.name())); } }
Source:
protected String[] getConfigurationStrings(Collection<IConfigAdvice> configAdvice) { String configurationData = ""; String unconfigurationData = ""; Set<String> properties = new HashSet<String>(); for (IConfigAdvice advice : configAdvice) { for (Entry<String, String> aProperty : advice.getProperties().entrySet()) { String key = aProperty.getKey(); if (shouldPublishProperty(key) && !properties.contains(key)) { properties.add(key); Map<String, String> parameters = new LinkedHashMap<String, String>(); parameters.put("propName", key); parameters.put("propValue", aProperty.getValue()); configurationData += TouchpointInstruction.encodeAction("setProgramProperty", parameters); parameters.put("propValue", ""); unconfigurationData += TouchpointInstruction.encodeAction("setProgramProperty", parameters); } } for (URLEntry urlEntry : advice.getUpdateRepositories()) { Map<String, String> parameters = new LinkedHashMap<String, String>(); parameters.put("type", "0"); parameters.put("location", urlEntry.getURL()); parameters.put("enabled", urlEntry.getAnnotation()); configurationData += TouchpointInstruction.encodeAction("addRepository", parameters); parameters.put("type", "1"); configurationData += TouchpointInstruction.encodeAction("addRepository", parameters); } } return new String[] {configurationData, unconfigurationData}; }

Target:
protected String[] getConfigurationStrings(Collection<IConfigAdvice> configAdvice) { String configurationData = ""; String unconfigurationData = ""; Set<String> properties = new HashSet<String>(); for (IConfigAdvice advice : configAdvice) { for (Entry<String, String> aProperty : advice.getProperties().entrySet()) { String key = aProperty.getKey(); if (shouldPublishProperty(key) && !properties.contains(key)) { properties.add(key); Map<String, String> parameters = new LinkedHashMap<String, String>(); parameters.put("propName", key); parameters.put("propValue", aProperty.getValue()); configurationData += TouchpointInstruction.encodeAction("setProgramProperty", parameters); parameters.put("propValue", ""); unconfigurationData += TouchpointInstruction.encodeAction("setProgramProperty", parameters); } } for (IRepositoryReference repo : advice.getUpdateRepositories()) { Map<String, String> parameters = new LinkedHashMap<String, String>(); parameters.put("type", Integer.toString(repo.getType())); parameters.put("location", repo.getLocation().toString()); parameters.put("enabled", Boolean.toString((repo.getOptions() & IRepository.ENABLED) == IRepository.ENABLED)); configurationData += TouchpointInstruction.encodeAction("addRepository", parameters); parameters.remove("enabled"); unconfigurationData += TouchpointInstruction.encodeAction("removeRepository", parameters); } } return new String[] {configurationData, unconfigurationData}; }
Source:
public void runWorkerShutdownHooks() { if (topology.is_set_worker_hooks()) { for (IWorkerHook hook : getDeserializedWorkerHooks()) { hook.shutdown(); } } }

Target:
public void runWorkerShutdownHooks() { for (IWorkerHook hook : getDeserializedWorkerHooks()) { hook.shutdown(); } }
Source:
public void shouldGetURL() throws IOException { final S3FileStore s3FileStore = new S3FileStore(bucketSchema); s3FileStore.initialize(mockAmazonS3Client); final URL url = s3FileStore.publicUrlForFilePath(filePath); verify(mockAmazonS3Client).generatePresignedUrl(eq(bucketSchema + "-" + filePath.directory()), eq(filePath.filename()), any(Date.class), eq(HttpMethod.GET)); }

Target:
public void shouldGetURL() throws IOException { final S3FileStore s3FileStore = new S3FileStore(bucketSchema); s3FileStore.initialize(mockAmazonS3Client); final int randommillis = Randoms.randomInt(1000); DateTimeUtils.setCurrentMillisFixed(randommillis); final URL url = s3FileStore.publicUrlForFilePath(filePath); verify(mockAmazonS3Client).generatePresignedUrl(bucketSchema + "-" + filePath.directory(), filePath.filename(), new Date(3600000 + randommillis), HttpMethod.GET); }
Source:
private Pattern getIsoPattern(OVirtNodeInfo info) { log.infoFormat("getIsoPatter - pattern [{0}]", info.pattern); String expectedPattern = info.pattern; if (isoPattern == null || !expectedPattern.equals(isoPattern.toString())) { isoPattern = Pattern.compile(expectedPattern); } return isoPattern; }

Target:
private static Pattern getIsoPattern(OVirtNodeInfo info) { String expectedPattern = info.pattern; if (isoPattern == null || !expectedPattern.equals(isoPattern.toString())) { isoPattern = Pattern.compile(expectedPattern); } return isoPattern; }
Source:
public static String signCertificateRequest( String request, String name, String hostname ) throws IOException { EngineLocalConfig config = EngineLocalConfig.getInstance(); try ( final OutputStream os = new FileOutputStream( new File( new File(config.getPKIDir(), "requests"), String.format("%s.req", name) ) ) ) { os.write(request.getBytes(StandardCharsets.UTF_8)); } if ( !new OpenSslCAWrapper().signCertificateRequest( new File(new File(config.getUsrDir(), "bin"), "pki-enroll-request.sh"), name, hostname ) ) { throw new RuntimeException("Certificate enrollment failed"); } return new String(Files.readAllBytes( new File(new File(config.getPKIDir(), "certs"), String.format("%s.cer", name)).toPath())); }

Target:
public static String signCertificateRequest( String request, String name, String hostname ) throws IOException { EngineLocalConfig config = EngineLocalConfig.getInstance(); try ( final OutputStream os = new FileOutputStream( new File( new File(config.getPKIDir(), "requests"), String.format("%s.req", name) ) ) ) { os.write(request.getBytes(StandardCharsets.UTF_8)); } if ( !new OpenSslCAWrapper().signCertificateRequest( new File(new File(config.getUsrDir(), "bin"), "pki-enroll-request.sh"), name, hostname ) ) { throw new RuntimeException("Certificate enrollment failed"); } return new String(Files.readAllBytes( Paths.get(config.getPKIDir().getPath(), "certs", String.format("%s.cer", name)))); }
Source:
protected void okPressed() { try { { String merge = branchText.getText(); if (merge.length() > 0) myConfig.setString(ConfigConstants.CONFIG_BRANCH_SECTION, myBranchName, ConfigConstants.CONFIG_KEY_MERGE, merge); else myConfig.unset(ConfigConstants.CONFIG_BRANCH_SECTION, myBranchName, ConfigConstants.CONFIG_KEY_MERGE); } { String remote = remoteText.getText(); if (remote.length() > 0) myConfig.setString(ConfigConstants.CONFIG_BRANCH_SECTION, myBranchName, ConfigConstants.CONFIG_KEY_REMOTE, remote); else myConfig.unset(ConfigConstants.CONFIG_BRANCH_SECTION, myBranchName, ConfigConstants.CONFIG_KEY_REMOTE); } { boolean rebaseFlag = rebase.getSelection(); if (rebaseFlag) myConfig.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, myBranchName, ConfigConstants.CONFIG_KEY_REBASE, true); else myConfig.unset(ConfigConstants.CONFIG_BRANCH_SECTION, myBranchName, ConfigConstants.CONFIG_KEY_REBASE); } try { myConfig.save(); super.okPressed(); } catch (IOException e) { Activator.handleError( UIText.BranchConfigurationDialog_SaveBranchConfigFailed, e, true); } } catch (RuntimeException e) { Activator.handleError(e.getMessage(), e, true); } }

Target:
protected void okPressed() { try { String merge = branchText.getText(); if (merge.length() > 0) myConfig.setString(ConfigConstants.CONFIG_BRANCH_SECTION, myBranchName, ConfigConstants.CONFIG_KEY_MERGE, merge); else myConfig.unset(ConfigConstants.CONFIG_BRANCH_SECTION, myBranchName, ConfigConstants.CONFIG_KEY_MERGE); String remote = remoteText.getText(); if (remote.length() > 0) myConfig.setString(ConfigConstants.CONFIG_BRANCH_SECTION, myBranchName, ConfigConstants.CONFIG_KEY_REMOTE, remote); else myConfig.unset(ConfigConstants.CONFIG_BRANCH_SECTION, myBranchName, ConfigConstants.CONFIG_KEY_REMOTE); boolean rebaseFlag = rebase.getSelection(); if (rebaseFlag) myConfig.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, myBranchName, ConfigConstants.CONFIG_KEY_REBASE, true); else myConfig.unset(ConfigConstants.CONFIG_BRANCH_SECTION, myBranchName, ConfigConstants.CONFIG_KEY_REBASE); try { myConfig.save(); super.okPressed(); } catch (IOException e) { Activator.handleError( UIText.BranchConfigurationDialog_SaveBranchConfigFailed, e, true); } } catch (RuntimeException e) { Activator.handleError(e.getMessage(), e, true); } }
Source:
public void testBrickFieldValidValue() throws InterpretationException { assertSame(BRICK_FORMULA_VALUE, brickFormula.interpretInteger(sprite)); }

Target:
public void testBrickFieldValidValue() throws InterpretationException { assertEquals(BRICK_FORMULA_VALUE, brickFormula.interpretInteger(sprite)); }
Source:
public void execute() throws MojoExecutionException, MojoFailureException { getLog().info(String.format("Transforming %d handlers to %s", files.size(), outputDirectory)); for (File file : files) { getLog().info(String.format("Transforming %s...", file)); if (!file.exists()) { throw new MojoFailureException(String.format("Grammar file %s does not exist!", file)); } else if (!file.isFile()) { throw new MojoFailureException(String.format("Grammar file %s is not a regular file!", file)); } Grammar grammar; Machine machine; try { grammar = new Parser(getLog()::debug, sourceDirectories).load(file); machine = grammar.build(maxSwitchStates, userSwitchThreshold, passContext); } catch (IOException e) { throw new MojoExecutionException(String.format("Cannot read file %s", file), e); } catch (ParserException | GeneratorException e) { throw new MojoFailureException(String.format("Error in file %s", file), e); } File output = new File(outputDirectory, grammar.getPackage().replaceAll("\\.", "\\" + File.separator) + File.separator + grammar.getSimpleName() + ".java"); output.getParentFile().mkdirs(); try { Files.write(Paths.get(output.toURI()), machine.buildSource().getBytes()); } catch (IOException e) { throw new MojoExecutionException(String.format("Cannot write generated source code to %s", output), e); } project.addCompileSourceRoot(outputDirectory.getAbsolutePath()); } }

Target:
public void execute() throws MojoExecutionException, MojoFailureException { getLog().info(String.format("Transforming %d handlers to %s", files.size(), outputDirectory)); for (File file : files) { getLog().info(String.format("Transforming %s...", file)); if (!file.exists()) { throw new MojoFailureException(String.format("Grammar file %s does not exist!", file)); } else if (!file.isFile()) { throw new MojoFailureException(String.format("Grammar file %s is not a regular file!", file)); } Grammar grammar; Machine machine; try { grammar = new Parser(getLog()::debug, sourceDirectories).load(file); machine = grammar.build(maxSwitchStates, userSwitchThreshold, passContext); } catch (IOException e) { throw new MojoExecutionException(String.format("Cannot read file %s", file), e); } catch (ParserException | GeneratorException e) { throw new MojoFailureException(String.format("Error in file %s", file), e); } File output = new File(outputDirectory, grammar.getPackage().replace('.', File.separatorChar) + File.separator + grammar.getSimpleName() + ".java"); output.getParentFile().mkdirs(); try { Files.write(Paths.get(output.toURI()), machine.buildSource().getBytes()); } catch (IOException e) { throw new MojoExecutionException(String.format("Cannot write generated source code to %s", output), e); } project.addCompileSourceRoot(outputDirectory.getAbsolutePath()); } }
Source:
void factoryStartFailsIfScenarioScopeIsNotBound() { factory = new GuiceFactory(Guice.createInjector()); Executable testMethod = () -> factory.start(); ConfigurationException actualThrown = assertThrows(ConfigurationException.class, testMethod); assertThat("Unexpected exception message", actualThrown.getMessage(), is(equalTo( "Guice configuration errors:" + System.lineSeparator() + System.lineSeparator() + "1) No implementation for io.cucumber.guice.ScenarioScope was bound." + System.lineSeparator() + " while locating io.cucumber.guice.ScenarioScope" + System.lineSeparator() + System.lineSeparator() + "1 error" ))); }

Target:
void factoryStartFailsIfScenarioScopeIsNotBound() { factory = new GuiceFactory(Guice.createInjector()); Executable testMethod = () -> factory.start(); ConfigurationException actualThrown = assertThrows(ConfigurationException.class, testMethod); assertThat("Unexpected exception message", actualThrown.getMessage(), is(equalToCompressingWhiteSpace( "Guice configuration errors:\n\n" + "1) No implementation for io.cucumber.guice.ScenarioScope was bound.\n" + " while locating io.cucumber.guice.ScenarioScope\n\n" + "1 error" ))); }
Source:
protected static boolean shouldClientBeTested(HttpClient client) { String configuredHttpClientToTest = Configuration.getGlobalConfiguration().get(AZURE_TEST_HTTP_CLIENTS); if (CoreUtils.isNullOrEmpty(configuredHttpClientToTest)) { return client.getClass().getSimpleName().equals(AZURE_TEST_HTTP_CLIENTS_VALUE_NETTY); } if (configuredHttpClientToTest.equals(AZURE_TEST_HTTP_CLIENTS_VALUE_ALL)) { return true; } return client.getClass().getSimpleName().equals(configuredHttpClientToTest); }

Target:
public static boolean shouldClientBeTested(HttpClient client) { String configuredHttpClientToTest = Configuration.getGlobalConfiguration().get(AZURE_TEST_HTTP_CLIENTS); if (CoreUtils.isNullOrEmpty(configuredHttpClientToTest)) { return client.getClass().getSimpleName().equals(AZURE_TEST_HTTP_CLIENTS_VALUE_NETTY); } if (configuredHttpClientToTest.equals(AZURE_TEST_HTTP_CLIENTS_VALUE_ALL)) { return true; } String[] configuredHttpClientList = configuredHttpClientToTest.split(","); return Arrays.stream(configuredHttpClientList).anyMatch(configuredHttpClient -> client.getClass().getSimpleName().equals(configuredHttpClient.trim())); }
Source:
private static boolean isBehindLiveWindow(ExoPlaybackException e) { com.google.android.exoplayer2.util.Log.e("ExoPlayer Exception", e.toString()); if (e.type != ExoPlaybackException.TYPE_SOURCE) { return false; } Throwable cause = e.getSourceException(); while (cause != null) { if (cause instanceof BehindLiveWindowException || cause instanceof HttpDataSource.HttpDataSourceException) { return true; } cause = cause.getCause(); } return false; }

Target:
private static boolean isBehindLiveWindow(ExoPlaybackException e) { Log.e("ExoPlayer Exception", e.toString()); if (e.type != ExoPlaybackException.TYPE_SOURCE) { return false; } Throwable cause = e.getSourceException(); while (cause != null) { if (cause instanceof BehindLiveWindowException || cause instanceof HttpDataSource.HttpDataSourceException) { return true; } cause = cause.getCause(); } return false; }
Source:
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (CloudPlatform.CLOUD_FOUNDRY.isActive(environment)) { Map<String, Object> map = new HashMap<>(); map.put("spring.boot.admin.client.auto-deregistration", "true"); MapPropertySource propertySource = new MapPropertySource( "cloudConfigPropertySource", map); environment.getPropertySources().addFirst(propertySource); } }

Target:
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (CloudPlatform.CLOUD_FOUNDRY.isActive(environment) && !environment.containsProperty("spring.boot.admin.client.auto-deregistration")) { Map<String, Object> map = new HashMap<>(); map.put("spring.boot.admin.client.auto-deregistration", "true"); MapPropertySource propertySource = new MapPropertySource( "springBootAdminClientCloudFoundryProperties", map); environment.getPropertySources().addFirst(propertySource); } }
Source:
protected void executeQueryCommand() { List<LUNs> luns = getLunsForVgId(getVgId()); List<LUNs> lunsFromDeviceList = getDeviceList(); for (LUNs lun : luns) { for (LUN_storage_server_connection_map map : getLunsMap(lun.getLUN_id())) { addConnection(lun, getConnection(map.getstorage_server_connection())); } for (LUNs lunFromDeviceList : lunsFromDeviceList) { if (lun.getLUN_id().equals(lunFromDeviceList.getLUN_id())) { lun.setPathsDictionary(lunFromDeviceList.getPathsDictionary()); } } } setReturnValue(luns); }

Target:
protected void executeQueryCommand() { List<LUNs> luns = getLunsForVgId(getVgId()); Map<String, LUNs> lunsFromDeviceMap = getLunsFromDeviceMap(); for (LUNs lun : luns) { for (LUN_storage_server_connection_map map : getLunsMap(lun.getLUN_id())) { addConnection(lun, getConnection(map.getstorage_server_connection())); } LUNs lunFromDeviceList = lunsFromDeviceMap.get(lun.getLUN_id()); lun.setPathsDictionary(lunFromDeviceList.getPathsDictionary()); } setReturnValue(luns); }
Source:
public void updateVariable(boolean isAdmin, UpdateTaskVariablePayload updateTaskVariablePayload) { if (!isAdmin) { getTaskToUpdate(updateTaskVariablePayload.getTaskId()); } if (updateTaskVariablePayload.getName() == null || updateTaskVariablePayload.getName().isEmpty()) { throw new IllegalStateException("You cannot update a variable without name"); } Map<String, org.activiti.engine.impl.persistence.entity.VariableInstance> variables = taskService.getVariableInstancesLocal(updateTaskVariablePayload.getTaskId()); if (variables == null) { throw new IllegalStateException("Variable does not exist"); } if (!variables.containsKey(updateTaskVariablePayload.getName())) { throw new IllegalStateException("Variable does not exist"); } taskService.setVariableLocal(updateTaskVariablePayload.getTaskId(), updateTaskVariablePayload.getName(), updateTaskVariablePayload.getValue()); }

Target:
public void updateVariable(boolean isAdmin, UpdateTaskVariablePayload updateTaskVariablePayload) { if (!isAdmin) { assertCanModifyTask(getInternalTask(updateTaskVariablePayload.getTaskId())); } if (updateTaskVariablePayload.getName() == null || updateTaskVariablePayload.getName().isEmpty()) { throw new IllegalStateException("You cannot update a variable without name"); } assertVariableExists(updateTaskVariablePayload); taskService.setVariableLocal(updateTaskVariablePayload.getTaskId(), updateTaskVariablePayload.getName(), updateTaskVariablePayload.getValue()); }
Source:
public int compareTo(RDotTxtEntry that) { if (this == that) { return 0; } ComparisonChain comparisonChain = ComparisonChain.start().compare(this.type, that.type); String thisNameParts = this.name.split("_"); String thatNameParts = that.name.split("_"); int index = 0; while (index < thisNameParts.length && index < thatNameParts.length) { comparisonChain = comparisonChain.compare(thisNameParts[index], thatNameParts[index]); index++; } if (index < thisNameParts.length) { comparisonChain = comparisonChain.compare(thisNameParts[index], ""); } else if (index < thatNameParts.length) { comparisonChain = comparisonChain.compare("", thatNameParts[index]); } return comparisonChain.result(); }

Target:
public int compareTo(RDotTxtEntry that) { if (this == that) { return 0; } ComparisonChain comparisonChain = ComparisonChain.start().compare(this.type, that.type); String thisNameParts = this.name.split("_"); String thatNameParts = that.name.split("_"); int index = 0; while (index < thisNameParts.length && index < thatNameParts.length) { comparisonChain = comparisonChain.compare(thisNameParts[index], thatNameParts[index]); index++; } if (index < thisNameParts.length || index < thatNameParts.length) { comparisonChain = comparisonChain.compare(thisNameParts.length, thatNameParts.length); } return comparisonChain.result(); }
Source:
public void execute(CommandContext context) { File f = findRestApiConfigFile(context); if (f.exists()) { AppConfig appConfig = context.getAppConfig(); ServerManager mgr = new ServerManager(context.getManageClient(), appConfig.getGroupName()); saveResource(mgr, context, f); if (appConfig.isTestPortSet()) { String payload = copyFileToString(f); String json = payloadTokenReplacer.replaceTokens(payload, appConfig, true); adjustPayloadBeforeSavingResource(mgr, context, f, json); mgr.save(json); } } else { logger.info(format("No REST API server file found at %s, so not updating the server", f.getAbsolutePath())); } }

Target:
public void execute(CommandContext context) { File f = findRestApiConfigFile(context); if (f != null && f.exists()) { AppConfig appConfig = context.getAppConfig(); ServerManager mgr = new ServerManager(context.getManageClient(), appConfig.getGroupName()); saveResource(mgr, context, f); if (appConfig.isTestPortSet()) { json = payloadTokenReplacer.replaceTokens(payload, appConfig, true); adjustPayloadBeforeSavingResource(mgr, context, f, json); mgr.save(json); } } }