auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Attendance resolveSectionFk(Attendance a, SchoolDay schoolDay, PsAttendance psAttendance) { if (null != schoolDay) { Cycle cycleDay = schoolCycles.get(schoolDay.getCycleId()); if (null != periods.get(psAttendance.periodid)) { Long periodNumber = periods.get(psAttendance.periodid).period_number; String letter = cycleDay.getLetter(); Set<Section> sections = studentClasses.get(Long.valueOf(student.getSourceSystemId())); if (null != sections) { for (Section section : sections) { Map<String, ArrayList<Long>> expression = section.getExpression(); if (null != expression) { if (null != expression.get(letter)) { for (Long sectionPeriod : expression.get(letter)) { if (sectionPeriod.equals(periodNumber) && schoolDay.getDate().isAfter(section.getStartDate()) && schoolDay.getDate().isBefore(section.getEndDate())) { a.setSectionId(section.getId()); } } } } } } } } return a; }

Target:
protected Attendance resolveSectionFk(Attendance a, SchoolDay schoolDay, PsAttendance psAttendance) { if (null != schoolDay) { PsCycle cycleDay = schoolCycles.get(schoolDay.getCycleId()); if (null != periods.get(psAttendance.periodid)) { Long periodNumber = periods.get(psAttendance.periodid).period_number; String letter = cycleDay.letter; Set<Section> sections = studentClasses.get(student.getId()); if (null != sections) { for (Section section : sections) { Map<String, ArrayList<Long>> expression = section.getExpression(); if (null != expression) { if (null != expression.get(letter)) { for (Long sectionPeriod : expression.get(letter)) { if (sectionPeriod.equals(periodNumber) && (schoolDay.getDate().isAfter(section.getStartDate()) || schoolDay.getDate().equals(section.getStartDate())) && (schoolDay.getDate().isBefore(section.getEndDate()) || schoolDay.getDate().equals(section.getEndDate())) ){ a.setSection(section); } } } } } } } } return a; }
Source:
public void deleteBox(Box box) throws IOException { authorizationManager.throwIfNotWritable(box); if (boxStore != null) { if (!boxStore.remove(box)) { throw new IOException("Unable to delete box."); } } else { throw new IOException("No boxStore available. Check that it has been declared in the Spring config."); } }

Target:
public void deleteBox(Box box) throws IOException { authorizationManager.throwIfNotWritable(box); if (!boxStore.remove(box)) { throw new IOException("Unable to delete box."); } }
Source:
public void start() throws LifecycleException { super.start(); if (jestClient == null) { log.info("Create a jest elastic search client for connection url [{}]", connectionUrl); JestClientFactory factory = new JestClientFactory(); factory.setHttpClientConfig( new HttpClientConfig.Builder(connectionUrl) .multiThreaded(true) .build()); jestClient = factory.getObject(); } else { log.info("Note: using injected jestClient instead of creating a new one: [{}]", jestClient); } createMapping(jestClient, indexName, TYPE_NAME); }

Target:
public void start() throws LifecycleException { super.start(); try { createMappingIfNeeded(jestClient, indexName, ELASTIC_TYPE_NAME); } catch (Exception e) { throw new LifecycleException("Failed to create elastic mapping.", e); } }
Source:
public void handle(Context withinContext) throws Exception { LOG.info("Processing#{} CREATE_TABLE message : {}", fromEventId(), eventMessageAsJSON); org.apache.hadoop.hive.metastore.api.Table tobj = eventMessage.getTableObj(); if (tobj == null) { LOG.debug("Event#{} was a CREATE_TABLE_EVENT with no table listed", fromEventId()); return; } Table qlMdTable = new Table(tobj); if (!Utils.shouldReplicate(withinContext.replicationSpec, qlMdTable, true, withinContext.getTablesForBootstrap(), withinContext.oldReplScope, withinContext.hiveConf)) { return; } if (qlMdTable.isView()) { withinContext.replicationSpec.setIsMetadataOnly(true); } if (withinContext.hiveConf.getBoolVar(HiveConf.ConfVars.REPL_DUMP_METADATA_ONLY) || (qlMdTable.getTableType().equals(TableType.EXTERNAL_TABLE) && withinContext.hiveConf.getBoolVar( HiveConf.ConfVars.REPL_DUMP_METADATA_ONLY_FOR_EXTERNAL_TABLE))) { qlMdTable.setStatsStateLikeNewTable(); } Path metaDataPath = new Path(withinContext.eventRoot, EximUtil.METADATA_NAME); EximUtil.createExportDump( metaDataPath.getFileSystem(withinContext.hiveConf), metaDataPath, qlMdTable, null, withinContext.replicationSpec, withinContext.hiveConf); Path dataPath = new Path(withinContext.eventRoot, "data"); Iterable<String> files = eventMessage.getFiles(); if (files != null) { try (BufferedWriter fileListWriter = writer(withinContext, dataPath)) { for (String file : files) { fileListWriter.write(file + "\n"); } } } withinContext.createDmd(this).write(); }

Target:
public void handle(Context withinContext) throws Exception { LOG.info("Processing#{} CREATE_TABLE message : {}", fromEventId(), eventMessageAsJSON); org.apache.hadoop.hive.metastore.api.Table tobj = eventMessage.getTableObj(); if (tobj == null) { LOG.debug("Event#{} was a CREATE_TABLE_EVENT with no table listed", fromEventId()); return; } Table qlMdTable = new Table(tobj); if (!Utils.shouldReplicate(withinContext.replicationSpec, qlMdTable, true, withinContext.getTablesForBootstrap(), withinContext.oldReplScope, withinContext.hiveConf)) { return; } if (qlMdTable.isView()) { withinContext.replicationSpec.setIsMetadataOnly(true); } if (Utils.shouldDumpMetaDataOnly(qlMdTable, withinContext.hiveConf)) { qlMdTable.setStatsStateLikeNewTable(); } Path metaDataPath = new Path(withinContext.eventRoot, EximUtil.METADATA_NAME); EximUtil.createExportDump( metaDataPath.getFileSystem(withinContext.hiveConf), metaDataPath, qlMdTable, null, withinContext.replicationSpec, withinContext.hiveConf); Path dataPath = new Path(withinContext.eventRoot, "data"); Iterable<String> files = eventMessage.getFiles(); if (files != null) { try (BufferedWriter fileListWriter = writer(withinContext, dataPath)) { for (String file : files) { fileListWriter.write(file + "\n"); } } } withinContext.createDmd(this).write(); }
Source:
private ReadPacket read(int numOfBytes) { byte[] response = new byte[numOfBytes]; int len; try { response = mSerialDevice.read(numOfBytes, IO_TIMEOUT); len = response.length; log.debug("Read " + len + " byte(s) complete."); Thread.sleep(100); String bytes = ""; int readAmount = len; for (int i = 0; i < readAmount; i++) bytes += String.format("%02x", response[i]) + " "; log.debug("Read data: " + bytes); } catch (IOException e) { log.error("Unable to read from serial device.", e); } catch (InterruptedException e) { e.printStackTrace(); } return new ReadPacket(response); }

