auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void shouldNotExpireChargesWhenAwaitingCaptureDelayIsLessThan48Hours() { String extChargeId1 = addCharge(CREATED, "ref", ZonedDateTime.now().minusMinutes(90), RandomIdGenerator.newId()); String extChargeId2 = addCharge(AWAITING_CAPTURE_REQUEST, "ref", ZonedDateTime.now().minusHours(48L).plusMinutes(1L), RandomIdGenerator.newId()); worldpayMockClient.mockCancelSuccess(); connectorRestApiClient .postChargeExpiryTask() .statusCode(OK.getStatusCode()) .contentType(JSON) .body("expiry-success", is(1)) .body("expiry-failed", is(0)); connectorRestApiClient .withAccountId(accountId) .withChargeId(extChargeId1) .getCharge() .statusCode(OK.getStatusCode()) .contentType(JSON) .body(JSON_CHARGE_KEY, is(extChargeId1)) .body(JSON_STATE_KEY, is(EXPIRED.toExternal().getStatus())); connectorRestApiClient .withAccountId(accountId) .withChargeId(extChargeId2) .getCharge() .statusCode(OK.getStatusCode()) .contentType(JSON) .body(JSON_CHARGE_KEY, is(extChargeId2)) .body(JSON_STATE_KEY, is(AWAITING_CAPTURE_REQUEST.toExternal().getStatus())); List<String> events1 = databaseTestHelper.getInternalEvents(extChargeId1); List<String> events2 = databaseTestHelper.getInternalEvents(extChargeId2); assertTrue(isEqualCollection(events1, asList(CREATED.getValue(), EXPIRED.getValue()))); assertTrue(isEqualCollection(events2, asList(AWAITING_CAPTURE_REQUEST.getValue()))); }

Target:
public void shouldNotExpireChargesWhenAwaitingCaptureDelayIsLessThan48Hours() { String chargeToBeExpiredCreatedStatus = addCharge(CREATED, "ref", ZonedDateTime.now().minusMinutes(90), RandomIdGenerator.newId()); String chargeToBeExpiredAwaitingCaptureRequest = addCharge(AWAITING_CAPTURE_REQUEST, "ref", ZonedDateTime.now().minusHours(48L).plusMinutes(1L), RandomIdGenerator.newId()); worldpayMockClient.mockCancelSuccess(); connectorRestApiClient .postChargeExpiryTask() .statusCode(OK.getStatusCode()) .contentType(JSON) .body("expiry-success", is(1)) .body("expiry-failed", is(0)); connectorRestApiClient .withAccountId(accountId) .withChargeId(chargeToBeExpiredCreatedStatus) .getCharge() .statusCode(OK.getStatusCode()) .contentType(JSON) .body(JSON_CHARGE_KEY, is(chargeToBeExpiredCreatedStatus)) .body(JSON_STATE_KEY, is(EXPIRED.toExternal().getStatus())); connectorRestApiClient .withAccountId(accountId) .withChargeId(chargeToBeExpiredAwaitingCaptureRequest) .getCharge() .statusCode(OK.getStatusCode()) .contentType(JSON) .body(JSON_CHARGE_KEY, is(chargeToBeExpiredAwaitingCaptureRequest)) .body(JSON_STATE_KEY, is(AWAITING_CAPTURE_REQUEST.toExternal().getStatus())); List<String> events1 = databaseTestHelper.getInternalEvents(chargeToBeExpiredCreatedStatus); List<String> events2 = databaseTestHelper.getInternalEvents(chargeToBeExpiredAwaitingCaptureRequest); assertTrue(isEqualCollection(events1, asList(CREATED.getValue(), EXPIRED.getValue()))); assertTrue(isEqualCollection(events2, asList(AWAITING_CAPTURE_REQUEST.getValue()))); }
Source:
public void updateSource(TaskSource sourceUpdate) { checkLockNotHeld("Can not update sources while holding the driver lock"); checkArgument(sourceOperator.isPresent() && sourceOperator.get().getSourceId().equals(sourceUpdate.getPlanNodeId())); pendingTaskSourceUpdates.updateAndGet(current -> current == null ? sourceUpdate : current.update(sourceUpdate)); tryWithLock(() -> TRUE); }

Target:
public void updateSource(TaskSource sourceUpdate) { checkState(initialized.get(), "Driver is not initialized"); checkLockNotHeld("Can not update sources while holding the driver lock"); checkArgument( sourceOperator.isPresent() && sourceOperator.get().getSourceId().equals(sourceUpdate.getPlanNodeId()), "sourceUpdate is for a plan node that is different from this Driver's source node"); pendingTaskSourceUpdates.updateAndGet(current -> current == null ? sourceUpdate : current.update(sourceUpdate)); tryWithLock(() -> TRUE); }
Source:
protected int persistHydrant( FireHydrant indexToPersist, DataSchema schema, Interval interval, Map<String, Object> metadataElems ) { synchronized (indexToPersist) { if (indexToPersist.hasSwapped()) { log.info( "DataSource[%s], Interval[%s], Hydrant[%s] already swapped. Ignoring request to persist.", schema.getDataSource(), interval, indexToPersist ); return 0; } log.info( "DataSource[%s], Interval[%s], Metadata [%s] persisting Hydrant[%s]", schema.getDataSource(), interval, metadataElems, indexToPersist ); try { int numRows = indexToPersist.getIndex().size(); final IndexSpec indexSpec = config.getIndexSpec(); indexToPersist.getIndex().getMetadata().putAll(metadataElems); final File persistedFile = indexMerger.persist( indexToPersist.getIndex(), interval, new File(computePersistDir(schema, interval), String.valueOf(indexToPersist.getCount())), indexSpec, config.getSegmentWriteOutMediumFactory() ); indexToPersist.swapSegment( new QueryableIndexSegment(indexIO.loadIndex(persistedFile), indexToPersist.getSegmentId()) ); return numRows; } catch (IOException e) { log.makeAlert("dataSource[%s] -- incremental persist failed", schema.getDataSource()) .addData("interval", interval) .addData("count", indexToPersist.getCount()) .emit(); throw new RuntimeException(e); } } }

