auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ByteBuffer subscriptionUserData(final Set<String> topics) { final TaskManager taskManager = taskManger(); taskManager.handleRebalanceStart(topics); if (usedSubscriptionMetadataVersion <= LATEST_SUPPORTED_VERSION) { return new SubscriptionInfo( usedSubscriptionMetadataVersion, LATEST_SUPPORTED_VERSION + 1, taskManager.processId(), userEndPoint(), taskManager.getTaskLags() ).encode(); } else { return new FutureSubscriptionInfo( usedSubscriptionMetadataVersion, taskManager.processId(), userEndPoint(), taskManager.getTaskLags()) .encode(); } }

Target:
public ByteBuffer subscriptionUserData(final Set<String> topics) { final TaskManager taskManager = taskManager(); handleRebalanceStart(topics); if (usedSubscriptionMetadataVersion <= LATEST_SUPPORTED_VERSION) { return new SubscriptionInfo( usedSubscriptionMetadataVersion, LATEST_SUPPORTED_VERSION + 1, taskManager.processId(), userEndPoint(), taskManager.getTaskOffsetSums() ).encode(); } else { return new FutureSubscriptionInfo( usedSubscriptionMetadataVersion, taskManager.processId(), SubscriptionInfo.getActiveTasksFromTaskOffsetSumMap(taskManager.getTaskOffsetSums()), SubscriptionInfo.getStandbyTasksFromTaskOffsetSumMap(taskManager.getTaskOffsetSums()), userEndPoint()) .encode(); } }
Source:
public void testStandingOrderGetSuccess() throws Exception { Response<PaymentCreateResponse> createPaymentResponse = PaymentCreateTest.createStandingOrder(client()); String paymentId = createPaymentResponse.body().getPaymentId(); assertNotNull(paymentId); String clientUserId = Long.toString((new Date()).getTime()); LinkTokenCreateRequest.User user = new LinkTokenCreateRequest.User(clientUserId); Response<LinkTokenCreateResponse> response = client().service() .linkTokenCreate(new LinkTokenCreateRequest(user, "client name", Collections.singletonList("payment_initiation"), Collections.singletonList("US"), "en") .withPaymentInitiation(new LinkTokenCreateRequest.PaymentInitiation(paymentId))) .execute(); assertSuccessResponse(response); Response<PaymentGetResponse> getPaymentResponse = client().service().paymentGet(new PaymentGetRequest(paymentId)) .execute(); assertSuccessResponse(getPaymentResponse); assertNotNull(getPaymentResponse.body().getPaymentId()); assertNotNull(getPaymentResponse.body().getReference()); assertNotNull(getPaymentResponse.body().getAmount()); assertNotNull(getPaymentResponse.body().getSchedule()); assertNotNull(getPaymentResponse.body().getStatus()); assertNotNull(getPaymentResponse.body().getLastStatusUpdate()); assertNotNull(getPaymentResponse.body().getRecipientId()); }

Target:
public void testStandingOrderGetSuccess() throws Exception { Response<PaymentCreateResponse> createPaymentResponse = PaymentCreateTest.createStandingOrder(client()); String paymentId = createPaymentResponse.body().getPaymentId(); assertNotNull(paymentId); String clientUserId = Long.toString((new Date()).getTime()); LinkTokenCreateRequest.User user = new LinkTokenCreateRequest.User(clientUserId); Response<LinkTokenCreateResponse> response = client().service() .linkTokenCreate(new LinkTokenCreateRequest(user, "client name", Collections.singletonList("payment_initiation"), Collections.singletonList("GB"), "en") .withPaymentInitiation(new LinkTokenCreateRequest.PaymentInitiation(paymentId))) .execute(); assertSuccessResponse(response); Response<PaymentGetResponse> getPaymentResponse = client().service().paymentGet(new PaymentGetRequest(paymentId)) .execute(); assertSuccessResponse(getPaymentResponse); assertNotNull(getPaymentResponse.body().getPaymentId()); assertNotNull(getPaymentResponse.body().getReference()); assertNotNull(getPaymentResponse.body().getAmount()); assertNotNull(getPaymentResponse.body().getSchedule()); assertNotNull(getPaymentResponse.body().getStatus()); assertNotNull(getPaymentResponse.body().getLastStatusUpdate()); assertNotNull(getPaymentResponse.body().getRecipientId()); }
Source:
private static ExecutorService createSharedExecutor(MetricsManager metricsManager) { return new InstrumentedExecutorService( PTExecutors.newThreadPoolExecutor( CORE_SHARED_EXECUTOR_THREADS, MAX_SHARED_EXECUTOR_THREADS, 5, TimeUnit.SECONDS, new SynchronousQueue<>(), new InstrumentedThreadFactory(new ThreadFactoryBuilder() .setNameFormat("paxos-timestamp-creator-%d") .setDaemon(true) .build(), metricsManager.getRegistry()), new ThreadPoolExecutor.CallerRunsPolicy()), metricsManager.getRegistry(), MetricRegistry.name(PaxosLeaderElectionService.class, "paxos-timestamp-creator", "executor")); }

Target:
private static ExecutorService createSharedExecutor(MetricsManager metricsManager) { return new InstrumentedExecutorService( PTExecutors.newThreadPoolExecutor( CORE_SHARED_EXECUTOR_THREADS, MAX_SHARED_EXECUTOR_THREADS, 5, TimeUnit.SECONDS, new SynchronousQueue<>(), new InstrumentedThreadFactory(new ThreadFactoryBuilder() .setNameFormat("paxos-timestamp-creator-%d") .setDaemon(true) .build(), metricsManager.getRegistry()), RejectionTrackingCallerRunsPolicy.createWithSafeLoggableUseCase( metricsManager, PAXOS_SHARED_EXECUTOR)), metricsManager.getRegistry(), MetricRegistry.name(PaxosLeaderElectionService.class, PAXOS_SHARED_EXECUTOR, "executor")); }
Source:
private void deleteCacheIfPossible(final ConnectionSlot slot) throws IOException { final boolean hasMoreConnectionsToPartition = ACQUIRED_SLOTS.stream() .anyMatch(s -> s.getPartition().equals(slot.getPartition()) && s.getClient().equals(slot.getClient()) && s.getEventType().equals(slot.getEventType())); if (!hasMoreConnectionsToPartition) { final String consumerPath = zkPathForConsumer(slot.getClient(), slot.getEventType(), slot.getPartition()); final PathChildrenCache cache = SLOTS_CACHES.getOrDefault(consumerPath, null); if (cache != null) { SLOTS_CACHES.remove(consumerPath); cache.close(); } } }