Target:
private ReadPacket read(int numOfBytes) { byte[] response = new byte[numOfBytes]; int len; try { response = mSerialDevice.read(numOfBytes, IO_TIMEOUT); len = response.length; log.debug("Read byte(s) complete.", len); Thread.sleep(100); String bytes = ""; int readAmount = len; for (int i = 0; i < readAmount; i++) bytes += String.format("%02x", response[i]) + " "; log.debug("Read data: {}", bytes); } catch (IOException e) { log.error("Unable to read from serial device. {}", e); } catch (InterruptedException e) { e.printStackTrace(); } return new ReadPacket(response); }
Source:
public ListenableFuture<Void> uploadBlobAsync( Digest digest, Chunker chunker, boolean forceUpload) { synchronized (lock) { checkState(!isShutdown, "Must not call uploadBlobs after shutdown."); if (!forceUpload && uploadedBlobs.contains(digest)) { return Futures.immediateFuture(null); } ListenableFuture<Void> inProgress = uploadsInProgress.get(digest); if (inProgress != null) { return inProgress; } ListenableFuture<Void> uploadResult = Futures.transform( startAsyncUpload(digest, chunker), (v) -> { synchronized (lock) { uploadedBlobs.add(digest); } return null; }, MoreExecutors.directExecutor()); uploadResult = Futures.catchingAsync( uploadResult, StatusRuntimeException.class, (sre) -> Futures.immediateFailedFuture( new IOException( String.format( "Error while uploading artifact with digest '%s/%s'", digest.getHash(), digest.getSizeBytes()), sre)), MoreExecutors.directExecutor()); uploadsInProgress.put(digest, uploadResult); uploadResult.addListener( () -> { synchronized (lock) { uploadsInProgress.remove(digest); } }, MoreExecutors.directExecutor()); return uploadResult; } }

Target:
public ListenableFuture<Void> uploadBlobAsync( Digest digest, Chunker chunker, boolean forceUpload) { synchronized (lock) { checkState(!isShutdown, "Must not call uploadBlobs after shutdown."); if (!forceUpload && uploadedBlobs.contains(HashCode.fromString(digest.getHash()))) { return Futures.immediateFuture(null); } ListenableFuture<Void> inProgress = uploadsInProgress.get(digest); if (inProgress != null) { return inProgress; } ListenableFuture<Void> uploadResult = Futures.transform( startAsyncUpload(digest, chunker), (v) -> { synchronized (lock) { uploadedBlobs.add(HashCode.fromString(digest.getHash())); } return null; }, MoreExecutors.directExecutor()); uploadResult = Futures.catchingAsync( uploadResult, StatusRuntimeException.class, (sre) -> Futures.immediateFailedFuture( new IOException( String.format( "Error while uploading artifact with digest '%s/%s'", digest.getHash(), digest.getSizeBytes()), sre)), MoreExecutors.directExecutor()); uploadsInProgress.put(digest, uploadResult); uploadResult.addListener( () -> { synchronized (lock) { uploadsInProgress.remove(digest); } }, MoreExecutors.directExecutor()); return uploadResult; } }
Source:
private void runAutodefineForOneProvider(Guid providerId, int index) { Network externalNetwork = createExternalNetwork(getNetworkName(index), providerId, EXTERNAL_DESCRIPTION); AddNetworkStoragePoolParameters storagePoolParameters = new AddNetworkStoragePoolParameters(getNetwork().getStoragePoolId(), externalNetwork); storagePoolParameters.setNetworkClusterList(createNetworkClusters(listOfClustersByProvider.get(providerId))); runInternalAction(ActionType.AddNetworkOnProvider, storagePoolParameters); }

Target:
private void runAutodefineForOneProvider(Guid providerId, int index) { Network externalNetwork = createExternalNetwork(getNetworkName(index), providerId); AddNetworkStoragePoolParameters storagePoolParameters = new AddNetworkStoragePoolParameters(getNetwork().getStoragePoolId(), externalNetwork); storagePoolParameters.setVnicProfileRequired(false); ActionReturnValue returnValue = runInternalAction(ActionType.AddNetworkOnProvider, storagePoolParameters); if (returnValue.getSucceeded()) { Guid networkId = returnValue.getActionReturnValue(); networkHelper.attachNetworkToClusters(networkId, listOfClustersByProvider.get(providerId)); externalNetwork.setId(networkId); addVnicProfile(externalNetwork); } }
Source:
private void connectToEureka() { updateInitialServerList(); if (eurekaClientProvider != null) { EurekaClient eurekaClient = eurekaClientProvider.get(); if (eurekaClient != null) { eurekaClient.registerEventListener(updateListener); } } }

Target:
private void connectToEureka() throws IllegalStateException { updateInitialServerList(); if (eurekaClientProvider != null) { EurekaClient eurekaClient = eurekaClientProvider.get(); if (eurekaClient == null) { throw new IllegalStateException("Cannot connect to eureka as the client provided is null"); } else { eurekaClient.registerEventListener(updateListener); } } }
Source:
private void parseNamespaces() { if (tag.getAttributes() != null) { String prefix; for (Attribute attribute : tag.getAttributes()) { if (attribute.getName().toLowerCase(Locale.ROOT).startsWith("xmlns")) { int colon = attribute.getName().indexOf(':', 5); prefix = colon <= 0 ? "" : attribute.getName().substring(colon); namespaces.put(prefix, attribute.getValue()); } } } }