Target:
protected int persistHydrant( FireHydrant indexToPersist, DataSchema schema, Interval interval, Map<String, Object> metadataElems ) { synchronized (indexToPersist) { if (indexToPersist.hasSwapped()) { log.info( "DataSource[%s], Interval[%s], Hydrant[%s] already swapped. Ignoring request to persist.", schema.getDataSource(), interval, indexToPersist ); return 0; } log.info( "DataSource[%s], Interval[%s], Metadata [%s] persisting Hydrant[%s]", schema.getDataSource(), interval, metadataElems, indexToPersist ); try { int numRows = indexToPersist.getIndex().size(); indexToPersist.getIndex().getMetadata().putAll(metadataElems); final File persistedFile = indexMerger.persist( indexToPersist.getIndex(), interval, new File(computePersistDir(schema, interval), String.valueOf(indexToPersist.getCount())), config.getIndexSpecForIntermediatePersists(), config.getSegmentWriteOutMediumFactory() ); indexToPersist.swapSegment( new QueryableIndexSegment(indexIO.loadIndex(persistedFile), indexToPersist.getSegmentId()) ); return numRows; } catch (IOException e) { log.makeAlert("dataSource[%s] -- incremental persist failed", schema.getDataSource()) .addData("interval", interval) .addData("count", indexToPersist.getCount()) .emit(); throw new RuntimeException(e); } } }
Source:
private void doBuildProject(File projectLocation, IProgressMonitor monitor) throws CoreException { if (monitor.isCanceled()) { return; } try { monitor.beginTask(Messages.MSBuild_BuildProjectTask, 10); String msBuild = getMSBuildPath(); if (msBuild != null) { File csprojFile = WPProjectUtils.getCsrojFile(projectLocation); Assert.isNotNull(csprojFile); StringBuilder cmdString = new StringBuilder(msBuild); cmdString.append(" "); if (isRelease()) { cmdString.append("/p:Configuration=Release "); } cmdString.append(csprojFile.getAbsolutePath()); ExternalProcessUtility processUtility = new ExternalProcessUtility(); if (monitor.isCanceled()) { return; } monitor.worked(1); TextDetectingStreamListener listener = new TextDetectingStreamListener( "Build succeeded."); processUtility.execSync(cmdString.toString(), projectLocation, listener, listener, monitor, null, getLaunchConfiguration()); if (!listener.isTextDetected()) { throw new CoreException(new Status(IStatus.ERROR, WPCore.PLUGIN_ID, Messages.MSBuild_MSBuildError)); } } } finally { monitor.done(); } }

Target:
private void doBuildProject(File projectLocation, IProgressMonitor monitor) throws CoreException { if (monitor.isCanceled()) { return; } try { monitor.beginTask(Messages.MSBuild_BuildProjectTask, 10); String msBuild = getMSBuildPath(); if (msBuild != null) { File csprojFile = WPProjectUtils.getCsrojFile(projectLocation); Assert.isNotNull(csprojFile); StringBuilder cmdString = new StringBuilder(addQuotes(msBuild)); cmdString.append(" "); if (isRelease()) { cmdString.append("/p:Configuration=Release "); } cmdString.append(addQuotes(csprojFile.getAbsolutePath())); ExternalProcessUtility processUtility = new ExternalProcessUtility(); if (monitor.isCanceled()) { return; } monitor.worked(1); TextDetectingStreamListener listener = new TextDetectingStreamListener( "Build succeeded."); processUtility.execSync(cmdString.toString(), projectLocation, listener, listener, monitor, null, getLaunchConfiguration()); if (!listener.isTextDetected()) { throw new CoreException(new Status(IStatus.ERROR, WPCore.PLUGIN_ID, Messages.MSBuild_MSBuildError)); } } } finally { monitor.done(); } }
Source:
private void initializeServices() { logger().debug("Initializing couchbase services on host: " + enabledServices); final String services = enabledServices.stream().map(s -> { switch (s) { case KV: return "kv"; case QUERY: return "n1ql"; case INDEX: return "index"; case SEARCH: return "fts"; default: throw new IllegalStateException("Unknown service!"); } }).collect(Collectors.joining(",")); Response response = doHttpRequest(MGMT_PORT, "/node/controller/setupServices", "POST", new FormBody.Builder() .add("services", services) .build(), false ); checkSuccessfulResponse(response, "Could not enable couchbase services"); }

Target:
private void initializeServices() { logger().debug("Initializing couchbase services on host: {}", enabledServices); final String services = enabledServices.stream().map(s -> { switch (s) { case KV: return "kv"; case QUERY: return "n1ql"; case INDEX: return "index"; case SEARCH: return "fts"; default: throw new IllegalStateException("Unknown service!"); } }).collect(Collectors.joining(",")); Response response = doHttpRequest(MGMT_PORT, "/node/controller/setupServices", "POST", new FormBody.Builder() .add("services", services) .build(), false ); checkSuccessfulResponse(response, "Could not enable couchbase services"); }
Source:
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> customHttpHeadersObject = context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY); if (customHttpHeadersObject.isPresent() && customHttpHeadersObject.get() instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) customHttpHeadersObject.get(); for (HttpHeader httpHeader : customHttpHeaders) { if (!Objects.isNull(httpHeader.getName()) && !Objects.isNull(httpHeader.getValue())) { context.getHttpRequest().getHeaders().put(httpHeader.getName(), httpHeader.getValue()); } } } return next.process(); }

Target:
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY).ifPresent(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; for (HttpHeader httpHeader : customHttpHeaders) { if (!Objects.isNull(httpHeader.getName()) && !Objects.isNull(httpHeader.getValue())) { context.getHttpRequest().getHeaders().put(httpHeader.getName(), httpHeader.getValue()); } } } }); return next.process(); }
Source:
public ExpressionAnalysis( Map<NodeRef<Expression>, Type> expressionTypes, Map<NodeRef<Expression>, Type> expressionCoercions, Set<NodeRef<InPredicate>> subqueryInPredicates, Set<NodeRef<SubqueryExpression>> scalarSubqueries, Set<NodeRef<ExistsPredicate>> existsSubqueries, Map<NodeRef<Expression>, FieldId> columnReferences, Set<NodeRef<Expression>> typeOnlyCoercions, Set<NodeRef<QuantifiedComparisonExpression>> quantifiedComparisons, Map<NodeRef<Identifier>, LambdaArgumentDeclaration> lambdaArgumentReferences) { this.expressionTypes = new LinkedHashMap<>(requireNonNull(expressionTypes, "expressionTypes is null")); this.expressionCoercions = new LinkedHashMap<>(requireNonNull(expressionCoercions, "expressionCoercions is null")); this.typeOnlyCoercions = new LinkedHashSet<>(requireNonNull(typeOnlyCoercions, "typeOnlyCoercions is null")); this.columnReferences = new LinkedHashMap<>(requireNonNull(columnReferences, "columnReferences is null")); this.subqueryInPredicates = new LinkedHashSet<>(requireNonNull(subqueryInPredicates, "subqueryInPredicates is null")); this.scalarSubqueries = new LinkedHashSet<>(requireNonNull(scalarSubqueries, "subqueryInPredicates is null")); this.existsSubqueries = new LinkedHashSet<>(requireNonNull(existsSubqueries, "existsSubqueries is null")); this.quantifiedComparisons = new LinkedHashSet<>(requireNonNull(quantifiedComparisons, "quantifiedComparisons is null")); this.lambdaArgumentReferences = new LinkedHashMap<>(requireNonNull(lambdaArgumentReferences, "lambdaArgumentReferences is null")); }

