auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean coversTheWholeDiff(ChangePatternInstance instancePattern, Diff diff) { for(Operation diffOperation : diff.getAllOperations()){ boolean foundOp = false; for(Operation instanceOperation : instancePattern.getActions()){ if(diffOperation.toString().equals(instanceOperation.toString())){ foundOp = true; break; } } if(!foundOp) return false; } return true; }

Target:
private boolean coversTheWholeDiff(ChangePatternInstance instancePattern, Diff diff) { for(Operation diffOperation : diff.getRootOperations()){ boolean foundOp = false; for(Operation instanceOperation : instancePattern.getActions()){ if(diffOperation.equals(instanceOperation)){ foundOp = true; break; } } if(!foundOp) return false; } return true; }
Source:
public String getStackRepositoryJson(Long stackId) { AmbariClient ambariClient = getAmbariClient(stackId); Stack stack = stackService.getById(stackId); Cluster cluster = stack.getCluster(); if (cluster == null) { throw new BadRequestException(String.format("There is no cluster installed on stack '%s'.", stack.getName())); } StackRepoDetails repoDetails = clusterComponentConfigProvider.getStackRepoDetails(cluster.getId()); String stackRepoId = repoDetails.getStack().get(REPO_ID_TAG); String osType = ambariRepositoryVersionService.getOsTypeForStackRepoDetails(repoDetails); if (osType != null && osType.isEmpty()) { LOGGER.info(String.format("The stored HDP repo details (%s) do not contain OS information for stack '%s'.", repoDetails, stack.getName())); return null; } try { String stackRepositoryJson = ambariClient.getLatestStackRepositoryAsJson(cluster.getName(), osType, stackRepoId); if (stackRepositoryJson == null) { throw new BadRequestException(String.format("Stack Repository response coming from Ambari server was null " + "for cluster '%s' and repo url '%s'.", cluster.getName(), stackRepoId)); } return stackRepositoryJson; } catch (Exception e) { if (e instanceof HttpResponseException) { HttpResponseException cast = HttpResponseException.class.cast(e); if (cast.getResponse().getStatus() == HttpStatus.SC_NOT_FOUND) { throw new BadRequestException("The specified osType is wrong. " + cast.getMessage()); } } throw e; } }

Target:
public String getStackRepositoryJson(Long stackId) { AmbariClient ambariClient = getAmbariClient(stackId); Stack stack = stackService.getById(stackId); Cluster cluster = stack.getCluster(); if (cluster == null) { throw new BadRequestException(String.format("There is no cluster installed on stack '%s'.", stack.getName())); } StackRepoDetails repoDetails = clusterComponentConfigProvider.getStackRepoDetails(cluster.getId()); String stackRepoId = repoDetails.getStack().get(REPO_ID_TAG); String osType = ambariRepositoryVersionService.getOsTypeForStackRepoDetails(repoDetails); if (osType != null && osType.isEmpty()) { LOGGER.info(String.format("The stored HDP repo details (%s) do not contain OS information for stack '%s'.", repoDetails, stack.getName())); return null; } try { String stackRepositoryJson = ambariClient.getLatestStackRepositoryAsJson(cluster.getName(), osType, stackRepoId); if (stackRepositoryJson == null) { throw new BadRequestException(String.format("Stack Repository response coming from Ambari server was null " + "for cluster '%s' and repo url '%s'.", cluster.getName(), stackRepoId)); } return stackRepositoryJson; } catch (Exception e) { LOGGER.error("Failed to get latest stack repository. osType: '{}'.", osType, e); if (e instanceof HttpResponseException) { HttpResponseException cast = HttpResponseException.class.cast(e); if (cast.getResponse().getStatus() == HttpStatus.SC_NOT_FOUND) { throw new BadRequestException("The specified osType is wrong. " + cast.getMessage()); } } throw e; } }
Source:
void allocate(File destinationFile, long sizeInBytes) throws IOException { long startTime = System.currentTimeMillis(); try { if (enablePooling && poolState != PoolState.INITIALIZED) { logger.info("Allocating segment of size to before pool is fully initialized", sizeInBytes, destinationFile.getAbsolutePath()); metrics.diskSpaceAllocatorAllocBeforeInitCount.inc(); } else { logger.debug("Allocating segment of size to {}", sizeInBytes, destinationFile.getAbsolutePath()); } if (destinationFile.exists()) { throw new IOException("Destination file already exists: " + destinationFile.getAbsolutePath()); } File reserveFile = null; if (poolState != PoolState.NOT_INVENTORIED) { reserveFile = reserveFiles.remove(sizeInBytes); } if (reserveFile == null) { if (enablePooling) { logger.info( "Segment of size not found in pool; attempting to create a new preallocated file; poolState: {}", sizeInBytes, poolState); metrics.diskSpaceAllocatorSegmentNotFoundCount.inc(); } Utils.preAllocateFileIfNeeded(destinationFile, sizeInBytes); } else { try { Files.move(reserveFile.toPath(), destinationFile.toPath()); } catch (Exception e) { reserveFiles.add(sizeInBytes, reserveFile); throw e; } } } finally { long elapsedTime = System.currentTimeMillis() - startTime; logger.debug("allocate took ms", elapsedTime); metrics.diskSpaceAllocatorAllocTimeMs.update(elapsedTime - startTime); } }