Target:
private void parseNamespaces() { if (tag.getAttributes() != null) { String prefix, attributeName; for (Attribute attribute : tag.getAttributes()) { attributeName = attribute.getName() == null ? "" : attribute.getName(); if (attributeName.toLowerCase(Locale.ROOT).startsWith("xmlns")) { int colon = attributeName.indexOf(':', 5); prefix = colon <= 0 ? "" : attributeName.substring(colon); namespaces.put(prefix, attribute.getValue()); } } } }
Source:
WindowAggProjection(StreamInput in) throws IOException { windowDefinition = new WindowDefinition(in); standaloneWithInputs = Symbols.listFromStream(in); int functionsCount = in.readVInt(); windowFunctionContexts = new ArrayList<>(); for (int i = 0; i < functionsCount; i++) { WindowFunction function = (WindowFunction) Symbols.fromStream(in); Symbol filter; if (in.getVersion().onOrAfter(Version.V_4_1_0)) { filter = Symbols.fromStream(in); } else { filter = Literal.BOOLEAN_TRUE; } List<Symbol> inputs = Symbols.listFromStream(in); windowFunctionContexts.add( new WindowFunctionContext(function, inputs, filter)); } windowFunctions = windowFunctionContexts.stream() .map(WindowFunctionContext::function) .collect(Collectors.toSet()); outputs = new ArrayList<>(windowFunctions); }

Target:
WindowAggProjection(StreamInput in) throws IOException { windowDefinition = new WindowDefinition(in); standaloneWithInputs = Symbols.listFromStream(in); int functionsCount = in.readVInt(); windowFunctionContexts = new ArrayList<>(functionsCount); windowFunctions = new HashSet<>(functionsCount); boolean onOrAfter4_1_0 = in.getVersion().onOrAfter(Version.V_4_1_0); for (int i = 0; i < functionsCount; i++) { WindowFunction function = (WindowFunction) Symbols.fromStream(in); Symbol filter; if (onOrAfter4_1_0) { filter = Symbols.fromStream(in); } else { filter = Literal.BOOLEAN_TRUE; } List<Symbol> inputs = Symbols.listFromStream(in); windowFunctionContexts.add( new WindowFunctionContext(function, inputs, filter)); windowFunctions.add(function); } outputs = new ArrayList<>(windowFunctions); }
Source:
private AccountGroup createGroup(ReviewDb db, String groupName, AccountGroup.UUID adminGroupUUID, String description) throws OrmException { AccountGroup.Id groupId = new AccountGroup.Id(db.nextAccountGroupId()); AccountGroup.NameKey nameKey = new AccountGroup.NameKey(groupName); AccountGroup.UUID uuid = GroupUUID.make(groupName, serverUser); AccountGroup group = new AccountGroup(nameKey, groupId, uuid); group.setOwnerGroupUUID(adminGroupUUID); group.setDescription(description); AccountGroupName gn = new AccountGroupName(group); db.accountGroupNames().insert(Collections.singleton(gn)); db.accountGroups().insert(Collections.singleton(group)); return group; }

Target:
private AccountGroup createGroup(ReviewDb db, String groupName, AccountGroup.UUID adminGroupUUID, String description) throws OrmException { AccountGroup.Id groupId = new AccountGroup.Id(db.nextAccountGroupId()); AccountGroup.NameKey nameKey = new AccountGroup.NameKey(groupName); AccountGroup.UUID uuid = GroupUUID.make(groupName, serverUser); AccountGroup group = new AccountGroup(nameKey, groupId, uuid); group.setOwnerGroupUUID(adminGroupUUID); group.setDescription(description); group.setType(AccountGroup.Type.SYSTEM); AccountGroupName gn = new AccountGroupName(group); db.accountGroupNames().insert(Collections.singleton(gn)); db.accountGroups().insert(Collections.singleton(group)); return group; }
Source:
protected double scoreForNonmatchingNonnullFormat(String planFormat, Object planData, RegisteredType type, RegisteredTypeLoadingContext context) { return 0; }

Target:
protected double scoreForNonmatchingNonnullFormat(String planFormat, Object planData, RegisteredType type, RegisteredTypeLoadingContext context) { return planFormat.equals(FORMAT) ? 0.9 : 0; }
Source:
public ValidationResult validateDuplicates(MacPoolPerCluster macPoolPerCluster) { return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_MAC_POOL_CONTAINS_DUPLICATES) .when(!macPool.isAllowDuplicateMacAddresses() && macPoolPerCluster.containsDuplicates(macPool.getId())); }

Target:
public ValidationResult validateDuplicates(MacPoolPerCluster macPoolPerCluster) { return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_MAC_POOL_CONTAINS_DUPLICATES) .when(!macPool.isAllowDuplicateMacAddresses() && macPoolPerCluster.isDuplicateMacAddressesAllowed(macPool.getId()) && macPoolPerCluster.containsDuplicates(macPool.getId())); }
Source:
public HTableInterface getTable(byte[] tableName) throws SQLException { try { return HBaseFactoryProvider.getHTableFactory().getTable(tableName, connection, getExecutor()); } catch (org.apache.hadoop.hbase.TableNotFoundException e) { byte[][] schemaAndTableName = new byte[2][]; SchemaUtil.getVarChars(tableName, schemaAndTableName); throw new TableNotFoundException(Bytes.toString(schemaAndTableName[0]), Bytes.toString(schemaAndTableName[1])); } catch (IOException e) { throw new SQLException(e); } }

Target:
public HTableInterface getTable(byte[] tableName) throws SQLException { try { return HBaseFactoryProvider.getHTableFactory().getTable(tableName, connection, null); } catch (org.apache.hadoop.hbase.TableNotFoundException e) { byte[][] schemaAndTableName = new byte[2][]; SchemaUtil.getVarChars(tableName, schemaAndTableName); throw new TableNotFoundException(Bytes.toString(schemaAndTableName[0]), Bytes.toString(schemaAndTableName[1])); } catch (IOException e) { throw new SQLException(e); } }
Source:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() == 1) { ExprEval value1 = args.get(0).eval(bindings); if (value1.type() != ExprType.LONG && value1.type() != ExprType.DOUBLE) { throw new IAE("first argument should be integer or double type but got %s type", value1.type()); } return eval(value1); } else if (args.size() == 2) { ExprEval value1 = args.get(0).eval(bindings); ExprEval value2 = args.get(1).eval(bindings); if (value1.type() != ExprType.LONG && value1.type() != ExprType.DOUBLE) { throw new IAE("first argument should be integer or double type but got %s type", value1.type()); } if (value2.type() != ExprType.LONG) { throw new IAE("second argument should be integer type but got %s type", value2.type()); } return eval(value1, value2.asInt()); } else { throw new IAE("Function[%s] needs 1 or 2 arguments", name()); } }

