auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void monitorPendingOperations() { for (PerChannelBookieClientPool clientPool : channels.values()) { clientPool.checkTimeoutOnPendingOperations(); } }

Target:
private void monitorPendingOperations() { for (PerChannelBookieClientPool clientPool : channels.values()) { clientPool.checkTimeoutOnPendingOperations(); } }
Source:
public static GraphRequest newCustomAudienceThirdPartyIdRequest(AccessToken accessToken, Context context, String applicationId, Callback callback) { if (applicationId == null && accessToken != null) { applicationId = accessToken.getApplicationId(); } if (applicationId == null) { applicationId = Utility.getMetadataApplicationId(context); } if (applicationId == null) { throw new FacebookException("Facebook App ID cannot be determined"); } String endpoint = applicationId + "/custom_audience_third_party_id"; AttributionIdentifiers attributionIdentifiers = AttributionIdentifiers.getAttributionIdentifiers(context); Bundle parameters = new Bundle(); if (accessToken == null) { try { String udid = attributionIdentifiers.getAttributionId() != null ? attributionIdentifiers.getAttributionId() : attributionIdentifiers.getAndroidAdvertiserId(); if (attributionIdentifiers.getAttributionId() != null) { parameters.putString("udid", udid); } } catch (NullPointerException e) { throw new FacebookException("attributionIdentifiers or attributionID or androidAdvertiserId is null"); } } if (FacebookSdk.getLimitEventAndDataUsage(context) || attributionIdentifiers.isTrackingLimited()) { parameters.putString("limit_event_usage", "1"); } return new GraphRequest(accessToken, endpoint, parameters, HttpMethod.GET, callback); }

Target:
public static GraphRequest newCustomAudienceThirdPartyIdRequest(AccessToken accessToken, Context context, String applicationId, Callback callback) { if (applicationId == null && accessToken != null) { applicationId = accessToken.getApplicationId(); } if (applicationId == null) { applicationId = Utility.getMetadataApplicationId(context); } if (applicationId == null) { throw new FacebookException("Facebook App ID cannot be determined"); } String endpoint = applicationId + "/custom_audience_third_party_id"; AttributionIdentifiers attributionIdentifiers = AttributionIdentifiers.getAttributionIdentifiers(context); Bundle parameters = new Bundle(); if (accessToken == null) { if (attributionIdentifiers == null) { throw new FacebookException("There is no access token and attribution identifiers could not be retrieved"); } String udid = attributionIdentifiers.getAttributionId() != null ? attributionIdentifiers.getAttributionId() : attributionIdentifiers.getAndroidAdvertiserId(); if (attributionIdentifiers.getAttributionId() != null) { parameters.putString("udid", udid); } } if (FacebookSdk.getLimitEventAndDataUsage(context) || (attributionIdentifiers != null && attributionIdentifiers.isTrackingLimited())) { parameters.putString("limit_event_usage", "1"); } return new GraphRequest(accessToken, endpoint, parameters, HttpMethod.GET, callback); }
Source:
public DataSet< V> intersect(DataSet< V> dataSet) { return subtract(dataSet,"Intersect Operator",null,false,null); }

Target:
public DataSet< V> intersect(DataSet< V> dataSet) { return intersect(dataSet,"Intersect Operator",null,false,null); }
Source:
public StreamNode parse(String name, String stream) { this.expressionString = stream; Tokenizer tokenizer = new Tokenizer(expressionString); tokenStream = tokenizer.getTokens(); tokenStreamLength = tokenStream.size(); tokenStreamPointer = 0; StreamNode ast = eatStream(); if (ast.getName() != null) { if (!isValidStreamName(ast.getName())) { throw new StreamDefinitionException(ast.getName(), 0, XDDSLMessages.ILLEGAL_STREAM_NAME, ast.getName()); } } if (name != null && !isValidStreamName(name)) { throw new StreamDefinitionException(name, 0, XDDSLMessages.ILLEGAL_STREAM_NAME, name); } if (ast.getModule(name) != null) { throw new StreamDefinitionException(stream, stream.indexOf(name), XDDSLMessages.STREAM_NAME_MATCHING_MODULE_NAME, name); } if (moreTokens()) { throw new StreamDefinitionException(this.expressionString, peekToken().startpos, XDDSLMessages.MORE_INPUT, toString(nextToken())); } ast.resolve(this); return ast; }

Target:
public StreamNode parse(String name, String stream) { this.expressionString = stream; Tokenizer tokenizer = new Tokenizer(expressionString); tokenStream = tokenizer.getTokens(); tokenStreamLength = tokenStream.size(); tokenStreamPointer = 0; StreamNode ast = eatStream(); if (ast.getName() != null && !isValidStreamName(ast.getName())) { throw new StreamDefinitionException(ast.getName(), 0, XDDSLMessages.ILLEGAL_STREAM_NAME, ast.getName()); } if (name != null && !isValidStreamName(name)) { throw new StreamDefinitionException(name, 0, XDDSLMessages.ILLEGAL_STREAM_NAME, name); } if (ast.getModule(name) != null) { throw new StreamDefinitionException(stream, stream.indexOf(name), XDDSLMessages.STREAM_NAME_MATCHING_MODULE_NAME, name); } if (moreTokens()) { throw new StreamDefinitionException(this.expressionString, peekToken().startpos, XDDSLMessages.MORE_INPUT, toString(nextToken())); } ast.resolve(this); return ast; }
Source:
protected String getVersionString(){ return "CommCare CLI: " + mPlatform.getMajorVersion() + "." + mPlatform.getMinorVersion(); }

Target:
protected String getVersionString(){ return "CommCare Version: " + mPlatform.getMajorVersion() + "." + mPlatform.getMinorVersion(); }
Source:
private void setDefaultUpstreamConfig() { String branchName = Repository.shortenRefName(this.fullBranch); BranchConfig branchConfig = new BranchConfig(repository.getConfig(), branchName); boolean alreadyConfigured = branchConfig.getMerge() != null; BranchRebaseMode config; if (alreadyConfigured) { config = PullCommand.getRebaseMode(branchName, repository.getConfig()); } else { config = CreateLocalBranchOperation .getDefaultUpstreamConfig(repository, Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + branchName); } this.upstreamConfig = config; }

