auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void findNextValidResultCursor() { while (queryIterator.hasNext()){ final DBObject currentQuery = queryIterator.next(); currentBindingSetCollection = rangeMap.get(currentQuery); final List<Document> pipeline = new ArrayList<>(); pipeline.add(new Document("$match", currentQuery)); pipeline.addAll(AggregationUtil.createRedactPipeline(auths)); log.debug(pipeline); final AggregationOptions opts = AggregationOptions.builder() .batchSize(1000) .build(); final AggregateIterable<Document> aggIter = coll.aggregate(pipeline); resultsIterator = aggIter.iterator(); if (resultsIterator.hasNext()) { break; } } }

Target:
private void findNextValidResultCursor() { while (queryIterator.hasNext()){ final DBObject currentQuery = queryIterator.next(); currentBindingSetCollection = rangeMap.get(currentQuery); final List<Document> pipeline = new ArrayList<>(); pipeline.add(new Document("$match", currentQuery)); pipeline.addAll(AggregationUtil.createRedactPipeline(auths)); log.debug(pipeline); final AggregateIterable<Document> aggIter = coll.aggregate(pipeline); aggIter.batchSize(1000); resultsIterator = aggIter.iterator(); if (resultsIterator.hasNext()) { break; } } }
Source:
public void delete(Question question) { session.createSQLQuery("SET foreign_key_checks = 0").executeUpdate(); QuestionQuery query = new QuestionQuery(question); query.execute("delete f,qf from Question q" + " join Question_Flags qf on qf.Question_id=q.id" + " join Flag f on f.id=qf.flags_id" + " where q.id=:id"); query.execute("delete w,qw from Question q" + " join Question_Watchers qw on qw.Question_id=q.id" + " join Watcher w on w.id=qw.watchers_id" + " where q.id=:id"); query.execute("delete from ReputationEvent where context_id=:id and context_type='QUESTION'"); deleteAttachments(question); deleteRelationshipTables(question); session.createSQLQuery("delete from QuestionInformation_Tag where QuestionInformation_id=:id") .setParameter("id", question.getInformation().getId()) .executeUpdate(); query.execute("delete from QuestionInformation where question_id=:id"); query.execute("delete from Question where id=:id"); session.createSQLQuery("SET foreign_key_checks = 1").executeUpdate(); }

Target:
public void delete(Question question) { session.delete(question); }
Source:
public OperationFuture<LoadBalancerPool> delete(LoadBalancerPool loadBalancerPool) { LoadBalancer loadBalancer = loadBalancerPool.getLoadBalancer(); loadBalancerPoolClient.delete( fetchDataCenterId(loadBalancer.getDataCenter()), fetchLoadBalancerId(loadBalancer), findByRef(loadBalancerPool).getId() ); return new OperationFuture<>( loadBalancerPool, new NoWaitingJobFuture() ); }

Target:
public OperationFuture<LoadBalancerPool> delete(LoadBalancerPool loadBalancerPool) { LoadBalancerPoolMetadata loadBalancerPoolMetadata = findByRef(loadBalancerPool); loadBalancerPoolClient.delete( loadBalancerPoolMetadata.getDataCenterId(), loadBalancerPoolMetadata.getLoadBalancerId(), loadBalancerPoolMetadata.getId() ); return new OperationFuture<>( loadBalancerPool, new NoWaitingJobFuture() ); }
Source:
public void test() throws Exception { deleteDb("concurrent"); final String url = getURL("concurrent", true); try (Connection conn = getConnection(url)) { Statement stat = conn.createStatement(); stat.execute("create table test(id int primary key, name varchar)"); Task[] tasks = new Task[THREADS]; for (int i = 0; i < THREADS; i++) { final int threadId = i; Task t = new Task() { @Override public void call() throws Exception { Random r = new Random(threadId); try (Connection conn = getConnection(url)) { PreparedStatement insert = conn.prepareStatement( "merge into test values(?, ?)"); PreparedStatement update = conn.prepareStatement( "update test set name = ? where id = ?"); PreparedStatement delete = conn.prepareStatement( "delete from test where id = ?"); PreparedStatement select = conn.prepareStatement( "select * from test where id = ?"); while (!stop) { int x = r.nextInt(ROW_COUNT); String data = "x" + r.nextInt(ROW_COUNT); switch (r.nextInt(3)) { case 0: insert.setInt(1, x); insert.setString(2, data); insert.execute(); break; case 1: update.setString(1, data); update.setInt(2, x); update.execute(); break; case 2: delete.setInt(1, x); delete.execute(); break; case 4: select.setInt(1, x); ResultSet rs = select.executeQuery(); while (rs.next()) { rs.getString(2); } break; } } } } }; tasks[i] = t; t.execute(); } for (int i = 0; i < 200; i++) { Thread.sleep(10); for (Task t : tasks) { if (t.isFinished()) { i = 1000; break; } } } for (Task t : tasks) { t.get(); } } }

Target:
public void test() throws Exception { deleteDb("concurrent"); final String url = getURL("concurrent", true); try (Connection conn = getConnection(url)) { Statement stat = conn.createStatement(); stat.execute("create table test(id int primary key, name varchar)"); Task[] tasks = new Task[THREADS]; for (int i = 0; i < THREADS; i++) { final int threadId = i; Task t = new Task() { @Override public void call() throws Exception { Random r = new Random(threadId); try (Connection conn = getConnection(url)) { PreparedStatement insert = conn.prepareStatement( "merge into test values(?, ?)"); PreparedStatement update = conn.prepareStatement( "update test set name = ? where id = ?"); PreparedStatement delete = conn.prepareStatement( "delete from test where id = ?"); PreparedStatement select = conn.prepareStatement( "select * from test where id = ?"); while (!stop) { int x = r.nextInt(ROW_COUNT); String data = "x" + r.nextInt(ROW_COUNT); switch (r.nextInt(4)) { case 0: insert.setInt(1, x); insert.setString(2, data); insert.execute(); break; case 1: update.setString(1, data); update.setInt(2, x); update.execute(); break; case 2: delete.setInt(1, x); delete.execute(); break; case 3: select.setInt(1, x); ResultSet rs = select.executeQuery(); while (rs.next()) { rs.getString(2); } break; } } } } }; tasks[i] = t; t.execute(); } for (int i = 0; i < 200; i++) { Thread.sleep(10); for (Task t : tasks) { if (t.isFinished()) { i = 1000; break; } } } for (Task t : tasks) { t.get(); } } }
Source:
public SubmissionResult toSubmissionResult() { SubmissionResult submissionResult = new SubmissionResult(); if (error == null && status == SubmissionResult.Status.ERROR) { error = "errored"; } submissionResult.setError(error); submissionResult.setStatus(status); ArrayList<String> submissionPoints = new ArrayList<>(); if (status == SubmissionResult.Status.OK) { submissionPoints.add(String.valueOf("1")); } else { submissionPoints.add(String.valueOf("0")); } submissionResult.setPoints(submissionPoints); submissionResult.setTestCases(testResults); return submissionResult; }