Target:
private void deleteCacheIfPossible(final ConnectionSlot slot) throws IOException { final boolean hasMoreConnectionsToPartition = ACQUIRED_SLOTS.stream() .anyMatch(s -> s.getPartition().equals(slot.getPartition()) && s.getClient().equals(slot.getClient()) && s.getEventType().equals(slot.getEventType())); if (!hasMoreConnectionsToPartition) { final String consumerPath = zkPathForConsumer(slot.getClient(), slot.getEventType(), slot.getPartition()); final PathChildrenCache cache = SLOTS_CACHES.remove(consumerPath); if (cache != null) { cache.close(); } } }
Source:
public void run() { OperationStatus priorStatus = null; final AtomicBoolean done = new AtomicBoolean(); while(!done.get()) { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<OperationStatus> foundStatus = new AtomicReference<OperationStatus>(); final OperationCallback cb=new OperationCallback() { public void receivedStatus(OperationStatus val) { if(val.getMessage().length() == 0) { done.set(true); node.authComplete(); getLogger().info("Authenticated to " + node.getSocketAddress()); } else { foundStatus.set(val); } } public void complete() { latch.countDown(); } }; final Operation op = buildOperation(priorStatus, cb); conn.insertOperation(node, op); try { latch.await(); Thread.sleep(100); } catch(InterruptedException e) { Thread.currentThread().interrupt(); if (op != null) { op.cancel("interrupted in the process of authentication" + e); } done.set(true); } priorStatus = foundStatus.get(); if(priorStatus != null) { if(!priorStatus.isSuccess()) { getLogger().warn("Authentication failed to " + node.getSocketAddress()); } } } return; }

Target:
public void run() { OperationStatus priorStatus = null; final AtomicBoolean done = new AtomicBoolean(); while(!done.get()) { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<OperationStatus> foundStatus = new AtomicReference<OperationStatus>(); final OperationCallback cb=new OperationCallback() { public void receivedStatus(OperationStatus val) { if(val.getMessage().length() == 0) { done.set(true); node.authComplete(); getLogger().info("Authenticated to " + node.getSocketAddress()); } else { foundStatus.set(val); } } public void complete() { latch.countDown(); } }; final Operation op = buildOperation(priorStatus, cb); conn.insertOperation(node, op); try { latch.await(); Thread.sleep(100); } catch(InterruptedException e) { Thread.currentThread().interrupt(); if (op != null) { op.cancel("interruption to authentication" + e); } done.set(true); } priorStatus = foundStatus.get(); if(priorStatus != null) { if(!priorStatus.isSuccess()) { getLogger().warn("Authentication failed to " + node.getSocketAddress()); } } } return; }
Source:
private SamplerConfiguration getIteratorSamplerConfigurationInternal() { SamplerConfiguration scannerSamplerConfig = getSamplerConfiguration(); if (scannerSamplerConfig != null) { if (iteratorSamplerConfig != null && !new SamplerConfigurationImpl(iteratorSamplerConfig).equals(new SamplerConfigurationImpl(scannerSamplerConfig))) { throw new IllegalStateException("Scanner and iterator sampler configuration differ"); } return scannerSamplerConfig; } return iteratorSamplerConfig; }

Target:
private SamplerConfiguration getIteratorSamplerConfigurationInternal() { SamplerConfiguration scannerSamplerConfig = getSamplerConfiguration(); if (scannerSamplerConfig != null) { if (iteratorSamplerConfig != null && !iteratorSamplerConfig.equals(scannerSamplerConfig)) { throw new IllegalStateException("Scanner and iterator sampler configuration differ"); } return scannerSamplerConfig; } return iteratorSamplerConfig; }
Source:
private Response logAndReplaceResponse(String url, Response response, Type type, long elapsedTime) throws IOException, ConversionException { log.log(String.format("<--- HTTP %s %s (%sms)", response.getStatus(), url, elapsedTime)); if (logLevel.ordinal() >= LogLevel.HEADERS.ordinal()) { for (Header header : response.getHeaders()) { log.log(header.toString()); } TypedInput body = response.getBody(); if (body != null) { long bodySize = body.length(); if (logLevel.ordinal() >= LogLevel.FULL.ordinal()) { log.log(""); if (!(body instanceof TypedByteArray)) { response = Utils.readBodyToBytesIfNecessary(response); body = response.getBody(); } byte[] bodyBytes = ((TypedByteArray) body).getBytes(); bodySize = bodyBytes.length; if (type == Response.class) { log.log("(not enough type information)"); } else if (converter instanceof LoggingConverter) { LoggingConverter loggingConverter = (LoggingConverter) converter; log.log(loggingConverter.bodyToString(body, type)); } else { log.log("(converter unable to log)"); } } log.log(String.format("<--- END HTTP (%s-byte body)", bodySize)); } else { log.log("<--- END HTTP (empty body)"); } } return response; }

Target:
private Response logAndReplaceResponse(String url, Response response, Type type, long elapsedTime) throws IOException, ConversionException { log.log(String.format("<--- HTTP %s %s (%sms)", response.getStatus(), url, elapsedTime)); if (logLevel.ordinal() >= LogLevel.HEADERS.ordinal()) { for (Header header : response.getHeaders()) { log.log(header.toString()); } TypedInput body = response.getBody(); if (body != null) { long bodySize = body.length(); if (logLevel.ordinal() >= LogLevel.FULL.ordinal()) { log.log(""); if (type == Response.class) { log.log("(not enough type information)"); } else if (converter instanceof LoggingConverter) { if (!(body instanceof TypedByteArray)) { response = Utils.readBodyToBytesIfNecessary(response); body = response.getBody(); } byte[] bodyBytes = ((TypedByteArray) body).getBytes(); bodySize = bodyBytes.length; LoggingConverter loggingConverter = (LoggingConverter) converter; log.log(loggingConverter.bodyToLogString(body, type)); } else { log.log("(converter unable to log)"); } } log.log(String.format("<--- END HTTP (%s-byte body)", bodySize)); } else { log.log("<--- END HTTP (empty body)"); } } return response; }
Source:
void initializeLocalUntainted(@Untainted Buffer b) { Buffer local = b; @Untainted Buffer copy = local; }