Target:
void allocate(File destinationFile, long sizeInBytes) throws IOException { long startTime = System.currentTimeMillis(); try { if (enablePooling && poolState != PoolState.INITIALIZED) { logger.info("Allocating segment of size to before pool is fully initialized", sizeInBytes, destinationFile.getAbsolutePath()); metrics.diskSpaceAllocatorAllocBeforeInitCount.inc(); } else { logger.debug("Allocating segment of size to {}", sizeInBytes, destinationFile.getAbsolutePath()); } if (destinationFile.exists()) { throw new IOException("Destination file already exists: " + destinationFile.getAbsolutePath()); } File reserveFile = null; if (poolState != PoolState.NOT_INVENTORIED) { reserveFile = reserveFiles.remove(sizeInBytes); } if (reserveFile == null) { if (enablePooling) { logger.info( "Segment of size not found in pool; attempting to create a new preallocated file; poolState: {}", sizeInBytes, poolState); metrics.diskSpaceAllocatorSegmentNotFoundCount.inc(); } Utils.preAllocateFileIfNeeded(destinationFile, sizeInBytes); } else { try { Files.move(reserveFile.toPath(), destinationFile.toPath()); } catch (Exception e) { reserveFiles.add(sizeInBytes, reserveFile); throw e; } } } finally { long elapsedTime = System.currentTimeMillis() - startTime; logger.debug("allocate took ms", elapsedTime); metrics.diskSpaceAllocatorAllocTimeMs.update(elapsedTime); } }
Source:
public void process(Trace trace, Node node, Direction direction, Map<String, ?> headers, Object[] values) { if (log.isLoggable(Level.FINEST)) { log.finest("ProcessManager/Processor: process trace=" + trace + " node=" + node + " direction=" + direction + " headers=" + headers + " values=" + values); if (values != null) { for (int i = 0; i < values.length; i++) { log.finest(" [value " + i + "] = " + values[i]); } } } if (processor.getNodeType() == node.getType() && processor.getDirection() == direction) { if (uriFilter != null && !uriFilter.test(node.getUri())) { return; } if (processor.getOperation() != null && !processor.getOperation().trim().isEmpty() && !processor.getOperation().equals(node.getOperation())) { return; } Set<Property> faults = node.getProperties(Constants.PROP_FAULT); if (faultFilter == null && !faults.isEmpty()) { return; } if (faultFilter != null && faults.stream().filter(f -> faultFilter.test(f.getValue())).count() == 0) { return; } if (issues != null) { node.getProperties().add(new Property(Constants.PROP_FAULT, issues)); } if (predicateHandler != null) { try { if (!predicateHandler.test(trace, node, direction, headers, values)) { if (log.isLoggable(Level.FINEST)) { log.finest("ProcessManager/Processor: process - predicate returned false"); } return; } } catch (Throwable t) { ProcessorIssue pi = new ProcessorIssue(); pi.setProcessor(processor.getDescription()); pi.setSeverity(Severity.Error); pi.setDescription(t.getMessage()); node.getProperties().add(new Property(Constants.PROP_FAULT, pi)); return; } } for (int i = 0; i < actions.size(); i++) { actions.get(i).process(trace, node, direction, headers, values); } } }

Target:
public void process(Trace trace, Node node, Direction direction, Map<String, ?> headers, Object[] values) { if (log.isLoggable(Level.FINEST)) { log.finest("ProcessManager/Processor: process trace=" + trace + " node=" + node + " direction=" + direction + " headers=" + headers + " values=" + values); if (values != null) { for (int i = 0; i < values.length; i++) { log.finest(" [value " + i + "] = " + values[i]); } } } if (processor.getNodeType() == node.getType() && processor.getDirection() == direction) { if (uriFilter != null && !uriFilter.test(node.getUri())) { return; } if (processor.getOperation() != null && !processor.getOperation().trim().isEmpty() && !processor.getOperation().equals(node.getOperation())) { return; } Set<Property> faults = node.getProperties(Constants.PROP_FAULT); if (faultFilter == null && !faults.isEmpty()) { return; } if (faultFilter != null && faults.stream().filter(f -> faultFilter.test(f.getValue())).count() == 0) { return; } if (predicateHandler != null) { try { if (!predicateHandler.test(trace, node, direction, headers, values)) { if (log.isLoggable(Level.FINEST)) { log.finest("ProcessManager/Processor: process - predicate returned false"); } return; } } catch (Throwable t) { log.severe(processor.getDescription(), t); return; } } for (int i = 0; i < actions.size(); i++) { actions.get(i).process(trace, node, direction, headers, values); } } }
Source:
public Observable<D2Progress> uploadDataValues(List<DataValue> dataValues) { return Observable.defer(() -> { if (dataValues.isEmpty()) { return Observable.empty(); } else { D2ProgressManager progressManager = new D2ProgressManager(2); return systemInfoDownloader.downloadMetadata().andThen(Observable.create(emitter -> { emitter.onNext(progressManager.increaseProgress(SystemInfo.class, false)); markPartitionsAsUploading(dataValues); DataValueSet dataValueSet = new DataValueSet(dataValues); DataValueImportSummary dataValueImportSummary = apiCallExecutor.executeObjectCall( dataValueService.postDataValues(dataValueSet)); dataValueImportHandler.handleImportSummary(dataValueSet, dataValueImportSummary); emitter.onNext(progressManager.increaseProgress(DataValue.class, true)); emitter.onComplete(); })); } }); }

Target:
public Observable<D2Progress> uploadDataValues(List<DataValue> dataValues) { return Observable.defer(() -> { if (dataValues.isEmpty()) { return Observable.empty(); } else { D2ProgressManager progressManager = new D2ProgressManager(2); return systemInfoDownloader.downloadMetadata().andThen(Observable.create(emitter -> { emitter.onNext(progressManager.increaseProgress(SystemInfo.class, false)); markPartitionsAs(dataValues, State.UPLOADING); try { DataValueSet dataValueSet = new DataValueSet(dataValues); DataValueImportSummary dataValueImportSummary = apiCallExecutor.executeObjectCall( dataValueService.postDataValues(dataValueSet)); dataValueImportHandler.handleImportSummary(dataValueSet, dataValueImportSummary); } catch (Exception e) { markPartitionsAs(dataValues, State.ERROR); throw e; } emitter.onNext(progressManager.increaseProgress(DataValue.class, true)); emitter.onComplete(); })); } }); }
Source:
ReliableChannel( Function<ClientChannelConfiguration, Result<ClientChannel>> chFactory, ClientConfiguration clientCfg ) throws ClientException { if (chFactory == null) throw new NullPointerException("chFactory"); if (clientCfg == null) throw new NullPointerException("clientCfg"); this.chFactory = chFactory; this.clientCfg = clientCfg; List<InetSocketAddress> addrs = parseAddresses(clientCfg.getAddresses()); srvCnt = addrs.size(); primary = addrs.get(new Random().nextInt(addrs.size())); for (InetSocketAddress a : addrs) { if (a != primary) backups.add(a); } ClientConnectionException lastEx = null; for (int i = 0; i < addrs.size(); i++) { try { ch = chFactory.apply(new ClientChannelConfiguration(clientCfg).setAddress(addrs.get(i))).get(); return; } catch (ClientConnectionException e) { lastEx = e; changeServer(ch); } } throw lastEx; }