Target:
public ExpressionAnalysis( Map<NodeRef<Expression>, Type> expressionTypes, Map<NodeRef<Expression>, Type> expressionCoercions, Set<NodeRef<InPredicate>> subqueryInPredicates, Set<NodeRef<SubqueryExpression>> scalarSubqueries, Set<NodeRef<ExistsPredicate>> existsSubqueries, Map<NodeRef<Expression>, FieldId> columnReferences, Set<NodeRef<Expression>> typeOnlyCoercions, Set<NodeRef<QuantifiedComparisonExpression>> quantifiedComparisons, Map<NodeRef<Identifier>, LambdaArgumentDeclaration> lambdaArgumentReferences) { this.expressionTypes = ImmutableMap.copyOf(requireNonNull(expressionTypes, "expressionTypes is null")); this.expressionCoercions = ImmutableMap.copyOf(requireNonNull(expressionCoercions, "expressionCoercions is null")); this.typeOnlyCoercions = ImmutableSet.copyOf(requireNonNull(typeOnlyCoercions, "typeOnlyCoercions is null")); this.columnReferences = ImmutableMap.copyOf(requireNonNull(columnReferences, "columnReferences is null")); this.subqueryInPredicates = ImmutableSet.copyOf(requireNonNull(subqueryInPredicates, "subqueryInPredicates is null")); this.scalarSubqueries = ImmutableSet.copyOf(requireNonNull(scalarSubqueries, "subqueryInPredicates is null")); this.existsSubqueries = ImmutableSet.copyOf(requireNonNull(existsSubqueries, "existsSubqueries is null")); this.quantifiedComparisons = ImmutableSet.copyOf(requireNonNull(quantifiedComparisons, "quantifiedComparisons is null")); this.lambdaArgumentReferences = ImmutableMap.copyOf(requireNonNull(lambdaArgumentReferences, "lambdaArgumentReferences is null")); }
Source:
public FreeStyleProject newInstance(Branch branch) { FreeStyleProject job = new FreeStyleProject(getOwner(), branch.getEncodedName()); setBranch(job, branch); try { job.setQuietPeriod(0); } catch(IOException e) { e.printStackTrace(); } return job; }

Target:
public FreeStyleProject newInstance(Branch branch) { FreeStyleProject job = new FreeStyleProject(getOwner(), branch.getEncodedName()); setBranch(job, branch); if (quietPeriodSeconds >= 0) { try { job.setQuietPeriod(quietPeriodSeconds); } catch(IOException e) { e.printStackTrace(); } } return job; }
Source:
public void init(final GlusterVolumeGeoRepCreateModel model) { super.init(model); model.getPropertyChangedEvent().addListener(new IEventListener<PropertyChangedEventArgs>() { @Override public void eventRaised(Event<? extends PropertyChangedEventArgs> ev, Object sender, PropertyChangedEventArgs args) { if(args.propertyName.equalsIgnoreCase("RecommendationViolations")) { getView().setSuggestedConfigViolations(model.getRecommendationViolations()); } else if (args.propertyName.equalsIgnoreCase("QueryFailed")) { getView().setFailureMessage(model.getQueryFailureMessage()); } } }); model.getSlaveUserName().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { String slaveUser = model.getSlaveUserName() .getEntity(); getView().setUserGroupVisibility(slaveUser != null && !slaveUser .equalsIgnoreCase(ConstantsManager.getInstance().getConstants().rootUser())); } }); }

Target:
public void init(final GlusterVolumeGeoRepCreateModel model) { super.init(model); model.getPropertyChangedEvent().addListener(new IEventListener<PropertyChangedEventArgs>() { @Override public void eventRaised(Event<? extends PropertyChangedEventArgs> ev, Object sender, PropertyChangedEventArgs args) { if(args.propertyName.equalsIgnoreCase("RecommendationViolations")) { getView().setSuggestedConfigViolations(model.getRecommendationViolations()); } else if (args.propertyName.equalsIgnoreCase("QueryFailed")) { getView().setFailureMessage(model.getQueryFailureMessage()); } } }); }
Source:
public Scheduler cleanupResponseUrlDataScheduler() throws SchedulerException { return this.constructScheduler(ResponseDataCleanupJob.class, KEY_CLEANUP_JOB_THREAD_COUNT, KEY_CLEANUP_JOB_CRON_EXPRESSION, this.getDatabaseUrl(), this.databaseUsername, this.databasePassword, this.databaseDriver); }

Target:
public Scheduler cleanupResponseUrlDataScheduler() throws SchedulerException { return this.constructScheduler(ResponseUrlDataCleanupJob.class, KEY_CLEANUP_JOB_THREAD_COUNT, KEY_CLEANUP_JOB_CRON_EXPRESSION, this.getDatabaseUrl(), this.databaseUsername, this.databasePassword, this.databaseDriver); }
Source:
public void generateType(final Ds3Type typeEntry) throws IOException { final Template typeTemplate = config.getTemplate("TypeEnumConstant.tmplt"); final Type type = TypeConverter.toType(typeEntry); final Path outputPath = getTypeOutputPath(type); final OutputStream outStream = fileUtils.getOutputFile(outputPath); final Writer writer = new OutputStreamWriter(outStream); try { typeTemplate.process(type, writer); } catch (final NullPointerException e) { LOG.error("Encountered NullPointerException while processing template " + typeTemplate.getName(), e); e.printStackTrace(); } catch (final TemplateException e) { LOG.error("Encountered TemplateException while processing template " + typeTemplate.getName(), e); e.printStackTrace(); } }

Target:
public void generateType(final Ds3Type typeEntry) throws IOException { final Template typeTemplate = config.getTemplate("TypeEnumConstant.tmplt"); final Type type = TypeConverter.toType(typeEntry); final Path outputPath = getTypeOutputPath(type); final OutputStream outStream = fileUtils.getOutputFile(outputPath); final Writer writer = new OutputStreamWriter(outStream); try { typeTemplate.process(type, writer); } catch (final NullPointerException e) { LOG.error("Encountered NullPointerException while processing template " + typeTemplate.getName(), e); } catch (final TemplateException e) { LOG.error("Encountered TemplateException while processing template " + typeTemplate.getName(), e); } }
Source:
private Map<Long, ISegmentAspect> getAspectsFromColumnsId(List<Long> desiredColumns) { Map<Long, ISegmentAspect> aspects = new LinkedHashMap<>(); if (!desiredColumns.isEmpty()) { for (Long columnsId : desiredColumns) { ISegmentAspect segmentAspect = fAspectMap.get(columnsId); if (segmentAspect != null) { aspects.put(columnsId, segmentAspect); } } return aspects; } return fAspectMap; }