Target:
void initializeLocalUntainted(@Untainted Buffer b) { Buffer local = b; @Untainted Buffer copy1 = local; @Tainted Buffer copy2 = local; }
Source:
private void updateBackup() { if (getCurrentStorageItem().getRole() == StorageDomainType.ISO || getCurrentStorageItem().getRole() == StorageDomainType.ImportExport) { getBackup().setIsAvailable(false); getBackup().setEntity(false); return; } boolean backupSupported = (Boolean) AsyncDataProvider.getInstance().getConfigValuePreConverted( ConfigValues.BackupSupported, getDataCenter().getSelectedItem().getCompatibilityVersion().toString()); getBackup().setIsAvailable(backupSupported); if (getBackup().getIsAvailable()) { if (isNewStorage()) { getBackup().setEntity(false); } else { getBackup().setEntity(getStorage().isBackup()); } } }

Target:
private void updateBackup() { if (getCurrentStorageItem().getRole() == StorageDomainType.ISO || getCurrentStorageItem().getRole() == StorageDomainType.ImportExport) { getBackup().setIsAvailable(false); getBackup().setEntity(false); return; } boolean backupSupported = (Boolean) AsyncDataProvider.getInstance().getConfigValuePreConverted( ConfigurationValues.BackupSupported, getDataCenter().getSelectedItem().getCompatibilityVersion().toString()); getBackup().setIsAvailable(backupSupported); getBackup().setEntity(isNewStorage() ? false : getStorage().isBackup()); }
Source:
private boolean tryLock() throws SQLException { List<Boolean> results = jdbcTemplate.query( "SELECT pg_try_advisory_lock(" + lockNum + ")", new RowMapper<Boolean>() { @Override public Boolean mapRow(ResultSet rs) throws SQLException { return rs.getBoolean(0); } }); return results.size() == 1 && results.get(0); }

Target:
private boolean tryLock() throws SQLException { List<Boolean> results = jdbcTemplate.query( "SELECT pg_try_advisory_lock(" + lockNum + ")", new RowMapper<Boolean>() { @Override public Boolean mapRow(ResultSet rs) throws SQLException { return rs.getBoolean(1); } }); return results.size() == 1 && results.get(0); }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof CtfIterator)) { return false; } CtfIterator other = (CtfIterator) obj; if (!NonNullUtils.equalsNullable(fTrace, other.fTrace)) { return false; } if (!NonNullUtils.equalsNullable(fCurLocation, other.fCurLocation)) { return false; } return fCurRank == other.fCurRank; }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof CtfIterator)) { return false; } CtfIterator other = (CtfIterator) obj; if (!equalsNullable(fTrace, other.fTrace)) { return false; } if (!equalsNullable(fCurLocation, other.fCurLocation)) { return false; } if (fCurRank != other.fCurRank) { return false; } return true; }
Source:
void rollback() { if (publishedFullRegistry == null) { return; } try { writeLock.lock(); clear(); copy(publishedFullRegistry, this); modified = false; } finally { writeLock.unlock(); } }

Target:
void rollback() { if (publishedFullRegistry == null) { return; } writeLock.lock(); try { publishedFullRegistry.readLock.lock(); try { clear(); copy(publishedFullRegistry, this); modified = false; } finally { publishedFullRegistry.readLock.unlock(); } } finally { writeLock.unlock(); } }
Source:
protected void parseService(FBType type) throws TypeImportException, XMLStreamException { String rightInterface = getAttributeValue(LibraryElementTags.RIGHT_INTERFACE_ATTRIBUTE); if (null != rightInterface) { ServiceInterface rightInter = LibraryElementFactory.eINSTANCE.createServiceInterface(); rightInter.setName(rightInterface); type.getService().setRightInterface(rightInter); } else { throw new TypeImportException(Messages.FBTImporter_SERVICE_INTERFACE_RIGHTINTERFACE_EXCEPTION); } String leftInterface = getAttributeValue(LibraryElementTags.LEFT_INTERFACE_ATTRIBUTE); if (null != leftInterface) { ServiceInterface leftInter = LibraryElementFactory.eINSTANCE.createServiceInterface(); leftInter.setName(leftInterface); type.getService().setLeftInterface(leftInter); } else { throw new TypeImportException(Messages.FBTImporter_SERVICE_INTERFACE_LEFTINTERFACE_EXCEPTION); } String comment = getAttributeValue(LibraryElementTags.COMMENT_ATTRIBUTE); if (null != comment) { type.setComment(comment); } processChildren(LibraryElementTags.SERVICE_ELEMENT, name -> { if (name.equals(LibraryElementTags.SERVICE_SEQUENCE_ELEMENT)) { parseServiceSequence(type); return true; } return false; }); }

Target:
protected void parseService(FBType type) throws TypeImportException, XMLStreamException { String rightInterface = getAttributeValue(LibraryElementTags.RIGHT_INTERFACE_ATTRIBUTE); if (null != rightInterface) { ServiceInterface rightInter = LibraryElementFactory.eINSTANCE.createServiceInterface(); rightInter.setName(rightInterface); type.getService().setRightInterface(rightInter); } else { throw new TypeImportException(Messages.FBTImporter_SERVICE_INTERFACE_RIGHTINTERFACE_EXCEPTION); } String leftInterface = getAttributeValue(LibraryElementTags.LEFT_INTERFACE_ATTRIBUTE); if (null != leftInterface) { ServiceInterface leftInter = LibraryElementFactory.eINSTANCE.createServiceInterface(); leftInter.setName(leftInterface); type.getService().setLeftInterface(leftInter); } else { throw new TypeImportException(Messages.FBTImporter_SERVICE_INTERFACE_LEFTINTERFACE_EXCEPTION); } String comment = getAttributeValue(LibraryElementTags.COMMENT_ATTRIBUTE); if (null != comment) { type.setComment(comment); } processChildren(LibraryElementTags.SERVICE_ELEMENT, name -> { if (LibraryElementTags.SERVICE_SEQUENCE_ELEMENT.equals(name)) { parseServiceSequence(type); return true; } return false; }); }
Source:
public void testCanAssign() throws Exception { VariableDeclarationFragment[] targets= createVariables(); StringBuilder errors= new StringBuilder(); for (VariableDeclarationFragment targetk : targets) { for (VariableDeclarationFragment targetn : targets) { VariableDeclarationFragment f1= targetk; VariableDeclarationFragment f2= targetn; String line= f2.getName().getIdentifier() + "= " + f1.getName().getIdentifier(); StringBuilder buf= new StringBuilder(); buf.append("package test1;\n"); buf.append("public class F<T, U extends Number> extends E<T, U> {\n"); buf.append(" void foo() {\n"); buf.append(" ").append(line).append(";\n"); buf.append(" }\n"); buf.append("}\n"); char[] content= buf.toString().toCharArray(); ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setSource(content); parser.setResolveBindings(true); parser.setProject(fJProject1); parser.setUnitName("F.java"); CompilationUnit astRoot= (CompilationUnit) parser.createAST(null); IProblem[] problems= astRoot.getProblems(); ITypeBinding b1= f1.resolveBinding().getType(); assertNotNull(b1); ITypeBinding b2= f2.resolveBinding().getType(); assertNotNull(b2); boolean res2= TypeRules.canAssign(b1, b2); if (res2 != (problems.length == 0)) { errors.append(line).append('\n'); } } } assertTrue(errors.toString(), errors.length() == 0); }