Target:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 1 && args.size() != 2) { throw new IAE("Function[%s] needs 1 or 2 arguments", name()); } ExprEval value1 = args.get(0).eval(bindings); if (value1.type() != ExprType.LONG && value1.type() != ExprType.DOUBLE) { throw new IAE("The first argument to the function[%s] should be integer or double type but get the %s type", name(), value1.type()); } if (args.size() == 1) { return eval(value1); } else { ExprEval value2 = args.get(1).eval(bindings); if (value2.type() != ExprType.LONG) { throw new IAE("The second argument to the function[%s] should be integer type but get the %s type", name(), value2.type()); } return eval(value1, value2.asInt()); } }
Source:
public PppAuthSecrets(String secretsFilename) { this.secretsFilename = secretsFilename; this.providers = new ArrayList<String>(); this.clients = new ArrayList<String>(); this.servers = new ArrayList<String>(); this.secrets = new ArrayList<String>(); this.ipAddresses = new ArrayList<String>(); BufferedReader br = null; try { File secretsFile = new File(this.secretsFilename); if (secretsFile.exists()) { String currentLine = null; StringTokenizer st = null; br = new BufferedReader(new FileReader(this.secretsFilename)); while ((currentLine = br.readLine()) != null) { currentLine = currentLine.trim(); if (currentLine.indexOf('#') > 0) { st = new StringTokenizer(currentLine); this.clients.add(st.nextToken()); this.servers.add(st.nextToken()); this.secrets.add(st.nextToken()); this.ipAddresses.add(st.nextToken()); this.providers.add(st.nextToken().substring(1)); } } for (int i = 0; i < this.providers.size(); ++i) { s_logger.debug(this.clients.get(i) + "\t"); s_logger.debug(this.servers.get(i) + "\t"); s_logger.debug(this.secrets.get(i) + "\t"); s_logger.debug(this.ipAddresses.get(i) + "\t"); s_logger.debug(this.providers.get(i) + "\n"); } } else { s_logger.info("File does not exist - creating " + this.secretsFilename); writeToFile(); } } catch (Exception e) { s_logger.error("Could not initialize", e); } finally { if (br != null) { try { br.close(); } catch (IOException ex) { s_logger.error("I/O Exception while closing BufferedReader!"); } } } }

Target:
public PppAuthSecrets(String secretsFilename) { this.secretsFilename = secretsFilename; this.providers = new ArrayList<String>(); this.clients = new ArrayList<String>(); this.servers = new ArrayList<String>(); this.secrets = new ArrayList<String>(); this.ipAddresses = new ArrayList<String>(); BufferedReader br = null; try { File secretsFile = new File(this.secretsFilename); if (secretsFile.exists()) { String currentLine = null; StringTokenizer st = null; br = new BufferedReader(new FileReader(this.secretsFilename)); while ((currentLine = br.readLine()) != null) { currentLine = currentLine.trim(); if (currentLine.indexOf('#') > 0) { st = new StringTokenizer(currentLine); this.clients.add(st.nextToken()); this.servers.add(st.nextToken()); this.secrets.add(st.nextToken()); this.ipAddresses.add(st.nextToken()); this.providers.add(st.nextToken().substring(1)); } } for (int i = 0; i < this.providers.size(); ++i) { s_logger.debug(this.clients.get(i)); s_logger.debug(this.servers.get(i)); s_logger.debug(this.secrets.get(i)); s_logger.debug(this.ipAddresses.get(i)); s_logger.debug(this.providers.get(i)); } } else { s_logger.info("File does not exist - creating {}", this.secretsFilename); writeToFile(); } } catch (Exception e) { s_logger.error("Could not initialize", e); } finally { if (br != null) { try { br.close(); } catch (IOException ex) { s_logger.error("I/O Exception while closing BufferedReader!"); } } } }
Source:
private boolean buildNoteObjectFromPNPayloadAndSaveIt(Bundle data) { if (data == null) { AppLog.e(T.NOTIFS, "Bundle is null! Cannot read '" + PUSH_ARG_NOTE_ID +"'."); return false; } String noteId = data.getString(PUSH_ARG_NOTE_ID, ""); String base64FullData = data.getString(PUSH_ARG_NOTE_FULL_DATA); Note note = Note.buildFromBase64EncodedData(noteId, base64FullData); if (note != null) { return NotificationsTable.saveNote(note, true); } return false; }

Target:
private boolean buildNoteObjectFromPNPayloadAndSaveIt(Bundle data) { if (data == null) { AppLog.e(T.NOTIFS, "Bundle is null! Cannot read '" + PUSH_ARG_NOTE_ID +"'."); } else { String noteId = data.getString(PUSH_ARG_NOTE_ID, ""); String base64FullData = data.getString(PUSH_ARG_NOTE_FULL_DATA); Note note = Note.buildFromBase64EncodedData(noteId, base64FullData); if (note != null) { return NotificationsTable.saveNote(note, true); } } AppLog.w(T.NOTIFS, "Cannot build the Note object by using info available in the PN payload. Please see " + "previous log messages for detailed information about the error."); return false; }
Source:
public URI getLocationHeaderAsURI() { try { return locationHeader != null ? new URI(locationHeader) : null; } catch (URISyntaxException e) { if (LRALogger.logger.isInfoEnabled()) { LRALogger.logger.infof("LRARecord.doEnd missing Location header on ACCEPTED response %s failed: %s", getRequestURI(), e.getMessage()); } return null; } }

Target:
public URI getLocationHeaderAsURI() throws URISyntaxException { return locationHeader != null ? new URI(locationHeader) : null; }
Source:
static void tidyUp() { WebDriverWrapper fxDriver; while (!freeDrivers.isEmpty()) { try { fxDriver = freeDrivers.pop(); fxDriver.getDriver().quit(); } catch (Exception e) { } } }