Target:
private Map<Long, ISegmentAspect> getAspectsFromColumnsId(List<Long> desiredColumns) { if (!desiredColumns.isEmpty()) { Map<Long, ISegmentAspect> aspects = new LinkedHashMap<>(); for (Long columnsId : desiredColumns) { ISegmentAspect segmentAspect = fAspectMap.get(columnsId); if (segmentAspect != null) { aspects.put(columnsId, segmentAspect); } } return aspects; } return fAspectMap; }
Source:
public String toString() { return "KubernetesCloud '" + name + "' serverUrl :" + serverUrl; }

Target:
public String toString() { return MoreObjects.toStringHelper(this).add("name", name).add("serverUrl", serverUrl).toString(); }
Source:
public int getOptimalTileWidth() { FormatTools.assertId(currentId, true, 1); RandomAccessInputStream plane = getPlane(getSeries(), 0); if (plane == null) return super.getOptimalTileWidth(); try { TiffParser tp = new TiffParser(plane); IFD ifd = tp.getFirstIFD(); return (int) ifd.getTileWidth(); } catch (FormatException e) { LOGGER.debug("Could not retrieve tile width", e); } catch (IOException e) { LOGGER.debug("Could not retrieve tile width", e); } finally { try { plane.close(); } catch (IOException e2) { LOGGER.debug("Could not close stream", e2); } } return super.getOptimalTileWidth(); }

Target:
public int getOptimalTileWidth() { FormatTools.assertId(currentId, true, 1); RandomAccessInputStream plane = getPlane(getSeries(), 0); if (plane == null) return super.getOptimalTileWidth(); try (RandomAccessInputStream p = plane) { TiffParser tp = new TiffParser(plane); IFD ifd = tp.getFirstIFD(); return (int) ifd.getTileWidth(); } catch (FormatException e) { LOGGER.debug("Could not retrieve tile width", e); } catch (IOException e) { LOGGER.debug("Could not retrieve tile width", e); } return super.getOptimalTileWidth(); }
Source:
public void createOrLoadKey() { String keyLocation = env.getProperty("keyLocation"); if (rsaJsonWebKey == null) { try { loadSavedKey(keyLocation); } catch (ClassNotFoundException | IOException e1) { logger.error("Key not found or error loading key. Creating new key. ", e1); try { RsaKeyUtil keyUtil = new RsaKeyUtil(); KeyPair keyPair; keyPair = keyUtil.generateKeyPair(2048); rsaJsonWebKey = (RsaJsonWebKey) PublicJsonWebKey.Factory.newPublicJwk(keyPair.getPublic()); rsaJsonWebKey.setPrivateKey(keyPair.getPrivate()); saveKey(keyLocation); } catch (JoseException e) { logger.error("Error creating key: ", e1); throw new RuntimeException(e); } } } }

Target:
public void createOrLoadKey() { String keyLocation = env.getProperty("keyLocation"); if (rsaJsonWebKey == null) { try { loadSavedKey(keyLocation); } catch (ClassNotFoundException | IOException e1) { logger.error("Key not found or error loading key. Creating new key. ", e1); try { RsaKeyUtil keyUtil = new RsaKeyUtil(); KeyPair keyPair; keyPair = keyUtil.generateKeyPair(KEY_BIT_LENGTH); rsaJsonWebKey = (RsaJsonWebKey) PublicJsonWebKey.Factory.newPublicJwk(keyPair.getPublic()); rsaJsonWebKey.setPrivateKey(keyPair.getPrivate()); saveKey(keyLocation); } catch (JoseException e) { logger.error("Error creating key: ", e); throw new RuntimeException(e); } } } }
Source:
public synchronized void onJobArrival(final JobEntity jobEntity) { final int numResourcesToUse = jobEntity.getNumWorkers() + jobEntity.getNumServers(); if (numAvailableResources >= numResourcesToUse) { LOG.log(Level.INFO, "Start job {0} with {1} resources. Remaining free resources: {2}", new Object[]{jobEntity.getJobId(), numAvailableResources, numAvailableResources - numResourcesToUse}); numAvailableResources -= numResourcesToUse; jobServerDriverFuture.get().executeJob(jobEntity); } else { LOG.log(Level.INFO, "Put job {0} into queue", jobEntity.getJobId()); jobWaitingQueue.add(jobEntity); } }

Target:
public synchronized boolean onJobArrival(final JobEntity jobEntity) { if (numTotalResources < jobEntity.getNumServers() + jobEntity.getNumWorkers()) { return false; } if (!tryExecute(jobEntity)) { LOG.log(Level.INFO, "Put job {0} into queue", jobEntity.getJobId()); jobWaitingQueue.add(jobEntity); } return true; }
Source:
AuthenticatingHttpConnector(final String user, final Optional<AgentProxy> agentProxyOpt, final Optional<Path> clientCertificatePath, final Optional<Path> clientKeyPath, final EndpointIterator endpointIterator, final DefaultHttpConnector delegate, final List<Identity> identities) { if (clientCertificatePath.isPresent() ^ clientKeyPath.isPresent()) { throw new IllegalArgumentException( "both or neither of clientCertificatePath and clientKeyPath must be specified"); } this.user = user; this.agentProxy = agentProxyOpt; this.clientCertificatePath = clientCertificatePath; this.clientKeyPath = clientKeyPath; this.endpointIterator = endpointIterator; this.delegate = delegate; this.identities = identities; }