Target:
ReliableChannel( Function<ClientChannelConfiguration, Result<ClientChannel>> chFactory, ClientConfiguration clientCfg ) throws ClientException { if (chFactory == null) throw new NullPointerException("chFactory"); if (clientCfg == null) throw new NullPointerException("clientCfg"); this.chFactory = chFactory; this.clientCfg = clientCfg; List<InetSocketAddress> addrs = parseAddresses(clientCfg.getAddresses()); srvCnt = addrs.size(); primary = addrs.get(new Random().nextInt(addrs.size())); for (InetSocketAddress a : addrs) { if (a != primary) backups.add(a); } ClientConnectionException lastEx = null; for (int i = 0; i < addrs.size(); i++) { try { ch = chFactory.apply(new ClientChannelConfiguration(clientCfg).setAddress(primary)).get(); return; } catch (ClientConnectionException e) { lastEx = e; rollAddress(); } } throw lastEx; }
Source:
private long profile( PagedFile file ) throws IOException { long pagesInMemory = 0; File outputNext = profileOutputFileNext( file ); try ( OutputStream outputStream = compressedOutputStream( outputNext ); PageCursor cursor = file.io( 0, PF_SHARED_READ_LOCK | PF_NO_FAULT ) ) { int stepper = 7; int b = 0; for ( ; ; ) { if ( stopped ) { return pagesInMemory; } if ( !cursor.next() ) { break; } b >>= 1; if ( cursor.getCurrentPageId() != PageCursor.UNBOUND_PAGE_ID ) { pagesInMemory++; b += 0b1000_0000; } if ( stepper == 0 ) { outputStream.write( b ); b = 0; stepper = 7; } else { stepper--; } } b >>= stepper + 1; outputStream.write( b ); outputStream.flush(); } File outputFinal = profileOutputFileFinal( file ); fs.renameFile( outputNext, outputFinal, StandardCopyOption.REPLACE_EXISTING ); return pagesInMemory; }

Target:
private long profile( PagedFile file ) throws IOException { long pagesInMemory = 0; File outputNext = profileOutputFileNext( file ); try ( OutputStream outputStream = compressedOutputStream( outputNext ); PageCursor cursor = file.io( 0, PF_SHARED_READ_LOCK | PF_NO_FAULT ) ) { int stepper = 0; int b = 0; for ( ; ; ) { if ( stopped ) { return pagesInMemory; } if ( !cursor.next() ) { break; } if ( cursor.getCurrentPageId() != PageCursor.UNBOUND_PAGE_ID ) { pagesInMemory++; b |= 1 << stepper; } stepper++; if ( stepper == 8 ) { outputStream.write( b ); b = 0; stepper = 0; } } outputStream.write( b ); outputStream.flush(); } File outputFinal = profileOutputFileFinal( file ); fs.renameFile( outputNext, outputFinal, StandardCopyOption.REPLACE_EXISTING ); return pagesInMemory; }
Source:
AuthenticationResult getAccessTokenUsingAssertion() throws AuthenticationException { final String methodName = ":getAccessTokenUsingAssertion"; final AuthenticationResult result = acquireTokenWithAssertion(); if (result != null && !StringExtensions.isNullOrBlank(result.getAccessToken())) { try { mTokenCacheAccessor.updateTokenCache(mAuthRequest, result); } catch (MalformedURLException e) { Logger.v(TAG + methodName, "Access token fetched but unable to update token cache"); throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_URL, e.getMessage(), e); } } return result; }

Target:
AuthenticationResult getAccessTokenUsingAssertion() throws AuthenticationException { final String methodName = ":getAccessTokenUsingAssertion"; final AuthenticationResult result = acquireTokenWithAssertion(); if (result != null && !StringExtensions.isNullOrBlank(result.getAccessToken())) { try { mTokenCacheAccessor.updateTokenCache(mAuthRequest, result); } catch (MalformedURLException e) { Logger.w(TAG + methodName, "Access token fetched but unable to update token cache"); throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_URL, e.getMessage(), e); } } return result; }
Source:
public void ensureCatchNoParametersSearch() throws AvroRemoteException { try { SearchGenotypePhenotypeRequest request = SearchGenotypePhenotypeRequest.newBuilder().build(); SearchGenotypePhenotypeResponse response = client.genotypePhenotype.searchGenotypePhenotype(request); fail("should have thrown error"); } catch ( Exception e) { } }

Target:
public void ensureCatchNoParametersSearch() throws AvroRemoteException { SearchGenotypePhenotypeRequest request = SearchGenotypePhenotypeRequest.newBuilder().build(); final GAWrapperException didThrow = catchGAWrapperException(() -> client.genotypePhenotype.searchGenotypePhenotype(request) ); assertThat(didThrow.getHttpStatusCode()).isEqualTo(HttpURLConnection.HTTP_BAD_REQUEST); }
Source:
public static Map<String, Object> getConfigFromClasspath(List<String> cp, Map<String, Object> conf) throws IOException { if (cp == null || cp.isEmpty()) { return conf; } Yaml yaml = new Yaml(new SafeConstructor()); Map<String, Object> defaultsConf = null; Map<String, Object> stormConf = null; for (String part: cp) { String wildcardSuffix = File.separator + "*"; if (part.endsWith(wildcardSuffix)) { File dir = new File(part.substring(0, part.length() - wildcardSuffix.length())); File[] jarFiles = dir.listFiles((dir1, name) -> name.endsWith(".jar")); if (jarFiles != null) { for (File jarFile : jarFiles) { JarConfigReader jarConfigReader = new JarConfigReader(yaml, defaultsConf, stormConf, jarFile).invoke(); defaultsConf = jarConfigReader.getDefaultsConf(); stormConf = jarConfigReader.getStormConf(); } } } else { File f = new File(part); if (f.isDirectory()) { if (defaultsConf == null) { defaultsConf = readConfIgnoreNotFound(yaml, new File(f, "defaults.yaml")); } if (stormConf == null) { stormConf = readConfIgnoreNotFound(yaml, new File(f, "storm.yaml")); } } else { JarConfigReader jarConfigReader = new JarConfigReader(yaml, defaultsConf, stormConf, f).invoke(); defaultsConf = jarConfigReader.getDefaultsConf(); stormConf = jarConfigReader.getStormConf(); } } } if (stormConf != null) { defaultsConf.putAll(stormConf); } return defaultsConf; }