Target:
static void tidyUp() { WebDriverWrapper driver; for (Entry<Browser, Stack<WebDriverWrapper>> map : freeDrivers.entrySet()) { while (!map.getValue().isEmpty()) { try { driver = map.getValue().pop(); driver.getDriver().quit(); } catch (Exception e) { } } } }
Source:
static void buildShardLevelInfo(Logger logger, ShardStats[] stats, ImmutableOpenMap.Builder<String, Long> shardSizes, ImmutableOpenMap.Builder<ShardRouting, String> newShardRoutingToDataPath, Map<ClusterInfo.NodeAndPath, ClusterInfo.ReservedSpace.Builder> reservedSpaceByShard) { for (ShardStats s : stats) { final ShardRouting shardRouting = s.getShardRouting(); newShardRoutingToDataPath.put(shardRouting, s.getDataPath()); final StoreStats storeStats = s.getStats().getStore(); final long size = storeStats.sizeInBytes(); final long reserved = storeStats.getReservedSize().getBytes(); final String shardIdentifier = ClusterInfo.shardIdentifierFromRouting(shardRouting); if (logger.isTraceEnabled()) { logger.trace("shard: size: reserved: {}", shardIdentifier, size, reserved); } shardSizes.put(shardIdentifier, size); if (reserved != StoreStats.UNKNOWN_RESERVED_BYTES) { reservedSpaceByShard.computeIfAbsent( new ClusterInfo.NodeAndPath(shardRouting.currentNodeId(), s.getDataPath()), t -> new ClusterInfo.ReservedSpace.Builder()).add(shardRouting.shardId(), reserved); } } }

Target:
static void buildShardLevelInfo(Logger logger, ShardStats[] stats, ImmutableOpenMap.Builder<String, Long> shardSizes, ImmutableOpenMap.Builder<ShardRouting, String> newShardRoutingToDataPath, Map<ClusterInfo.NodeAndPath, ClusterInfo.ReservedSpace.Builder> reservedSpaceByShard) { for (ShardStats s : stats) { final ShardRouting shardRouting = s.getShardRouting(); newShardRoutingToDataPath.put(shardRouting, s.getDataPath()); final StoreStats storeStats = s.getStats().getStore(); final long size = storeStats.sizeInBytes(); final long reserved = storeStats.getReservedSize().getBytes(); final String shardIdentifier = ClusterInfo.shardIdentifierFromRouting(shardRouting); logger.trace("shard: size: reserved: {}", shardIdentifier, size, reserved); shardSizes.put(shardIdentifier, size); if (reserved != StoreStats.UNKNOWN_RESERVED_BYTES) { reservedSpaceByShard.computeIfAbsent( new ClusterInfo.NodeAndPath(shardRouting.currentNodeId(), s.getDataPath()), t -> new ClusterInfo.ReservedSpace.Builder()).add(shardRouting.shardId(), reserved); } } }
Source:
public ResponseEntity<Object> postImports( @PathVariable(required = false) Long id, @RequestParam(name = "async", required = false, defaultValue = "false") boolean async, @RequestParam(name = "exec", required = false, defaultValue = "false") boolean exec, @RequestBody(required = false) ImportContext obj, UriComponentsBuilder builder) throws IOException { ImportContext context = (ImportContext) context(id, true, false); if (context != null) { try { runImport(context, async); } catch (Throwable t) { if (t instanceof ValidationException) { throw new RestException(t.getMessage(), HttpStatus.BAD_REQUEST, t); } else { LOGGER.log( Level.SEVERE, "Error occurred while executing import (POST) " + t.getMessage(), t); throw new RestException( "Error occurred executing import", HttpStatus.INTERNAL_SERVER_ERROR, t); } } return new ResponseEntity<>("", new HttpHeaders(), HttpStatus.NO_CONTENT); } context = createImport(id, obj, async, exec); if (context != null) { importer.changed(context); } else { throw new RestException( "Error occurred executing import", HttpStatus.INTERNAL_SERVER_ERROR); } UriComponents uriComponents = getUriComponents(context.getId().toString(), builder); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setLocation(uriComponents.toUri()); return new ResponseEntity<>(context, headers, HttpStatus.CREATED); }

Target:
public ResponseEntity<Object> postImports( @PathVariable(required = false) Long id, @RequestParam(name = "async", required = false, defaultValue = "false") boolean async, @RequestParam(name = "exec", required = false, defaultValue = "false") boolean exec, @RequestBody(required = false) ImportContext obj, UriComponentsBuilder builder) throws IOException { ImportContext context = (ImportContext) context(id, true, false); if (context != null) { try { runImport(context, async); } catch (Throwable t) { if (t instanceof ValidationException) { throw new RestException(t.getMessage(), HttpStatus.BAD_REQUEST, t); } else { throw new RestException( "Error occurred executing import", HttpStatus.INTERNAL_SERVER_ERROR, t); } } return new ResponseEntity<>("", new HttpHeaders(), HttpStatus.NO_CONTENT); } context = createImport(id, obj, async, exec); if (context != null) { importer.changed(context); } else { throw new RestException( "Error occurred executing import", HttpStatus.INTERNAL_SERVER_ERROR); } UriComponents uriComponents = getUriComponents(context.getId().toString(), builder); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setLocation(uriComponents.toUri()); return new ResponseEntity<>(context, headers, HttpStatus.CREATED); }
Source:
private void runAnsibleRemovePlaybook() { AuditLogable auditable = new AuditLogableImpl(); auditable.setVdsName(getVds().getName()); auditable.setVdsId(getVds().getId()); auditable.setCorrelationId(getCorrelationId()); try { AnsibleCommandBuilder command = new AnsibleCommandBuilder() .hosts(getVds()) .playbook(AnsibleConstants.HOST_REMOVE_PLAYBOOK); auditLogDirector.log(auditable, AuditLogType.VDS_ANSIBLE_HOST_REMOVE_STARTED); AnsibleReturnValue ansibleReturnValue = ansibleExecutor.runCommand(command); command.build(); auditable.addCustomValue("LogFile", command.logFile().getAbsolutePath()); if (ansibleReturnValue.getAnsibleReturnCode() != AnsibleReturnCode.OK) { auditLogDirector.log(auditable, AuditLogType.VDS_ANSIBLE_HOST_REMOVE_FAILED); } else { auditLogDirector.log(auditable, AuditLogType.VDS_ANSIBLE_HOST_REMOVE_FINISHED); } } catch (Exception e) { auditable.addCustomValue("Message", e.getMessage()); auditLogDirector.log(auditable, AuditLogType.VDS_ANSIBLE_HOST_REMOVE_EXECUTION_FAILED); } }