Target:
private void setDefaultUpstreamConfig() { if (fullBranch == null) { return; } String branchName = Repository.shortenRefName(this.fullBranch); BranchConfig branchConfig = new BranchConfig(repository.getConfig(), branchName); boolean alreadyConfigured = branchConfig.getMerge() != null; BranchRebaseMode config; if (alreadyConfigured) { config = PullCommand.getRebaseMode(branchName, repository.getConfig()); } else { config = CreateLocalBranchOperation .getDefaultUpstreamConfig(repository, Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + branchName); } this.upstreamConfig = config; }
Source:
public SampleAliquot createAliquotFromParent(Sample stock) throws IOException { SampleAliquot aliquot = new SampleAliquotImpl(); DetailedSample sample = (DetailedSample) stock; aliquot.setScientificName(sample.getScientificName()); aliquot.setSampleType(sample.getSampleType()); aliquot.setParent(sample); if (sample.getSubproject() != null) aliquot.setSubproject(sample.getSubproject()); aliquot.setGroupId(sample.getGroupId()); aliquot.setGroupDescription(sample.getGroupDescription()); aliquot.setSampleClass(sampleClassService.getAll().stream() .filter(sampleClass -> { try { return sampleClass.getSampleCategory().equals("Aliquot") && sampleValidRelationshipService.getAll().stream() .anyMatch( validRelationship -> !validRelationship.getArchived() && validRelationship.getChild().getId() == sampleClass.getId() && validRelationship.getParent().getId() == sample.getSampleClass().getId()); } catch (IOException e) { e.printStackTrace(); return false; } }) .findFirst().orElse(null)); aliquot.setSamplePurpose(samplePurposeService.getAll().stream().filter(samplePurpose -> samplePurpose.getAlias().equals("Library")) .findFirst().orElse(null)); aliquot.setProject(sample.getProject()); return aliquot; }

Target:
public SampleAliquot createAliquotFromParent(Sample stock) throws IOException { SampleAliquot aliquot = new SampleAliquotImpl(); DetailedSample sample = (DetailedSample) stock; aliquot.setScientificName(sample.getScientificName()); aliquot.setSampleType(sample.getSampleType()); aliquot.setParent(sample); if (sample.getSubproject() != null) aliquot.setSubproject(sample.getSubproject()); aliquot.setGroupId(sample.getGroupId()); aliquot.setGroupDescription(sample.getGroupDescription()); aliquot.setSampleClass(sampleClassService.getAll().stream() .filter(sampleClass -> { try { return sampleClass.getSampleCategory().equals("Aliquot") && sampleValidRelationshipService.getAll().stream() .anyMatch( validRelationship -> !validRelationship.getArchived() && validRelationship.getChild().getId().equals(sampleClass.getId()) && validRelationship.getParent().getId().equals(sample.getSampleClass().getId())); } catch (IOException e) { log.error("Error getting SampleValidRelationship", e); return false; } }) .findFirst().orElse(null)); aliquot.setSamplePurpose(samplePurposeService.getAll().stream().filter(samplePurpose -> samplePurpose.getAlias().equals("Library")) .findFirst().orElse(null)); aliquot.setProject(sample.getProject()); return aliquot; }
Source:
private String getServiceName(String host) { return host.replaceAll("\\.", "-"); }

Target:
private String getServiceName(String host) { int idx = host.indexOf("."); if (idx > 1) { return host.substring(0, idx - 1); } else { return host; } }
Source:
protected SerializationContextInitializer[] contextInitializers() { SerializationContextInitializer sci = contextInitializer(); return sci == null ? new SerializationContextInitializer[0] : new SerializationContextInitializer[]{sci}; }

Target:
protected List<SerializationContextInitializer> contextInitializers() { SerializationContextInitializer sci = contextInitializer(); return sci == null ? Collections.emptyList() : Arrays.asList(sci); }
Source:
public boolean removeQueueNames(String... queueNames) { Assert.notNull(queueNames, "'queueNames' cannot be null"); Assert.noNullElements(queueNames, "'queueNames' cannot contain null elements"); AtomicBoolean result = new AtomicBoolean(); if (this.queues.size() > 0) { Set<String> toRemove = new HashSet<>(Arrays.asList(queueNames)); this.queues.stream().forEach(q -> { if (toRemove.contains(q.getName()) || toRemove.contains(q.getDeclaredName())) { this.queues.remove(q); result.set(true); } }); } return result.get(); }

Target:
public boolean removeQueueNames(String... queueNames) { Assert.notNull(queueNames, "'queueNames' cannot be null"); Assert.noNullElements(queueNames, "'queueNames' cannot contain null elements"); if (this.queues.size() > 0) { Set<String> toRemove = new HashSet<>(Arrays.asList(queueNames)); return this.queues.removeIf( q -> toRemove.contains(q.getActualName())); } return false; }
Source:
public Response getTheDataSource( @PathParam("dataSourceName") final String dataSourceName, @QueryParam("full") final String full ) { final ImmutableDruidDataSource dataSource = getDataSource(dataSourceName); if (dataSource == null) { return Response.noContent().build(); } if (full != null) { final Map<String, Object> fullResult = ImmutableMap.of( "name", dataSource.getName(), "properties", dataSource.getProperties(), "segments", dataSource.getIdToSegments().values() ); return Response.ok(fullResult).build(); } return Response.ok(getSimpleDatasource(dataSourceName)).build(); }

Target:
public Response getTheDataSource( @PathParam("dataSourceName") final String dataSourceName, @QueryParam("full") final String full ) { final ImmutableDruidDataSource dataSource = getDataSource(dataSourceName); if (dataSource == null) { return Response.noContent().build(); } if (full != null) { return Response.ok(dataSource).build(); } return Response.ok(getSimpleDatasource(dataSourceName)).build(); }
Source:
public void onErratumSelectionChange(ErrataSelectionChangeEvent event) { logger.info(this.getClass().toString() + " onErratumSelectionChange"); updateMainTabSelection(event.getSelectedItems()); }

Target:
public void onErratumSelectionChange(ErrataSelectionChangeEvent event) { updateMainTabSelection(event.getSelectedItems()); }
Source:
private void validateNotifySettingsRequest(JsonNode payload){ String op = payload.get(FIELD_OPERATION).asText(); if (!VALID_ATTRIBUTE_UPDATE_OPERATIONS.get(FIELD_OPERATION).contains(op)) { throw new ValidationException(Collections.singletonList(format("Operation [%s] is not valid for path [%s]", op, FIELD_OPERATION))); } if (!op.equalsIgnoreCase("remove")) { JsonNode valueNode = payload.get(FIELD_VALUE); if(null == valueNode) { throw new ValidationException(Collections.singletonList(format("Field [%s] is required", FIELD_VALUE))); } List<String> missingMandatoryFields = requestValidator.checkIfExistsOrEmpty(valueNode, FIELD_NOTIFY_API_TOKEN, FIELD_NOTIFY_TEMPLATE_ID); if (!missingMandatoryFields.isEmpty()) { throw new ValidationException(missingMandatoryFields); } } }