Target:
public void testCanAssign() throws Exception { VariableDeclarationFragment[] targets= createVariables(); StringBuilder errors= new StringBuilder(); for (VariableDeclarationFragment f1 : targets) { for (VariableDeclarationFragment f2 : targets) { String line= f2.getName().getIdentifier() + "= " + f1.getName().getIdentifier(); StringBuilder buf= new StringBuilder(); buf.append("package test1;\n"); buf.append("public class F<T, U extends Number> extends E<T, U> {\n"); buf.append(" void foo() {\n"); buf.append(" ").append(line).append(";\n"); buf.append(" }\n"); buf.append("}\n"); char[] content= buf.toString().toCharArray(); ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setSource(content); parser.setResolveBindings(true); parser.setProject(fJProject1); parser.setUnitName("F.java"); CompilationUnit astRoot= (CompilationUnit) parser.createAST(null); IProblem[] problems= astRoot.getProblems(); ITypeBinding b1= f1.resolveBinding().getType(); assertNotNull(b1); ITypeBinding b2= f2.resolveBinding().getType(); assertNotNull(b2); boolean res2= TypeRules.canAssign(b1, b2); if (res2 != (problems.length == 0)) { errors.append(line).append('\n'); } } } assertTrue(errors.toString(), errors.length() == 0); }
Source:
private String buildUpdateScript(final String content) { Validate.notNull(content); final StringWriter raw = new StringWriter(); final PrintWriter script = new PrintWriter(raw); final StringBuilder sb = new StringBuilder(); final StringBuilder cb = new StringBuilder(); sb.append(":syntax => :scss"); for (final String require : requires) { script.println(" require '" + require + "' "); } for (int i = 0; i < content.length(); i++) { cb.append(String.format("\\u%04x", content.codePointAt(i))); } final String scriptAsString = String.format("result = Sass::Engine.new(\"%s\", {%s}).render", cb.toString(), sb.toString()); LOG.debug("scriptAsString: {}", scriptAsString); script.println(scriptAsString); script.flush(); return raw.toString(); }

Target:
private String buildUpdateScript(final String content) { Validate.notNull(content); final StringWriter raw = new StringWriter(); final PrintWriter script = new PrintWriter(raw); final StringBuilder sb = new StringBuilder(); final StringBuilder cb = new StringBuilder(); sb.append(":syntax => :scss"); for (final String require : requires) { script.println(" require '" + require + "' "); } final int BACKSLASH = 0x5c; for (int i = 0; i < content.length(); i++) { final int code = content.codePointAt(i); if (code < 0x80) { if (code == BACKSLASH) { cb.append("\\"); } cb.append(content.charAt(i)); } else { cb.append(String.format("\\u%04x", code)); } } final String scriptAsString = String.format("result = Sass::Engine.new(\"%s\", {%s}).render", cb.toString().replace("\"", "\\\"").replace("#", "\\#"), sb.toString()); LOG.debug("scriptAsString: {}", scriptAsString); script.println(scriptAsString); script.flush(); return raw.toString(); }
Source:
public RuntimeInfo getRuntimeInfo(ExecutionEngine engine, ComponentProperties properties, ConnectorTopology connectorTopology) { assertEngineCompatibility(engine); assertConnectorTopologyCompatibility(connectorTopology); return getRuntimeInfo(GoogleDriveConnectionDefinition.SOURCE_CLASS); }

Target:
public RuntimeInfo getRuntimeInfo(ExecutionEngine engine, ComponentProperties properties, ConnectorTopology connectorTopology) { return this.getRuntimeInfo(engine, connectorTopology, GoogleDriveConnectionDefinition.SOURCE_CLASS); }
Source:
public SeekableStreamDataSourceMetadata getCurrentCheckPoint() { return checkpointMetadata; }

Target:
private SeekableStreamDataSourceMetadata getCurrentCheckPoint() { return checkpointMetadata; }
Source:
MockStore( Cursors cursors ) { super( cursors, null ); }

Target:
MockStore( Cursors cursors ) { super( cursors, mock( TxStateHolder.class ) ); }
Source:
public CompletableFuture<Void> close() { CompletableFuture<Void> future = new CompletableFuture<>(); threadContext.execute(() -> { clusterMembershipService.removeListener(membershipEventListener); primaryElection.removeListener(primaryElectionListener); role.close(); future.complete(null); }); return future; }

Target:
public CompletableFuture<Void> close() { CompletableFuture<Void> future = new CompletableFuture<>(); threadContext.execute(() -> { try { clusterMembershipService.removeListener(membershipEventListener); primaryElection.removeListener(primaryElectionListener); role.close(); } finally { future.complete(null); } }); return future; }
Source:
public Invocations getInvocations() { return new Invocations.Builder() .invocation().methods(GET).path("/v2/protobuf").handleWith(this::getSchemasNames) .invocation().methods(PUT, POST).path("/v2/protobuf/{schemaName}").handleWith(this::addOrEditSchema) .invocation().methods(GET).path("/v2/protobuf/{schemaName}").handleWith(this::getSchema) .invocation().method(DELETE).path("/v2/protobuf/{schemaName}").handleWith(this::deleteSchema) .create(); }

Target:
public Invocations getInvocations() { return new Invocations.Builder() .invocation().methods(GET).path("/v2/schemas").handleWith(this::getSchemasNames) .invocation().methods(POST).path("/v2/schemas/{schemaName}").handleWith(r -> createOrReplace(r,true)) .invocation().methods(PUT).path("/v2/schemas/{schemaName}").handleWith(r -> createOrReplace(r,false)) .invocation().methods(GET).path("/v2/schemas/{schemaName}").handleWith(this::getSchema) .invocation().method(DELETE).path("/v2/schemas/{schemaName}").handleWith(this::deleteSchema) .create(); }
Source:
public BluetoothGattService buildBatteryService() { BluetoothGattCharacteristic batteryCharacteristic = new BluetoothGattCharacteristic(BATTERY_LEVEL_UUID, BATTERY_LEVEL_PROPERTIES, BATTERY_LEVEL_PERMISSIONS); batteryCharacteristic.setValue(BATTERY_LEVEL_SAMPLE); BluetoothGattService batteryService = new BluetoothGattService(BATTERY_SERVICE_UUID, BATTERY_SERVICE_TYPE); batteryService.addCharacteristic(batteryCharacteristic); return batteryService; }