Target:
private void runAnsibleRemovePlaybook() { AuditLogable auditable = new AuditLogableImpl(); auditable.setVdsName(getVds().getName()); auditable.setVdsId(getVds().getId()); auditable.setCorrelationId(getCorrelationId()); try { AnsibleCommandBuilder command = new AnsibleCommandBuilder() .hosts(getVds()) .playbook(AnsibleConstants.HOST_REMOVE_PLAYBOOK); auditLogDirector.log(auditable, AuditLogType.VDS_ANSIBLE_HOST_REMOVE_STARTED); AnsibleReturnValue ansibleReturnValue = ansibleExecutor.runCommand(command); auditable.addCustomValue("LogFile", ansibleReturnValue.getLogFile().getAbsolutePath()); if (ansibleReturnValue.getAnsibleReturnCode() != AnsibleReturnCode.OK) { auditLogDirector.log(auditable, AuditLogType.VDS_ANSIBLE_HOST_REMOVE_FAILED); } else { auditLogDirector.log(auditable, AuditLogType.VDS_ANSIBLE_HOST_REMOVE_FINISHED); } } catch (Exception e) { auditable.addCustomValue("Message", e.getMessage()); auditLogDirector.log(auditable, AuditLogType.VDS_ANSIBLE_HOST_REMOVE_EXECUTION_FAILED); } }
Source:
public void recordSensorEvent(SensorEvent sensorEvent, JsonObject jsonObject) { int sensorType = sensorEvent.sensor.getType(); String sensorTypeKey = SENSOR_TYPE_TO_DATA_TYPE.get(sensorType); if (Strings.isNullOrEmpty(sensorTypeKey)) { logger.warn("Unable find type key for sensor type: " + sensorType); return; } jsonObject.addProperty(SENSOR_DATA_TYPE_KEY, sensorTypeKey); jsonObject.addProperty(SENSOR_EVENT_ACCURACY_KEY, sensorEvent.accuracy); switch (sensorType) { case Sensor.TYPE_ACCELEROMETER: recordAccelerometerEvent(sensorEvent, jsonObject); break; case Sensor.TYPE_GRAVITY: recordGravityEvent(sensorEvent, jsonObject); break; case Sensor.TYPE_LINEAR_ACCELERATION: recordLinearAccelerometerEvent(sensorEvent, jsonObject); break; case Sensor.TYPE_GYROSCOPE: recordGyroscope(sensorEvent, jsonObject); break; case Sensor.TYPE_MAGNETIC_FIELD: recordMagneticField(sensorEvent, jsonObject); break; case Sensor.TYPE_GAME_ROTATION_VECTOR: case Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR: case Sensor.TYPE_ROTATION_VECTOR: recordRotationVector(sensorEvent, jsonObject); break; default: logger.warn("Unable to record sensor type: " + sensorType); } }

Target:
public void recordSensorEvent(SensorEvent sensorEvent, JsonObject jsonObject) { int sensorType = sensorEvent.sensor.getType(); String sensorTypeKey = SENSOR_TYPE_TO_DATA_TYPE.get(sensorType); if (Strings.isNullOrEmpty(sensorTypeKey)) { logger.warn("Unable find type key for sensor type: " + sensorType); return; } jsonObject.addProperty(SENSOR_DATA_TYPE_KEY, sensorTypeKey); jsonObject.addProperty(SENSOR_EVENT_ACCURACY_KEY, sensorEvent.accuracy); switch (sensorType) { case Sensor.TYPE_ACCELEROMETER: recordAccelerometerEvent(sensorEvent, jsonObject); break; case Sensor.TYPE_GRAVITY: recordGravityEvent(sensorEvent, jsonObject); break; case Sensor.TYPE_LINEAR_ACCELERATION: recordLinearAccelerometerEvent(sensorEvent, jsonObject); break; case Sensor.TYPE_GYROSCOPE: recordGyroscope(sensorEvent, jsonObject); break; case Sensor.TYPE_MAGNETIC_FIELD: recordMagneticField(sensorEvent, jsonObject); break; case Sensor.TYPE_GYROSCOPE_UNCALIBRATED: case Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED: case Sensor.TYPE_ACCELEROMETER_UNCALIBRATED: recordUncalibrated(sensorEvent, jsonObject); break; case Sensor.TYPE_GAME_ROTATION_VECTOR: case Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR: case Sensor.TYPE_ROTATION_VECTOR: recordRotationVector(sensorEvent, jsonObject); break; default: logger.warn("Unable to record sensor type: " + sensorType); } }
Source:
public void testNoTimeoutReturnsHealthy() throws Exception { String validationQuery = "select 1"; Jdbi jdbi = mock(Jdbi.class); Handle handle = mock(Handle.class); when(jdbi.open()).thenReturn(handle); when(jdbi.withHandle(Mockito.any())).thenCallRealMethod(); when(handle.execute(validationQuery)).thenAnswer((Answer<Integer>) invocation -> null); ExecutorService executorService = Executors.newSingleThreadExecutor(); JdbiHealthCheck jdbiHealthCheck = new JdbiHealthCheck(executorService, Duration.milliseconds(5), jdbi, validationQuery); HealthCheck.Result result = jdbiHealthCheck.check(); executorService.shutdown(); assertThat(result.isHealthy()).isTrue(); }

Target:
public void testNoTimeoutReturnsHealthy() throws Exception { when(handle.execute(VALIDATION_QUERY)).thenReturn(0); HealthCheck.Result result = sut.check(); assertThat(result.isHealthy()).isTrue(); }
Source:
public void refresh(HelixDataAccessor accessor) { long startTime = System.currentTimeMillis(); _customizedViewCache.refresh(accessor); long endTime = System.currentTimeMillis(); LOG.info("Refresh " + _customizedViewCache.getPropertyMap().size() + " CustomizedViews of type " + _customizedStateType + " for cluster " + _clusterName + ", took " + (endTime - startTime) + " ms"); }