Target:
public SubmissionResult toSubmissionResult() { SubmissionResult submissionResult = new SubmissionResult(); if (error == null && status == SubmissionResult.Status.ERROR) { error = "errored"; } submissionResult.setError(error); submissionResult.setStatus(status); ArrayList<String> submissionPoints = new ArrayList<>(); if (status == SubmissionResult.Status.OK) { submissionPoints.add("1"); } else { submissionPoints.add("0"); } submissionResult.setPoints(submissionPoints); submissionResult.setTestCases(testResults); return submissionResult; }
Source:
public static <T> Notification<T> createOnNext(T value) { Objects.requireNonNull(value, "value is null"); return new NextNotification<T>(value); }

Target:
public static <T> Notification<T> createOnNext(T value) { Objects.requireNonNull(value, "value is null"); return new Notification<T>(value); }
Source:
protected void doStartMachine(KubernetesServerResolver serverResolver) throws InfrastructureException { machineStartupTraces = new ConcurrentHashMap<>(getContext().getEnvironment().getPods().size()); final KubernetesEnvironment environment = getContext().getEnvironment(); final Map<String, InternalMachineConfig> machineConfigs = environment.getMachines(); final String workspaceId = getContext().getIdentity().getWorkspaceId(); LOG.debug("Begin pods creation for workspace '{}'", workspaceId); for (Pod toCreate : environment.getPods().values()) { final Pod createdPod = namespace.deployments().deploy(toCreate); LOG.debug( "Creating pod '{}' in workspace '{}'", toCreate.getMetadata().getName(), workspaceId); final ObjectMeta podMetadata = createdPod.getMetadata(); for (Container container : createdPod.getSpec().getContainers()) { String machineName = Names.machineName(toCreate, container); machineStartupTraces.put( machineName, tracer .buildSpan("container-create") .asChildOf(tracer.activeSpan()) .withTag("machineName", machineName) .start()); LOG.debug("Creating machine '{}' in workspace '{}'", machineName, workspaceId); machines.put( getContext().getIdentity(), new KubernetesMachineImpl( workspaceId, machineName, podMetadata.getName(), container.getName(), MachineStatus.STARTING, machineConfigs.get(machineName).getAttributes(), serverResolver.resolve(machineName))); eventPublisher.sendStartingEvent(machineName, getContext().getIdentity()); } } LOG.debug("Pods creation finished in workspace '{}'", workspaceId); }

Target:
protected void doStartMachine(KubernetesServerResolver serverResolver) throws InfrastructureException { machineStartupTraces = new ConcurrentHashMap<>(getContext().getEnvironment().getMachines().size()); final KubernetesEnvironment environment = getContext().getEnvironment(); final Map<String, InternalMachineConfig> machineConfigs = environment.getMachines(); final String workspaceId = getContext().getIdentity().getWorkspaceId(); LOG.debug("Begin pods creation for workspace '{}'", workspaceId); for (Pod toCreate : environment.getPods().values()) { startTracingContainersStartup(toCreate); final Pod createdPod = namespace.deployments().deploy(toCreate); LOG.debug( "Creating pod '{}' in workspace '{}'", toCreate.getMetadata().getName(), workspaceId); final ObjectMeta podMetadata = createdPod.getMetadata(); for (Container container : createdPod.getSpec().getContainers()) { String machineName = Names.machineName(toCreate, container); LOG.debug("Creating machine '{}' in workspace '{}'", machineName, workspaceId); machines.put( getContext().getIdentity(), new KubernetesMachineImpl( workspaceId, machineName, podMetadata.getName(), container.getName(), MachineStatus.STARTING, machineConfigs.get(machineName).getAttributes(), serverResolver.resolve(machineName))); eventPublisher.sendStartingEvent(machineName, getContext().getIdentity()); } } LOG.debug("Pods creation finished in workspace '{}'", workspaceId); }
Source:
public boolean isBandwidthRestricted() { if (bandwidthLimit == Long.MAX_VALUE) { return false; } return true; }

Target:
public boolean isBandwidthRestricted() { return bandwidthLimit != Long.MAX_VALUE; }
Source:
private void setGameModes() { for (Field f: GameModes.class.getDeclaredFields()) { try { f.set(null, gameModeMappings.get(f.getName())); } catch (Exception e) { e.printStackTrace(); } } }

Target:
private void setGameModes() { RegistryHelper.mapFields(GameModes.class, gameModeMappings); }
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getParameters().getClusterId() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if (getParameters().getConfigParams() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAMS_IS_EMPTY); return false; } for (GlusterVolumeSnapshotConfig param : getParameters().getConfigParams()) { if (StringUtils.isEmpty(param.getParamValue())) { addCustomValue("snapshotConfigParam", param.getParamName()); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAM_VALUE_IS_EMPTY); return false; } } return true; }

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getParameters().getClusterId() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTER_IS_NOT_VALID); return false; } if (!GlusterFeatureSupported.glusterSnapshot(getVdsGroup().getCompatibilityVersion())) { failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VOLUME_SNAPSHOT_NOT_SUPPORTED); } if (getParameters().getConfigParams() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAMS_IS_EMPTY); return false; } for (GlusterVolumeSnapshotConfig param : getParameters().getConfigParams()) { if (StringUtils.isEmpty(param.getParamValue())) { addCustomValue("snapshotConfigParam", param.getParamName()); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_SNAPSHOT_CONFIG_PARAM_VALUE_IS_EMPTY); return false; } } return true; }
Source:
public void addRequestable( IAEItemStack option ) { if( this.isStackNull( option ) ) { return; } final IAEItemStack st = this.getItemRecord( option.getItem() ).get( option ); if( st != null ) { ( (IAEItemStack) st ).setCountRequestable( st.getCountRequestable() + option.getCountRequestable() ); return; } final IAEItemStack opt = (IAEItemStack) option.copy(); opt.setStackSize( 0 ); opt.setCraftable( false ); opt.setCountRequestable( opt.getCountRequestable() ); this.putItemRecord( opt ); }