Target:
private void validateNotifySettingsRequest(JsonNode payload) { String op = payload.get(FIELD_OPERATION).asText(); if (!VALID_ATTRIBUTE_UPDATE_OPERATIONS.get(FIELD_OPERATION).contains(op)) { throw new ValidationException(Collections.singletonList(format("Operation [%s] is not valid for path [%s]", op, FIELD_OPERATION))); } if (!op.equalsIgnoreCase("remove")) { JsonNode valueNode = payload.get(FIELD_VALUE); if(null == valueNode || valueNode.isNull()) { throw new ValidationException(Collections.singletonList(format("Field [%s] is required", FIELD_VALUE))); } List<String> missingMandatoryFields = requestValidator.checkIfExistsOrEmpty(valueNode, FIELD_NOTIFY_API_TOKEN, FIELD_NOTIFY_PAYMENT_CONFIRMED_TEMPLATE_ID); if (!missingMandatoryFields.isEmpty()) { throw new ValidationException(missingMandatoryFields); } } }
Source:
private RegionScannerHolder newRegionScanner(ScanRequest request, ScanResponse.Builder builder) throws IOException { HRegion region = getRegion(request.getRegion()); rejectIfInStandByState(region); ClientProtos.Scan protoScan = request.getScan(); boolean isLoadingCfsOnDemandSet = protoScan.hasLoadColumnFamiliesOnDemand(); Scan scan = ProtobufUtil.toScan(protoScan); if (!isLoadingCfsOnDemandSet) { scan.setLoadColumnFamiliesOnDemand(region.isLoadingCfsOnDemandDefault()); } if (!scan.hasFamilies()) { for (byte[] family : region.getTableDescriptor().getColumnFamilyNames()) { scan.addFamily(family); } } if (region.getCoprocessorHost() != null) { region.getCoprocessorHost().preScannerOpen(scan); } RegionScannerImpl coreScanner = region.getScanner(scan); Shipper shipper = coreScanner; RegionScanner scanner = coreScanner; if (region.getCoprocessorHost() != null) { scanner = region.getCoprocessorHost().postScannerOpen(scan, scanner); } long scannerId = scannerIdGenerator.generateNewScannerId(); builder.setScannerId(scannerId); builder.setMvccReadPoint(scanner.getMvccReadPoint()); builder.setTtl(scannerLeaseTimeoutPeriod); String scannerName = String.valueOf(scannerId); boolean isFullRegionScan = false; if(!region.getRegionInfo().getTable().isSystemTable()) { if(checkFullRegionScan(scan, region)){ isFullRegionScan = true; } else { isFullRegionScan = false; } } else { isFullRegionScan = false; } return addScanner(scannerName, scanner, shipper, region, scan.isNeedCursorResult(), isFullRegionScan); }

Target:
private RegionScannerHolder newRegionScanner(ScanRequest request, ScanResponse.Builder builder) throws IOException { HRegion region = getRegion(request.getRegion()); rejectIfInStandByState(region); ClientProtos.Scan protoScan = request.getScan(); boolean isLoadingCfsOnDemandSet = protoScan.hasLoadColumnFamiliesOnDemand(); Scan scan = ProtobufUtil.toScan(protoScan); if (!isLoadingCfsOnDemandSet) { scan.setLoadColumnFamiliesOnDemand(region.isLoadingCfsOnDemandDefault()); } if (!scan.hasFamilies()) { for (byte[] family : region.getTableDescriptor().getColumnFamilyNames()) { scan.addFamily(family); } } if (region.getCoprocessorHost() != null) { region.getCoprocessorHost().preScannerOpen(scan); } RegionScannerImpl coreScanner = region.getScanner(scan); Shipper shipper = coreScanner; RegionScanner scanner = coreScanner; if (region.getCoprocessorHost() != null) { scanner = region.getCoprocessorHost().postScannerOpen(scan, scanner); } long scannerId = scannerIdGenerator.generateNewScannerId(); builder.setScannerId(scannerId); builder.setMvccReadPoint(scanner.getMvccReadPoint()); builder.setTtl(scannerLeaseTimeoutPeriod); String scannerName = String.valueOf(scannerId); boolean fullRegionScan = !region.getRegionInfo().getTable().isSystemTable() && isFullRegionScan(scan, region); return addScanner(scannerName, scanner, shipper, region, scan.isNeedCursorResult(), fullRegionScan); }
Source:
private void recycleConnection(PooledConnection pc) { int active = activeConnections.decrementAndGet(); if (active < 0) { throw new AssertionError(); } if (!isDisposed.get() && active < maxConnections) { recycledConnections.add(pc); if (isDisposed.get()) { dispose(); } } else { closeConnection(pc); } }

Target:
private void recycleConnection(PooledConnection pc) { int active = activeConnections.decrementAndGet(); if (active < 0) { activeConnections.incrementAndGet(); throw new AssertionError(); } if (!isDisposed.get() && active < maxConnections) { recycledConnections.add(pc); if (isDisposed.get()) { dispose(); } } else { closeConnection(pc); } }
Source:
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if (isInit == false) return invoker.invoke(invocation); RpcContext rpcContext = RpcContext.getContext(); Kind kind = rpcContext.isProviderSide() ? Kind.SERVER : Kind.CLIENT; final Span span; if (kind.equals(Kind.CLIENT)) { span = tracer.nextSpan(); injector.inject(span.context(), invocation.getAttachments()); } else { TraceContextOrSamplingFlags extracted = extractor.extract(invocation.getAttachments()); span = extracted.context() != null ? tracer.joinSpan(extracted.context()) : tracer.nextSpan(extracted); } if (!span.isNoop()) { span.kind(kind); String service = invoker.getInterface().getSimpleName(); String method = RpcUtils.getMethodName(invocation); span.name(service + "/" + method); parseRemoteAddress(rpcContext, span); span.start(); } boolean isOneway = false, deferFinish = false; try (Tracer.SpanInScope scope = tracer.withSpanInScope(span)) { Result result = invoker.invoke(invocation); if (result.hasException()) { onError(result.getException(), span); } isOneway = RpcUtils.isOneway(invoker.getUrl(), invocation); Future<Object> future = rpcContext.getFuture(); if (future instanceof FutureAdapter) { deferFinish = true; ResponseFuture responseFuture = ((FutureAdapter<Object>) future).getFuture(); ResponseFuture responseFutureDelegate = new AsyncResponseFutureDelegate(span, responseFuture); RpcContext.getContext().setFuture(new FutureAdapter<>(responseFutureDelegate)); } return result; } catch (Error | RuntimeException e) { onError(e, span); throw e; } finally { if (isOneway) { span.flush(); } else if (!deferFinish) { span.finish(); } } }