Target:
public void refresh(HelixDataAccessor accessor) { _customizedViewCache.refresh(accessor); }
Source:
private Object getBPMNProcessDiagram(String processId, String sessionId) { HttpPost httpPost; CloseableHttpResponse response; BufferedReader rd; String line; StringEntity stringEntity; String imageUrl = null; try { httpPost = new HttpPost( baseUrl + "/services/BPMNDeploymentService.BPMNDeploymentServiceHttpsSoap11Endpoint/"); httpPost.addHeader("COOKIE", sessionId); httpPost.addHeader("SOAPAction", "urn:getProcessDiagram"); httpPost.addHeader("Content-Type", "text/xml"); String imgPayload = "<soapenv:Envelope xmlns:soapenv=\"<LINK_1>\" " + "xmlns:ser=\"<LINK_0>" + ".org\"><soapenv:Header/><soapenv:Body><ser:getProcessDiagram><ser:processId>" + processId + "</ser:processId></ser:getProcessDiagram></soapenv:Body></soapenv:Envelope>"; stringEntity = new StringEntity(imgPayload, "UTF-8"); stringEntity.setChunked(true); httpPost.setEntity(stringEntity); response = client.execute(httpPost); rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), Charset.defaultCharset())); StringBuffer imgResult = new StringBuffer(); while ((line = rd.readLine()) != null) { imgResult.append(line); } String imageData = imgResult.toString().split(":return")[1]; imageUrl = "data:image/png;base64," + imageData.substring(1, imageData.length() - 4); } catch (ClientProtocolException e) { log.error("Exception : ", e); } catch (IOException e) { log.error("Exception : ", e); } return imageUrl; }

Target:
private Object getBPMNProcessDiagram(String processId, String sessionId) throws IOException { HttpPost httpPost; String line; StringEntity stringEntity; String imageUrl = null; try (CloseableHttpResponse response = null; BufferedReader rd = null) { httpPost = new HttpPost( baseUrl + "/services/BPMNDeploymentService.BPMNDeploymentServiceHttpsSoap11Endpoint/"); httpPost.addHeader(Constants.COOKIE, sessionId); httpPost.addHeader(Constants.SOAP_ACTION, Constants.SOAP_ACTION_GET_PROCESS_DIAGRAM); httpPost.addHeader(Constants.CONTENT_TYPE, Constants.XML_CONTENT_TYPE); String imgPayload = "<soapenv:Envelope xmlns:soapenv=\"<LINK_1>\" " + "xmlns:ser=\"<LINK_0>" + ".org\"><soapenv:Header/><soapenv:Body><ser:getProcessDiagram><ser:processId>" + processId + "</ser:processId></ser:getProcessDiagram></soapenv:Body></soapenv:Envelope>"; stringEntity = new StringEntity(imgPayload, Constants.UTF_8_ENCODING); stringEntity.setChunked(true); httpPost.setEntity(stringEntity); response = client.execute(httpPost); rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), Charset.defaultCharset())); StringBuffer imgResult = new StringBuffer(); while ((line = rd.readLine()) != null) { imgResult.append(line); } String imageData = imgResult.toString().split(":return")[1]; imageUrl = "data:image/png;base64," + imageData.substring(1, imageData.length() - 4); } catch (ClientProtocolException e) { log.error(Constants.CLIENT_PROTOCOL_EX, e); } return imageUrl; }
Source:
public void waitWithAnyMonitor(long timeout, EventMonitor... monitors) throws ProActiveTimeoutException { TimeoutAccounter counter = TimeoutAccounter.getAccounter(timeout); synchronized (monitors) { Arrays.stream(monitors).forEach(monitor -> monitor.setTimeouted(false)); while (!counter.isTimeoutElapsed()) { if (Arrays.stream(monitors).anyMatch(monitor -> monitor.eventOccured)) { return; } try { Thread.sleep(1000); } catch (InterruptedException e) { System.exit(1); } } Arrays.stream(monitors).forEach(monitor -> monitor.setTimeouted(true)); } throw new ProActiveTimeoutException("timeout elapsed"); }

Target:
public void waitWithAnyMonitor(long timeout, EventMonitor... monitors) throws ProActiveTimeoutException, InterruptedException { TimeoutAccounter counter = TimeoutAccounter.getAccounter(timeout); synchronized (monitors) { Arrays.stream(monitors).forEach(monitor -> monitor.setTimeouted(false)); while (!counter.isTimeoutElapsed()) { if (Arrays.stream(monitors).anyMatch(monitor -> monitor.eventOccured)) { return; } Thread.sleep(1000); } Arrays.stream(monitors).forEach(monitor -> monitor.setTimeouted(true)); } throw new ProActiveTimeoutException("timeout elapsed"); }
Source:
public void clickMenu(String... menuNames) { for (int i = 0; i < menuNames.length; i++) { click(menuNames[i]); } }

Target:
public void clickMenu(String... menuNames) { for (String menuName : menuNames) { click(menuName); } }
Source:
public Response getProfileLogs(@QueryParam("queryId") final Long queryId, @QueryParam("fragmentId") final Long fragmentId, @QueryParam("start") final Long start, @QueryParam("end") final Long end, @DefaultValue("0") @QueryParam("minLength") final Long minLength, @DefaultValue("false") @QueryParam("onlyRootOp") final boolean onlyRootOp, @Context final UriInfo uriInfo) throws DbException { Preconditions.checkArgument(queryId != null, "Missing required field queryId."); Preconditions.checkArgument(fragmentId != null, "Missing required field fragmentId."); Preconditions.checkArgument(start != null, "Missing required field start."); Preconditions.checkArgument(end != null, "Missing required field end."); Preconditions.checkArgument(minLength >= 0, "MinLength has to be greater than or equal to 0"); ResponseBuilder response = Response.ok(); response.type(MediaType.TEXT_PLAIN); PipedOutputStream writerOutput = new PipedOutputStream(); PipedInputStream input; try { input = new PipedInputStream(writerOutput, MyriaConstants.DEFAULT_PIPED_INPUT_STREAM_SIZE); } catch (IOException e) { throw new DbException(e); } PipedStreamingOutput entity = new PipedStreamingOutput(input); response.entity(entity); TupleWriter writer = new CsvTupleWriter(writerOutput); try { server.startLogDataStream(queryId, fragmentId, start, end, minLength, onlyRootOp, writer); } catch (IllegalArgumentException e) { throw new MyriaApiException(Status.BAD_REQUEST, e); } return response.build(); }