Target:
public void addRequestable( IAEItemStack option ) { if( option == null ) { return; } final IAEItemStack st = this.getItemRecord( option.getItem() ).get( option ); if( st != null ) { st.setCountRequestable( st.getCountRequestable() + option.getCountRequestable() ); return; } final IAEItemStack opt = option.copy(); opt.setStackSize( 0 ); opt.setCraftable( false ); opt.setCountRequestable( option.getCountRequestable() ); this.putItemRecord( opt ); }
Source:
private KieSession marshallAndUnmarshall(final KieServices ks, final KieBase kbase, KieSession ksession, final KieSessionConfiguration sessionConfig) { Marshaller marshaller = ks.getMarshallers().newMarshaller(kbase); try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { marshaller.marshall(baos, ksession); try (final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) { marshaller = MarshallerFactory.newMarshaller(kbase); ksession = marshaller.unmarshall(bais, sessionConfig, null); } } catch (Exception e) { e.printStackTrace(); Assertions.fail("unexpected exception :" + e.getMessage()); } return ksession; }

Target:
private KieSession marshallAndUnmarshall(final KieServices ks, final KieBase kbase, KieSession ksession, final KieSessionConfiguration sessionConfig) { Marshaller marshaller = ks.getMarshallers().newMarshaller(kbase); try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { marshaller.marshall(baos, ksession); try (final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) { marshaller = MarshallerFactory.newMarshaller(kbase); ksession = marshaller.unmarshall(bais, sessionConfig, null); } } catch (Exception e) { Assertions.fail("Unexpected exception: ", e); } return ksession; }
Source:
static ChangedFileSet getTextSymbols(@NonNull IProject project) { String path = getRelativeAndroidOut(project); ChangedFileSet set = new ChangedFileSet( "textSymbols", path + "/R.txt"); return set; }

Target:
static ChangedFileSet getTextSymbols(@NonNull IProject project) { String path = getRelativeAndroidOut(project); ChangedFileSet set = new ChangedFileSet( "textSymbols", path + '/' + SdkConstants.FN_RESOURCE_TEXT); return set; }
Source:
private SupportedTypesResourceDefinition(SimpleAttributeDefinition... attributes) { super(ModelElement.SUPPORTED_TYPES, new IDMConfigAddStepHandler(attributes), null, attributes); }

Target:
private SupportedTypesResourceDefinition(SimpleAttributeDefinition... attributes) { super(ModelElement.SUPPORTED_TYPES, new IDMConfigAddStepHandler(attributes), attributes); }
Source:
private void saveParsingIssue(SensorContext context, RecognitionException e, InputFile inputFile) { if (parsingErrorRuleKey != null) { NewIssue issue = context.newIssue(); NewIssueLocation location = issue.newLocation() .message(e.getMessage()) .on(inputFile); if (e.getLine() > 0) { location.at(inputFile.selectLine(e.getLine())); } issue .forRule(parsingErrorRuleKey) .at(location) .save(); } }

Target:
private void saveParsingIssue(SensorContext context, RecognitionException e, InputFile inputFile) { if (parsingErrorRuleKey != null) { NewIssue issue = context.newIssue(); NewIssueLocation location = issue.newLocation() .message(e.getMessage()) .on(inputFile) .at(inputFile.selectLine(e.getLine())); issue .forRule(parsingErrorRuleKey) .at(location) .save(); } }
Source:
public String getSizeOfDataset() { GetDatasetStorageSizeCommand cmd = new GetDatasetStorageSizeCommand(dvRequestService.getDataverseRequest(), dataset, false, GetDatasetStorageSizeCommand.Mode.DOWNLOAD, workingVersion); try { long bytes = commandEngine.submit(cmd); return FileSizeChecker.bytesToHumanReadable(bytes); } catch (CommandException ex) { return ""; } }

Target:
public String getSizeOfDataset() { boolean original = false; return DatasetUtil.getDownloadSize(workingVersion, original); }
Source:
private int averageSizeAroundAllNodes() { int totalSize = 0; for (Ignite ignite : IgnitionEx.allGrids()) { for (String cacheName : CACHE_NAMES) { totalSize += ignite.cache(cacheName).size(); } } return totalSize / IgnitionEx.allGrids().size(); }

Target:
private int averageSizeAroundAllNodes() { int totalSize = 0; for (Ignite ignite : IgnitionEx.allGrids()) { for (String cacheName : CACHE_NAMES) totalSize += ignite.cache(cacheName).size(); } return totalSize / IgnitionEx.allGrids().size(); }
Source:
protected void ensureHashTableLoaded() { if (this.hashTables != null) { return; } synchronized (this) { if (this.hashTables != null) { return; } int[] offsets = getOffsets(); int elementCount = getRawKeyBlock().getPositionCount(); int mapCount = offsets.length - 1; boolean[] mapIsNull = getMapIsNull(); int[] hashTables = new int[elementCount * HASH_MULTIPLIER]; Arrays.fill(hashTables, -1); for (int i = 0; i < mapCount; i++) { int keyOffset = offsets[i]; int keyCount = offsets[i + 1] - keyOffset; if (keyCount < 0) { throw new IllegalArgumentException(format("Offset is not monotonically ascending. offsets[%s]=%s, offsets[%s]=%s", i, offsets[i], i + 1, offsets[i + 1])); } if (mapIsNull != null && mapIsNull[i] && keyCount != 0) { throw new IllegalArgumentException("A null map must have zero entries"); } buildHashTable( getRawKeyBlock(), keyOffset, keyCount, keyBlockHashCode, hashTables, keyOffset * HASH_MULTIPLIER, keyCount * HASH_MULTIPLIER); } this.hashTables = hashTables; } }