Target:
public BluetoothGattService buildBatteryService() { BluetoothGattCharacteristic batteryCharacteristic = new BluetoothGattCharacteristic(BATTERY_LEVEL_UUID, BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY, BluetoothGattCharacteristic.PERMISSION_READ); batteryCharacteristic.setValue( 50, BluetoothGattCharacteristic.FORMAT_UINT8, 0); BluetoothGattService batteryService = new BluetoothGattService(BATTERY_SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY); batteryService.addCharacteristic(batteryCharacteristic); return batteryService; }
Source:
public void apply(DebugConfiguration debugConfiguration) { if (debuggerManager.getActiveDebugger() != null) { dialogFactory.createMessageDialog(localizationConstants.connectToRemote(), localizationConstants.debuggerAlreadyConnected(), null).show(); return; } final Debugger debugger = debuggerManager.getDebugger(debugConfiguration.getType().getId()); if (debugger != null) { debuggerManager.setActiveDebugger(debugger); Map<String, String> connectionProperties = new HashMap<>(2 + debugConfiguration.getConnectionProperties().size()); connectionProperties.put("HOST", debugConfiguration.getHost()); connectionProperties.put("PORT", String.valueOf(debugConfiguration.getPort())); connectionProperties.putAll(debugConfiguration.getConnectionProperties()); debugger.connect(connectionProperties).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError arg) throws OperationException { debuggerManager.setActiveDebugger(null); } }); } }

Target:
public void apply(DebugConfiguration debugConfiguration) { if (debugConfiguration == null) { return; } if (debuggerManager.getActiveDebugger() != null) { dialogFactory.createMessageDialog(localizationConstants.connectToRemote(), localizationConstants.debuggerAlreadyConnected(), null).show(); return; } final Debugger debugger = debuggerManager.getDebugger(debugConfiguration.getType().getId()); if (debugger != null) { debuggerManager.setActiveDebugger(debugger); Map<String, String> connectionProperties = new HashMap<>(2 + debugConfiguration.getConnectionProperties().size()); connectionProperties.put("HOST", debugConfiguration.getHost()); connectionProperties.put("PORT", String.valueOf(debugConfiguration.getPort())); connectionProperties.putAll(debugConfiguration.getConnectionProperties()); debugger.connect(connectionProperties).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError arg) throws OperationException { debuggerManager.setActiveDebugger(null); } }); } }
Source:
public ClientHttpResponse execute() throws IOException { if (this.response == null) { LOGGER.warn("Attempting to load cached URI before actual caching: " + this.originalRequest.getURI()); } else { LOGGER.debug("Loading cached URI resource " + this.originalRequest.getURI()); } return this.response; }

Target:
public ClientHttpResponse execute() throws IOException { if (!HttpRequestCache.this.cached) { LOGGER.warn("Attempting to load cached URI before actual caching: " + this.originalRequest.getURI()); } else if (this.response == null) { LOGGER.warn("Attempting to load cached URI from failed request: " + this.originalRequest.getURI()); } else { LOGGER.debug("Loading cached URI resource " + this.originalRequest.getURI()); } return this.response; }
Source:
public boolean requiresTransaction() { return tokens.stream().filter(t -> t.requiresTransaction()).findAny().isPresent(); }

Target:
public boolean requiresTransaction() { return requiresTransaction; }
Source:
public void fallBackToUnsupported() { BlockStrategies strategies = new BlockStrategies(Sets.newHashSet(BlockType.PARAGRAPH)); List<BlockType> unsupportedBlockTypes = ImmutableList.of(BlockType.TABLE, BlockType.TABLE_ROW, BlockType.BULLETED_LIST, BlockType.NUMERIC_LIST, BlockType.DEFINITION_LIST); for (BlockType blockType : unsupportedBlockTypes) { BlockStrategy strategy = strategies.getStrategy(blockType, new Attributes()); assertNotNull(strategy); assertTrue(UnsupportedBlockStrategy.class.equals(strategy.getClass()) || NoOpBlockStrategy.class.equals(strategy.getClass())); } }

Target:
public void fallBackToUnsupported() { BlockStrategies strategies = new BlockStrategies(Sets.newHashSet(BlockType.PARAGRAPH)); BlockStrategy strategy = strategies.getStrategy(BlockType.TABLE_ROW, new Attributes()); assertNotNull(strategy); assertTrue(UnsupportedBlockStrategy.class.equals(strategy.getClass())); }
Source:
public void registerPublisher(Function<NodeEngine, MetricsPublisher> registerFunction) { MetricsPublisher publisher = registerFunction.apply(nodeEngine); publishers.add(publisher); }

Target:
public void registerPublisher(Function<NodeEngine, MetricsPublisher> registerFunction) { if (config.isEnabled()) { MetricsPublisher publisher = registerFunction.apply(nodeEngine); publishers.add(publisher); scheduleMetricsCollectorIfNeeded(); } else { logger.fine(String.format("Custom publisher is not registered with function %s as the metrics system is disabled", registerFunction)); } }
Source:
protected void buildEntryList(@NonNull ITmfTrace trace, @NonNull ITmfTrace parentTrace, @NonNull IProgressMonitor monitor) { long start = trace.getStartTime().toNanos(); TraceEntry traceEntry = new TraceEntry(trace.getName(), start, start); addToEntryList(parentTrace, Collections.singletonList(traceEntry)); Iterable<@NonNull ITmfAnalysisModuleWithStateSystems> modules = Iterables. filter(trace.getAnalysisModules(), ITmfAnalysisModuleWithStateSystems.class); boolean complete = false; while (!complete) { complete = true; long end = start; for (ITmfAnalysisModuleWithStateSystems module : modules) { ModuleEntry moduleEntry = getOrCreateModuleEntry(traceEntry, module); if (module.isAutomatic()) { module.waitForInitialization(); } for (ITmfStateSystem ss : module.getStateSystems()) { complete &= ss.waitUntilBuilt(0); end = Long.max(end, ss.getCurrentEndTime()); getOrCreateStateSystemEntry(moduleEntry, ss); } } traceEntry.updateEndTime(end); long resolution = Long.max(1, (end - start) / getDisplayWidth()); zoomEntries(flatten(traceEntry), start, end, resolution, monitor); if (parentTrace == getTrace()) { synchronized (this) { setStartTime(Long.min(getStartTime(), start)); setEndTime(Long.max(getEndTime(), end)); } refresh(); } if (!complete) { try { Thread.sleep(ITERATION_WAIT); } catch (InterruptedException e) { Activator.getDefault().logError("Failed to wait", e); } } } }