Target:
public static Map<String, Object> getConfigFromClasspath(List<String> cp, Map<String, Object> conf) throws IOException { if (cp == null || cp.isEmpty()) { return conf; } Yaml yaml = new Yaml(new SafeConstructor()); Map<String, Object> defaultsConf = null; Map<String, Object> stormConf = null; for (String part: cp) { File f = new File(part); if (f.getName().equals("*")) { File dir = f.getParentFile(); if (dir == null) { dir = new File("."); } File[] jarFiles = dir.listFiles((dir1, name) -> name.endsWith(".jar") || name.endsWith(".JAR")); if (jarFiles == null) { throw new IOException("Fail to list jar files in directory: " + dir); } for (File jarFile : jarFiles) { JarConfigReader jarConfigReader = new JarConfigReader(yaml, defaultsConf, stormConf, jarFile).readJar(); defaultsConf = jarConfigReader.getDefaultsConf(); stormConf = jarConfigReader.getStormConf(); } } else if (f.isDirectory()) { if (defaultsConf == null) { defaultsConf = readConfIgnoreNotFound(yaml, new File(f, "defaults.yaml")); } if (stormConf == null) { stormConf = readConfIgnoreNotFound(yaml, new File(f, "storm.yaml")); } } else if (f.isFile()) { String fileName = f.getName(); if (fileName.endsWith(".zip") || fileName.endsWith(".ZIP")) { JarConfigReader jarConfigReader = new JarConfigReader(yaml, defaultsConf, stormConf, f).readZip(); defaultsConf = jarConfigReader.getDefaultsConf(); stormConf = jarConfigReader.getStormConf(); } else if (fileName.endsWith(".jar") || fileName.endsWith(".JAR")) { JarConfigReader jarConfigReader = new JarConfigReader(yaml, defaultsConf, stormConf, f).readJar(); defaultsConf = jarConfigReader.getDefaultsConf(); stormConf = jarConfigReader.getStormConf(); } } } if (stormConf != null) { defaultsConf.putAll(stormConf); } return defaultsConf; }
Source:
private static boolean isSnapshot(File jarFile) { return jarFile.getName() .matches(".*SNAPSHOT(-selfcontained)?\\.jar$"); }

Target:
static boolean isSnapshot(File jarFile) { return SNAPSHOT_JAR.matcher(jarFile.getName()).matches(); }
Source:
public int getLanguagePosition() { String lang = LanguageUtils.getLanguage(); int i; for(i = 0;i<languageList.length;i++) { if(lang.equals(languageList[i])) break; } return i; }

Target:
public int getLanguagePosition() { String lang = LanguageUtils.getLanguage(); String[] languageList = ApplicationConstants.OpenMRSlanguage.LANGUAGE_LIST; int i; for (i = 0; i < languageList.length; i++) { if (lang.equals(languageList[i])) { return i; } } return 0; }
Source:
protected static void createDirIfNotExists(File file) { if (!file.exists()) { try { file.mkdir(); logger.info("The " + file.getName() + " directory is created"); } catch (Exception e) { logger.error("Couldn't create destination directory!"); System.exit(1); } } else { logger.info("The given local path " + file.getName() + " already exists"); } }

Target:
static void createDirIfNotExists(File file) { if (!file.exists()) { try { file.mkdir(); logger.info("The " + file.getName() + " directory is created"); } catch (Exception e) { logger.error("Couldn't create destination directory! " + file.getName()); System.exit(1); } } else { logger.info("The given local path " + file.getName() + " already exists"); } }
Source:
public Process runServer() throws IOException { final String serverConsoleLogPath = "/Users/maxi/Projects/tmp/test.result"; File logPath = new File(getCorfuServerLogPath(host, port)); if (!logPath.exists()) { logPath.mkdir(); } ProcessBuilder builder = new ProcessBuilder(); builder.command("sh", "-c", "bin/corfu_replication_server " + getOptionsString()); builder.directory(new File(CORFU_PROJECT_DIR)); Process corfuReplicationServerProcess = builder.start(); StreamGobbler streamGobbler = new StreamGobbler(corfuReplicationServerProcess.getInputStream(), serverConsoleLogPath); Executors.newSingleThreadExecutor().submit(streamGobbler); return corfuReplicationServerProcess; }

Target:
public Process runServer() throws IOException { final String serverConsoleLogPath = CORFU_LOG_PATH + File.separator + host + "_" + port + "_consolelog"; File logPath = new File(getCorfuServerLogPath(host, port)); if (!logPath.exists()) { logPath.mkdir(); } ProcessBuilder builder = new ProcessBuilder(); builder.command("sh", "-c", "bin/corfu_replication_server " + getOptionsString()); builder.directory(new File(CORFU_PROJECT_DIR)); Process corfuReplicationServerProcess = builder.start(); StreamGobbler streamGobbler = new StreamGobbler(corfuReplicationServerProcess.getInputStream(), serverConsoleLogPath); Executors.newSingleThreadExecutor().submit(streamGobbler); return corfuReplicationServerProcess; }
Source:
public String getVersion(){ if (mVersion != null){ return mVersion; } else if (mPkgInfo != null){ return Integer.toString(mPkgInfo.versionCode); } return null; }

Target:
public String getVersion(){ if (mVersion != null){ return mVersion; } mVersion = Integer.toString(mPkgInfo.versionCode); return mVersion; }
Source:
public static void validateCacheGroupName(String name) throws IllegalArgumentException { if (name != null) A.ensure(name.length() <= MAX_FILE_NAME_LENGTH, "Length of cache group name can not exceed "+ MAX_FILE_NAME_LENGTH +"."); }

Target:
public static void validateCacheGroupName(String name) throws IllegalArgumentException { if (name != null) A.ensure(name.length() <= CACHE_NAME_MAX_LENGTH, "Length of cache group name can not exceed " + CACHE_NAME_MAX_LENGTH + "."); }
Source:
public String generaterRandomDNAString(int n, String vertexId) { char[] chars = "ACGT".toCharArray(); StringBuilder sb = new StringBuilder(); while (true) { sb = new StringBuilder(); for (int i = 0; i < n; i++) { char c = chars[randGenerator.nextInt(chars.length)]; sb.append(c); } if (!existKmerString.contains(vertexId + sb.toString())) break; } existKmerString.add(vertexId + sb.toString()); return vertexId + sb.toString(); }