Target:
protected void ensureHashTableLoaded() { if (this.hashTables != null) { return; } synchronized (this) { if (this.hashTables != null) { return; } int[] hashTables = new int[getRawKeyBlock().getPositionCount() * HASH_MULTIPLIER]; Arrays.fill(hashTables, -1); for (int i = 0; i < offsets.length - 1; i++) { int keyOffset = offsets[i]; int keyCount = offsets[i + 1] - keyOffset; if (keyCount < 0) { throw new IllegalArgumentException(format("Offset is not monotonically ascending. offsets[%s]=%s, offsets[%s]=%s", i, offsets[i], i + 1, offsets[i + 1])); } if (mapIsNull != null && mapIsNull[i] && keyCount != 0) { throw new IllegalArgumentException("A null map must have zero entries"); } buildHashTable( getRawKeyBlock(), keyOffset, keyCount, keyBlockHashCode, hashTables, keyOffset * HASH_MULTIPLIER, keyCount * HASH_MULTIPLIER); } this.hashTables = hashTables; } }
Source:
public void applyPartitions(List<Map<String, String>> remainingPartitions) { if (catalogTable.getPartitionKeys() != null && catalogTable.getPartitionKeys().size() != 0) { this.remainingPartitions = remainingPartitions; } }

Target:
public void applyPartitions(List<Map<String, String>> remainingPartitions) { if (catalogTable.getPartitionKeys() != null && catalogTable.getPartitionKeys().size() != 0) { this.remainingPartitions = remainingPartitions; } else { throw new UnsupportedOperationException( "Should not apply partitions to a non-partitioned table."); } }
Source:
public <T> T withLock(Function<Boolean, T> function) { try { return function.apply(lock.tryLock()); } finally { lock.unlock(); } }

Target:
public <T> T withLock(Function<Boolean, T> function) { try { return function.apply(lock.tryLock()); } finally { try { lock.unlock(); } catch (IllegalMonitorStateException ignored) { } } }
Source:
private boolean isTraceActionDecoratedByRxWorker(Runnable action) { try { if (action instanceof Disposable) { Field modifiersField = action.getClass() .getDeclaredField("decoratedRun"); modifiersField.setAccessible(true); return modifiersField.get(action) instanceof TraceAction; } return false; } catch (Exception e) { return false; } }

Target:
private boolean isTraceActionDecoratedByRxWorker(Runnable action) { if (action instanceof TraceAction) { return true; } else if (action instanceof SchedulerRunnableIntrospection) { SchedulerRunnableIntrospection runnableIntrospection = (SchedulerRunnableIntrospection) action; return runnableIntrospection.getWrappedRunnable() instanceof TraceAction; } return false; }
Source:
public String createProject(Project project, User user) { return this.projectDao.create(project, user); }

Target:
public String createProject(Project project, User user) { validateInput(project); return this.projectDao.create(project, user); }
Source:
public void addChildElement(PropertyWriter p) { this.childElements.put(p.getElement().getId(), p); if (p instanceof BoundaryEventPropertyWriter) { process.getFlowElements().add(p.getFlowElement()); } else { process.getFlowElements().add(0, p.getFlowElement()); } p.setParent(this); ElementParameters simulationParameters = p.getSimulationParameters(); if (simulationParameters != null) { this.simulationParameters.add(simulationParameters); } this.itemDefinitions.addAll(p.itemDefinitions); this.rootElements.addAll(p.rootElements); }

Target:
public void addChildElement(PropertyWriter p) { p.setParent(this); Processes.addChildElement( p, childElements, process, simulationParameters, itemDefinitions, rootElements); }
Source:
public void testReportsServiceDownWhenKilled() throws Exception { LOG.info("test=testReportsServiceDownWithKilled; entity="+entity+"; app="+entity.getApplication()); Entities.start(entity.getApplication(), ImmutableList.of(loc)); EntityTestUtils.assertAttributeEqualsEventually(MutableMap.of("timeout", 120 * 1000), entity, Startable.SERVICE_UP, true); killEntityBehindBack(entity); LOG.info("Killed behind mgmt's back, waiting for service up false in mgmt context", entity); EntityTestUtils.assertAttributeEqualsEventually(entity, Startable.SERVICE_UP, false); LOG.info("success getting service up false in primary mgmt universe"); }