Target:
protected void buildEntryList(@NonNull ITmfTrace trace, @NonNull ITmfTrace parentTrace, @NonNull IProgressMonitor monitor) { long start = trace.getStartTime().toNanos(); long end = start; TraceEntry traceEntry = new TraceEntry(trace.getName(), start, end); addToEntryList(parentTrace, Collections.singletonList(traceEntry)); Iterable<@NonNull ITmfAnalysisModuleWithStateSystems> modules = Iterables. filter(trace.getAnalysisModules(), ITmfAnalysisModuleWithStateSystems.class); Iterables.filter(modules, IAnalysisModule::isAutomatic) .forEach(ITmfAnalysisModuleWithStateSystems::waitForInitialization); boolean complete = false; while (!complete) { complete = true; for (ITmfAnalysisModuleWithStateSystems module : modules) { ModuleEntry moduleEntry = getOrCreateModuleEntry(traceEntry, module); for (ITmfStateSystem ss : module.getStateSystems()) { complete &= ss.waitUntilBuilt(0); end = Long.max(end, ss.getCurrentEndTime()); getOrCreateStateSystemEntry(moduleEntry, ss); } } traceEntry.updateEndTime(end); long resolution = Long.max(1, (end - start) / getDisplayWidth()); zoomEntries(flatten(traceEntry), start, end, resolution, monitor); if (parentTrace == getTrace()) { synchronized (this) { setStartTime(Long.min(getStartTime(), start)); setEndTime(Long.max(getEndTime(), end)); } refresh(); } if (!complete) { try { Thread.sleep(ITERATION_WAIT); } catch (InterruptedException e) { Activator.getDefault().logError("Failed to wait", e); } } } }
Source:
public void configure(Binder binder) { configBinder(binder).bindConfig(StorageManagerConfig.class); binder.bind(RaptorConnectorId.class).toInstance(new RaptorConnectorId(connectorId)); binder.bind(RaptorConnector.class).in(Scopes.SINGLETON); binder.bind(RaptorMetadataFactory.class).in(Scopes.SINGLETON); binder.bind(RaptorSplitManager.class).in(Scopes.SINGLETON); binder.bind(RaptorPageSourceProvider.class).in(Scopes.SINGLETON); binder.bind(RaptorPageSinkProvider.class).in(Scopes.SINGLETON); binder.bind(RaptorHandleResolver.class).in(Scopes.SINGLETON); binder.bind(RaptorNodePartitioningProvider.class).in(Scopes.SINGLETON); binder.bind(RaptorSessionProperties.class).in(Scopes.SINGLETON); binder.bind(RaptorTableProperties.class).in(Scopes.SINGLETON); Multibinder<SystemTable> tableBinder = newSetBinder(binder, SystemTable.class); tableBinder.addBinding().to(ShardMetadataSystemTable.class).in(Scopes.SINGLETON); tableBinder.addBinding().to(TableMetadataSystemTable.class).in(Scopes.SINGLETON); tableBinder.addBinding().to(TableStatsSystemTable.class).in(Scopes.SINGLETON); }

Target:
public void configure(Binder binder) { binder.bind(RaptorConnectorId.class).toInstance(new RaptorConnectorId(connectorId)); binder.bind(RaptorConnector.class).in(Scopes.SINGLETON); binder.bind(RaptorMetadataFactory.class).in(Scopes.SINGLETON); binder.bind(RaptorSplitManager.class).in(Scopes.SINGLETON); binder.bind(RaptorPageSourceProvider.class).in(Scopes.SINGLETON); binder.bind(RaptorPageSinkProvider.class).in(Scopes.SINGLETON); binder.bind(RaptorHandleResolver.class).in(Scopes.SINGLETON); binder.bind(RaptorNodePartitioningProvider.class).in(Scopes.SINGLETON); binder.bind(RaptorSessionProperties.class).in(Scopes.SINGLETON); binder.bind(RaptorTableProperties.class).in(Scopes.SINGLETON); Multibinder<SystemTable> tableBinder = newSetBinder(binder, SystemTable.class); tableBinder.addBinding().to(ShardMetadataSystemTable.class).in(Scopes.SINGLETON); tableBinder.addBinding().to(TableMetadataSystemTable.class).in(Scopes.SINGLETON); tableBinder.addBinding().to(TableStatsSystemTable.class).in(Scopes.SINGLETON); }
Source:
public void testIsCheckstyleModule() { assertTrue(ModuleReflectionUtils.isCheckstyleModule(CheckClass.class)); assertTrue(ModuleReflectionUtils.isCheckstyleModule(FileSetModuleClass.class)); assertTrue(ModuleReflectionUtils.isCheckstyleModule(FilterClass.class)); assertTrue(ModuleReflectionUtils.isCheckstyleModule(FileFilterModuleClass.class)); assertTrue(ModuleReflectionUtils.isCheckstyleModule(RootModuleClass.class)); assertTrue(ModuleReflectionUtils.isCheckstyleModule(TreeWalkerFilterClass.class)); }

Target:
public void testIsCheckstyleModule() { assertTrue("Should return true when checkstyle module is passed", ModuleReflectionUtils.isCheckstyleModule(CheckClass.class)); assertTrue("Should return true when checkstyle module is passed", ModuleReflectionUtils.isCheckstyleModule(FileSetModuleClass.class)); assertTrue("Should return true when checkstyle module is passed", ModuleReflectionUtils.isCheckstyleModule(FilterClass.class)); assertTrue("Should return true when checkstyle module is passed", ModuleReflectionUtils.isCheckstyleModule(TreeWalkerFilterClass.class)); assertTrue("Should return true when checkstyle module is passed", ModuleReflectionUtils.isCheckstyleModule(FileFilterModuleClass.class)); assertTrue("Should return true when checkstyle module is passed", ModuleReflectionUtils.isCheckstyleModule(RootModuleClass.class)); }
Source:
private ConnectorPageSinkProvider providerFor(ConnectorId connectorId) { ConnectorPageSinkProvider provider = pageSinkProviders.get(connectorId); checkArgument(provider != null, "No page sink provider for catalog '%s'", connectorId); return provider; }