Target:
AuthenticatingHttpConnector(final String user, final Optional<AgentProxy> agentProxyOpt, final Optional<Path> clientCertificatePath, final Optional<Path> clientKeyPath, final EndpointIterator endpointIterator, final DefaultHttpConnector delegate, final List<Identity> identities) { if (clientCertificatePath.isPresent() != clientKeyPath.isPresent()) { throw new IllegalArgumentException( "both or neither of clientCertificatePath and clientKeyPath must be specified"); } this.user = user; this.agentProxy = agentProxyOpt; this.clientCertificatePath = clientCertificatePath; this.clientKeyPath = clientKeyPath; this.endpointIterator = endpointIterator; this.delegate = delegate; this.identities = identities; }
Source:
public Set<List<JavaFileScannerContext.Location>> flow(List<Integer> parameterIndices, List<Class<? extends Constraint>> domains) { Preconditions.checkArgument(!parameterIndices.isEmpty(), "computing flow on empty symbolic value list should never happen"); if(node == null || behavior == null) { return Collections.emptySet(); } String key = parameterIndices.stream().sorted().map(Object::toString).reduce("", String::concat); String domainKey = domains.stream().map(Class::getName).sorted().reduce("", String::concat); Map<String, Set<List<JavaFileScannerContext.Location>>> flowByDomain = cachedFlows.computeIfAbsent(key, k -> new HashMap<>()); return flowByDomain.computeIfAbsent(domainKey, k -> FlowComputation.flow(node, getSymbolicValues(parameterIndices), c -> true, c -> false, domains, node.programState.getLastEvaluated())); }

Target:
public Set<List<JavaFileScannerContext.Location>> flow(List<Integer> parameterIndices, List<Class<? extends Constraint>> domains) { Preconditions.checkArgument(!parameterIndices.isEmpty(), "computing flow on empty symbolic value list should never happen"); if(node == null || behavior == null) { return Collections.emptySet(); } String key = parameterIndices.stream().sorted().map(Object::toString).collect(Collectors.joining(",")); String domainKey = domains.stream().map(Class::getName).sorted().reduce("", String::concat); Map<String, Set<List<JavaFileScannerContext.Location>>> flowByDomain = cachedFlows.computeIfAbsent(key, k -> new HashMap<>()); return flowByDomain.computeIfAbsent(domainKey, k -> FlowComputation.flow(node, getSymbolicValues(parameterIndices), c -> true, c -> false, domains, node.programState.getLastEvaluated())); }
Source:
public synchronized void handleMessageLayoutPrepare( @NonNull CorfuPayloadMsg<LayoutPrepareRequest> msg, ChannelHandlerContext ctx, @NonNull IServerRouter r) { if (!isBootstrapped(msg, ctx, r)) { return; } final long msgEpoch = msg.getPayload().getEpoch(); final long serverEpoch = getServerEpoch(); final Rank prepareRank = new Rank(msg.getPayload().getRank(), msg.getClientID()); final Rank phase1Rank = getPhase1Rank(msgEpoch); if (msgEpoch != serverEpoch) { r.sendResponse(ctx, msg, new CorfuPayloadMsg<>(CorfuMsgType.WRONG_EPOCH, serverEpoch)); log.trace("handleMessageLayoutPrepare: Incoming message with wrong epoch, got {}, " + "expected {}, message was: {}", msg.getPayload().getEpoch(), serverEpoch, msg); return; } Layout proposedLayout = getProposedLayout(msgEpoch); if (phase1Rank != null && prepareRank.lessThanEqualTo(phase1Rank)) { log.debug("handleMessageLayoutPrepare: Rejected phase 1 prepare of rank={}, " + "phase1Rank={}", prepareRank, phase1Rank); r.sendResponse(ctx, msg, CorfuMsgType.LAYOUT_PREPARE_REJECT.payloadMsg(new LayoutPrepareResponse(phase1Rank.getRank(), proposedLayout))); } else { Rank highestProposedRank = proposedLayout == null ? new Rank(-1L, msg.getClientID()) : getPhase2Rank(msgEpoch); setPhase1Rank(prepareRank, msgEpoch); log.debug("handleMessageLayoutPrepare: New phase 1 rank={}", getPhase1Rank(msgEpoch)); r.sendResponse(ctx, msg, CorfuMsgType.LAYOUT_PREPARE_ACK.payloadMsg(new LayoutPrepareResponse(highestProposedRank.getRank(), proposedLayout))); } }

Target:
public synchronized void handleMessageLayoutPrepare( @NonNull CorfuPayloadMsg<LayoutPrepareRequest> msg, ChannelHandlerContext ctx, @NonNull IServerRouter r) { if (!isBootstrapped(msg, ctx, r)) { return; } final long payloadEpoch = msg.getPayload().getEpoch(); final long serverEpoch = getServerEpoch(); final Rank prepareRank = new Rank(msg.getPayload().getRank(), msg.getClientID()); final Rank phase1Rank = getPhase1Rank(payloadEpoch); if (payloadEpoch != serverEpoch) { r.sendResponse(ctx, msg, new CorfuPayloadMsg<>(CorfuMsgType.WRONG_EPOCH, serverEpoch)); log.trace("handleMessageLayoutPrepare: Incoming message with wrong epoch, got {}, " + "expected {}, message was: {}", msg.getPayload().getEpoch(), serverEpoch, msg); return; } Layout proposedLayout = getProposedLayout(payloadEpoch); if (phase1Rank != null && prepareRank.lessThanEqualTo(phase1Rank)) { log.debug("handleMessageLayoutPrepare: Rejected phase 1 prepare of rank={}, " + "phase1Rank={}", prepareRank, phase1Rank); r.sendResponse(ctx, msg, CorfuMsgType.LAYOUT_PREPARE_REJECT.payloadMsg(new LayoutPrepareResponse(phase1Rank.getRank(), proposedLayout))); } else { Rank highestProposedRank = proposedLayout == null ? new Rank(-1L, msg.getClientID()) : getPhase2Rank(payloadEpoch); setPhase1Rank(prepareRank, payloadEpoch); log.debug("handleMessageLayoutPrepare: New phase 1 rank={}", prepareRank); r.sendResponse(ctx, msg, CorfuMsgType.LAYOUT_PREPARE_ACK.payloadMsg(new LayoutPrepareResponse(highestProposedRank.getRank(), proposedLayout))); } }
Source:
public void setSpeed(Double degreesPerSecond) { if (maxSpeed != -1 && degreesPerSecond > maxSpeed) { speed = maxSpeed; log.info("Trying to set speed to a value greater than max speed"); } this.speed = degreesPerSecond; for (String controller : controllers) { ServiceInterface si = Runtime.getService(controller); if (si.isLocal()) { ((ServoController) Runtime.getService(controller)).servoSetVelocity(this); } else { send(controller, "servoSetVelocity", this); } } broadcastState(); }

Target:
public void setSpeed(Double degreesPerSecond) { if (degreesPerSecond == null) { log.info("disabling speed control"); speed = null; } if (maxSpeed != -1 && degreesPerSecond != null && degreesPerSecond > maxSpeed) { speed = maxSpeed; log.info("Trying to set speed to a value greater than max speed"); } this.speed = degreesPerSecond; for (String controller : controllers) { send(controller, "servoSetVelocity", this); } broadcastState(); }
Source:
private String getMemberName(String topic) { String[] topicElements = getTopicElements(topic); if (topicElements.length != 5) throw new IllegalArgumentException("Event creation failed, invalid topic: " + topic); return topicElements[5]; }