Target:
public void testReportsServiceDownWhenKilled() throws Exception { LOG.info("test=testReportsServiceDownWithKilled; entity="+entity+"; app="+entity.getApplication()); Entities.start(entity.getApplication(), ImmutableList.of(loc)); EntityTestUtils.assertAttributeEqualsEventually(MutableMap.of("timeout", Duration.minutes(2)), entity, Startable.SERVICE_UP, true); killEntityBehindBack(entity); LOG.info("Killed behind mgmt's back, waiting for service up false in mgmt context", entity); EntityTestUtils.assertAttributeEqualsEventually(entity, Startable.SERVICE_UP, false); LOG.info("success getting service up false in primary mgmt universe"); }
Source:
public void testUnsupportedFs() throws Exception { FileSystem mockFs = Mockito.mock(FileSystem.class); Mockito.doThrow( new UnsupportedOperationException("Mock unsupported exception.")) .when(mockFs).concat(any(Path.class), any(Path[].class)); Mockito.doAnswer(invocationOnMock -> new URI("mockfs:/ .getUri(); Concat.setTstFs(mockFs); PrintStream oldErr = System.err; final ByteArrayOutputStream err = new ByteArrayOutputStream(); System.setErr(new PrintStream(err)); shellRun(1, "-concat", dstPath.toString(), testRootDir + "/file-*"); System.setErr(oldErr); System.err.print(err.toString()); assertTrue(err.toString() .contains("Dest filesystem 'mockfs' doesn't support concat")); }

Target:
public void testUnsupportedFs() throws Exception { FileSystem mockFs = Mockito.mock(FileSystem.class); Mockito.doThrow( new UnsupportedOperationException("Mock unsupported exception.")) .when(mockFs).concat(any(Path.class), any(Path[].class)); Mockito.doAnswer(invocationOnMock -> new URI("mockfs:/ .getUri(); Concat.setTestFs(mockFs); final ByteArrayOutputStream err = new ByteArrayOutputStream(); PrintStream oldErr = System.err; System.setErr(new PrintStream(err)); try { shellRun(1, "-concat", dstPath.toString(), testRootDir + "/file-*"); } finally { System.setErr(oldErr); } System.err.print(err.toString()); String expectedErrMsg = "Dest filesystem 'mockfs' doesn't support concat"; Assertions.assertThat(err.toString().contains(expectedErrMsg)) .withFailMessage("The err message should contain \"" + expectedErrMsg + "\" message.").isTrue(); }
Source:
public boolean execute(CommandSender sender, String commandLabel, String[] args) { if (!(sender instanceof GlowPlayer)) { return innerExecute(sender, commandLabel, args); } localeChangeLock.lock(); try { Locale locale = Locale.forLanguageTag(((GlowPlayer) sender).getLocale()); if (locale.equals(lastLoadedLocale)) { return innerExecute(sender, commandLabel, args); } lastLoadedLocale = locale; String oldDescription = getDescription(); String oldUsage = getUsage(); String oldPermissionMessage = getPermissionMessage(); ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_BASE_NAME, locale); description = bundle.getString(getName() + DESCRIPTION_SUFFIX); usageMessage = bundle.getString(getName() + USAGE_SUFFIX); super.setPermissionMessage(bundle.getString(getName() + PERMISSION_SUFFIX)); try { return innerExecute(sender, commandLabel, args); } finally { description = oldDescription; usageMessage = oldUsage; super.setPermissionMessage(oldPermissionMessage); } } finally { localeChangeLock.unlock(); } }

Target:
public boolean execute(CommandSender sender, String commandLabel, String[] args) { CommandMessages localizedMessages = null; if (sender instanceof GlowPlayer) { try { localizedMessages = bundleToMessageCache.get( STRING_TO_BUNDLE_CACHE.get(((GlowPlayer) sender).getLocale())); } catch (ExecutionException e) { ConsoleMessages.Warn.Command.L10N_FAILED.log(e, getName(), sender); } } if (localizedMessages == null) { localizedMessages = new CommandMessages(getDescription(), getUsage(), getPermissionMessage()); } return execute(sender, commandLabel, args, localizedMessages); }
Source:
public MatrixBuild getMatrixBuild() { if( parent == null ) { try { parent = (MatrixBuild)Run.fromExternalizableId(parentId); } catch (Exception e) { parent = null; } } return parent; }

Target:
public MatrixBuild getMatrixBuild() { if (parent == null && parentId != null) { try { parent = (MatrixBuild)Run.fromExternalizableId(parentId); } catch (Exception e) { parent = null; } } return parent; }
Source:
private void trackNewServerEvent(int succesful) { UsageEventType eventType = JBossServerUIPlugin.getDefault().getNewServerEventType(); UsageReporter.getInstance().trackEvent(eventType.event(newRuntimeWorkingCopy.getId(), succesful)); }

Target:
private void trackNewServerEvent(int succesful) { IServerAttributes server = (IServerAttributes)getTaskModel().getObject(TaskModel.TASK_SERVER); String serverType = server.getServerType().getId(); UsageEventType eventType = JBossServerUIPlugin.getDefault().getNewServerEventType(); UsageReporter.getInstance().trackEvent(eventType.event(serverType, succesful)); }
Source:
public byte[] getImageContent(String location, String name) { org.kie.api.definition.process.Process process = kieContainer.getKieBase(kieBaseName).getProcess(name); if (process != null) { String sourcePath = process.getResource().getSourcePath(); if (sourcePath != null) { String processDirectory = ""; if (sourcePath != null && sourcePath.indexOf("/") != -1) { processDirectory = sourcePath.substring(0, sourcePath.lastIndexOf("/") + 1); } byte[] data = seek(processDirectory, name, kieModule); if (data != null) { return data; } location = processDirectory; } } byte[] data = seek(location, name, kieModule); if (data == null && kieModule.getKieDependencies() != null) { for (InternalKieModule depKieModule : kieModule.getKieDependencies().values()) { data = seek(location, name, depKieModule); if (data != null) { break; } } } return data; }

Target:
public byte[] getImageContent(String location, String name) { org.kie.api.definition.process.Process process = kieContainer.getKieBase(kieBaseName).getProcess(name); if (process != null) { String sourcePath = process.getResource().getSourcePath(); if (sourcePath != null) { String processDirectory = ""; if (sourcePath.indexOf("/") != -1) { processDirectory = sourcePath.substring(0, sourcePath.lastIndexOf("/") + 1); } byte[] data = seek(processDirectory, name, kieModule); if (data != null) { return data; } location = processDirectory; } } byte[] data = seek(location, name, kieModule); if (data == null && kieModule.getKieDependencies() != null) { for (InternalKieModule depKieModule : kieModule.getKieDependencies().values()) { data = seek(location, name, depKieModule); if (data != null) { break; } } } return data; }
Source:
private boolean matchId(CsvRow row, String id) { String scheme = row.findValue(ID_SCHEME_HEADER).orElse(DEFAULT_SCHEME); String rowId = row.findValue(ID_HEADER).map(str -> StandardId.of(scheme, str).toString()).orElse(""); return id.equals(rowId); }

Target:
private static boolean matchId(CsvRow row, String id) { String scheme = row.findValue(ID_SCHEME_HEADER).orElse(DEFAULT_SCHEME); String rowId = row.findValue(ID_HEADER).map(str -> StandardId.of(scheme, str).toString()).orElse(""); return id.equals(rowId); }
Source:
protected boolean canDoAction() { String user = getParameters().getLoginName(); if (StringUtils.isEmpty(user)) { ExtMap authRecord = (ExtMap) getParameters().getAuthRecord(); if (authRecord != null) { user = authRecord.get(AuthRecord.PRINCIPAL); } } String profile = getParameters().getProfileName(); if (StringUtils.isEmpty(profile)) { profile = "UNKNOWN"; } setUserName(String.format("%s@%s", user, profile)); boolean result = isUserCanBeAuthenticated(); if (! result) { logAutheticationFailure(); } return result; }

Target:
protected boolean canDoAction() { String user = getParameters().getLoginName(); if (StringUtils.isEmpty(user)) { ExtMap authRecord = (ExtMap) getParameters().getAuthRecord(); if (authRecord != null) { user = authRecord.get(AuthRecord.PRINCIPAL); } } String profile = getParameters().getProfileName(); if (StringUtils.isEmpty(profile)) { profile = "N/A"; } setUserName(String.format("%s@%s", user, profile)); boolean result = isUserCanBeAuthenticated(); if (! result) { logAutheticationFailure(); } return result; }
Source:
public void setRefreshInterval(final long refreshInterval) { REFRESH_INTERVAL_IN_SECONDS = refreshInterval; }

Target:
public void setRefreshInterval(final long refreshInterval) { this.refreshInterval = refreshInterval; }
Source:
public void selectContainer( FormModelCreationContainer container ) { Assert.notNull( "Manager cannot be null", container ); if ( currentManager != null ) { currentManager.hideCreationView(); } currentManager = container; currentManager.showCreationView(); }

Target:
public void selectContainer( FormModelCreationContainer container ) { PortablePreconditions.checkNotNull( "container", container ); if ( currentManager != null ) { currentManager.hideCreationView(); } currentManager = container; currentManager.showCreationView(); }
Source:
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IProject project = null; IEditorPart editorPart = window.getActivePage().getActiveEditor(); if (editorPart != null) { IFileEditorInput input = (IFileEditorInput) editorPart.getEditorInput(); IFile file = input.getFile(); project = file.getProject(); } else { if (window != null) { IStructuredSelection selection = (IStructuredSelection) window.getSelectionService().getSelection(); if (selection instanceof TreeSelection) { TreeSelection treeSelection = (TreeSelection) selection; TreePath path = treeSelection.getPaths()[0]; Object first = path.getFirstSegment(); if (first instanceof IAdaptable) { project = ((IAdaptable) first).getAdapter(IProject.class); } } else { Object firstElement = selection.getFirstElement(); if (firstElement instanceof IAdaptable) { project = ((IAdaptable) firstElement).getAdapter(IProject.class); } } } } if (project != null) { if (project.getFile("/gulpfile.js").exists()) { return true; } } return false; }

Target:
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IContainer container = null; if (window != null) { IWorkbenchPage page = window.getActivePage(); if (page != null) { IWorkbenchPart part = page.getActivePart(); if (part != null) { IFile activeEditorFile = getEditorFile(part); if (activeEditorFile != null) { if (RunGulpTaskCommand.GULP_FILE_NAME.equals(activeEditorFile.getName())) { return true; } else { container = activeEditorFile.getProject(); } } } if (container == null) { IStructuredSelection selection = (IStructuredSelection) window.getSelectionService().getSelection(); if (selection instanceof TreeSelection) { TreeSelection treeSelection = (TreeSelection) selection; Object element = treeSelection.getFirstElement(); if (element != null) { element.toString(); if (element instanceof IFile && RunGulpTaskCommand.GULP_FILE_NAME.equals(((IFile) element).getName())) { return true; } else if (element instanceof ITask) { return true; } } TreePath path = treeSelection.getPaths()[0]; Object first = path.getFirstSegment(); if (first instanceof IAdaptable) { container = ((IAdaptable) first).getAdapter(IContainer.class); } } else { Object firstElement = selection.getFirstElement(); if (firstElement instanceof IAdaptable) { container = ((IAdaptable) firstElement).getAdapter(IContainer.class); } } } } } if (container != null) { try { IFile file = WorkbenchResourceUtil.findFileRecursively(container, RunGulpTaskCommand.GULP_FILE_NAME); return file != null && file.exists(); } catch (CoreException ex) { } } return false; }
Source:
protected Toolbar createMainToolbar() { Toolbar toolbar = new Toolbar("SVN Tab"); toolbar.addLeftWidget(diffButton_ = commands_.vcsDiff().createToolbarButton()); toolbar.addLeftSeparator(); toolbar.addLeftWidget(commands_.vcsAddFiles().createToolbarButton()); toolbar.addLeftWidget(commands_.vcsRemoveFiles().createToolbarButton()); toolbar.addLeftSeparator(); toolbar.addLeftWidget(commands_.vcsCommit().createToolbarButton()); toolbar.addLeftSeparator(); ToolbarPopupMenu moreMenu = new ToolbarPopupMenu(); moreMenu.addItem(commands_.vcsRevert().createMenuItem(false)); moreMenu.addItem(commands_.vcsIgnore().createMenuItem(false)); moreMenu.addSeparator(); moreMenu.addItem(commands_.vcsResolve().createMenuItem(false)); moreMenu.addSeparator(); moreMenu.addItem(commands_.vcsPull().createMenuItem(false)); moreMenu.addItem(commands_.vcsCleanup().createMenuItem(false)); moreMenu.addSeparator(); moreMenu.addItem(commands_.vcsShowHistory().createMenuItem(false)); moreMenu.addSeparator(); moreMenu.addItem(commands_.showShellDialog().createMenuItem(false)); toolbar.addLeftWidget(new ToolbarMenuButton( "More", ToolbarButton.NoTitle, new ImageResource2x(StandardIcons.INSTANCE.more_actions2x()), moreMenu)); toolbar.addLeftSeparator(); toolbar.addRightWidget(commands_.vcsRefresh().createToolbarButton()); return toolbar; }

Target:
protected Toolbar createMainToolbar() { Toolbar toolbar = new Toolbar("SVN Tab"); toolbar.addLeftWidget(commands_.vcsDiff().createToolbarButton()); toolbar.addLeftSeparator(); toolbar.addLeftWidget(commands_.vcsAddFiles().createToolbarButton()); toolbar.addLeftWidget(commands_.vcsRemoveFiles().createToolbarButton()); toolbar.addLeftSeparator(); toolbar.addLeftWidget(commands_.vcsCommit().createToolbarButton()); toolbar.addLeftSeparator(); ToolbarPopupMenu moreMenu = new ToolbarPopupMenu(); moreMenu.addItem(commands_.vcsRevert().createMenuItem(false)); moreMenu.addItem(commands_.vcsIgnore().createMenuItem(false)); moreMenu.addSeparator(); moreMenu.addItem(commands_.vcsResolve().createMenuItem(false)); moreMenu.addSeparator(); moreMenu.addItem(commands_.vcsPull().createMenuItem(false)); moreMenu.addItem(commands_.vcsCleanup().createMenuItem(false)); moreMenu.addSeparator(); moreMenu.addItem(commands_.vcsShowHistory().createMenuItem(false)); moreMenu.addSeparator(); moreMenu.addItem(commands_.showShellDialog().createMenuItem(false)); toolbar.addLeftWidget(new ToolbarMenuButton( "More", ToolbarButton.NoTitle, new ImageResource2x(StandardIcons.INSTANCE.more_actions2x()), moreMenu)); toolbar.addLeftSeparator(); toolbar.addRightWidget(commands_.vcsRefresh().createToolbarButton()); return toolbar; }
Source:
public void onRemoteOpen(Connection connection) throws Exception { handler.requireHandler(); try { initInternal(); } catch (Exception e) { log.error("Error init connection", e); } if (!validateConnection(connection)) { connection.close(); } else { connection.setContext(AMQPConnectionContext.this); connection.setContainer(containerId); connection.setProperties(connectionProperties); connection.setOfferedCapabilities(getConnectionCapabilitiesOffered()); connection.open(); } initialise(); if (connection.getRemoteProperties() == null || !connection.getRemoteProperties().containsKey(CONNECTION_OPEN_FAILED)) { long nextKeepAliveTime = handler.tick(true); scheduledFutureRef.getAndUpdate(value -> { if (value != null && nextKeepAliveTime != 0 && scheduledPool != null) { return scheduledPool.schedule(new ScheduleRunnable(), (nextKeepAliveTime - TimeUnit.NANOSECONDS.toMillis(System.nanoTime())), TimeUnit.MILLISECONDS); } return value; }); } }

Target:
public void onRemoteOpen(Connection connection) throws Exception { handler.requireHandler(); try { initInternal(); } catch (Exception e) { log.error("Error init connection", e); } if (!validateConnection(connection)) { connection.close(); } else { connection.setContext(AMQPConnectionContext.this); connection.setContainer(containerId); connection.setProperties(connectionProperties); connection.setOfferedCapabilities(getConnectionCapabilitiesOffered()); connection.open(); } initialise(); if (connection.getRemoteProperties() == null || !connection.getRemoteProperties().containsKey(CONNECTION_OPEN_FAILED)) { long nextKeepAliveTime = handler.tick(true); if (nextKeepAliveTime != 0 && scheduledPool != null) { scheduleOp.setDelay(nextKeepAliveTime - TimeUnit.NANOSECONDS.toMillis(System.nanoTime())); scheduledFutureRef.getAndUpdate(scheduleOp); } } }
Source:
public void testSimple() throws Exception { final String path1 = "/a"; final String path2 = "/a/b"; final byte[] data1 = "here's a string".getBytes(); final byte[] data2 = "here's another string".getBytes(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); client.inTransaction().create().compressed().forPath(path1, data1).and(). create().compressed().forPath(path2, data2).and().commit(); Assert.assertNotEquals(data1, client.getData().forPath(path1)); Assert.assertEquals(data1.length, client.getData().decompressed().forPath(path1).length); Assert.assertNotEquals(data2, client.getData().forPath(path2)); Assert.assertEquals(data2.length, client.getData().decompressed().forPath(path2).length); } finally { CloseableUtils.closeQuietly(client); } }

Target:
public void testSimple() throws Exception { final String path1 = "/a"; final String path2 = "/a/b"; final byte[] data1 = "here's a string".getBytes(); final byte[] data2 = "here's another string".getBytes(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); client.inTransaction().create().compressed().forPath(path1, data1).and(). create().compressed().forPath(path2, data2).and().commit(); Assert.assertNotEquals(data1, client.getData().forPath(path1)); Assert.assertEquals(data1, client.getData().decompressed().forPath(path1)); Assert.assertNotEquals(data2, client.getData().forPath(path2)); Assert.assertEquals(data2, client.getData().decompressed().forPath(path2)); } finally { CloseableUtils.closeQuietly(client); } }
Source:
long next() { if (!hasNext()) { throw new NoSuchElementException(); } final long ret = currentRecord; try { currentRecord = is.readLong(); } catch (EOFException eof) { isCurrentRecord = false; currentRecord = 0; } catch (IOException e) { throw new RuntimeException(e); } return ret; }

Target:
long next() { if (!hasNext()) { throw new NoSuchElementException(); } final long ret = currentRecord; try { currentRecord = is.readLong(); } catch (final EOFException eof) { isCurrentRecord = false; currentRecord = 0; } catch (final IOException e) { throw new RuntimeException(e); } return ret; }
Source:
public XMLRecordReader(FileSplit split, Configuration conf) throws IOException { file = split.getPath(); fileName = file.toUri().toString(); fs = file.getFileSystem(conf); XMLInputFactory factory = XMLInputFactory.newInstance(); FSDataInputStream fdDataInputStream = fs.open(file); inputStream = new PublishingInputStream(fdDataInputStream); availableBytes = inputStream.available(); try { reader = factory.createXMLStreamReader(inputStream); } catch (XMLStreamException exception) { throw new RuntimeException("XMLStreamException exception : ", exception); } nodePath = conf.get(XMLInputFormat.XML_INPUTFORMAT_NODE_PATH); if (nodePath.indexOf("/") == 0) { nodePath = nodePath.substring(1, nodePath.length()); } nodes = nodePath.split("/"); totalNodes = nodes.length; actualNodeLevelMap = new HashMap<Integer, String>(); for (int i = 0; i < totalNodes; i++) { actualNodeLevelMap.put(i, nodes[i]); } currentNodeLevelMap = new HashMap<Integer, String>(); tempFilePath = conf.get(XMLInputFormat.XML_INPUTFORMAT_PROCESSED_DATA_TEMP_FILE); fileAction = conf.get(XMLInputFormat.XML_INPUTFORMAT_FILE_ACTION); targetFolder = conf.get(XMLInputFormat.XML_INPUTFORMAT_TARGET_FOLDER); }

Target:
public XMLRecordReader(FileSplit split, Configuration conf) throws IOException { file = split.getPath(); fileName = file.toUri().toString(); fs = file.getFileSystem(conf); XMLInputFactory factory = XMLInputFactory.newInstance(); FSDataInputStream fdDataInputStream = fs.open(file); inputStream = new TrackingInputStream(fdDataInputStream); availableBytes = inputStream.available(); try { reader = factory.createXMLStreamReader(inputStream); } catch (XMLStreamException exception) { throw new RuntimeException("XMLStreamException exception : ", exception); } String nodePath = conf.get(XMLInputFormat.XML_INPUTFORMAT_NODE_PATH); if (nodePath.indexOf("/") == 0) { nodePath = nodePath.substring(1, nodePath.length()); } nodes = nodePath.split("/"); currentNodeLevelMap = new HashMap<Integer, String>(); tempFilePath = conf.get(XMLInputFormat.XML_INPUTFORMAT_PROCESSED_DATA_TEMP_FOLDER); fileAction = conf.get(XMLInputFormat.XML_INPUTFORMAT_FILE_ACTION); targetFolder = conf.get(XMLInputFormat.XML_INPUTFORMAT_TARGET_FOLDER); }
Source:
public MarketplaceProxy() { try { url = new URL(MP_URL); ThreadPoolManager.getScheduledPool("marketplace").scheduleWithFixedDelay(() -> refresh(), 0, refresh_interval, TimeUnit.SECONDS); } catch (MalformedURLException e) { throw new IllegalArgumentException("Something is very wrong - cannot instantiate URL " + MP_URL); } }

Target:
public MarketplaceProxy() { try { url = new URL(MP_URL); this.executorService = Executors.newSingleThreadScheduledExecutor(); this.refreshJob = this.executorService.scheduleWithFixedDelay(() -> refresh(), 0, refresh_interval, TimeUnit.SECONDS); } catch (MalformedURLException e) { throw new IllegalArgumentException("Something is very wrong - cannot instantiate URL " + MP_URL); } }
Source:
public void testSingleFileUpdate() throws InterruptedException, IOException { Files.write(file1.toPath(), new byte[]{11}, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); Thread.sleep(150); Assert.assertEquals(poller.getUpdatedFilesSinceLastTime(), ImmutableSet.of(file1)); }

Target:
public void testSingleFileUpdate() throws InterruptedException, IOException { long fileChanges = poller.getStats().getFileChangesDetected(); Files.write(file1.toPath(), new byte[]{11}, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); while (fileChanges == poller.getStats().getFileChangesDetected()) { Thread.sleep(25); } Assert.assertEquals(poller.getUpdatedFilesSinceLastTime(), ImmutableSet.of(file1)); }
Source:
public ReadableBuffer getSendBuffer(int deliveryCount, MessageReference reference) { ensureDataIsValid(); DeliveryAnnotations deliveryAnnotations; if (reference != null && reference.getProtocolData() != null && reference.getProtocolData() instanceof DeliveryAnnotations) { deliveryAnnotations = (DeliveryAnnotations) reference.getProtocolData(); } else { deliveryAnnotations = null; } if (deliveryCount > 1) { return createCopyWithNewDeliveryCount(deliveryCount, deliveryAnnotations); } else if (deliveryAnnotationsPosition != VALUE_NOT_PRESENT || deliveryAnnotations != null || (deliveryAnnotationsForSendBuffer != null && !deliveryAnnotationsForSendBuffer.getValue().isEmpty())) { return createCopyWithSkippedOrExplicitlySetDeliveryAnnotations(deliveryAnnotations); } else { return getData().duplicate(); } }

Target:
public ReadableBuffer getSendBuffer(int deliveryCount, MessageReference reference) { ensureDataIsValid(); DeliveryAnnotations daToWrite; if (reference != null && reference.getProtocolData() instanceof DeliveryAnnotations) { daToWrite = (DeliveryAnnotations) reference.getProtocolData(); } else { daToWrite = deliveryAnnotationsForSendBuffer; } if (deliveryCount > 1 || daToWrite != null || deliveryAnnotationsPosition != VALUE_NOT_PRESENT) { return createDeliveryCopy(deliveryCount, daToWrite); } else { return getData().duplicate(); } }
Source:
private void updateTcpBufferSizes(NetworkAgentInfo nai) { if (isDefaultNetwork(nai) == false) { return; } String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes(); String[] values = null; if (tcpBufferSizes != null) { values = tcpBufferSizes.split(","); } if (values == null || values.length != 6) { if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults"); tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES; values = tcpBufferSizes.split(","); } if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return; try { if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes); String rmemValues = values[0] + " " + values[1] + " " +values[2]; String wmemValues = values[3] + " " + values[4] + " " +values[5]; mNetd.setTcpRWmemorySize(rmemValues, wmemValues); mCurrentTcpBufferSizes = tcpBufferSizes; } catch (RemoteException e) { loge("Can't set TCP buffer sizes:" + e); } Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.TCP_DEFAULT_INIT_RWND, mSystemProperties.getInt("net.tcp.default_init_rwnd", 0)); final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd"; if (rwndValue != 0) { mSystemProperties.set(sysctlKey, rwndValue.toString()); } }

Target:
private void updateTcpBufferSizes(NetworkAgentInfo nai) { if (isDefaultNetwork(nai) == false) { return; } String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes(); String[] values = null; if (tcpBufferSizes != null) { values = tcpBufferSizes.split(","); } if (values == null || values.length != 6) { if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults"); tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES; values = tcpBufferSizes.split(","); } if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return; try { if (VDBG || DDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes); String rmemValues = String.join(" ", values[0], values[1], values[2]); String wmemValues = String.join(" ", values[3], values[4], values[5]); mNetd.setTcpRWmemorySize(rmemValues, wmemValues); mCurrentTcpBufferSizes = tcpBufferSizes; } catch (RemoteException | ServiceSpecificException e) { loge("Can't set TCP buffer sizes:" + e); } Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.TCP_DEFAULT_INIT_RWND, mSystemProperties.getInt("net.tcp.default_init_rwnd", 0)); final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd"; if (rwndValue != 0) { mSystemProperties.set(sysctlKey, rwndValue.toString()); } }