Target:
public Response getProfileLogs(@QueryParam("queryId") final Long queryId, @QueryParam("fragmentId") final Long fragmentId, @QueryParam("start") final Long start, @QueryParam("end") final Long end, @DefaultValue("0") @QueryParam("minLength") final Long minLength, @DefaultValue("false") @QueryParam("onlyRootOp") final boolean onlyRootOp, @Context final UriInfo uriInfo) throws DbException { Preconditions.checkArgument(queryId != null, "Missing required field queryId."); Preconditions.checkArgument(fragmentId != null, "Missing required field fragmentId."); Preconditions.checkArgument(start != null, "Missing required field start."); Preconditions.checkArgument(end != null, "Missing required field end."); Preconditions.checkArgument(minLength >= 0, "MinLength has to be greater than or equal to 0"); ResponseBuilder response = Response.ok(); response.type(MediaType.TEXT_PLAIN); PipedOutputStream writerOutput = new PipedOutputStream(); PipedInputStream input; try { input = new PipedInputStream(writerOutput, MyriaConstants.DEFAULT_PIPED_INPUT_STREAM_SIZE); } catch (IOException e) { throw new DbException(e); } PipedStreamingOutput entity = new PipedStreamingOutput(input); response.entity(entity); TupleWriter writer = new CsvTupleWriter(writerOutput); server.startLogDataStream(queryId, fragmentId, start, end, minLength, onlyRootOp, writer); return response.build(); }
Source:
public String getTableToolContent(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user")@Auth Optional<User> user, @ApiParam(value = "workflowId", required = true) @PathParam("workflowId") Long workflowId, @ApiParam(value = "workflowVersionId", required = true) @PathParam("workflowVersionId") Long workflowVersionId) { Workflow workflow = workflowDAO.findById(workflowId); checkEntry(workflow); checkOptionalAuthRead(user, workflow); WorkflowVersion workflowVersion = getWorkflowVersion(workflow, workflowVersionId); if (workflowVersion == null) { throw new CustomWebApplicationException("workflow version " + workflowVersionId + " does not exist", HttpStatus.SC_BAD_REQUEST); } if (workflowVersion.getToolTableJson() != null) { return workflowVersion.getToolTableJson(); } SourceFile mainDescriptor = getMainDescriptorFile(workflowVersion); if (mainDescriptor != null) { Set<SourceFile> secondaryDescContent = extractDescriptorAndSecondaryFiles(workflowVersion); LanguageHandlerInterface lInterface = LanguageHandlerFactory.getInterface(workflow.getFileType()); final Optional<String> toolTableJson = lInterface.getContent(workflowVersion.getWorkflowPath(), mainDescriptor.getContent(), secondaryDescContent, LanguageHandlerInterface.Type.TOOLS, toolDAO); if (toolTableJson.isPresent()) { workflowVersion.setToolTableJson(toolTableJson.get()); return toolTableJson.get(); } return null; } return null; }

Target:
public String getTableToolContent(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user")@Auth Optional<User> user, @ApiParam(value = "workflowId", required = true) @PathParam("workflowId") Long workflowId, @ApiParam(value = "workflowVersionId", required = true) @PathParam("workflowVersionId") Long workflowVersionId) { Workflow workflow = workflowDAO.findById(workflowId); checkEntry(workflow); checkOptionalAuthRead(user, workflow); WorkflowVersion workflowVersion = getWorkflowVersion(workflow, workflowVersionId); if (workflowVersion == null) { throw new CustomWebApplicationException("workflow version " + workflowVersionId + " does not exist", HttpStatus.SC_BAD_REQUEST); } if (workflowVersion.getToolTableJson() != null) { return workflowVersion.getToolTableJson(); } SourceFile mainDescriptor = getMainDescriptorFile(workflowVersion); if (mainDescriptor != null) { Set<SourceFile> secondaryDescContent = extractDescriptorAndSecondaryFiles(workflowVersion); LanguageHandlerInterface lInterface = LanguageHandlerFactory.getInterface(workflow.getFileType()); final Optional<String> toolTableJson = lInterface.getContent(workflowVersion.getWorkflowPath(), mainDescriptor.getContent(), secondaryDescContent, LanguageHandlerInterface.Type.TOOLS, toolDAO); final String json = toolTableJson.orElseGet(null); workflowVersion.setToolTableJson(json); return json; } return null; }
Source:
public static void signOAuth(final String host, final String path, final String method, final boolean https, final Parameters params, final OAuthTokens tokens, final String consumerKey, final String consumerSecret) { params.put( "oauth_consumer_key", consumerKey, "oauth_nonce", CryptUtils.md5(Long.toString(System.currentTimeMillis())), "oauth_signature_method", "HMAC-SHA1", "oauth_timestamp", Long.toString(System.currentTimeMillis() / 1000), "oauth_version", "1.0"); if (tokens.getTokenPublic() != null && !tokens.getTokenPublic().isEmpty()) { params.put("oauth_token", StringUtils.defaultString(tokens.getTokenPublic())); } params.put("oauth_signature", signCompletedOAuth(host, path, method, https, params, tokens.getTokenSecret(), consumerSecret)); }

Target:
public static void signOAuth(final String host, final String path, final String method, final boolean https, final Parameters params, final OAuthTokens tokens, final String consumerKey, final String consumerSecret) { params.put( "oauth_consumer_key", consumerKey, "oauth_nonce", CryptUtils.md5(Long.toString(System.currentTimeMillis())), "oauth_signature_method", "HMAC-SHA1", "oauth_timestamp", Long.toString(System.currentTimeMillis() / 1000), "oauth_version", "1.0"); if (StringUtils.isNotEmpty(tokens.getTokenPublic())) { params.put("oauth_token", StringUtils.defaultString(tokens.getTokenPublic())); } params.put("oauth_signature", signCompletedOAuth(host, path, method, https, params, tokens.getTokenSecret(), consumerSecret)); }
Source:
public int getActiveNodesTotal(boolean onlyNewComputers) { int totalServers = 0; for (Server server : getRunningNodes()) { JCloudsComputer computer = (JCloudsComputer) Jenkins.getActiveInstance().getNode(server.getName()).toComputer(); if (computer != null && !computer.isPendingDelete() && !(computer.getOfflineCause() instanceof OfflineCause.UserCause)) { if (onlyNewComputers) { if (!computer.isUsed()) { totalServers++; } } else { totalServers++; } } } return totalServers; }

Target:
public int getActiveNodesTotal(boolean onlyNewComputers) { int totalServers = 0; for (Node node : Jenkins.getActiveInstance().getNodes()) { if (node instanceof JCloudsSlave) { JCloudsSlave slave = (JCloudsSlave) node; if (slave.getId().getCloudName().equals(cloud.name) && slave.getId().getTemplateName().equals(name)) { JCloudsComputer computer = (JCloudsComputer) slave.toComputer(); if (computer != null && !computer.isPendingDelete() && !(computer.getOfflineCause() instanceof OfflineCause.UserCause)) { if (onlyNewComputers) { if (!computer.isUsed()) { totalServers++; } } else { totalServers++; } } } } } return totalServers; }