Target:
@Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if (isInit == false) return invoker.invoke(invocation); RpcContext rpcContext = RpcContext.getContext(); Kind kind = rpcContext.isProviderSide() ? Kind.SERVER : Kind.CLIENT; final Span span; if (kind.equals(Kind.CLIENT)) { span = tracer.nextSpan(); injector.inject(span.context(), invocation.getAttachments()); } else { TraceContextOrSamplingFlags extracted = extractor.extract(invocation.getAttachments()); span = extracted.context() != null ? tracer.joinSpan(extracted.context()) : tracer.nextSpan(extracted); } if (!span.isNoop()) { span.kind(kind); String service = invoker.getInterface().getSimpleName(); String method = RpcUtils.getMethodName(invocation); span.name(service + "/" + method); parseRemoteAddress(rpcContext, span); span.start(); } boolean isOneway = false, deferFinish = false; try (CurrentTraceContext.Scope scope = current.newScope(span.context())) { Result result = invoker.invoke(invocation); isOneway = RpcUtils.isOneway(invoker.getUrl(), invocation); if (!span.isNoop()) { deferFinish = ensureSpanFinishes(rpcContext, span, result); } return result; } catch (Error | RuntimeException e) { onError(e, span); throw e; } finally { if (isOneway) { span.flush(); } else if (!deferFinish) { span.finish(); } } }
Source:
public void statelessTopologyShouldNotCreateStateDirectory() throws Exception { final String inputTopic = testName.getMethodName() + "-input"; final String outputTopic = testName.getMethodName() + "-output"; final Topology topology = new Topology(); topology.addSource("source", Serdes.String().deserializer(), Serdes.String().deserializer(), inputTopic) .addProcessor("process", (ProcessorSupplier<String, String>) () -> new AbstractProcessor<String, String>() { @Override public void process(final String key, final String value) { if (value.length() % 2 == 0) { context().forward(key, key + value); } } }, "source") .addSink("sink", outputTopic, new StringSerializer(), new StringSerializer(), "process"); startStreamsAndCheckDirExists(topology, false); }

Target:
public void statelessTopologyShouldNotCreateStateDirectory() throws Exception { final String inputTopic = testName.getMethodName() + "-input"; final String outputTopic = testName.getMethodName() + "-output"; final Topology topology = new Topology(); topology.addSource("source", Serdes.String().deserializer(), Serdes.String().deserializer(), inputTopic) .addProcessor("process", () -> new AbstractProcessor<String, String>() { @Override public void process(final String key, final String value) { if (value.length() % 2 == 0) { context().forward(key, key + value); } } }, "source") .addSink("sink", outputTopic, new StringSerializer(), new StringSerializer(), "process"); startStreamsAndCheckDirExists(topology, false); }
Source:
public State convertToState(int[] data, ComfoAirCommandType commandType) { int[] get_reply_data_pos = commandType.getGetReplyDataPos(); int value = 0; int base = 0; for (int i = get_reply_data_pos.length - 1; i >= 0; i--) { if (get_reply_data_pos[i] < data.length) { value += data[get_reply_data_pos[i]] << base; base += 8; } else { return null; } } int[] possibleValues = commandType.getPossibleValues(); if (possibleValues != null) { for (int possibleValue : possibleValues) { if ((value & possibleValue) == possibleValue) { return new DecimalType(value); } } return null; } return new DecimalType(value); }

Target:
public State convertToState(int[] data, ComfoAirCommandType commandType) { if (data == null || commandType == null) { logger.trace("\"DataTypeNumber\" class \"convertToState\" method parameter: null"); return null; } else { int[] get_reply_data_pos = commandType.getGetReplyDataPos(); int value = 0; int base = 0; for (int i = get_reply_data_pos.length - 1; i >= 0; i--) { if (get_reply_data_pos[i] < data.length) { value += data[get_reply_data_pos[i]] << base; base += 8; } else { return null; } } int[] possibleValues = commandType.getPossibleValues(); if (possibleValues != null) { for (int possibleValue : possibleValues) { if ((value & possibleValue) == possibleValue) { return new DecimalType(value); } } return null; } return new DecimalType(value); } }
Source:
public Response cancelCharge(@Auth String accountId, @PathParam(PAYMENT_KEY) String chargeId) { logger.info("received cancel payment request: [{}]", chargeId); Response connectorResponse = client.target(chargeUrl + "/" + chargeId + "/cancel") .request() .post(Entity.json(jsonStringBuilder() .add(GATEWAY_ACCOUNT_KEY, accountId) .build())); if (connectorResponse.getStatus() == HttpStatus.SC_NO_CONTENT) { return Response.noContent().build(); } return badRequestResponse(logger, "Cancellation of charge failed."); }