Target:
private String getMemberName(String topic) { String[] topicElements = getTopicElements(topic); if (topicElements.length < 5) throw new IllegalArgumentException("Event creation failed, invalid topic: " + topic); return topicElements[3]; }
Source:
private int countOccurrencesInTopology(final String topologyString, final String searchPattern) { final Matcher matcher = Pattern.compile(searchPattern).matcher(topologyString); final List<String> repartitionTopicsFound = new ArrayList<>(); while (matcher.find()) { repartitionTopicsFound.add(matcher.group()); } return repartitionTopicsFound.size(); }

Target:
private static int countOccurrencesInTopology(final String topologyString, final String searchPattern) { final Matcher matcher = Pattern.compile(searchPattern).matcher(topologyString); final List<String> repartitionTopicsFound = new ArrayList<>(); while (matcher.find()) { repartitionTopicsFound.add(matcher.group()); } return repartitionTopicsFound.size(); }
Source:
public void run() { if (StringUtils.isNotBlank(id)) { boolean hasParent; if (vocabularyAndHasParent.get(name) == null) { String dirSchema = directoryService.getDirectorySchema(name); Schema schema = schemaManager.getSchema(dirSchema); hasParent = schema.hasField("parent"); vocabularyAndHasParent.put(name, hasParent); } else { hasParent = vocabularyAndHasParent.get(name); } Session directorySession = directoryService.open(name); if (!directorySession.hasEntry(id)) { Map<String, Object> entry = new HashMap<>(); entry.put("id", id); if (StringUtils.isEmpty(label)) { label = id; } entry.put("label", label); if (hasParent) { entry.put("parent", parent); } entry.put("obsolete", obsolete); entry.put("ordering", ordering); directorySession.createEntry(entry); } directorySession.close(); } }

Target:
public void run() { if (StringUtils.isBlank(id)) { return; } try(Session directorySession = directoryService.open(name)) { if (directorySession.hasEntry(id)) { return; } Map<String, Object> entry = new HashMap<>(); entry.put("id", id); entry.put("label", defaultIfEmpty(label, id)); String dirSchema = directoryService.getDirectorySchema(name); Schema schema = schemaManager.getSchema(dirSchema); if (schema.hasField("parent")) { entry.put("parent", parent); } entry.put("obsolete", obsolete); entry.put("ordering", ordering); directorySession.createEntry(entry); } }
Source:
private EntitySpec<? extends Entity> build(Topology topology, String node, Set<String> visited) { final Map<String, NodeTemplate> nodeTemplates = topology.getNodeTemplates(); final NodeTemplate nodeTemplate = nodeTemplates.get(node); visited.add(node); EntitySpec<?> spec = createSpec(node, nodeTemplate, topology); LOG.info("applying spec modifiers {}", specModifiers); for (EntitySpecModifier builder : specModifiers) { builder.apply(spec, nodeTemplate, topology); } for (String child : children.get(node)) { if (!visited.contains(child)) { final EntitySpec<? extends Entity> childSpec = build(topology, child, visited); spec.child(childSpec) .configure(SoftwareProcess.CHILDREN_STARTABLE_MODE, SoftwareProcess.ChildStartableMode.BACKGROUND_LATE); } } return spec; }

Target:
private EntitySpec<? extends Entity> build(Topology topology, String node, Set<String> visited) { final Map<String, NodeTemplate> nodeTemplates = topology.getNodeTemplates(); final NodeTemplate nodeTemplate = nodeTemplates.get(node); visited.add(node); EntitySpec<?> spec = createSpec(node, nodeTemplate, topology); LOG.trace("applying spec modifiers to spec {}", specModifiers, spec); for (EntitySpecModifier builder : specModifiers) { builder.apply(spec, nodeTemplate, topology); } for (String child : children.get(node)) { if (!visited.contains(child)) { final EntitySpec<? extends Entity> childSpec = build(topology, child, visited); spec.child(childSpec) .configure(SoftwareProcess.CHILDREN_STARTABLE_MODE, SoftwareProcess.ChildStartableMode.BACKGROUND_LATE); } } return spec; }
Source:
public static ReviewCompareAnnotationSupport getAnnotationSupport(Viewer contentViewer) { ReviewCompareAnnotationSupport support = (ReviewCompareAnnotationSupport) contentViewer.getData(KEY_ANNOTAION_SUPPORT); if (support == null) { if (support == null) { support = new ReviewCompareAnnotationSupport(contentViewer); contentViewer.setData(KEY_ANNOTAION_SUPPORT, support); } } return support; }

Target:
public static ReviewCompareAnnotationSupport getAnnotationSupport(Viewer contentViewer) { ReviewCompareAnnotationSupport support = (ReviewCompareAnnotationSupport) contentViewer.getData(KEY_ANNOTAION_SUPPORT); if (support == null) { support = new ReviewCompareAnnotationSupport(contentViewer); contentViewer.setData(KEY_ANNOTAION_SUPPORT, support); } return support; }
Source:
private static Type getComponentOrElementType(Type arrayOrListType, ClientLogger logger) { if (arrayOrListType.getClass().isArray()) { return arrayOrListType.getClass().getComponentType(); } if (isList(arrayOrListType)) { ParameterizedType pt = (ParameterizedType) arrayOrListType; return pt.getActualTypeArguments()[0]; } throw logger.logExceptionAsError(new RuntimeException("Should not be there")); }

Target:
private static Type getComponentOrElementType(Type arrayOrListType, ClientLogger logger) { if (arrayOrListType.getClass().isArray()) { return arrayOrListType.getClass().getComponentType(); } if (isList(arrayOrListType)) { ParameterizedType pt = (ParameterizedType) arrayOrListType; return pt.getActualTypeArguments()[0]; } throw logger.logExceptionAsError(new RuntimeException(String.format( "Collection type %s is not supported.", arrayOrListType.getTypeName()))); }
Source:
private ThriftType convertEnumTypeField(Class enumClass, String fieldName){ List<ThriftType.EnumValue> enumValues = new ArrayList<ThriftType.EnumValue>(); String enumName = enumClass.getName(); try { List enumCollection = getEnumList(enumName); for (Object enumObj : enumCollection) { ScroogeEnumDesc enumDesc = ScroogeEnumDesc.fromEnum(enumObj); enumValues.add(new ThriftType.EnumValue(enumDesc.id, enumDesc.originalName)); } return new ThriftType.EnumType(enumValues); } catch (Exception e) { throw new ScroogeSchemaConversionException("Can not convert enum field " + fieldName, e); } }