Target:
public String generaterRandomDNAString(int n, String vertexId) { char[] chars = "ACGT".toCharArray(); StringBuilder sb; while (true) { sb = new StringBuilder(); for (int i = 0; i < n; i++) { char c = chars[randGenerator.nextInt(chars.length)]; sb.append(c); } if (!existKmerString.contains(vertexId + sb.toString())) break; } existKmerString.add(vertexId + sb.toString()); return vertexId + sb.toString(); }
Source:
public List<NotificationAction> getActions() { return new ArrayList<>(); }

Target:
public List<NotificationAction> getActions() { return Collections.emptyList(); }
Source:
static MonotonicCounter newAtomicMonotonicCounter() { return new MonotonicCounter() { private final AtomicLong value = new AtomicLong( 0L ); @Override public long increment() { int initialValue; int incrementedValue; do { initialValue = value.intValue(); incrementedValue = initialValue < 0 ? 0 : initialValue + 1; } while ( !value.compareAndSet( initialValue, incrementedValue ) ); return incrementedValue; } }; }

Target:
static MonotonicCounter newAtomicMonotonicCounter() { return new MonotonicCounter() { private final AtomicLong value = new AtomicLong( 0L ); @Override public long incrementAndGet() { return value.incrementAndGet(); } }; }
Source:
public StringSchema.Builder load() { StringSchema.Builder builder = StringSchema.builder(); ls.schemaJson().maybe("minLength").map(JsonValue::requireInteger).ifPresent(builder::minLength); ls.schemaJson().maybe("maxLength").map(JsonValue::requireInteger).ifPresent(builder::maxLength); if (useDefault) ls.schemaJson().maybe("default").map(JsonValue::requireString).ifPresent(builder::defaultValue); ls.schemaJson().maybe("pattern").map(JsonValue::requireString).ifPresent(builder::pattern); ls.schemaJson().maybe("format").map(JsonValue::requireString) .ifPresent(format -> addFormatValidator(builder, format)); return builder; }

Target:
public StringSchema.Builder load() { StringSchema.Builder builder = StringSchema.builder(); ls.schemaJson().maybe("minLength").map(JsonValue::requireInteger).ifPresent(builder::minLength); ls.schemaJson().maybe("maxLength").map(JsonValue::requireInteger).ifPresent(builder::maxLength); ls.schemaJson().maybe("pattern").map(JsonValue::requireString).ifPresent(builder::pattern); ls.schemaJson().maybe("format").map(JsonValue::requireString) .ifPresent(format -> addFormatValidator(builder, format)); return builder; }
Source:
public void validate_javadoc_retention() { FreeStyleJob job = jenkins.jobs.create(); setup(job); Build b = job.startBuild().shouldSucceed(); assertThat(job, hasAction(JAVADOC_ACTION)); try { assertThat(b, hasAction(JAVADOC_ACTION)); Assert.fail("Build #1 should not have Javadoc action"); } catch (AssertionError ex) this.setupForRetention(job); b = job.startBuild().shouldSucceed(); assertThat(job, hasAction(JAVADOC_ACTION)); assertThat(b, hasAction(JAVADOC_ACTION)); }

Target:
public void validate_javadoc_retention() { FreeStyleJob job = jenkins.jobs.create(); setup(job); Build b = job.startBuild().shouldSucceed(); assertThat(job, hasAction(JAVADOC_ACTION)); assertThat("Build #1 should not have Javadoc action", b, not(hasAction(JAVADOC_ACTION))); this.setupForRetention(job); b = job.startBuild().shouldSucceed(); assertThat(job, hasAction(JAVADOC_ACTION)); assertThat(b, hasAction(JAVADOC_ACTION)); }
Source:
private List<HttpHeaders> getHeadersList() { List<HttpHeaders> headersList = new ArrayList<HttpHeaders>(); HttpHeaders headers = new DefaultHttpHeaders(); headers.add(HttpHeaders.Names.CONTENT_LENGTH, new Random().nextLong()); headersList.add(headers); headers = new DefaultHttpHeaders(); headers.add(INVALID_HEADER_KEY_PREFIX + "1", "headerValue1"); headers.add(HttpHeaders.Names.CONTENT_LENGTH, new Random().nextLong()); headersList.add(headers); headers = new DefaultHttpHeaders(); headers.add(INVALID_HEADER_KEY_PREFIX + "1", "headerVxalue1"); headers.add(INVALID_HEADER_KEY_PREFIX + "2", "headerValue2"); headersList.add(headers); headers = new DefaultHttpHeaders(); headers.add(HttpHeaders.Names.HOST, "host1"); headers.add(HttpHeaders.Names.CONTENT_LENGTH, new Random().nextLong()); headers.add(RestUtils.Headers.CONTENT_TYPE, "content-type1"); headersList.add(headers); return headersList; }

Target:
private List<HttpHeaders> getHeadersList() { List<HttpHeaders> headersList = new ArrayList<HttpHeaders>(); HttpHeaders headers = new DefaultHttpHeaders(); headers.add(HttpHeaders.Names.CONTENT_TYPE, "content-type1"); headersList.add(headers); headers = new DefaultHttpHeaders(); headers.add(NOT_LOGGED_HEADER_KEY + "1", "headerValue1"); headers.add(HttpHeaders.Names.CONTENT_TYPE, "content-type2"); headersList.add(headers); headers = new DefaultHttpHeaders(); headers.add(NOT_LOGGED_HEADER_KEY + "1", "headerValue1"); headers.add(NOT_LOGGED_HEADER_KEY + "2", "headerValue2"); headersList.add(headers); headers = new DefaultHttpHeaders(); headers.add(HttpHeaders.Names.HOST, "host1"); headers.add(RestUtils.Headers.CONTENT_TYPE, "content-type3"); headers.add(EchoMethodHandler.RESPONSE_HEADER_KEY_1, "responseHeaderValue1"); headers.add(EchoMethodHandler.RESPONSE_HEADER_KEY_2, "responseHeaderValue1"); headersList.add(headers); return headersList; }
Source:
public void doubleClickOnReference(String visibleText) { Actions action = actionsFactory.createAction(seleniumWebDriver); clickOnReference(visibleText); waitReferenceSelection(visibleText); action.doubleClick().perform(); }