Target:
public Response cancelCharge(@Auth String accountId, @PathParam(PAYMENT_KEY) String chargeId) { logger.info("received cancel payment request: [{}]", chargeId); Response connectorResponse = client.target(connectorUrl + format(CONNECTOR_ACCOUNT_CHARGE_CANCEL_RESOURCE, accountId, chargeId)) .request() .post(Entity.json("{}")); if (connectorResponse.getStatus() == HttpStatus.SC_NO_CONTENT) { return Response.noContent().build(); } return badRequestResponse(logger, "Cancellation of charge failed."); }
Source:
public void run() { if ( resources == null || resources.isEmpty() ) { logger.info( "No resources for downloading" ); return; } logger.info( "Start downloading: {}", resources ); final AtomicBoolean scheduled = new AtomicBoolean( false ); for ( Map.Entry<RemoteRepository, List<ConcreteResource>> entry : resources.entrySet() ) { final RemoteRepository repo = entry.getKey(); final List<ConcreteResource> res = entry.getValue(); res.forEach( r -> { try { final String path = r.getPath(); if ( path == null || path.equals( "" ) || path.endsWith( "/" ) || path.endsWith( LISTING_HTML_FILE ) ) { List<String> dirPaths = buildPaths( r ); logger.info( "{} is folder, will use it to schedule new Resources {}", r, dirPaths ); frontier.scheduleRepo( repo, dirPaths ); scheduled.set( true ); } else { logger.info( "{} is file", r ); final Transfer tr = transfers.retrieve( r ); if ( !exists( tr ) ) { logger.warn( "Download failed during prefetch for {}, reason is resource not exists", r ); } } } catch ( TransferException e ) { logger.error( "Download failed during prefetch because of transfer getting failed for {}, Reason: {}", r, e.getMessage() ); } } ); } if ( scheduled.get() ) { prefetchManager.triggerWorkers(); } }

Target:
public void run() { if ( resources == null || resources.isEmpty() ) { logger.trace( "No resources for downloading" ); return; } logger.trace( "Start downloading: {}", resources ); final AtomicBoolean scheduled = new AtomicBoolean( false ); for ( Map.Entry<RemoteRepository, List<ConcreteResource>> entry : resources.entrySet() ) { final RemoteRepository repo = entry.getKey(); final List<ConcreteResource> res = entry.getValue(); res.forEach( r -> { try { final String path = r.getPath(); if ( path == null || path.equals( "" ) || path.endsWith( "/" ) || path.endsWith( LISTING_HTML_FILE ) ) { List<String> dirPaths = buildPaths( r ); logger.trace( "{} is folder, will use it to schedule new Resources {}", r, dirPaths ); frontier.scheduleRepo( repo, dirPaths ); scheduled.set( true ); } else { logger.trace( "{} is file", r ); transfers.retrieve( r ); } } catch ( TransferException e ) { logger.error( "Download failed during prefetch because of transfer getting failed for {}, Reason: {}", r, e.getMessage() ); } } ); } if ( scheduled.get() ) { prefetchManager.triggerWorkers(); } }
Source:
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { try { CommCareApplication._().getUserDbHandle(); } catch(SessionUnavailableException sue) { return null; } int match = CaseDataAPI.UriMatch(uri); System.out.println("428 match is: " + match); switch(match) { case CaseDataAPI.MetadataColumns.MATCH_CASES: case CaseDataAPI.MetadataColumns.MATCH_CASE: return queryCaseList(uri, projection, selection, selectionArgs, sortOrder); case CaseDataAPI.DataColumns.MATCH_DATA: return queryCaseData(uri.getLastPathSegment(), projection, selection, selectionArgs, sortOrder); case CaseDataAPI.AttachmentColumns.MATCH_ATTACHMENTS: return queryCaseAttachments(uri.getLastPathSegment(), projection, selection, selectionArgs, sortOrder); case CaseDataAPI.IndexColumns.MATCH_INDEX: return null; } throw new IllegalArgumentException("URI: " + uri.toString() +" is not a valid content path for CommCare Case Data"); }

Target:
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { try { CommCareApplication._().getUserDbHandle(); } catch(SessionUnavailableException sue) { return null; } int match = CaseDataAPI.UriMatch(uri); switch(match) { case CaseDataAPI.MetadataColumns.MATCH_CASES: case CaseDataAPI.MetadataColumns.MATCH_CASE: return queryCaseList(uri, projection, selection, selectionArgs, sortOrder); case CaseDataAPI.DataColumns.MATCH_DATA: return queryCaseData(uri.getLastPathSegment()); case CaseDataAPI.AttachmentColumns.MATCH_ATTACHMENTS: return queryCaseAttachments(uri.getLastPathSegment()); case CaseDataAPI.IndexColumns.MATCH_INDEX: return null; } throw new IllegalArgumentException("URI: " + uri.toString() +" is not a valid content path for CommCare Case Data"); }
Source:
private String appendXMLRPCPath(String url) throws IllegalArgumentException { if (!URLUtil.isValidUrl(url)) { throw new IllegalArgumentException("Input URL " + url + " is not valid!"); } if (!url.contains("xmlrpc.php")) { if (url.substring(url.length() - 1, url.length()).equals("/")) { url = url.substring(0, url.length() - 1); } url += "/xmlrpc.php"; if (!URLUtil.isValidUrl(url)) { throw new IllegalArgumentException("The new URL " + url + " is not valid!"); } } return url; }

Target:
private String appendXMLRPCPath(String url) throws IllegalArgumentException { if (!URLUtil.isValidUrl(url)) { throw new IllegalArgumentException("Input URL " + url + " is not valid!"); } if (!url.contains("xmlrpc.php")) { if (url.charAt(url.length() - 1) == '/') { url = url.substring(0, url.length() - 1); } url += "/xmlrpc.php"; if (!URLUtil.isValidUrl(url)) { throw new IllegalArgumentException("The new URL " + url + " is not valid!"); } } return url; }
Source:
protected A play(I id, AggregateHistory history) { A result = create(id); AggregateTransaction<I, ?, ?> tx = AggregateTransaction.start(result); BatchDispatchOutcome outcome = result.play(history); boolean success = outcome.getSuccessful(); tx.commitIfActive(); if (!success) { lifecycleOf(id).onCorruptedState(outcome); throw newIllegalStateException( "Aggregate %s (ID: %s) cannot be loaded.%n", aggregateClass().value().getName(), result.idAsString() ); } return result; }