Target:
private ThriftType convertEnumTypeField(Class enumClass, String fieldName) { List<ThriftType.EnumValue> enumValues = new ArrayList<ThriftType.EnumValue>(); String enumName = enumClass.getName(); try { List enumCollection = getEnumList(enumName); for (Object enumObj : enumCollection) { ScroogeEnumDesc enumDesc = ScroogeEnumDesc.fromEnum(enumObj); enumValues.add(new ThriftType.EnumValue(enumDesc.id, enumDesc.originalName)); } return new ThriftType.EnumType(enumValues); } catch (ReflectiveOperationException e) { throw new ScroogeSchemaConversionException("Can not convert enum field " + fieldName, e); } catch (RuntimeException e) { throw new ScroogeSchemaConversionException("Can not convert enum field " + fieldName, e); } }
Source:
public static Map<String, DbmsType> all() { Map<String, DbmsType> types = new HashMap<>(); types.put("ARRAY", ARRAY); types.put("BIGINT", BIGINT); types.put("BINARY", BINARY); types.put("BOOLEAN", BOOLEAN); types.put("CHARACTER", CHARACTER); types.put("DATE", DATE); types.put("DATETIME", DATETIME); types.put("DECIMAL", DECIMAL); types.put("DOUBLE", DOUBLE); types.put("DOUBLE PRECISION", DOUBLE_PRECISION); types.put("FLOAT", FLOAT); types.put("FLOAT4", FLOAT4); types.put("FLOAT8", FLOAT8); types.put("INT", INT); types.put("INTEGER", INTEGER); types.put("NUMBER", NUMBER); types.put("NUMERIC", NUMERIC); types.put("OBJECT", OBJECT); types.put("REAL", REAL); types.put("SMALLINT", SMALLINT); types.put("STRING", STRING); types.put("TEXT", TEXT); types.put("TIME", TIME); types.put("TIMESTAMP", TIMESTAMP); types.put("TIMESTAMP_LTZ", TIMESTAMP_LTZ); types.put("TIMESTAMP_NTZ", TIMESTAMP_NTZ); types.put("TIMESTAMP_TZ", TIMESTAMP_TZ); types.put("VARBINARY", VARBINARY); types.put("VARCHAR", VARCHAR); types.put("VARIANT", VARIANT); return types; }

Target:
public static Map<String, DbmsType> all() { return Collections.unmodifiableMap(allTypes); }
Source:
private void restoreState(Bundle savedInstanceState) { if (savedInstanceState == null) return; boolean isInMultiSelectMode = savedInstanceState.getBoolean(BUNDLE_IN_MULTI_SELECT_MODE); if (isInMultiSelectMode) { mGridAdapter.setInMultiSelect(true); if (savedInstanceState.containsKey(BUNDLE_SELECTED_STATES)) { ArrayList<Integer> selectedItems = ListUtils.fromIntArray(savedInstanceState.getIntArray(BUNDLE_SELECTED_STATES)); mGridAdapter.setSelectedItems(selectedItems); setFilterSpinnerVisible(mGridAdapter.getSelectedItems().size() == 0); mSwipeToRefreshHelper.setEnabled(false); } } mHasRetrievedAllMedia = savedInstanceState.getBoolean(BUNDLE_HAS_RETRIEVED_ALL_MEDIA, false); mFilter = Filter.getFilter(savedInstanceState.getInt(BUNDLE_FILTER)); mEmptyViewMessageType = EmptyViewMessageType.getEnumFromString(savedInstanceState. getString(BUNDLE_EMPTY_VIEW_MESSAGE)); mIsDateFilterSet = savedInstanceState.getBoolean(BUNDLE_DATE_FILTER_SET, false); mStartDay = savedInstanceState.getInt(BUNDLE_DATE_FILTER_START_DAY); mStartMonth = savedInstanceState.getInt(BUNDLE_DATE_FILTER_START_MONTH); mStartYear = savedInstanceState.getInt(BUNDLE_DATE_FILTER_START_YEAR); mEndDay = savedInstanceState.getInt(BUNDLE_DATE_FILTER_END_DAY); mEndMonth = savedInstanceState.getInt(BUNDLE_DATE_FILTER_END_MONTH); mEndYear = savedInstanceState.getInt(BUNDLE_DATE_FILTER_END_YEAR); boolean datePickerShowing = savedInstanceState.getBoolean(BUNDLE_DATE_FILTER_VISIBLE); if (datePickerShowing) showDatePicker(); }

Target:
private void restoreState(Bundle savedInstanceState) { if (savedInstanceState == null) return; boolean isInMultiSelectMode = savedInstanceState.getBoolean(BUNDLE_IN_MULTI_SELECT_MODE); if (isInMultiSelectMode) { mGridAdapter.setInMultiSelect(true); if (savedInstanceState.containsKey(BUNDLE_SELECTED_STATES)) { ArrayList<Integer> selectedItems = ListUtils.fromIntArray(savedInstanceState.getIntArray(BUNDLE_SELECTED_STATES)); mGridAdapter.setSelectedItems(selectedItems); setFilterSpinnerVisible(mGridAdapter.getSelectedItems().size() == 0); mSwipeToRefreshHelper.setEnabled(false); } } mHasRetrievedAllMedia = savedInstanceState.getBoolean(BUNDLE_HAS_RETRIEVED_ALL_MEDIA, false); mFilter = Filter.getFilter(savedInstanceState.getInt(BUNDLE_FILTER)); mEmptyViewMessageType = EmptyViewMessageType.getEnumFromString(savedInstanceState. getString(BUNDLE_EMPTY_VIEW_MESSAGE)); }
Source:
public ClusterFeature get() { Cluster cluster = parent.getClusterEntity(); SupportedAdditionalClusterFeature feature = cluster.getAddtionalFeaturesSupported() .stream() .filter(f -> f.getFeature().getId().equals(asGuid(id))) .findFirst() .orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND)); return ClusterFeaturesMapper.map(feature.getFeature(), null); }

Target:
public ClusterFeature get() { SupportedAdditionalClusterFeature feature = BackendClusterFeatureHelper.getEnabledFeature(this, asGuid(clusterId), asGuid(id)); return ClusterFeaturesMapper.map(feature.getFeature(), null); }
Source:
public Iterator getLocations() { return ORDERING.sortedCopy(this.storageLocations).iterator(); }

Target:
public Iterator<StorageLocation> getLocations() { return ORDERING.sortedCopy(this.storageLocations).iterator(); }
Source:
public CoprocessorRpcChannel coprocessorService(ServerName serverName) { return null; }