Target:
private ConnectorPageSinkProvider providerFor(ConnectorId connectorId) { ConnectorPageSinkProvider provider = pageSinkProviders.get(connectorId); checkArgument(provider != null, "No page sink provider for catalog '%s'", connectorId.getCatalogName()); return provider; }
Source:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1) { if (resultCode == Activity.RESULT_OK) { updateScenario(); } if (resultCode == Activity.RESULT_CANCELED) { startActivity(new Intent(GameActivity.this, MapActivity.class)); finish(); } } }

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == getResources().getInteger(R.integer.display_points_request_code)) { if (resultCode == Activity.RESULT_OK) { updateScenario(); } if (resultCode == Activity.RESULT_CANCELED) { startActivity(new Intent(GameActivity.this, MapActivity.class)); finish(); } } }
Source:
public void prepareTestProject() throws Exception { projectServiceClient.importProject( ws.getId(), Paths.get( getClass() .getResource("/projects/plugins/JavaTestRunnerPlugin/" + JUNIT4_PROJECT) .toURI()), JUNIT4_PROJECT, ProjectTemplates.CONSOLE_JAVA_SIMPLE); ide.open(ws); ide.waitOpenedWorkspaceIsReadyToUse(); projectExplorer.waitItem(JUNIT4_PROJECT); consoles.waitJDTLSProjectResolveFinishedMessage(JUNIT4_PROJECT); notifications.waitProgressPopupPanelClose(); projectExplorer.quickExpandWithJavaScript(); runCompileCommand(); }

Target:
public void prepareTestProject() throws Exception { CompileCommand compileCommand = new CompileCommand(); testCommandServiceClient.createCommand(DtoConverter.asDto(compileCommand), ws.getId()); projectServiceClient.importProject( ws.getId(), Paths.get( getClass() .getResource("/projects/plugins/JavaTestRunnerPlugin/" + JUNIT4_PROJECT) .toURI()), JUNIT4_PROJECT, ProjectTemplates.CONSOLE_JAVA_SIMPLE); ide.open(ws); ide.waitOpenedWorkspaceIsReadyToUse(); projectExplorer.waitItem(JUNIT4_PROJECT); consoles.waitJDTLSProjectResolveFinishedMessage(JUNIT4_PROJECT); notifications.waitProgressPopupPanelClose(); projectExplorer.quickExpandWithJavaScript(); try { runCompileCommandByPallete(compileCommand); } catch (TimeoutException ex) { fail("Known random failure <LINK_0>"); } }
Source:
public SpongeExecutorService get() { return this.schedulerService.createAsyncExecutor(this.container.getInstance()); }

Target:
public SpongeExecutorService get() { return this.schedulerService.createAsyncExecutor(this.container); }
Source:
public void visit(NodeTraversal traversal, Node node, Node parent) { Preconditions.checkNotNull(globalNames != null, "Cannot call visit() before process()"); if (isPolymerCall(node)) { if (polymerElementExterns != null) { rewritePolymer1ClassDefinition(node, parent, traversal); } else if (!warnedPolymer1ExternsMissing) { compiler.report(JSError.make(polymerElementExterns, POLYMER_MISSING_EXTERNS)); warnedPolymer1ExternsMissing = true; } } else if (isPolymerClass(node)) { rewritePolymer2ClassDefinition(node, parent, traversal); } }

Target:
public void visit(NodeTraversal traversal, Node node, Node parent) { Preconditions.checkNotNull(globalNames, "Cannot call visit() before process()"); if (PolymerPassStaticUtils.isPolymerCall(node)) { if (polymerElementExterns != null) { rewritePolymer1ClassDefinition(node, parent, traversal); } else if (!warnedPolymer1ExternsMissing) { compiler.report(JSError.make(polymerElementExterns, POLYMER_MISSING_EXTERNS)); warnedPolymer1ExternsMissing = true; } } else if (PolymerPassStaticUtils.isPolymerClass(node)) { rewritePolymer2ClassDefinition(node, parent, traversal); } }
Source:
public Collection<MongoDBRouter> getRouters() { return FluentIterable.from(getMembers()) .transform(new Function<Entity, MongoDBRouter>() { @Override public MongoDBRouter apply(Entity input) { return (MongoDBRouter)input; } }) .toSet(); }

Target:
public Collection<MongoDBRouter> getRouters() { return ImmutableList.copyOf(Iterables.filter(getMembers(), MongoDBRouter.class)); }
Source:
public XMLHighlighting(String xmlStrContent) throws XMLStreamException{ content = xmlStrContent; InputStream inputStream = new ByteArrayInputStream(xmlStrContent.getBytes(StandardCharsets.UTF_8)); highlightXML(inputStream, Charset.defaultCharset()); }

Target:
public XMLHighlighting(String xmlStrContent) throws XMLStreamException{ content = xmlStrContent; highlightXML(new StringReader(xmlStrContent)); }
Source:
default boolean bypassCache() { return true; }

Target:
default boolean bypassCache() { return false; }
Source:
private void verifyQuery(String queryResource) throws Exception { String queryResponseTemplate; try { InputStream is = AbstractITBatchIndexTest.class.getResourceAsStream(queryResource); queryResponseTemplate = IOUtils.toString(is, StandardCharsets.UTF_8); } catch (IOException e) { throw new ISE(e, "could not read query file: %s", queryResource); } queryResponseTemplate = StringUtils.replace( queryResponseTemplate, "%%DATASOURCE%%", fullDatasourceName ); queryHelper.testQueriesFromString(queryResponseTemplate, 5); }

Target:
private void verifyQuery(String queryResource) throws Exception { String queryResponseTemplate; try { InputStream is = AbstractITBatchIndexTest.class.getResourceAsStream(queryResource); queryResponseTemplate = IOUtils.toString(is, StandardCharsets.UTF_8); } catch (IOException e) { throw new ISE(e, "could not read query file: %s", queryResource); } queryResponseTemplate = StringUtils.replace( queryResponseTemplate, "%%DATASOURCE%%", fullDatasourceName ); queryHelper.testQueriesFromString(queryResponseTemplate, 2); }
Source:
public void publish(ChatRoom chatRoom, TranslationResult result) { String name = result.getName(); String translation = result.getTranslatedText(); String toSend = name + ": " + translation; super.sendMessage(chatRoom, toSend); }