Target:
protected A play(I id, AggregateHistory history) { A result = create(id); AggregateTransaction<I, ?, ?> tx = AggregateTransaction.start(result); BatchDispatchOutcome outcome = result.play(history); boolean success = outcome.getSuccessful(); tx.commitIfActive(); if (!success) { lifecycleOf(id).onCorruptedState(outcome); throw newIllegalStateException("Aggregate `%s` (ID: %s) cannot be loaded.%n", aggregateClass().value() .getName(), result.idAsString()); } return result; }
Source:
private static void writeValue(ByteBuf buf, Object value, MetadataType type) throws IOException { switch (type) { case BYTE: buf.writeByte((Byte) value); break; case INT: ByteBufUtils.writeVarInt(buf, (Integer) value); break; case FLOAT: buf.writeFloat((Float) value); break; case STRING: ByteBufUtils.writeUTF8(buf, (String) value); break; case CHAT: writeChat(buf, (TextMessage) value); break; case OPTCHAT: writeChat(buf, (TextMessage) value); case ITEM: writeSlot(buf, (ItemStack) value); break; case BOOLEAN: buf.writeBoolean((Boolean) value); break; case VECTOR: EulerAngle angle = (EulerAngle) value; buf.writeFloat((float) Math.toDegrees(angle.getX())); buf.writeFloat((float) Math.toDegrees(angle.getY())); buf.writeFloat((float) Math.toDegrees(angle.getZ())); break; case POSITION: case OPTPOSITION: BlockVector vector = (BlockVector) value; buf.writeLong(Position.getPosition(vector)); break; case DIRECTION: ByteBufUtils.writeVarInt(buf, (Integer) value); break; case OPTUUID: writeUuid(buf, (UUID) value); break; case BLOCKID: ByteBufUtils.writeVarInt(buf, (Integer) value); break; case NBTTAG: writeCompound(buf, (CompoundTag) value); break; case PARTICLE: writeParticle(buf, (ParticleBuilder) value); break; default: } }

Target:
private static void writeValue(ByteBuf buf, Object value, MetadataType type) throws IOException { switch (type) { case BYTE: buf.writeByte((Byte) value); break; case INT: ByteBufUtils.writeVarInt(buf, (Integer) value); break; case FLOAT: buf.writeFloat((Float) value); break; case STRING: ByteBufUtils.writeUTF8(buf, (String) value); break; case CHAT: case OPTCHAT: writeChat(buf, (TextMessage) value); break; case ITEM: writeSlot(buf, (ItemStack) value); break; case BOOLEAN: buf.writeBoolean((Boolean) value); break; case VECTOR: EulerAngle angle = (EulerAngle) value; buf.writeFloat((float) Math.toDegrees(angle.getX())); buf.writeFloat((float) Math.toDegrees(angle.getY())); buf.writeFloat((float) Math.toDegrees(angle.getZ())); break; case POSITION: case OPTPOSITION: BlockVector vector = (BlockVector) value; buf.writeLong(Position.getPosition(vector)); break; case DIRECTION: ByteBufUtils.writeVarInt(buf, (Integer) value); break; case OPTUUID: writeUuid(buf, (UUID) value); break; case BLOCKID: ByteBufUtils.writeVarInt(buf, (Integer) value); break; case NBTTAG: writeCompound(buf, (CompoundTag) value); break; case PARTICLE: writeParticle(buf, (ParticleBuilder) value); break; default: } }
Source:
public void handleDaemonConfigChanged(final Event event) { DaemonTools.handleReloadEvent(event, "PollerBackEnd", (e)->{ m_pollerBackEnd.configurationUpdated(); }); }

Target:
public void handleDaemonConfigChanged(final Event event) { DaemonTools.handleReloadEvent(event, "PollerBackEnd", (e)-> m_pollerBackEnd.configurationUpdated()); }
Source:
public PiecewisePolynomialResult interpolate(final double[] xValues, final double[] yValues) { return (new PiecewiseCubicHermiteSplineInterpolator()).interpolate(xValues, yValues); }

Target:
public PiecewisePolynomialResult interpolate(final double[] xValues, final double[] yValues) { return INTERP.interpolate(xValues, yValues); }
Source:
public void run() { for(String file : reader.getFiles()) { S3ObjectInputStreamWrapper is = new S3ObjectInputStreamWrapper(reader.getAmazonS3Client().getObject(reader.getBucketName(), file)); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is)); LOGGER.info("Reading: ", file); String line = ""; try { while((line = bufferedReader.readLine()) != null) { if( !Strings.isNullOrEmpty(line) ) { reader.countersCurrent.incrementAttempt(); String[] fields = line.split(Character.toString(reader.DELIMITER)); StreamsDatum entry = new StreamsDatum(fields[3], fields[0]); write( entry ); reader.countersCurrent.incrementStatus(DatumStatus.SUCCESS); } } } catch (Exception e) { e.printStackTrace(); LOGGER.warn(e.getMessage()); reader.countersCurrent.incrementStatus(DatumStatus.FAIL); } LOGGER.info("Completed: " + file); try { closeSafely(file, is); } catch (Exception e) { e.printStackTrace(); LOGGER.error(e.getMessage()); } } }

Target:
public void run() { for(String file : reader.getFiles()) { S3ObjectInputStreamWrapper is = new S3ObjectInputStreamWrapper(reader.getAmazonS3Client().getObject(reader.getBucketName(), file)); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is)); LOGGER.info("Reading: ", file); String line = ""; try { while((line = bufferedReader.readLine()) != null) { if( !Strings.isNullOrEmpty(line) ) { reader.countersCurrent.incrementAttempt(); String[] fields = line.split(Character.toString(reader.DELIMITER)); StreamsDatum entry = new StreamsDatum(fields[3], fields[0]); ComponentUtils.offerUntilSuccess(entry, reader.persistQueue); reader.countersCurrent.incrementStatus(DatumStatus.SUCCESS); } } } catch (Exception e) { e.printStackTrace(); LOGGER.warn(e.getMessage()); reader.countersCurrent.incrementStatus(DatumStatus.FAIL); } LOGGER.info("Completed: " + file); try { closeSafely(file, is); } catch (Exception e) { LOGGER.error(e.getMessage()); } } }
Source:
protected void executeCommand() { T bckndCmdParams = getParameters(); final SetupNetworksVdsCommandParameters vdsCmdParams = new SetupNetworksVdsCommandParameters( getVdsId(), getNetworks(), getRemovedNetworks(), getBonds(), getRemovedBonds(), getInterfaces()); vdsCmdParams.setForce(bckndCmdParams.isForce()); vdsCmdParams.setCheckConnectivity(bckndCmdParams.isCheckConnectivity()); int timeout = bckndCmdParams.getConectivityTimeout() != null ? bckndCmdParams.getConectivityTimeout() : Config.<Integer> GetValue(ConfigValues.NetworkConnectivityCheckTimeoutInSeconds); vdsCmdParams.setConectivityTimeout(timeout); FutureVDSCall<VDSReturnValue> setupNetworksTask = createFutureTask(vdsCmdParams); if (bckndCmdParams.isCheckConnectivity()) { pollInterruptively(setupNetworksTask); } try { VDSReturnValue retVal = setupNetworksTask.get(timeout, TimeUnit.SECONDS); if (retVal != null) { VDSBrokerFrontendImpl.handleVdsResult(retVal); if (retVal.getSucceeded()) { setSucceeded(TransactionSupport.executeInNewTransaction(updateVdsNetworksInTx(bckndCmdParams))); } } } catch (TimeoutException e) { log.debugFormat("Setup networks command timed out for {0} seconds", timeout); } }