Target:
public CoprocessorRpcChannel coprocessorService(ServerName serverName) { throw new UnsupportedOperationException("coprocessorService"); }
Source:
public static String getGatewayAliasDefaultTo(String overrideAlias) { if (StringUtils.isNotBlank(overrideAlias)) { return overrideAlias; } String alias = System.getProperty(NhincConstants.CLIENT_KEY_ALIAS); return StringUtils.isBlank(alias) ? NhincConstants.DEFAULT_CLIENT_KEY_ALIAS : alias; }

Target:
public static String getGatewayAliasDefaultTo(String overrideAlias) { if (StringUtils.isNotBlank(overrideAlias)) { return overrideAlias; } return getPrivateKeyAlias(); }
Source:
public String toString() { return "exceededCount=" + m_exceededCount + "\nm_armed=" + m_armed; }

Target:
public String toString() { return "exceededCount=" + m_exceededCount + "\narmed=" + m_armed; }
Source:
private void updateFileCacheSizeLimit() { boolean isAvailableSpaceLowerThanHighLimit; if(mDiskCacheIsExternal){ isAvailableSpaceLowerThanHighLimit = mStatFsHelper.testLowDiskSpace( StatFsHelper.StorageType.EXTERNAL, mDefaultCacheSizeLimit - mCacheStats.getSize()); } else{ isAvailableSpaceLowerThanHighLimit = mStatFsHelper.testLowDiskSpace( StatFsHelper.StorageType.INTERNAL, mDefaultCacheSizeLimit - mCacheStats.getSize()); } if (isAvailableSpaceLowerThanHighLimit) { mCacheSizeLimit = mLowDiskSpaceCacheSizeLimit; } else { mCacheSizeLimit = mDefaultCacheSizeLimit; } }

Target:
private void updateFileCacheSizeLimit() { boolean isAvailableSpaceLowerThanHighLimit; StatFsHelper.StorageType storageType = mStorage.isExternal() ? StatFsHelper.StorageType.EXTERNAL : StatFsHelper.StorageType.INTERNAL; isAvailableSpaceLowerThanHighLimit = mStatFsHelper.testLowDiskSpace( storageType, mDefaultCacheSizeLimit - mCacheStats.getSize()); if (isAvailableSpaceLowerThanHighLimit) { mCacheSizeLimit = mLowDiskSpaceCacheSizeLimit; } else { mCacheSizeLimit = mDefaultCacheSizeLimit; } }
Source:
BufferAndBacklog pollBuffer() { synchronized (buffers) { if (isBlocked) { return null; } Buffer buffer = null; if (buffers.isEmpty()) { flushRequested = false; } while (!buffers.isEmpty()) { BufferConsumer bufferConsumer = buffers.peek().getBufferConsumer(); buffer = bufferConsumer.build(); checkState(bufferConsumer.isFinished() || buffers.size() == 1 || (buffers.size() == 2 && buffers.peekLast().getBufferConsumer().getDataType() == Buffer.DataType.RECOVERY_COMPLETION), "When there are multiple buffers, an unfinished bufferConsumer can not be at the head of the buffers queue."); if (buffers.size() == 1) { flushRequested = false; } if (bufferConsumer.isFinished()) { buffers.poll().getBufferConsumer().close(); decreaseBuffersInBacklogUnsafe(bufferConsumer.isBuffer()); } if (buffer.readableBytes() > 0) { break; } buffer.recycleBuffer(); buffer = null; if (!bufferConsumer.isFinished()) { break; } } if (buffer == null) { return null; } if (buffer.getDataType().isBlockingUpstream()) { isBlocked = true; } updateStatistics(buffer); return new BufferAndBacklog( buffer, getBuffersInBacklog(), isDataAvailableUnsafe() ? getNextBufferTypeUnsafe() : Buffer.DataType.NONE, sequenceNumber++); } }

Target:
BufferAndBacklog pollBuffer() { synchronized (buffers) { if (isBlocked) { return null; } Buffer buffer = null; if (buffers.isEmpty()) { flushRequested = false; } while (!buffers.isEmpty()) { BufferConsumerWithPartialRecordLength bufferConsumerWithPartialRecordLength = buffers.peek(); BufferConsumer bufferConsumer = bufferConsumerWithPartialRecordLength.getBufferConsumer(); buffer = buildSliceBuffer(bufferConsumerWithPartialRecordLength); checkState(bufferConsumer.isFinished() || buffers.size() == 1, "When there are multiple buffers, an unfinished bufferConsumer can not be at the head of the buffers queue."); if (buffers.size() == 1) { flushRequested = false; } if (bufferConsumer.isFinished()) { requireNonNull(buffers.poll()).getBufferConsumer().close(); decreaseBuffersInBacklogUnsafe(bufferConsumer.isBuffer()); } if (buffer.readableBytes() > 0) { break; } buffer.recycleBuffer(); buffer = null; if (!bufferConsumer.isFinished()) { break; } } if (buffer == null) { return null; } if (buffer.getDataType().isBlockingUpstream()) { isBlocked = true; } updateStatistics(buffer); return new BufferAndBacklog( buffer, getBuffersInBacklog(), isDataAvailableUnsafe() ? getNextBufferTypeUnsafe() : Buffer.DataType.NONE, sequenceNumber++); } }
Source:
public InMemoryMessageExchangeStore(final NetworkConfig config, TokenProvider tokenProvider) { if (config == null) { throw new NullPointerException("Configuration must not be null"); } if (tokenProvider == null) { throw new NullPointerException("TokenProvider must not be null"); } this.tokenProvider = tokenProvider; this.config = config; this.tokenLength = config.getInt(NetworkConfig.Keys.TOKEN_SIZE_LIMIT, MAX_TOKEN_LENGTH); LOGGER.log(Level.CONFIG, "using tokens of {0} bytes in length", tokenLength); }

Target:
public InMemoryMessageExchangeStore(final NetworkConfig config, TokenProvider tokenProvider) { if (config == null) { throw new NullPointerException("Configuration must not be null"); } if (tokenProvider == null) { throw new NullPointerException("TokenProvider must not be null"); } this.tokenProvider = tokenProvider; this.config = config; }
Source:
public ChangeInfo format(RevisionResource rsrc) throws OrmException { ChangeData cd = changeDataFactory.create(db.get(), rsrc.getControl()); Optional<PatchSet.Id> ps = Optional.of(rsrc.getPatchSet().getId()); return format(cd, ps); }

Target:
public Map<String, ActionInfo> format(RevisionResource rsrc) throws OrmException { ChangeData cd = changeDataFactory.create(db.get(), rsrc.getControl()); return toRevisionActionInfoMap(cd, rsrc.getPatchSet().getId()); }