Target:
public void publish(ChatRoom chatRoom, TranslationResult result) { }
Source:
public MainController(String applicationName, LibraryController libraryController, AppsController appsController, EnginesController enginesController, ContainersController containersController, SettingsController settingsController, ThemeManager themeManager, SettingsManager settingsManager) { super(); this.applicationName = applicationName; this.mainWindow = new MainWindow(applicationName, libraryController.getView(), appsController.getView(), enginesController.getView(), containersController.getView(), settingsController.getView(), themeManager, settingsManager); this.settingsManager = settingsManager; libraryController.setOnTabOpened(mainWindow::showLibrary); appsController.setOnAppLoaded(() -> { enginesController.loadEngines(); containersController.loadContainers(); libraryController.updateLibrary(); }); appsController.loadApps(); }

Target:
public MainController(String applicationName, LibraryController libraryController, AppsController appsController, EnginesController enginesController, ContainersController containersController, SettingsController settingsController, ThemeManager themeManager, SettingsManager settingsManager) { super(); this.applicationName = applicationName; this.mainWindow = new MainWindow(applicationName, libraryController.getView(), appsController.getView(), enginesController.getView(), containersController.getView(), settingsController.getView(), themeManager, settingsManager); this.settingsManager = settingsManager; libraryController.setOnTabOpened(mainWindow::showLibrary); appsController.setOnAppLoaded(() -> { enginesController.loadEngines(); containersController.loadContainers(); }); appsController.loadApps(); }
Source:
protected String[] loadRoles(String property) { DynamicReadOnlyProperties props = JNDISingleton.getInstance(); String adminRole = props.getProperty(property, ""); if(adminRole == null || adminRole.trim().isEmpty()) { adminRole = DEFAULT_ADMIN_ROLE; } return new String[] {adminRole}; }

Target:
protected String[] loadRoles(String property) { DynamicReadOnlyProperties props = JNDISingleton.getInstance(); String adminRole = props.getProperty(property, ""); if(StringUtils.isBlank(adminRole)) { adminRole = DEFAULT_ADMIN_ROLE; } return new String[] {adminRole}; }
Source:
public RebaseCommand setSkip() { this.abortRebase = false; this.skipRebase = true; this.continueRebase = false; return this; }

Target:
public RebaseCommand setSkip() { this.operation = Operation.SKIP; return this; }
Source:
public RollingUpdateOp start(final DeploymentGroup deploymentGroup, final RollingUpdateReason reason, final ZooKeeperClient client) throws KeeperException { final List<ZooKeeperOperation> ops = Lists.newArrayList(); final List<Map<String, Object>> events = Lists.newArrayList(); final List<RolloutTask> rolloutTasks = tasks.getRolloutTasks(); events.add(eventFactory.rollingUpdateStarted(deploymentGroup, reason)); final Stat tasksStat = client.exists( Paths.statusDeploymentGroupTasks(deploymentGroup.getName())); if (tasksStat == null) { ops.add(create(Paths.statusDeploymentGroupTasks(deploymentGroup.getName()))); } final DeploymentGroupStatus status; if (rolloutTasks.isEmpty()) { status = DeploymentGroupStatus.newBuilder() .setState(DONE) .build(); ops.add(delete(Paths.statusDeploymentGroupTasks(deploymentGroup.getName()))); events.add(eventFactory.rollingUpdateDone(deploymentGroup)); } else { final DeploymentGroupTasks tasks = DeploymentGroupTasks.newBuilder() .setRolloutTasks(rolloutTasks) .setTaskIndex(0) .setDeploymentGroup(deploymentGroup) .build(); status = DeploymentGroupStatus.newBuilder() .setState(ROLLING_OUT) .build(); ops.add(set(Paths.statusDeploymentGroupTasks(deploymentGroup.getName()), tasks)); } ops.add(set(Paths.statusDeploymentGroup(deploymentGroup.getName()), status)); return new RollingUpdateOp(ImmutableList.copyOf(ops), ImmutableList.copyOf(events)); }

Target:
public RollingUpdateOp start(final DeploymentGroup deploymentGroup, final RollingUpdateReason reason, final ZooKeeperClient client) throws KeeperException { client.ensurePath(Paths.statusDeploymentGroupTasks()); final List<ZooKeeperOperation> ops = Lists.newArrayList(); final List<Map<String, Object>> events = Lists.newArrayList(); final List<RolloutTask> rolloutTasks = tasks.getRolloutTasks(); events.add(eventFactory.rollingUpdateStarted(deploymentGroup, reason)); final Stat tasksStat = client.exists( Paths.statusDeploymentGroupTasks(deploymentGroup.getName())); if (tasksStat == null) { ops.add(create(Paths.statusDeploymentGroupTasks(deploymentGroup.getName()))); } final DeploymentGroupStatus status; if (rolloutTasks.isEmpty()) { status = DeploymentGroupStatus.newBuilder() .setState(DONE) .build(); ops.add(delete(Paths.statusDeploymentGroupTasks(deploymentGroup.getName()))); events.add(eventFactory.rollingUpdateDone(deploymentGroup)); } else { final DeploymentGroupTasks tasks = DeploymentGroupTasks.newBuilder() .setRolloutTasks(rolloutTasks) .setTaskIndex(0) .setDeploymentGroup(deploymentGroup) .build(); status = DeploymentGroupStatus.newBuilder() .setState(ROLLING_OUT) .build(); ops.add(set(Paths.statusDeploymentGroupTasks(deploymentGroup.getName()), tasks)); } ops.add(set(Paths.statusDeploymentGroup(deploymentGroup.getName()), status)); return new RollingUpdateOp(ImmutableList.copyOf(ops), ImmutableList.copyOf(events)); }
Source:
public void delete(PageId pageId) throws IOException, PageNotFoundException { Path p = getFilePath(pageId); if (!Files.exists(p)) { throw new PageNotFoundException(p.toString()); } Files.delete(p); mSize.decrementAndGet(); Path parent = Preconditions.checkNotNull(p.getParent(), "parent"); try (DirectoryStream<Path> stream = Files.newDirectoryStream(parent)) { if (!stream.iterator().hasNext()) { Files.delete(parent); } } }

Target:
public void delete(PageId pageId) throws IOException, PageNotFoundException { Path p = getFilePath(pageId); if (!Files.exists(p)) { throw new PageNotFoundException(p.toString()); } Files.delete(p); mSize.decrementAndGet(); Path parent = Preconditions.checkNotNull(p.getParent(), "parent of cache file should not be null"); try (DirectoryStream<Path> stream = Files.newDirectoryStream(parent)) { if (!stream.iterator().hasNext()) { Files.delete(parent); } } }