Target:
protected void executeCommand() { T bckndCmdParams = getParameters(); final SetupNetworksVdsCommandParameters vdsCmdParams = new SetupNetworksVdsCommandParameters( getVdsId(), getNetworks(), getRemovedNetworks(), getBonds(), getRemovedBonds(), getInterfaces()); vdsCmdParams.setForce(bckndCmdParams.isForce()); vdsCmdParams.setCheckConnectivity(bckndCmdParams.isCheckConnectivity()); int timeout = bckndCmdParams.getConectivityTimeout() != null ? bckndCmdParams.getConectivityTimeout() : Config.<Integer> GetValue(ConfigValues.NetworkConnectivityCheckTimeoutInSeconds); vdsCmdParams.setConectivityTimeout(timeout); FutureVDSCall<VDSReturnValue> setupNetworksTask = createFutureTask(vdsCmdParams); if (bckndCmdParams.isCheckConnectivity()) { pollInterruptively(setupNetworksTask); } try { VDSReturnValue retVal = setupNetworksTask.get(timeout, TimeUnit.SECONDS); if (retVal != null) { VdsHandler.handleVdsResult(retVal); if (retVal.getSucceeded()) { setSucceeded(TransactionSupport.executeInNewTransaction(updateVdsNetworksInTx(bckndCmdParams))); } } } catch (TimeoutException e) { log.debugFormat("Setup networks command timed out for {0} seconds", timeout); } }
Source:
public void givenASingleGetRequestWhenResponseThenBlockWithCompletableAndLog() throws InterruptedException, ExecutionException { AtomicInteger completedReqs = new AtomicInteger(0); WSClient ws = play.test.WSTestClient.newClient(port); WSResponse wsResponse = ws.url(url) .setRequestFilter(new AhcCurlRequestLogger()) .addHeader("key", "value") .addQueryParameter("num", "" + 1) .get() .toCompletableFuture() .get(); log.debug("Thread#" + Thread.currentThread() .getId() + " Request complete: Response code = " + wsResponse.getStatus() + " | Response: " + wsResponse.getBody() + " | Current Time:" + System.currentTimeMillis()); }

Target:
public void givenASingleGetRequestWhenResponseThenBlockWithCompletableAndLog() throws Exception { WSClient ws = play.test.WSTestClient.newClient(port); WSResponse wsResponse = ws.url(url) .setRequestFilter(new AhcCurlRequestLogger()) .addHeader("key", "value") .addQueryParameter("num", "" + 1) .get() .toCompletableFuture() .get(); log.debug("Thread#" + Thread.currentThread() .getId() + " Request complete: Response code = " + wsResponse.getStatus() + " | Response: " + wsResponse.getBody() + " | Current Time:" + System.currentTimeMillis()); assert (HttpStatus.SC_OK == wsResponse.getStatus()); }
Source:
public static Throwable create() { if (System.getProperty("rxjava.captureSchedulerContext", "false").equals("true")) { return new SchedulerContextException(); } return null; }

Target:
public static Throwable create() { String def = "false"; String setTo = System.getProperty("rxjava.captureSchedulerContext", def); return setTo != def && "true".equals(setTo) ? new SchedulerContextException("Asynchronous work scheduled at") : CONTEXT_MISSING; }
Source:
public boolean matches(MethodParams params) { return params.is(CommandMessage.class) && params.is(GeneratedMessageV3.class); }

Target:
public boolean matches(MethodParams params) { return params.match(criteria); }
Source:
public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) { Matcher matcher = PATTERN.matcher(spec); if (!matcher.matches()) { throw new IllegalArgumentException("Invalid location '" + spec + "'; must specify something like single(named:foo)"); } String args = matcher.group(2); Map locationArgs = KeyValueParser.parseMap(args); String target = locationArgs.get("target").toString(); locationArgs.remove("target"); for (Object key : locationArgs.keySet()) { Object value = locationArgs.get(key); if (value instanceof String) { Matcher listMatcher = LIST_PATTERN.matcher(value.toString()); if (listMatcher.matches()) { List<String> strings = KeyValueParser.parseList(listMatcher.group(1)); List<Integer> integers = new ArrayList<Integer>(); boolean intList = true; for (String string : strings) { if (INTEGER_PATTERN.matcher(string).matches()) { integers.add(Integer.parseInt(string)); } else { intList = false; break; } } locationArgs.put(key, intList ? integers : strings); } } } if (!managementContext.getLocationRegistry().canResolve(target)) { throw new IllegalArgumentException("Invalid target location '" + target + "'; must be resolvable location"); } return new SingleMachineProvisioningLocation<MachineLocation>(target, locationArgs); }

Target:
public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) { Matcher matcher = PATTERN.matcher(spec); if (!matcher.matches()) { throw new IllegalArgumentException("Invalid location '" + spec + "'; must specify something like single(named:foo)"); } String args = matcher.group(2); Map locationArgs = KeyValueParser.parseMap(args); if (locationArgs == null || locationArgs.get("target") == null) { throw new IllegalArgumentException("target must be specified in spec"); } String target = locationArgs.get("target").toString(); locationArgs.remove("target"); if (!managementContext.getLocationRegistry().canResolve(target)) { throw new IllegalArgumentException("Invalid target location '" + target + "'; must be resolvable location"); } return new SingleMachineProvisioningLocation<MachineLocation>(target, locationArgs); }
Source:
public void enforceCpuLimits() { for (QueryExecution query : queries.values()) { Duration cpuTime = query.getTotalCpuTime(); Duration sessionLimit = getQueryMaxCpuTime(query.getSession()); Duration limit = maxQueryCpuTime.compareTo(sessionLimit) < 0 ? maxQueryCpuTime : sessionLimit; if (cpuTime.compareTo(limit) > 0) { query.fail(new ExceededCpuLimitException(limit)); } } }

