auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected List<ILogData> getNextEntries(T context, long maxGlobal, Function<ILogData, Boolean> contextCheckFn) { final List<ILogData> dataList = new ArrayList<>(); ILogData thisData; while ((thisData = streamReadWithCheck(()->getNextEntry(context, maxGlobal), maxGlobal)) != null) { // Add this read to the list of reads to return. dataList.add(thisData); // Update the pointer, because the underlying implementation // will expect it to be updated when we call getNextEntry() again. updatePointer(thisData); // If this entry changes the context, don't continue reading. if (contextCheckFn.apply(thisData)) { break; } } return dataList; }

Target:
protected List<ILogData> getNextEntries(T context, long maxGlobal, Function<ILogData, Boolean> contextCheckFn) { final List<ILogData> dataList = new ArrayList<>(); ILogData thisData; while ((thisData = getNextEntry(context, maxGlobal)) != null) { // Add this read to the list of reads to return. dataList.add(thisData); // Update the pointer, because the underlying implementation // will expect it to be updated when we call getNextEntry() again. updatePointer(thisData); // If this entry changes the context, don't continue reading. if (contextCheckFn.apply(thisData)) { break; } } return dataList; }
Source:
public synchronized ILogData current() { final QueuedStreamContext context = getCurrentContext(); if (Address.nonAddress(context.getGlobalPointer())) { return null; } // The ILogData returned by current() would be used for rollback. return read(context.getGlobalPointer()); }

Target:
public synchronized ILogData current() { final QueuedStreamContext context = getCurrentContext(); if (Address.nonAddress(context.getGlobalPointer())) { return null; } // The ILogData returned by current() would be used for rollback. return read(context.getGlobalPointer(), context.getGlobalPointer()); }
Source:
public void gcUnsafe() { while (garbageSendingDeque.size() < SENDING_QUEUE_CAPACITY) { List<SMRGarbageEntry> garbageEntries = new ArrayList<>(); int drainedNum = garbageReceivingQueue.drainTo(garbageEntries, BATCH_SIZE); GarbageBatch garbageBatch = new GarbageBatch(compressGarbage(garbageEntries)); garbageSendingDeque.offer(garbageBatch); if (drainedNum < BATCH_SIZE) { break; } } log.debug("GarbageInformer: Drains sending queue"); sendGarbage(); }

Target:
public void gcUnsafe() { while (garbageSendingDeque.size() < SENDING_QUEUE_CAPACITY) { List<SMRGarbageEntry> garbageEntries = new ArrayList<>(); int drainedNum = garbageReceivingQueue.drainTo(garbageEntries, BATCH_SIZE); // checks drainNum to prevent empty garbage batch if (drainedNum == 0) { break; } GarbageBatch garbageBatch = new GarbageBatch(compressGarbage(garbageEntries)); garbageSendingDeque.offer(garbageBatch); if (drainedNum < BATCH_SIZE) { break; } } log.debug("GarbageInformer: Drains sending queue"); sendGarbage(); }
Source:
protected List<Object> identifyRemoveGarbage(Object locator, K key) { List<Object> garbage = new ArrayList<>(); // TODO(Xin): Distinguish put and remove in the future garbage.addAll(locatorStore.addUnsafe(key, (SMRRecordLocator) locator)); return garbage; }

Target:
protected List<Object> identifyRemoveGarbage(Object locator, K key) { // TODO(Xin): Distinguish put and remove in the future return new ArrayList<>(locatorStore.addUnsafe(key, (SMRRecordLocator) locator)); }
Source:
public static ISerializer getSerializer(Byte type) { if (type <= SYSTEM_SERIALIZERS_COUNT) { if (serializersMap.containsKey(type)) { return serializersMap.get(type); } } else { if (customSerializers.containsKey(type)) { return customSerializers.get(type); } } log.error("Serializer with type code not found. Please check custom serializers " + "for this client.", type.intValue()); throw new SerializerException(type); }

Target:
public static ISerializer getSerializer(Byte type) { if (type <= SYSTEM_SERIALIZERS_COUNT) { if (serializersMap.containsKey(type)) { return serializersMap.get(type); } } else if (customSerializers.containsKey(type)) { return customSerializers.get(type); } log.error("Serializer with type code not found. Please check custom serializers " + "for this client.", type.intValue()); throw new SerializerException(type); }
Source:
private void prefixTrim(CorfuPayloadMsg<TrimRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { try { TrimRequest req = msg.getPayload(); batchWriter.prefixTrim(new Token(msg.getEpoch(), req.getAddress().getSequence())); r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); } catch (TrimmedException ex) { r.sendResponse(ctx, msg, CorfuMsgType.ERROR_TRIMMED.msg()); } }

Target:
private void prefixTrim(CorfuPayloadMsg<TrimRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { try { TrimRequest req = msg.getPayload(); batchWriter.prefixTrim(req.getAddress().getSequence(), msg.getEpoch()); r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); } catch (TrimmedException ex) { r.sendResponse(ctx, msg, CorfuMsgType.ERROR_TRIMMED.msg()); } }
Source:
public synchronized void trimCache(CorfuPayloadMsg<Long> msg, ChannelHandlerContext ctx, IServerRouter r) { log.info("trimCache: Starting cache eviction"); if (trimMark < msg.getPayload()) { // Advance the trim mark, if the new trim request has a higher trim mark. trimMark = msg.getPayload(); } cache.invalidateUpTo(trimMark); r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); }

Target:
public synchronized void trimCache(CorfuPayloadMsg<Long> msg, ChannelHandlerContext ctx, IServerRouter r) { log.info("trimCache: Starting cache eviction"); if (trimMark < msg.getPayload()) { // Advance the trim mark, if the new trim request has a higher trim mark. trimMark = msg.getPayload(); cache.invalidateUpTo(trimMark); } r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); }
Source:
public AbstractViewTest() { // Force all new CorfuRuntimes to override the getRouterFn CorfuRuntime.overrideGetRouterFunction = this::getRouterFunction; final Duration holeFillTimeout = Duration.ofSeconds(5); runtime = CorfuRuntime.fromParameters(CorfuRuntimeParameters.builder() .nettyEventLoop(NETTY_EVENT_LOOP) .holeFillTimeout(holeFillTimeout) .build()); // Default number of times to read before hole filling to 0 // (most aggressive, to surface concurrency issues). runtime.getParameters().setHoleFillRetry(0); }

Target:
public AbstractViewTest() { // Force all new CorfuRuntimes to override the getRouterFn CorfuRuntime.overrideGetRouterFunction = this::getRouterFunction; runtime = CorfuRuntime.fromParameters(CorfuRuntimeParameters.builder() .nettyEventLoop(NETTY_EVENT_LOOP) .build()); // Default number of times to read before hole filling to 0 // (most aggressive, to surface concurrency issues). runtime.getParameters().setHoleFillRetry(0); }
Source:
public void gc(long trimMark) { Timer.Context vloGcDuration = VloMetricsHelper.getVloGcContext(); long ts = lock.writeLock(); try { pendingUpcalls.removeIf(e -> e < trimMark); upcallResults.entrySet().removeIf(e -> e.getKey() < trimMark); smrStream.gc(trimMark); } finally { lock.unlock(ts); if (vloGcDuration != null) { vloGcDuration.stop(); } } }

Target:
public void gc(long trimMark) { long ts = 0; try (Timer.Context vloGcDuration = VloMetricsHelper.getVloGcContext()) { ts = lock.writeLock(); pendingUpcalls.removeIf(e -> e < trimMark); upcallResults.entrySet().removeIf(e -> e.getKey() < trimMark); smrStream.gc(trimMark); } finally { lock.unlock(ts); } }
Source:
private long getCompactionCounter() { final Timer compactionTimer = metricRegistry.timer(StreamLogCompaction.STREAM_COMPACT_METRIC); return compactionTimer == null ? 0 : compactionTimer.getCount(); }

Target:
private long getCompactionCounter() { return metricRegistry .timer(StreamLogCompaction.STREAM_COMPACT_METRIC) .getCount(); }
Source:
public synchronized void sealServerWithEpoch(long epoch) { batchWriter.waitForSealComplete(epoch); log.info("LogUnit sealServerWithEpoch: sealed and flushed with epoch {}", epoch); }

Target:
public void sealServerWithEpoch(long epoch) { batchWriter.waitForSealComplete(epoch); log.info("LogUnit sealServerWithEpoch: sealed and flushed with epoch {}", epoch); }
Source:
public List<AbstractServer> getServers() { return ImmutableList.copyOf(servers); }

Target:
public List<AbstractServer> getServers() { return servers; }
Source:
private boolean canHandleReconfigurations() { // We check for the following condition here: If the node is NOT a part of the // current layout, it should not attempt to change layout. Layout layout = serverContext.getManagementLayout(); if (!layout.getAllServersNodes().contains(getLocalEndpoint())) { return false; } return true; }

Target:
private boolean canHandleReconfigurations() { // We check for the following condition here: If the node is NOT a part of the // current layout, it should not attempt to change layout. Layout layout = serverContext.getManagementLayout(); return layout.getAllServersNodes().contains(getLocalEndpoint()); }
Source:
public CorfuTable() { this(IndexRegistry.empty()); log.warn("CorfuTable: Creating a table without secondary indexes! Secondary index lookup" + " will fail."); }

Target:
public CorfuTable() { this(IndexRegistry.empty()); }
Source:
private void consumeOperationQueue() { // Assign a worker for each thread in the pool for (int i = 0; i < numThreads; i++) { workers.execute(() -> { while (!operationQueueLock && !operationQueue.isEmpty()) { try { Operation op = operationQueue.take(); op.execute(); } catch (Exception e) { log.error("Operation failed with", e); } } }); } }

Target:
private void consumeOperationQueue() { // Assign a worker for each thread in the pool for (int i = 0; i < numThreads; i++) { workers.execute(() -> { while (true) { if (!operationQueueLock && !operationQueue.isEmpty()) { try { Operation op = operationQueue.take(); op.execute(); } catch (Exception e) { log.error("Operation failed with", e); } } } }); } }
Source:
public void shutdown() { executor.shutdownNow(); try { executor.awaitTermination(ServerContext.SHUTDOWN_TIMER.getSeconds(), TimeUnit.SECONDS); } catch (InterruptedException ie) { log.debug("Orchestrator executor awaitTermination interrupted : {}", ie); Thread.currentThread().interrupt(); } getRuntime.cleanup(CorfuRuntime::shutdown); log.info("Orchestrator shutting down."); }

Target:
public void shutdown() { executor.shutdownNow(); try { executor.awaitTermination(ServerContext.SHUTDOWN_TIMER.getSeconds(), TimeUnit.SECONDS); } catch (InterruptedException ie) { log.debug("Orchestrator executor awaitTermination interrupted : {}", ie); Thread.currentThread().interrupt(); } log.info("Orchestrator shutting down."); }
Source:
private void updateLocalMetrics() { suppressExceptions(() -> { // Initializing the status of components // No need to poll unless node is bootstrapped. Layout layout = serverContext.copyManagementLayout(); if (layout == null) { return; } // Build and replace existing locally stored nodeMetrics localServerMetrics = new ServerMetrics(NodeLocator.parseString(getLocalEndpoint()), queryLocalSequencerMetrics(layout)); }); }

Target:
private void updateLocalMetrics() { // Initializing the status of components // No need to poll unless node is bootstrapped. Layout layout = serverContext.copyManagementLayout(); if (layout == null) { return; } // Build and replace existing locally stored nodeMetrics localServerMetrics = new ServerMetrics(NodeLocator.parseString(getLocalEndpoint()), queryLocalSequencerMetrics(layout)); }
Source:
protected UUID sendRequest(@Nonnull ManagementClient managementClient) throws TimeoutException { // Select the current tail node and send an add node request to the orchestrator CreateWorkflowResponse resp = managementClient.addNodeRequest(nodeForWorkflow); log.debug("sendRequest: requested to add on orchestrator {}:{}", nodeForWorkflow, managementClient.getRouter().getHost(), managementClient.getRouter().getPort()); return resp.getWorkflowId(); }

Target:
protected UUID sendRequest(@Nonnull ManagementClient managementClient) throws TimeoutException { // Select the current tail node and send an add node request to the orchestrator CreateWorkflowResponse resp = managementClient.addNodeRequest(nodeForWorkflow); log.info("sendRequest: requested to add on orchestrator {}:{}", nodeForWorkflow, managementClient.getRouter().getHost(), managementClient.getRouter().getPort()); return resp.getWorkflowId(); }
Source:
public boolean hasNext() { if (currInd < maxInd) { return true; } else { return false; } }

Target:
public boolean hasNext() { if (currInd.get() < maxInd.get()) { return true; } else { return false; } }
Source:
public synchronized <T> void put(Class<T> tclass, String prefix, String key, T value) { String json = JsonUtils.parser.toJson(value, tclass); T tmpVal = JsonUtils.parser.fromJson(json, tclass); DataStoreKey dsk = new DataStoreKey(getKey(prefix, key), tclass); cache.put(dsk, tmpVal); }

Target:
public synchronized <T> void put(Class<T> tclass, String prefix, String key, T value) { cache.put(getKey(prefix, key), value); }
Source:
public AddNodeWorkflow(Request request) { this.id = UUID.randomUUID(); this.request = (AddNodeRequest) request; actions = Arrays.asList(new BootstrapNode(), new AddNodeToLayout(), new StateTransfer(), new MergeSegments()); }

Target:
public AddNodeWorkflow(Request request) { this.id = UUID.randomUUID(); this.request = (AddNodeRequest) request; actions = ImmutableList.of(new BootstrapNode(), new AddNodeToLayout(), new StateTransfer(), new MergeSegments()); }
Source:
void handleQuery(CorfuPayloadMsg<OrchestratorRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { QueryRequest req = (QueryRequest) msg.getPayload().getRequest(); Response resp; if (activeWorkflows.contains(req.getId())) { resp = new QueryResponse(true); } else { resp = new QueryResponse(false); } r.sendResponse(ctx, msg, CorfuMsgType.ORCHESTRATOR_RESPONSE .payloadMsg(new OrchestratorResponse(resp ))); }

Target:
void handleQuery(CorfuPayloadMsg<OrchestratorRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { QueryRequest req = (QueryRequest) msg.getPayload().getRequest(); Response resp; if (activeWorkflows.values().contains(req.getId())) { resp = new QueryResponse(true); } else { resp = new QueryResponse(false); } r.sendResponse(ctx, msg, CorfuMsgType.ORCHESTRATOR_RESPONSE .payloadMsg(new OrchestratorResponse(resp ))); }
Source:
public Layout getCurrentLayout() { while (true) { try { return runtime.layout.get(); } catch (SystemUnavailableException sue) { throw sue; } catch (Exception ex) { log.warn("Error executing remote call, invalidating view and retrying in {}s", runtime.retryRate, ex); runtime.invalidateLayout(); try { Thread.sleep(runtime.retryRate * 1000); } catch (InterruptedException ie) { throw new UnrecoverableCorfuInterruptedError("Interrupted while fetching layout", ie); } } } }

Target:
public Layout getCurrentLayout() { while (true) { try { return runtime.layout.get(); } catch (Exception ex) { log.warn("Error executing remote call, invalidating view and retrying in {}s", runtime.retryRate, ex); runtime.invalidateLayout(); try { Thread.sleep(runtime.retryRate * 1000); } catch (InterruptedException ie) { throw new UnrecoverableCorfuInterruptedError("Interrupted while fetching layout", ie); } } } }
Source:
public Collection<Object> getByIndex(@Nonnull F indexFunction, I index) { return indexFunction.getProjectionFunction() .generateProjection(index, indexMap .getOrDefault(indexFunction, ImmutableMultimap.of()).get(index)); }

Target:
public @Nonnull Collection<Object> getByIndex(@Nonnull F indexFunction, I index) { return getByIndex(indexFunction, indexFunction.getProjectionFunction(), index); }
Source:
public V put(@ConflictParameter K key, V value) { V previous = mainMap.put(key, value); // If we have index functions, update the secondary indexes. if (indexFunctions.isEmpty()) { unmapSecondaryIndexes(key, previous); mapSecondaryIndexes(key, value); } return previous; }

Target:
public V put(@ConflictParameter K key, V value) { V previous = mainMap.put(key, value); // If we have index functions, update the secondary indexes. if (!indexFunctions.isEmpty()) { unmapSecondaryIndexes(key, previous); mapSecondaryIndexes(key, value); } return previous; }
Source:
public TrimmedException() { address = -1; }

Target:
public TrimmedException() { }
Source:
public ServerNotReadyException() { super("Server not ready to accept messages."); }

Target:
public ServerNotReadyException() { }
Source:
public synchronized long getTailSegment() { Long tailSegment = dataStore.get(Long.class, PREFIX_TAIL_SEGMENT, KEY_TAIL_SEGMENT); return tailSegment == null ? 0 : tailSegment; }

Target:
public long getTailSegment() { Long tailSegment = dataStore.get(Long.class, PREFIX_TAIL_SEGMENT, KEY_TAIL_SEGMENT); return tailSegment == null ? 0 : tailSegment; }
Source:
private synchronized void safeUpdateLayout(Layout layout) { // Cannot update with a null layout. if (layout == null) return; // Update if new layout has a higher epoch than the existing layout. // Or if the cluster ID is different. if (latestLayout == null || layout.getEpoch() > latestLayout.getEpoch() || !layout.getClusterId().equals(latestLayout.getClusterId())) { latestLayout = layout; // Persisting this new updated layout setCurrentLayout(latestLayout); } }

Target:
private synchronized void safeUpdateLayout(Layout layout) { // Cannot update with a null layout. if (layout == null) { return; } // Update only if new layout has a higher epoch than the existing layout. if (latestLayout == null || layout.getEpoch() > latestLayout.getEpoch()) { latestLayout = layout; // Persisting this new updated layout setCurrentLayout(latestLayout); } }
Source:
public <R> R access(ICorfuSMRAccess<R, T> accessMethod, Object[] conflictObject) { R value; boolean isEnabled = MetricsUtils.isMetricsCollectionEnabled(); Timer.Context context = MetricsUtils.getConditionalContext(isEnabled, timerAccess); try { value = accessInner(accessMethod, conflictObject, isEnabled); } finally { MetricsUtils.stopConditionalContext(isEnabled, context); } return value; }

Target:
public <R> R access(ICorfuSMRAccess<R, T> accessMethod, Object[] conflictObject) { boolean isEnabled = MetricsUtils.isMetricsCollectionEnabled(); try (Timer.Context context = MetricsUtils.getConditionalContext(isEnabled, timerAccess)){ return accessInner(accessMethod, conflictObject, isEnabled); } }
Source:
public CompletableFuture<Boolean> writeStream(long address, Map<UUID, Long> streamAddresses, Object object) { Timer.Context context = getTimerContext("writeStreamObject"); ByteBuf payload = ByteBufAllocator.DEFAULT.buffer(); Serializers.CORFU.serialize(object, payload); CompletableFuture<Boolean> cf = writeStream(address, streamAddresses, payload); return context == null ? cf : cf.thenApply(x -> { context.stop(); return x; }); }

Target:
public CompletableFuture<Boolean> writeStream(long address, Map<UUID, Long> streamAddresses, Object object) { Timer.Context context = getTimerContext("writeStreamObject"); ByteBuf payload = ByteBufAllocator.DEFAULT.buffer(); Serializers.CORFU.serialize(object, payload); CompletableFuture<Boolean> cf = writeStream(address, streamAddresses, payload); return cf.thenApply(x -> { context.stop(); return x; }); }
Source:
public synchronized void handleHearbeatRequest(CorfuMsg msg, ChannelHandlerContext ctx, IServerRouter r) { // Currently builds a default instance of the model. // TODO: Collect metrics from Layout, Sequencer and LogUnit Servers. NodeMetrics nodeMetrics = NodeMetrics.getDefaultInstance(); r.sendResponse(ctx, msg, new CorfuPayloadMsg<>(CorfuMsgType.HEARTBEAT_RESPONSE, nodeMetrics.toByteArray())); }

Target:
public void handleHearbeatRequest(CorfuMsg msg, ChannelHandlerContext ctx, IServerRouter r) { // Currently builds a default instance of the model. // TODO: Collect metrics from Layout, Sequencer and LogUnit Servers. NodeMetrics nodeMetrics = NodeMetrics.getDefaultInstance(); r.sendResponse(ctx, msg, new CorfuPayloadMsg<>(CorfuMsgType.HEARTBEAT_RESPONSE, nodeMetrics.toByteArray())); }
Source:
public synchronized long obtainSnapshotTimestamp() { AbstractTransactionalContext atc = getRootContext(); if (atc != null && atc != this) { // If we're in a nested transaction, the first read timestamp // needs to come from the root. return atc.getSnapshotTimestamp(); } else { // Otherwise, fetch a read token from the sequencer the linearize // ourselves against. long currentTail = builder.runtime .getSequencerView().nextToken(Collections.emptySet(), 0).getToken(); log.trace("Set first read timestamp for tx to {}", transactionID, currentTail); return currentTail; } }

Target:
public synchronized long obtainSnapshotTimestamp() { final AbstractTransactionalContext atc = getRootContext(); if (atc != null && atc != this) { // If we're in a nested transaction, the first read timestamp // needs to come from the root. return atc.getSnapshotTimestamp(); } else { // Otherwise, fetch a read token from the sequencer the linearize // ourselves against. long currentTail = builder.runtime .getSequencerView().nextToken(Collections.emptySet(), 0).getToken(); log.trace("Set first read timestamp for tx to {}", transactionID, currentTail); return currentTail; } }
Source:
public void shutdown() { // Shutting the fault detector. isShutdown = true; failureDetectorService.shutdownNow(); // Shut down the Corfu Runtime. if (corfuRuntime != null) { corfuRuntime.shutdown(); } try { failureDetectorService.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException ie) { log.debug("failureDetectorService awaitTermination interrupted : {}", ie); } }

Target:
public void shutdown() { // Shutting the fault detector. failureDetectorService.shutdownNow(); // Shut down the Corfu Runtime. if (corfuRuntime != null) { corfuRuntime.shutdown(); } try { failureDetectorService.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException ie) { log.debug("failureDetectorService awaitTermination interrupted : {}", ie); } }
Source:
public Set<Type> getImportTypes() { Set<Type> types = new HashSet<Type>(); for ( MapperReference mapperReference : mapperReferences ) { types.add( mapperReference.getType() ); } for ( Annotation annotation : annotations ) { types.add( annotation.getType() ); } return types; }

Target:
public Set<Type> getImportTypes() { Set<Type> types = new HashSet<Type>(); for ( MapperReference mapperReference : mapperReferences ) { types.addAll( mapperReference.getImportTypes() ); } for ( Annotation annotation : annotations ) { types.addAll( annotation.getImportTypes() ); } return types; }
Source:
public Parameter(String name, Type type, boolean mappingTarget, boolean targetType, boolean mappingContext) { // issue #909: FreeMarker doesn't like "values" as a parameter name this.name = "values".equals( name ) ? "values_" : name; this.originalName = name; this.type = type; this.mappingTarget = mappingTarget; this.targetType = targetType; this.mappingContext = mappingContext; }

Target:
private Parameter(String name, Type type, boolean mappingTarget, boolean targetType, boolean mappingContext) { // issue #909: FreeMarker doesn't like "values" as a parameter name this.name = "values".equals( name ) ? "values_" : name; this.originalName = name; this.type = type; this.mappingTarget = mappingTarget; this.targetType = targetType; this.mappingContext = mappingContext; }
Source:
private static Node provisionNewNode(final CloudProvisioningRecord whatWeShouldSpinUp, final String cloneName) throws VSphereException, FormException, IOException, InterruptedException { final vSphereCloudSlaveTemplate template = whatWeShouldSpinUp.getTemplate(); final vSphereCloudProvisionedSlave slave = template.provision(cloneName, StreamTaskListener.fromStdout()); // ensure Jenkins knows about us before we forget what we're doing, // otherwise it'll just ask for more. Jenkins.get().addNode(slave); return slave; }

Target:
private static Node provisionNewNode(final CloudProvisioningRecord whatWeShouldSpinUp, final String cloneName) throws VSphereException, FormException, IOException, InterruptedException { final vSphereCloudSlaveTemplate template = whatWeShouldSpinUp.getTemplate(); final vSphereCloudProvisionedSlave slave = template.provision(cloneName, StreamTaskListener.fromStdout()); // ensure Jenkins knows about us before we forget what we're doing, // otherwise it'll just ask for more. Jenkins.getInstance().addNode(slave); return slave; }
Source:
public void setup() { // disable auto init of timers since ejb timer service supports persistence of timers System.setProperty("org.jbpm.rm.init.timer", "false"); logger.info("Using local cache for EJB timers: {}", (USE_LOCAL_CACHE ? "true" : "false")); }

Target:
public void setup() { // disable auto init of timers since ejb timer service supports persistence of timers System.setProperty("org.jbpm.rm.init.timer", "false"); logger.info("Using local cache for EJB timers: {}", USE_LOCAL_CACHE); }
Source:
public void cleanup() { cleanupSingletonSessionId(); if (units != null && !units.isEmpty()) { for (DeploymentUnit unit : units) { try { deploymentService.undeploy(unit); } catch (Exception e) { // do nothing in case of some failed tests to avoid next test to fail as well logger.error("---------------------------" + e.getLocalizedMessage()); logger.error("--do nothing in case of some failed tests to avoid next test to fail as well-------------------------" + unit.getIdentifier()); } } units.clear(); } close(); }

Target:
public void cleanup() { cleanupSingletonSessionId(); if (units != null && !units.isEmpty()) { for (DeploymentUnit unit : units) { try { deploymentService.undeploy(unit); } catch (Exception e) { // do nothing in case of some failed tests to avoid next test to fail as well } } units.clear(); } close(); }
Source:
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { try { manager.completeWorkItem(workItem.getId(), null); } catch(Throwable cause) { handleException(cause); manager.abortWorkItem(workItem.getId()); } }

Target:
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { try { // handler impl here manager.completeWorkItem(workItem.getId(), null); } catch(Throwable cause) { handleException(cause); } }
Source:
public String getVersionChanges(String versionStr) { Map<String, String> depends = new HashMap<>(); JSONObject version = versions.getJSONObject(versionStr); if (version.containsKey("changes")) { return version.getString("changes"); } return null; }

Target:
public String getVersionChanges(String versionStr) { JSONObject version = versions.getJSONObject(versionStr); return version.containsKey("changes") ? version.getString("changes") : null; }
Source:
public void stop() { LOG.debug("Shutting down Zuul."); serverGroup.stop(); // remove the shutdown hook that was added when the proxy was started, since it has now been stopped try { Runtime.getRuntime().removeShutdownHook(jvmShutdownHook); } catch (IllegalStateException e) { // This can happen if the VM is already shutting down LOG.debug("Failed to remove shutdown hook", e); } LOG.debug("Completed zuul shutdown."); }

Target:
public void stop() { LOG.info("Shutting down Zuul."); serverGroup.stop(); // remove the shutdown hook that was added when the proxy was started, since it has now been stopped try { Runtime.getRuntime().removeShutdownHook(jvmShutdownHook); } catch (IllegalStateException e) { // This can happen if the VM is already shutting down LOG.debug("Failed to remove shutdown hook", e); } LOG.info("Completed zuul shutdown."); }
Source:
public String getDefaultApp(Set<String> supportedApps) { String defaultApp = getAut(); if (getLaunchActivity() == null) { if (!defaultApp.contains(":")) { // App version is not specified. Get the latest version from the apps store. defaultApp = getDefaultVersion(supportedApps, defaultApp); } else { defaultApp = supportedApps.contains(defaultApp) ? defaultApp : null; } } return defaultApp; }

Target:
public String getDefaultApp(Set<String> supportedApps) { String defaultApp = getAut(); // if the launch activity is specified, just return. if (getLaunchActivity() != null) { return defaultApp; } // App version is not specified. Get the latest version from the apps store. if (!defaultApp.contains(":")) { return getDefaultVersion(supportedApps, defaultApp); } return supportedApps.contains(defaultApp) ? defaultApp : null; }
Source:
public void regexValidationFailsIfLengthMoreThan255(){ SpamRuleDto spamRuleDto = randomSpamRuleDto().setRegex(alphanumeric(256)); Set<ConstraintViolation<SpamRuleDto>> constraintViolations = validator.validate(spamRuleDto); Assert.assertEquals(constraintViolations.size(), 1); }

Target:
public void regexValidationFailsIfLengthMoreThan255(){ SpamRuleDto spamRuleDto = randomSpamRuleDto().setRegex(alphanumeric(256)); Set<ConstraintViolation<SpamRuleDto>> constraintViolations = validator.validate(spamRuleDto); assertEquals(constraintViolations.size(), 1); }
Source:
public GroupDto(Group group) { this.id = group.getId(); this.name = group.getName(); this.users = UserDto.convertToUserDtoList(group.getUsers()); }

Target:
public GroupDto(Group group) { this.id = group.getId(); this.name = group.getName(); }
Source:
private void store(Map.Entry<RepositoryPath, Path> e) { try (InputStream is = Files.newInputStream(e.getValue())) { artifactManagementService.store(e.getKey(), is); } catch (IOException ioe) { throw new UndeclaredThrowableException(ioe); } ThrowingConsumer.unchecked(Files::delete).accept(e.getValue()); }

Target:
private void store(Map.Entry<RepositoryPath, Path> e) throws IOException { try (InputStream is = Files.newInputStream(e.getValue())) { artifactManagementService.store(e.getKey(), is); } catch (IOException ioe) { throw new UndeclaredThrowableException(ioe); } Files.delete(e.getValue()); }
Source:
private Object doInit() { MutableConfiguration configuration; try { configuration = configurationFileManager.read(); setConfiguration(configuration); setRepositoryArtifactCoordinateValidators(); } catch (IOException e) { throw new org.springframework.cglib.proxy.UndeclaredThrowableException(e); } return null; }

Target:
private Object doInit() { MutableConfiguration configuration; try { configuration = configurationFileManager.read(); setConfiguration(configuration); setRepositoryArtifactCoordinateValidators(); } catch (IOException e) { throw new UndeclaredThrowableException(e); } return null; }
Source:
public void testValidDoubleQuotedQuerySpecificChars() { String query = "repository: \"releases#1\""; AqlQueryParser aqlParser = new AqlQueryParser(query); Map<Pair<Integer, Integer>, String> errorMap = null; aqlParser.parseQuery(); logger.info(String.format("Query [%s] parse tree:\n[%s]", query, aqlParser)); assertFalse(aqlParser.hasErrors()); assertNull(errorMap); }

Target:
public void testValidDoubleQuotedQuerySpecificChars() { String query = "repository: \"releases#1\""; AqlQueryParser aqlParser = new AqlQueryParser(query); aqlParser.parseQuery(); logger.info(String.format("Query [%s] parse tree:\n[%s]", query, aqlParser)); assertFalse(aqlParser.hasErrors()); }
Source:
public final void run() { try (CloseableRestResponse response = artifactResolver.get(url)) { // Left empty because the original method had no other logic than the now-removed // closure of a CloseableRestResponse } catch (Exception e) { LOGGER.error(e.getMessage(), e); } }

Target:
public final void run() { try (CloseableRestResponse response = artifactResolver.get(url)) { // Left empty because the original method had no other logic than the now-removed // closure of a CloseableRestResponse } catch (Exception e) { logger.error(e.getMessage(), e); } }
Source:
public void generate(Artifact artifact, String packaging) throws IOException, XmlPullParserException, NoSuchAlgorithmException { synchronized (ArtifactUtils.convertArtifactToPath(artifact)) { generatePom(artifact, packaging); createArchive(artifact); } }

Target:
public void generate(Artifact artifact, String packaging) throws IOException, NoSuchAlgorithmException { generatePom(artifact, packaging); createArchive(artifact); }
Source:
public void deleteJob(String cronTaskConfigurationName) { TriggerKey triggerKey = TriggerKey.triggerKey(cronTaskConfigurationName); JobKey jobKey = JobKey.jobKey(cronTaskConfigurationName); try { scheduler.unscheduleJob(triggerKey); scheduler.deleteJob(jobKey); } catch (SchedulerException e) { logger.error(String.format("Failed to delete cron job [%s]", jobKey)); } logger.debug("Job '" + cronTaskConfigurationName + "' un-scheduled."); }

Target:
public void deleteJob(String cronTaskConfigurationName) { JobKey jobKey = JobKey.jobKey(cronTaskConfigurationName); try { scheduler.deleteJob(jobKey); } catch (SchedulerException e) { logger.error(String.format("Failed to delete cron job [%s]", jobKey)); } logger.debug("Job '" + cronTaskConfigurationName + "' un-scheduled."); }
Source:
public void store(final Configuration configuration) { try { Resource configurationResource = getConfigurationResource(); //Check that target resource stored on FS and not under classpath for example if (!configurationResource.isFile()) { LOGGER.warn(String.format("Skip configuration resource store [%s]", configurationResource)); return; } parser.store(configuration, configurationResource.getFile()); } catch (JAXBException | IOException e) { throw new ConfigurationSaveException(e); } }

Target:
public void store(final Configuration configuration) { try { parser.store(configuration, getConfigurationResource()); } catch (JAXBException | IOException e) { throw new ConfigurationSaveException(e); } }
Source:
public List<ArtifactEntry> findByCoordinates(Map<String, String> coordinates) { if (coordinates == null || coordinates.keySet() .isEmpty()) { return findAll().orElse(Collections.EMPTY_LIST); } // prepare custom query based on all non-null coordinates that were joined by logical AND // read more about fetching strategies here: http://orientdb.com/docs/2.2/Fetching-Strategies.html String nativeQuery = buildQuery(coordinates); OSQLSynchQuery<ArtifactEntry> query = new OSQLSynchQuery<>(nativeQuery); logger.info("[findByCoordinates] SQL -> \n\t" + nativeQuery); List<ArtifactEntry> resultList = getDelegate().query(query); return resultList; }

Target:
public List<ArtifactEntry> findByCoordinates(Map<String, String> coordinates) { if (coordinates == null || coordinates.keySet() .isEmpty()) { return findAll().orElse(Collections.EMPTY_LIST); } // prepare custom query based on all non-null coordinates that were joined by logical AND // read more about fetching strategies here: http://orientdb.com/docs/2.2/Fetching-Strategies.html String nativeQuery = buildQuery(coordinates); OSQLSynchQuery<ArtifactEntry> query = new OSQLSynchQuery<>(nativeQuery); logger.info("[findByCoordinates] SQL -> \n\t" + nativeQuery); return getDelegate().query(query); }
Source:
private static RepositoryPath rebase(RepositoryPath source, RepositoryPath targetBase) { FileSystem sourceFileSystem = source.getTarget().getFileSystem(); FileSystem targetFileSystem = targetBase.getTarget().getFileSystem(); String sourceRelative = source.getRoot() .relativize(source.getTarget()) .toString(); // sbespalov: We try to convert path form source to target FileSystem // sbespalov: Need to check this on different Storage types. String sTargetPath = sourceRelative.replaceAll(sourceFileSystem.getSeparator(), targetFileSystem.getSeparator()); RepositoryPath target = targetBase.resolve(sTargetPath); return target; }

Target:
private static RepositoryPath rebase(RepositoryPath source, RepositoryPath targetBase) { FileSystem sourceFileSystem = source.getTarget().getFileSystem(); FileSystem targetFileSystem = targetBase.getTarget().getFileSystem(); String sourceRelative = source.getRoot() .relativize(source.getTarget()) .toString(); // XXX[SBESPALOV]: We try to convert path form source to target FileSystem and need to check this on different // Storage types. // Note that this is only draft implementation, and probably in the future we will need something like separate // `FileSystemPathConverter` to convert Paths from one FileSystem to another. Such `FileSystemPathConverter` can // be provided by the `ReposytoryFileSystem` instance. String sTargetPath = sourceRelative.replaceAll(sourceFileSystem.getSeparator(), targetFileSystem.getSeparator()); return targetBase.resolve(sTargetPath); }
Source:
AggregateModel<T> buildAggregateModel() { if (aggregateModel == null) { return inspectAggregateModel(); } else { return aggregateModel; } }

Target:
protected AggregateModel<T> buildAggregateModel() { if (aggregateModel == null) { return inspectAggregateModel(); } else { return aggregateModel; } }
Source:
public boolean emit(U update) { // this is empty implementation, since regular query handler will not invoke it return true; }

Target:
public boolean emit(U update) { // this is empty implementation, since regular query handler will not invoke it return false; }
Source:
public boolean complete() { // this is empty implementation, since regular query handler will not invoke it return true; }

Target:
public void complete() { // this is empty implementation, since regular query handler will not invoke it }
Source:
public boolean error(Throwable error) { // this is empty implementation, since regular query handler will not invoke it return true; }

Target:
public void error(Throwable error) { // this is empty implementation, since regular query handler will not invoke it }
Source:
public double calculatePacketLoss( NetworkStatistics previousStats, NetworkStatistics currentStats, String switchName, String portId, long previousTimestamp, long currentTimestamp) throws Exception { // pk_loss = (receiveDropped(t1) + receiveErrors(t1) + receiveFrameErrors(t1) + receiveOverrunErrors(t1) + receiveCRCErrors(t1) - // (receiveDropped(t0) + receiveErrors(t0) + receiveFrameErrors(t0) + receiveOverrunErrors(t0) + receiveCRCErrors(t0))) / // (receivePacket(t1) - receivePackets(t0)) long currentReceiveErrors = getPortReceiveErrors(currentStats, switchName, portId); long previousReceiveErrors = getPortReceiveErrors(currentStats, switchName, portId); long currentReceivedPackets = getPortReceivedPackets(currentStats, switchName, portId); long previousReceivedPackets = getPortReceivedPackets(currentStats, switchName, portId); if (currentReceivedPackets == previousReceivedPackets) return 0; return (currentReceiveErrors - previousReceiveErrors) / (currentReceivedPackets - previousReceivedPackets); }

Target:
public double calculatePacketLoss( NetworkStatistics previousStats, NetworkStatistics currentStats, String switchName, String portId, long previousTimestamp, long currentTimestamp) throws Exception { // pk_loss = (receiveDropped(t1) + receiveErrors(t1) + receiveFrameErrors(t1) + receiveOverrunErrors(t1) + receiveCRCErrors(t1) - // (receiveDropped(t0) + receiveErrors(t0) + receiveFrameErrors(t0) + receiveOverrunErrors(t0) + receiveCRCErrors(t0))) / // (receivePacket(t1) - receivePackets(t0)) long currentReceiveErrors = getPortReceiveErrors(currentStats, switchName, portId); long previousReceiveErrors = getPortReceiveErrors(previousStats, switchName, portId); long currentReceivedPackets = getPortReceivedPackets(currentStats, switchName, portId); long previousReceivedPackets = getPortReceivedPackets(previousStats, switchName, portId); if (currentReceivedPackets == previousReceivedPackets) return 0; return (currentReceiveErrors - previousReceiveErrors) / (currentReceivedPackets - previousReceivedPackets); }
Source:
public void configureOSPF(OSPFService ospfService) throws CapabilityException { IAction action = createActionAndCheckParams(OSPFActionSet.OSPF_CONFIGURE, ospfService); ospfService.setEnabledState(EnabledState.DISABLED); // mark OSPF as disabled, we are configuring only queueAction(action); }

Target:
public void configureOSPF(OSPFService ospfService) throws CapabilityException { ospfService.setEnabledState(EnabledState.DISABLED); // mark OSPF as disabled, we are configuring only IAction action = createActionAndCheckParams(OSPFActionSet.OSPF_CONFIGURE, ospfService); queueAction(action); }
Source:
public void testVertexCentricQuery() { int noVertices = 10000; }

Target:
public void testVertexCentricQuery() { testVertexCentricQuery(10000 /*noVertices*/); }
Source:
private List<String> visitInvocationArguments(AbstractInvocation invocation) { List<String> argumentNames = new ArrayList<>(); for (ExpressionStatement argument : invocation.getArguments()) { if (invocation instanceof FunctionInvocation && ((FunctionInvocation) invocation).usesNamedArguments()) { NamedArgument namedArgument = (NamedArgument) argument; argumentNames.add(namedArgument.getName()); argument = namedArgument.getExpression(); } argument.accept(this); } return argumentNames; }

Target:
private List<String> visitInvocationArguments(AbstractInvocation invocation) { List<String> argumentNames = new ArrayList<>(); for (ExpressionStatement argument : invocation.getArguments()) { if (invocation.usesNamedArguments()) { NamedArgument namedArgument = (NamedArgument) argument; argumentNames.add(namedArgument.getName()); argument = namedArgument.getExpression(); } argument.accept(this); } return argumentNames; }
Source:
public <T> AttributeRenderer<? super T> getAttributeRenderer(Class<? extends T> attributeType) { if ( renderers==null ) { return null; } //noinspection unchecked return renderers.get(attributeType); }

Target:
public <T> AttributeRenderer<? super T> getAttributeRenderer(Class<? extends T> attributeType) { if ( renderers==null ) { return null; } //noinspection unchecked return (AttributeRenderer<? super T>) renderers.get(attributeType); }
Source:
public String toString(Object o, String formatString, Locale locale) { // o will be instanceof Number if ( formatString==null ) return o.toString(); Formatter f = new Formatter(locale); f.format(formatString, o); String str = f.toString(); f.close(); return str; }

Target:
public String toString(Object o, String formatString, Locale locale) { // o will be instanceof Number if ( formatString==null ) return o.toString(); Formatter f = new Formatter(locale); try { f.format(formatString, o); return f.toString(); } finally { f.close(); } }
Source:
public String toString(Object o, String formatString, Locale locale) { // o will be instanceof Number if ( formatString==null ) return o.toString(); Formatter f = null; String str = ""; try { f = new Formatter(locale); f.format(formatString, o); str = f.toString(); } finally { if (f != null) f.close(); } return str; }

Target:
public String toString(Object o, String formatString, Locale locale) { // o will be instanceof Number if ( formatString==null ) return o.toString(); Formatter f = new Formatter(locale); try { f.format(formatString, o); return f.toString(); } finally { f.close(); } }
Source:
protected void onResume() { super.onResume(); if (mAppAdapter != null) mAppAdapter.notifyDataSetChanged(); // Set up the progress bar final View vProgressEmpty = (View) findViewById(R.id.vProgressEmpty); vProgressEmpty.post(new Runnable() { @Override public void run() { mProgressWidth = vProgressEmpty.getMeasuredWidth(); updateProgress(); } }); }

Target:
protected void onResume() { super.onResume(); if (mAppAdapter != null) mAppAdapter.notifyDataSetChanged(); }
Source:
public synchronized void sendUpdates(Map<String, Object> state, Set<String> changed) { if (state.get("ScoreBoard.CurrentPeriodNumber") != "0") { // If the jam has just ended or the score is now official, write out a file. if ((inJam && !bool(state.get("ScoreBoard.InJam"))) || (bool(state.get("ScoreBoard.OfficialScore")) && !bool(state.get("ScoreBoard.StatsLocked")) && containsRelevantUpdate(changed))) { writeFile(state); } } inJam = bool(state.get("ScoreBoard.InJam")); }

Target:
public synchronized void sendUpdates(Map<String, Object> state, Set<String> changed) { if (state.get("ScoreBoard.CurrentPeriodNumber") != "0") { // If the jam has just ended or the score is now official, write out a file. if ((inJam && !bool(state.get("ScoreBoard.InJam"))) || (bool(state.get("ScoreBoard.OfficialScore")) && containsRelevantUpdate(changed))) { writeFile(state); } } inJam = bool(state.get("ScoreBoard.InJam")); }
Source:
protected void initializeType(File typeDir) { Iterator<File> files = Arrays.asList(typeDir.listFiles((FileFilter)mediaFileFilter)).iterator(); while (files.hasNext()) addMediaElement(typeDir.getName(), files.next()); // Ensure we have an entry, even if dir is empty. synchronized (updateLock) { update(createTypeElement(typeDir.getName())); } }

Target:
protected void initializeType(File typeDir) { Iterator<File> files = Arrays.asList(typeDir.listFiles((FileFilter)mediaFileFilter)).iterator(); while (files.hasNext()) { addMediaElement(typeDir.getName(), files.next()); } // Ensure we have an entry, even if dir is empty. synchronized (updateLock) { update(createTypeElement(typeDir.getName())); } }
Source:
public HCatClient getHCatClient() throws InterruptedException { HCatClient hcatClient = null; int retryCount = 0; while (hcatClient == null && retryCount < numOfRetries) { hcatClient = hcatUtil.getHCatClient(); retryCount++; } return hcatClient; }

Target:
protected HCatClient getHCatClient() throws InterruptedException { return hcatUtil.getHCatClient(); }
Source:
private ForkliftConsumerI getGroupedTopic(GroupedTopicSource source) throws ConnectorException { if (!source.groupSpecified()) throw new ConnectorException("No consumer group specified"); // Sanitize the group and topic names so that group and topic names don't accidentally // mess up ActiveMQ's pattern matching final String groupName = source.getGroup().replaceAll("\\.", "_"); final String topicName = source.getName().replaceAll("\\.", "_"); return getConsumerForSource(new QueueSource("Consumer." + groupName + ".VirtualTopic." + topicName)); }

Target:
private ForkliftConsumerI getGroupedTopic(GroupedTopicSource source) throws ConnectorException { if (!source.groupSpecified()) throw new ConnectorException("No consumer group specified"); // Sanitize the group and topic names so that group and topic names don't accidentally // mess up ActiveMQ's pattern matching (e.g. by making a group name of // "test.VirtualTopic.blah" and a topic of "topic", which would cause AMQ to look for a topic // named "blah.VirtualTopic.topic" and a group of "test") final String groupName = source.getGroup().replaceAll("\\.", "_"); final String topicName = source.getName(); return getConsumerForSource(new QueueSource("Consumer." + groupName + ".VirtualTopic." + topicName)); }
Source:
protected byte[] searchRaw(Query query) throws AlgoliaException { String paramsString = query.getQueryString(); if (paramsString.length() > 0) return client.getRequestRaw("/1/indexes/" + encodedIndexName + "?" + paramsString, true); else return client.getRequestRaw("/1/indexes/" + encodedIndexName, true); }

Target:
protected byte[] searchRaw(Query query) throws AlgoliaException { String paramsString = query.getQueryString(); if (paramsString.length() > 0) { return client.getRequestRaw("/1/indexes/" + encodedIndexName + "?" + paramsString, true); } else { return client.getRequestRaw("/1/indexes/" + encodedIndexName, true); } }
Source:
protected void finalize() throws Throwable { super.finalize(); // if we haven't done so, release the exported object on the remote side. // if the object is auto-unexported, the export entry could have already been removed. if(channel!=null) { channel.send(new Unexport(channel.newIoId(),oid)); oid = -1; } }

Target:
protected void finalize() throws Throwable { super.finalize(); // if we haven't done so, release the exported object on the remote side. // if the object is auto-unexported, the export entry could have already been removed. if(channel != null && oid != -1) { channel.send(new Unexport(channel.newIoId(),oid)); oid = -1; } }
Source:
/*package*/ static ClassFilter createDefaultInstance() { List<Pattern> patternOverride = loadPatternOverride(); try { if (patternOverride != null) { LOGGER.log(Level.FINE, "Using user specified overrides for class blacklisting"); return new RegExpClassFilter(patternOverride); } else { LOGGER.log(Level.FINE, "Using default in built class blacklisting"); return new RegExpClassFilter(DEFAULT_PATTERNS); } } catch (Error e) { // when being used by something like XStream the actual cause gets swallowed LOGGER.log(Level.SEVERE, "Failed to initialize the default class filter", e); throw e; } }

Target:
/*package*/ static ClassFilter createDefaultInstance() { try { List<Pattern> patternOverride = loadPatternOverride(); if (patternOverride != null) { LOGGER.log(Level.FINE, "Using user specified overrides for class blacklisting"); return new RegExpClassFilter(patternOverride); } else { LOGGER.log(Level.FINE, "Using default in built class blacklisting"); return new RegExpClassFilter(DEFAULT_PATTERNS); } } catch (Error e) { // when being used by something like XStream the actual cause gets swallowed LOGGER.log(Level.SEVERE, "Failed to initialize the default class filter", e); throw e; } }