Target:
public void doubleClickOnReference(String visibleText) { clickOnReference(visibleText); waitReferenceSelection(visibleText); seleniumWebDriverHelper.doubleClick(); }
Source:
private static boolean runExistingTasksFrom(Queue<Runnable> taskQueue) { Runnable task = pollTaskFrom(taskQueue); if (task == null) { return false; } int remaining = taskQueue.size(); safeExecute(task); while (remaining-- > 0 && (task = taskQueue.poll()) != null) { safeExecute(task); } return true; }

Target:
private boolean runExistingTasksFrom(Queue<Runnable> taskQueue) { Runnable task = pollTaskFrom(taskQueue); if (task == null) { return false; } int remaining = Math.min(maxPendingTasks, taskQueue.size()); safeExecute(task); while (remaining-- > 0 && (task = taskQueue.poll()) != null) { safeExecute(task); } return true; }
Source:
public void setValue(EObject object, EStructuralFeature feature, Object value, int position) { if (migrationNeeded) { Object newValue = RepresentationsFileMigrationService.getInstance().getValue(object, feature, value, version); if (newValue != null) { super.setValue(object, feature, newValue, position); } else if (!(object instanceof DRepresentation && REPRESENTATION_NAME_FEATURE_LABEL.equals(feature.getName())) && !(object instanceof DRepresentation && REPRESENTATION_DOCUMENTATION_FEATURE_LABEL.equals(feature.getName()))) { super.setValue(object, feature, value, position); } } else { super.setValue(object, feature, value, position); } }

Target:
public void setValue(EObject object, EStructuralFeature feature, Object value, int position) { if (migrationNeeded) { Object newValue = RepresentationsFileMigrationService.getInstance().getValue(object, feature, value, version); if (newValue != null) { super.setValue(object, feature, newValue, position); } else if (!(object instanceof DRepresentation && (REPRESENTATION_NAME_FEATURE_LABEL.equals(feature.getName()) || REPRESENTATION_DOCUMENTATION_FEATURE_LABEL.equals(feature.getName())))) { super.setValue(object, feature, value, position); } } else { super.setValue(object, feature, value, position); } }
Source:
public void testContainerNotRecoveredAfterExhaustingRecoveryBackOff() throws Exception { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(mock(ConnectionFactory.class)); container.setQueueNames("foo"); container.setRecoveryBackOff(new FixedBackOff(100, 3)); container.setConcurrentConsumers(10); container.afterPropertiesSet(); container.start(); int n = 0; while (container.isActive() && n++ < 10) { Thread.sleep(100); } assertThat(n, lessThanOrEqualTo(10)); }

Target:
public void testContainerNotRecoveredAfterExhaustingRecoveryBackOff() throws Exception { SimpleMessageListenerContainer container = spy(new SimpleMessageListenerContainer(mock(ConnectionFactory.class))); container.setQueueNames("foo"); container.setRecoveryBackOff(new FixedBackOff(100, 3)); container.setConcurrentConsumers(3); doAnswer(new Answer<BlockingQueueConsumer>() { @Override public BlockingQueueConsumer answer(InvocationOnMock invocation) throws Throwable { BlockingQueueConsumer consumer = spy((BlockingQueueConsumer) invocation.callRealMethod()); doThrow(RuntimeException.class).when(consumer).start(); return consumer; } }).when(container).createBlockingQueueConsumer(); container.afterPropertiesSet(); container.start(); int n = 0; while (container.isActive() && n++ < 10) { Thread.sleep(100); } assertThat(n, lessThanOrEqualTo(10)); }
Source:
public Mono<ThroughputResponse> readThroughput() { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return this.database.getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }

Target:
public Mono<ThroughputResponse> readThroughput() { return this.read() .flatMap(response -> this.database.getDocClientWrapper() .queryOffers(database.getOfferQuerySpecFromResourceId(response .getProperties() .getResourceId()) , new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource " + this.getId())); } return this.database.getDocClientWrapper() .readOffer(offerFeedResponse.getResults() .get(0) .getSelfLink()) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }
Source:
protected PageDataSink createPageDataSink(FileSystem fileSystem, Path path) throws IOException { return new OutputStreamPageDataSink(fileSystem.create(path), pagesSerde); }

Target:
protected DataSink createPageDataSink(FileSystem fileSystem, Path path) throws IOException { return new OutputStreamDataSink(fileSystem.create(path)); }
Source:
static List<NationalAppealChamberJudgment> createNacJudgmentListWithRandomData(int size){ List<NationalAppealChamberJudgment> judgments = new ArrayList<>(size); for(int i=0; i<size; ++i){ String prefix = i + "__"; NationalAppealChamberJudgment judgment = createNacJudgmentWithRandomData(prefix, i); judgments.add(judgment); } return judgments; }

Target:
public static List<NationalAppealChamberJudgment> createNacJudgmentListWithRandomData(int size){ List<NationalAppealChamberJudgment> judgments = new ArrayList<>(size); for(int i=0; i<size; ++i){ String prefix = i + "__"; NationalAppealChamberJudgment judgment = createNacJudgmentWithRandomData(prefix, i); judgments.add(judgment); } return judgments; }
Source:
private boolean considerBinding(IBinding binding, ASTNode node) { if (!(binding instanceof IVariableBinding)) return false; boolean result= Bindings.equals(fFieldBinding, ((IVariableBinding)binding).getVariableDeclaration()); if (!result || (fEncapsulateDeclaringClass && !fGetter.isEmpty() && !fSetter.isEmpty())) return result; AbstractTypeDeclaration type= ASTNodes.getParent(node, AbstractTypeDeclaration.class); if (type != null) { ITypeBinding declaringType= type.resolveBinding(); return !Bindings.equals(fDeclaringClassBinding, declaringType); } return true; }

Target:
private boolean considerBinding(IBinding binding, ASTNode node) { if (!(binding instanceof IVariableBinding)) return false; boolean result= Bindings.equals(fFieldBinding, ((IVariableBinding)binding).getVariableDeclaration()); if (!result || fEncapsulateDeclaringClass) return result; if (binding instanceof IVariableBinding) { AbstractTypeDeclaration type= ASTNodes.getParent(node, AbstractTypeDeclaration.class); if (type != null) { ITypeBinding declaringType= type.resolveBinding(); return !Bindings.equals(fDeclaringClassBinding, declaringType); } } return true; }
Source:
public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException { try { return LocalTime.parse(defaultStr, DateTimeFormatter.ofPattern("HH:mm:ss[.SSSSSS]")); } catch (NumberFormatException e) { throw SqlExceptionUtil.create("Problems with field " + fieldType + " parsing default LocalDateTime value: " + defaultStr, e); } }

Target:
public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException { return LocalTime.parse(defaultStr, new DateTimeFormatterBuilder() .appendPattern("HH:mm:ss") .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true) .toFormatter()); }
Source:
public Object[] transform(I input) { if (input instanceof QueryableEntry) { Object[] result = new Object[attributePaths.length]; for (int i = 0; i < attributePaths.length; i++) { result[i] = extractAttributeValue((QueryableEntry) input, attributePaths[i], fromName(attributePaths[i])); } return result; } throw new IllegalArgumentException("The given map entry is not extractable"); }

Target:
public Object[] transform(I input) { if (input instanceof QueryableEntry) { Object[] result = new Object[attributePaths.length]; for (int i = 0; i < attributePaths.length; i++) { result[i] = extractAttributeValue((QueryableEntry) input, attributePaths[i], getAttributeOrigin(i)); } return result; } throw new IllegalArgumentException("The given map entry is not extractable"); }
Source:
public ConnectorSplitSource getSplits(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorTableLayoutHandle layoutHandle) { MemoryTableLayoutHandle layout = (MemoryTableLayoutHandle) layoutHandle; Map<HostAddress, Long> rowsOnHosts = layout.getHosts(); ImmutableList.Builder<ConnectorSplit> splits = ImmutableList.builder(); for (Map.Entry<HostAddress, Long> rowsOnHost : rowsOnHosts.entrySet()) { for (int i = 0; i < splitsPerNode; i++) { splits.add( new MemorySplit( layout.getTable(), i, splitsPerNode, ImmutableList.of(rowsOnHost.getKey()), rowsOnHost.getValue())); } } return new FixedSplitSource(splits.build()); }

Target:
public ConnectorSplitSource getSplits(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorTableLayoutHandle layoutHandle) { MemoryTableLayoutHandle layout = (MemoryTableLayoutHandle) layoutHandle; List<MemoryDataFragment> dataFragments = layout.getDataFragments(); ImmutableList.Builder<ConnectorSplit> splits = ImmutableList.builder(); for (MemoryDataFragment dataFragment : dataFragments) { for (int i = 0; i < splitsPerNode; i++) { splits.add( new MemorySplit( layout.getTable(), i, splitsPerNode, dataFragment.getHostAddress(), dataFragment.getRows())); } } return new FixedSplitSource(splits.build()); }
Source:
public void testGetAllSnapshotsForLeaf() { List<DiskImage> images = dao.getAllSnapshotsForLeaf(FixturesTool.IMAGE_ID); assertFalse(images.isEmpty()); }

Target:
public void testGetAllSnapshotsForLeaf() { List<DiskImage> images = dao.getAllSnapshotsForLeaf(FixturesTool.IMAGE_ID); assertFalse(images.isEmpty()); assertFalse(CollectionUtils.exists(images, new Predicate() { public boolean evaluate(Object disk) { return ((DiskImage) disk).getVmEntityType() == VmEntityType.TEMPLATE; } })); }
Source:
public void onMouseEnteredClanTag() { clanService.getClanByTag(player.getClan()).thenAccept(optionalClan -> { if (!optionalClan.isPresent()) { return; } if (!clanMenu.getItems().isEmpty()) { clanMenu.getItems().clear(); } Clan clan = optionalClan.get(); if (playerService.isOnline(clan.getLeader().getId())) { MenuItem messageLeaderItem = new MenuItem(i18n.get("clan.messageLeader")); messageLeaderItem.setOnAction(event -> eventBus.post(new InitiatePrivateChatEvent(clan.getLeader().getUsername()))); clanMenu.getItems().add(messageLeaderItem); } MenuItem visitClanPageAction = new MenuItem(i18n.get("clan.visitPage")); visitClanPageAction.setOnAction(event -> { platformService.showDocument(clan.getWebsiteUrl()); }); clanMenu.getItems().add(visitClanPageAction); if (clanMenu.getTooltip() != null) { clanTooltipController.setClan(clan); return; } Tooltip clanTooltip = new Tooltip(); clanTooltipController = uiService.loadFxml("theme/chat/clan_tooltip.fxml"); clanTooltip.setMaxHeight(clanTooltipController.getRoot().getHeight()); clanTooltip.setGraphic(clanTooltipController.getRoot()); clanTooltipController.setClan(clan); clanMenu.setTooltip(clanTooltip); clanTooltip.show(StageHolder.getStage()); }); }

Target:
public void onMouseEnteredClanTag() { clanService.getClanByTag(player.getClan()).thenAccept(optionalClan -> { if (!optionalClan.isPresent()) { return; } clanMenu.getItems().clear(); Clan clan = optionalClan.get(); if (playerService.isOnline(clan.getLeader().getId())) { MenuItem messageLeaderItem = new MenuItem(i18n.get("clan.messageLeader")); messageLeaderItem.setOnAction(event -> eventBus.post(new InitiatePrivateChatEvent(clan.getLeader().getUsername()))); clanMenu.getItems().add(messageLeaderItem); } MenuItem visitClanPageAction = new MenuItem(i18n.get("clan.visitPage")); visitClanPageAction.setOnAction(event -> { platformService.showDocument(clan.getWebsiteUrl()); }); clanMenu.getItems().add(visitClanPageAction); if (clanMenu.getTooltip() != null) { clanTooltipController.setClan(clan); return; } Tooltip clanTooltip = new Tooltip(); clanTooltipController = uiService.loadFxml("theme/chat/clan_tooltip.fxml"); clanTooltip.setMaxHeight(clanTooltipController.getRoot().getHeight()); clanTooltip.setGraphic(clanTooltipController.getRoot()); clanTooltipController.setClan(clan); clanMenu.setTooltip(clanTooltip); clanTooltip.show(StageHolder.getStage()); }); }
Source:
public void close() { if (!isClosed) { isClosed = true; AeronCloseHelper.close(errorHandler, logFactory); AeronCloseHelper.close(errorHandler, lossReport); IoUtil.unmap(lossReportBuffer); lossReportBuffer = null; if (errorHandler instanceof AutoCloseable) { CloseHelper.quietClose((AutoCloseable)errorHandler); } IoUtil.unmap(cncByteBuffer); cncByteBuffer = null; if (dirDeleteOnShutdown && null != aeronDirectory()) { CloseHelper.quietClose(this::deleteAeronDirectory); } super.close(); } }

Target:
public void close() { if (!isClosed) { isClosed = true; AeronCloseHelper.close(errorHandler, logFactory); AeronCloseHelper.close(errorHandler, lossReport); IoUtil.unmap(lossReportBuffer); lossReportBuffer = null; if (errorHandler instanceof AutoCloseable) { CloseHelper.quietClose((AutoCloseable)errorHandler); } IoUtil.unmap(cncByteBuffer); cncByteBuffer = null; if (dirDeleteOnShutdown && null != aeronDirectory()) { deleteAeronDirectory(); } super.close(); } }
Source:
public static void main(String[] args) { System.out.println("Support for Kafka version 0.8 is being deprecated. The default kafkaloader is Kafka version 0.10."); final KafkaExternalLoaderCLIArguments cfg = new KafkaExternalLoaderCLIArguments(); cfg.parse(KafkaExternalLoader.class.getName(), args); KafkaExternalLoader kloader = new KafkaExternalLoader(cfg); try { kloader.initialize(); kloader.processKafkaMessages(); } catch (Exception e) { kloader.close(); m_log.error("Exception in KafkaExternalLoader", e); System.exit(-1); } System.exit(0); }

Target:
public static void main(String[] args) { System.out.println("Support for Kafka version 0.8 has been deprecated. The default kafkaloader is Kafka version 0.10."); final KafkaExternalLoaderCLIArguments cfg = new KafkaExternalLoaderCLIArguments(); cfg.parse(KafkaExternalLoader.class.getName(), args); KafkaExternalLoader kloader = new KafkaExternalLoader(cfg); try { kloader.initialize(); kloader.processKafkaMessages(); } catch (Exception e) { kloader.close(); m_log.error("Exception in KafkaExternalLoader", e); System.exit(-1); } System.exit(0); }
Source:
public static Geometry deserialize(Slice shape) { if (shape == null) { return null; } BasicSliceInput input = shape.getInput(); input.skip(SIZE_OF_INT); if (input.available() == 0) { return GEOMETRY_FACTORY.createGeometryCollection(); } List<Geometry> geometries = new ArrayList<>(); while (input.available() > 0) { int length = input.readInt(); geometries.add(readGeometry(input.readSlice(length).getInput())); } if (geometries.size() == 1) { return geometries.get(0); } Geometry res = GEOMETRY_FACTORY.createGeometryCollection(geometries.toArray(new Geometry[0])); return res; }

Target:
public static Geometry deserialize(Slice shape) { if (shape == null) { return null; } BasicSliceInput input = shape.getInput(); int geometryType = input.readByte(); if (geometryType != GeometryUtils.GeometryTypeName.GEOMETRY_COLLECTION.code()) { return readGeometry(input); } if (input.available() == 0) { return GEOMETRY_FACTORY.createGeometryCollection(); } List<Geometry> geometries = new ArrayList<>(); while (input.available() > 0) { int length = input.readInt(); geometries.add(readGeometry(input.readSlice(length).getInput())); } return GEOMETRY_FACTORY.createGeometryCollection(geometries.toArray(new Geometry[0])); }
Source:
public ProjectInformation(String groupId, String artifactId, String version, String packaging, Path projectBaseFolder, Path buildDirectory) { this.groupId = groupId; this.artifactId = artifactId; this.version = version; this.packaging = packaging; this.projectBaseFolder = projectBaseFolder; this.buildDirectory = buildDirectory; }

Target:
private ProjectInformation(String groupId, String artifactId, String version, String packaging, Path projectBaseFolder, Path buildDirectory) { this.groupId = groupId; this.artifactId = artifactId; this.version = version; this.packaging = packaging; this.projectBaseFolder = projectBaseFolder; this.buildDirectory = buildDirectory; }
Source:
public ObjectCachingColumnSelectorFactory(ColumnSelectorFactory delegate, boolean concurrentEventAdd) { this.delegate = delegate; if (concurrentEventAdd) { longColumnSelectorMap = Maps.newConcurrentMap(); floatColumnSelectorMap = Maps.newConcurrentMap(); objectColumnSelectorMap = Maps.newConcurrentMap(); } else { longColumnSelectorMap = Maps.newHashMap(); floatColumnSelectorMap = Maps.newHashMap(); objectColumnSelectorMap = Maps.newHashMap(); } }

Target:
public ObjectCachingColumnSelectorFactory(ColumnSelectorFactory delegate, boolean concurrentEventAdd) { this.delegate = delegate; if (concurrentEventAdd) { longColumnSelectorMap = new ConcurrentHashMap<>(); floatColumnSelectorMap = new ConcurrentHashMap<>(); objectColumnSelectorMap = new ConcurrentHashMap<>(); } else { longColumnSelectorMap = new HashMap<>(); floatColumnSelectorMap = new HashMap<>(); objectColumnSelectorMap = new HashMap<>(); } }
Source:
public static Slice truncateToLength(Slice slice, int maxLength) { requireNonNull(slice, "slice is null"); if (maxLength < 0) { throw new IllegalArgumentException("Max length must be greater or equal than zero"); } if (maxLength == 0) { return Slices.EMPTY_SLICE; } int indexEnd = getTruncatedEndIndex(slice, 0, maxLength); if (indexEnd < 0) { return slice; } return slice.slice(0, indexEnd); }

Target:
public static Slice truncateToLength(Slice slice, int maxLength) { requireNonNull(slice, "slice is null"); if (maxLength < 0) { throw new IllegalArgumentException("Max length must be greater or equal than zero"); } if (maxLength == 0) { return Slices.EMPTY_SLICE; } return slice.slice(0, byteCount(slice, 0, slice.length(), maxLength)); }