Target:
public void enforceCpuLimits() { for (QueryExecution query : queries.values()) { Duration cpuTime = query.getTotalCpuTime(); Duration sessionLimit = getQueryMaxCpuTime(query.getSession()); Duration limit = Ordering.natural().min(maxQueryCpuTime, sessionLimit); if (cpuTime.compareTo(limit) > 0) { query.fail(new ExceededCpuLimitException(limit)); } } }
Source:
public void testServerIsNotifiedAboutNewAttributesAndTheirPms() { final AtomicReference<Command> receivedCommand = new AtomicReference<Command>(null); CommandHandler testServerAction = new CommandHandler<CreatePresentationModelCommand>() { @Override public void handleCommand(CreatePresentationModelCommand command, List<Command> response) { receivedCommand.set(command); } }; serverConnector.getRegistry().register(CreatePresentationModelCommand.class, testServerAction); clientModelStore.add(new ClientPresentationModel("testPm", Arrays.asList(new ClientAttribute("name", null)))); clientDolphin.sync(new Runnable() { @Override public void run() { Assert.assertNotNull(receivedCommand.get()); Assert.assertEquals("CreatePresentationModel", receivedCommand.get().getId()); Assert.assertEquals(CreatePresentationModelCommand.class, receivedCommand.get().getClass()); CreatePresentationModelCommand cmd = (CreatePresentationModelCommand) receivedCommand.get(); Assert.assertEquals("testPm", cmd.getPmId()); config.assertionsDone(); } }); }

Target:
public void testServerIsNotifiedAboutNewAttributesAndTheirPms() { final AtomicReference<Command> receivedCommand = new AtomicReference<>(null); CommandHandler<CreatePresentationModelCommand> testServerAction = new CommandHandler<CreatePresentationModelCommand>() { @Override public void handleCommand(CreatePresentationModelCommand command, List<Command> response) { receivedCommand.set(command); } }; serverConnector.getRegistry().register(CreatePresentationModelCommand.class, testServerAction); clientModelStore.add(new ClientPresentationModel("testPm", Arrays.asList(new ClientAttribute("name", null)))); clientDolphin.sync(new Runnable() { @Override public void run() { Assert.assertNotNull(receivedCommand.get()); Assert.assertEquals("CreatePresentationModel", receivedCommand.get().getId()); Assert.assertEquals(CreatePresentationModelCommand.class, receivedCommand.get().getClass()); CreatePresentationModelCommand cmd = (CreatePresentationModelCommand) receivedCommand.get(); Assert.assertEquals("testPm", cmd.getPmId()); config.assertionsDone(); } }); }
Source:
public BigInteger getPrivKey() { if (privKey == null) { throw new MissingPrivateKeyException(); } else if (privKey instanceof BCECPrivateKey) { return ((BCECPrivateKey) privKey).getS(); } else { throw new MissingPrivateKeyException(); } }

Target:
public BigInteger getPrivKey() { if (privKey == null) { throw new MissingPrivateKeyException(); } else if (privKey instanceof BCECPrivateKey) { return ((BCECPrivateKey) privKey).getD(); } else { throw new MissingPrivateKeyException(); } }
Source:
public void whenStreamTimeoutReachedThenEventsFlushed() throws Exception { final TestStreamingClient client = TestStreamingClient .create(URL, subscription.getId(), "batch_flush_timeout=600&batch_limit=1000&stream_timeout=2&max_uncommitted_events=3") .start(); waitFor(() -> assertThat(client.getSessionId(), not(equalTo(SESSION_ID_UNKNOWN)))); publishEvents(eventType.getName(), 4, x -> "{\"foo\":\"bar\"}"); waitFor(() -> assertThat(client.getBatches(), hasSize(2))); assertThat(client.getBatches().get(0).getEvents(), hasSize(3)); assertThat(client.getBatches().get(1).getEvents(), hasSize(0)); }

Target:
public void whenStreamTimeoutReachedThenEventsFlushed() throws Exception { final TestStreamingClient client = TestStreamingClient .create(URL, subscription.getId(), "batch_flush_timeout=600&batch_limit=1000&stream_timeout=2&max_uncommitted_events=1000") .start(); waitFor(() -> assertThat(client.getSessionId(), not(equalTo(SESSION_ID_UNKNOWN)))); publishEvents(eventType.getName(), 4, x -> "{\"foo\":\"bar\"}"); waitFor(() -> assertThat(client.getBatches(), hasSize(2))); assertThat(client.getBatches().get(0).getEvents(), hasSize(4)); assertThat(client.getBatches().get(1).getEvents(), hasSize(0)); System.out.println(client.getBatches()); }
Source:
public void afterPropertiesSet() { eventBus.register(this); faWindowTitle = clientProperties.getForgedAlliance().getWindowTitle(); currentGame.addListener((observable, oldValue, newValue) -> { if (newValue == null) { discordRichPresenceService.clearGameInfo(); return; } InvalidationListener listener = generateNumberOfPlayersChangeListener(newValue); JavaFxUtil.addListener(newValue.numPlayersProperty(), listener); listener.invalidated(newValue.numPlayersProperty()); ChangeListener<GameStatus> statusChangeListener = generateGameStatusListener(newValue); JavaFxUtil.addListener(newValue.statusProperty(), statusChangeListener); statusChangeListener.changed(newValue.statusProperty(), newValue.getStatus(), newValue.getStatus()); }); games = FXCollections.observableList(new ArrayList<>(), item -> new Observable[]{item.statusProperty(), item.getTeams()} ); JavaFxUtil.attachListToMap(games, uidToGameInfoBean); fafService.addOnMessageListener(GameInfoMessage.class, message -> Platform.runLater(() -> onGameInfo(message))); fafService.addOnMessageListener(LoginMessage.class, message -> onLoggedIn()); JavaFxUtil.addListener(fafService.connectionStateProperty(), (observable, oldValue, newValue) -> { if (newValue == ConnectionState.DISCONNECTED) { synchronized (uidToGameInfoBean) { uidToGameInfoBean.clear(); } } }); }

Target:
public void afterPropertiesSet() { eventBus.register(this); fafService.addOnMessageListener(GameInfoMessage.class, message -> Platform.runLater(() -> onGameInfo(message))); fafService.addOnMessageListener(LoginMessage.class, message -> onLoggedIn()); JavaFxUtil.addListener(fafService.connectionStateProperty(), (observable, oldValue, newValue) -> { if (newValue == ConnectionState.DISCONNECTED) { synchronized (uidToGameInfoBean) { uidToGameInfoBean.clear(); } } }); }