auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String localize(final String errorMsg, final Locale requestLocale) { Locale locale = requestLocale == null ? Locale.getDefault() : requestLocale; String ret = ""; Map<String, String> messages = getMessages(locale); if (messages != null && messages.containsKey(errorMsg)) { ret = messages.get(errorMsg); } else { if (!(errorMsg == null || errorMsg.isEmpty())) { String[] splitted = errorMsg.toLowerCase().split("[_]", -1); ret = StringUtils.join(splitted, " "); } } return ret; }

Target:
public String localize(final String errorMsg, final Locale requestLocale) { String localizedErrorMsg = ""; ResourceBundle resourceBundle = getResourceBundle(requestLocale == null ? Locale.getDefault() : requestLocale); if (resourceBundle != null && resourceBundle.containsKey(errorMsg)) { localizedErrorMsg = resourceBundle.getString(errorMsg); } else if (!StringUtils.isEmpty(errorMsg)) { localizedErrorMsg = StringUtils.join(errorMsg.toLowerCase().split("[_]", -1), " "); } return localizedErrorMsg; }
Source:
public void mergeStatistics(Statistics stats) { if (stats.isEmpty()) return; if (this.getClass() == stats.getClass() && Objects.equals(comparator(), stats.comparator())) { incrementNumNulls(stats.getNumNulls()); if (stats.hasNonNullValue()) { mergeStatisticsMinMax(stats); markAsNotEmpty(); } } else { throw StatisticsClassException.create(this, stats); } }

Target:
public void mergeStatistics(Statistics stats) { if (stats.isEmpty()) return; if (type.equals(stats.type)) { incrementNumNulls(stats.getNumNulls()); if (stats.hasNonNullValue()) { mergeStatisticsMinMax(stats); markAsNotEmpty(); } } else { throw StatisticsClassException.create(this, stats); } }
Source:
public void visitNode(Tree tree) { MethodInvocationTree mit = (MethodInvocationTree) tree; Arguments arguments = mit.arguments(); int nbrArgument = arguments.size(); if (nbrArgument <= 1) { return; } Set<ExpressionTree> reported = new HashSet<>(); for (int i = 0; i < nbrArgument; i++) { ExpressionTree arg = arguments.get(i); if (isLiteral(arg) || arg.is(Tree.Kind.IDENTIFIER) || arg.is(Tree.Kind.NEW_CLASS)) { continue; } for (int j = i + 1; j < nbrArgument; j++) { ExpressionTree otherArg = arguments.get(j); if (!reported.contains(otherArg) && SyntacticEquivalence.areEquivalent(arg, otherArg)) { reportIssue( otherArg, String.format("Verify that this is the intended value; it is the same as the %s argument.", argumentNumber(i + 1)), Collections.singletonList(new JavaFileScannerContext.Location("", arg)), null); reported.add(otherArg); } } } }

Target:
public void visitNode(Tree tree) { MethodInvocationTree mit = (MethodInvocationTree) tree; Arguments arguments = mit.arguments(); int arity = arguments.size(); if (arity <= 1) { return; } Set<ExpressionTree> reported = new HashSet<>(); for (int i = 0; i < arity; i++) { ExpressionTree arg = ExpressionUtils.skipParentheses(arguments.get(i)); if (isLiteral(arg) || arg.is(Tree.Kind.IDENTIFIER) || arg.is(Tree.Kind.NEW_CLASS)) { continue; } for (int j = i + 1; j < arity; j++) { ExpressionTree otherArg = ExpressionUtils.skipParentheses(arguments.get(j)); if (!reported.contains(otherArg) && SyntacticEquivalence.areEquivalent(arg, otherArg)) { reportIssue( otherArg, String.format("Verify that this is the intended value; it is the same as the %s argument.", argumentNumber(i + 1)), Collections.singletonList(new JavaFileScannerContext.Location("", arg)), null); reported.add(otherArg); } } } }
Source:
public String getFileNameRegexToDownload(String version) { return null; }

Target:
public String getFileNameRegexToDownload(String version) { if (version.equals(FIRST_VERSION)) { return FIRST_FILE.getName(); } else { return LATEST_FILE.getName(); } }
Source:
public void onMessage(ClientMessage msg) { boolean messageWasDiverted = msg.containsProperty(AMQ_ORIG_MSG_ID); String origMsgId = messageWasDiverted ? String.valueOf(msg.getLongProperty(AMQ_ORIG_MSG_ID)) : String.valueOf(msg.getMessageID()); String msgId = String.valueOf(msg.getMessageID()); String body = ""; try { if (messageWasDiverted) { log.debug("Message was diverted from: {}:{} -> {}:{}", msg.getStringProperty(AMQ_ORIG_ADDRESS), origMsgId, msg.getAddress(), msg.getMessageID()); } body = msg.getBodyBuffer().readString(); log.debug("Got event: {}", body); Event event = mapper.readValue(body, Event.class); listener.onEvent(event); log.debug("Message listener processed message: [{}]: SUCCESS", listener, msgId, origMsgId); msg.acknowledge(); session.commit(); } catch (Exception e) { log.debug("Message listener processed message: [{}]: FAILED", listener, msgId, origMsgId); log.error("Unable to process message {}[{}]: {}", msgId, origMsgId, e); log.debug("Unable to process message. Rolling back client session.\n{}", body, e); if (!(e instanceof QpidConnectionException)) { log.warn("Unexpected exception thrown by listener. This message will be discarded: [{}]", msgId, origMsgId, e); try { msg.acknowledge(); } catch (ActiveMQException amqe) { log.error("Unable to acknowledge message.", amqe); } try { session.rollback(); } catch (ActiveMQException amqe) { log.warn("Unable to roll back session.", amqe); } } } }

Target:
public void onMessage(ClientMessage msg) { boolean messageWasDiverted = msg.containsProperty(AMQ_ORIG_MSG_ID); String origMsgId = messageWasDiverted ? String.valueOf(msg.getLongProperty(AMQ_ORIG_MSG_ID)) : String.valueOf(msg.getMessageID()); String msgId = String.valueOf(msg.getMessageID()); String body = ""; try { if (messageWasDiverted) { log.debug("Message was diverted from: {}:{} -> {}:{}", msg.getStringProperty(AMQ_ORIG_ADDRESS), origMsgId, msg.getAddress(), msg.getMessageID()); } body = msg.getBodyBuffer().readString(); log.debug("Got event: {}", body); Event event = mapper.readValue(body, Event.class); listener.onEvent(event); log.debug("Message listener processed message: [{}]: SUCCESS", listener, msgId, origMsgId); msg.acknowledge(); session.commit(); } catch (Exception e) { log.debug("Message listener processed message: [{}]: FAILED", listener, msgId, origMsgId); log.error("Unable to process message {}[{}]: {}", msgId, origMsgId, e); log.debug("Unable to process message. Rolling back client session.\n{}", body); if (!(e instanceof QpidConnectionException)) { log.warn("Unexpected exception thrown by listener. This message will be discarded: [{}]", msgId, origMsgId, e); try { msg.acknowledge(); } catch (ActiveMQException amqe) { log.error("Unable to acknowledge message.", amqe); } try { session.rollback(); } catch (ActiveMQException amqe) { log.warn("Unable to roll back session.", amqe); } } } }
Source:
void callUpgradeCdhCommand(String stackProductVersion, ClustersResourceApi clustersResourceApi, Stack stack, ApiClient apiClient) throws ApiException, CloudbreakException { LOGGER.info("Upgrading the CDP Runtime..."); Optional<ApiCommand> optionalUpgradeCommand = findUpgradeApiCommand(clustersResourceApi, stack); try { ApiCommand upgradeCommand; if (optionalUpgradeCommand.isPresent()) { upgradeCommand = optionalUpgradeCommand.get(); LOGGER.debug("Upgrade of CDP Runtime is already running with id: [{}]", upgradeCommand.getId()); } else { ApiCdhUpgradeArgs upgradeArgs = new ApiCdhUpgradeArgs(); upgradeArgs.setCdhParcelVersion(stackProductVersion); upgradeCommand = clustersResourceApi.upgradeCdhCommand(stack.getName(), upgradeArgs); } PollingResult pollingResult = clouderaManagerPollingServiceProvider.startPollingCdpRuntimeUpgrade(stack, apiClient, upgradeCommand.getId()); if (isExited(pollingResult)) { throw new CancellationException("Cluster was terminated while waiting for CDP Runtime to be upgraded"); } else if (isTimeout(pollingResult)) { throw new CloudbreakException("Timeout during CDP Runtime upgrade."); } } catch (ApiException ex) { if (ex.getResponseBody().contains("Cannot upgrade because the version is already CDH")) { LOGGER.info("The Runtime has already been upgraded to {}", stackProductVersion); } else { throw ex; } } LOGGER.info("Runtime is successfully upgraded!"); }

Target:
void callUpgradeCdhCommand(String stackProductVersion, ClustersResourceApi clustersResourceApi, Stack stack, ApiClient apiClient) throws ApiException, CloudbreakException { LOGGER.info("Upgrading the CDP Runtime..."); Optional<ApiCommand> optionalUpgradeCommand = findUpgradeApiCommand(clustersResourceApi, stack); try { ApiCommand upgradeCommand; if (optionalUpgradeCommand.isPresent()) { upgradeCommand = optionalUpgradeCommand.get(); LOGGER.debug("Upgrade of CDP Runtime is already running with id: [{}]", upgradeCommand.getId()); } else { ApiCdhUpgradeArgs upgradeArgs = new ApiCdhUpgradeArgs(); upgradeArgs.setCdhParcelVersion(stackProductVersion); upgradeCommand = clustersResourceApi.upgradeCdhCommand(stack.getName(), upgradeArgs); } PollingResult pollingResult = clouderaManagerPollingServiceProvider.startPollingCdpRuntimeUpgrade(stack, apiClient, upgradeCommand.getId()); pollingResultErrorHandler.handlePollingResult(pollingResult, "Cluster was terminated while waiting for CDP Runtime to be upgraded", "Timeout during CDP Runtime upgrade."); } catch (ApiException ex) { String responseBody = ex.getResponseBody(); if (StringUtils.hasText(responseBody) && responseBody.contains("Cannot upgrade because the version is already CDH")) { LOGGER.info("The Runtime has already been upgraded to {}", stackProductVersion); } else { throw ex; } } LOGGER.info("Runtime is successfully upgraded!"); }
Source:
private void chooseDcForCheckingIfGetNamesFromExternalProviderSupported() { Version chosenDataCenterVersion = null; Guid chosenDataCenterId = provider.getAdditionalProperties().getStoragePoolId(); if (chosenDataCenterId == null) { for (StoragePool sp : dbFacade.getStoragePoolDao().getAll()) { if (chosenDataCenterVersion == null || chosenDataCenterVersion.less(sp.getCompatibilityVersion())) { chosenDataCenterVersion = sp.getCompatibilityVersion(); chosenDataCenterId = sp.getId(); } } provider.getAdditionalProperties().setStoragePoolId(chosenDataCenterId); } }

Target:
private void chooseDcForCheckingIfGetNamesFromExternalProviderSupported() { Version chosenDataCenterVersion = null; Guid chosenDataCenterId = provider.getAdditionalProperties().getStoragePoolId(); if (chosenDataCenterId == null) { for (StoragePool sp : storagePoolDao.getAllByStatus(StoragePoolStatus.Up)) { if (chosenDataCenterVersion == null || chosenDataCenterVersion.less(sp.getCompatibilityVersion())) { chosenDataCenterVersion = sp.getCompatibilityVersion(); chosenDataCenterId = sp.getId(); } } provider.getAdditionalProperties().setStoragePoolId(chosenDataCenterId); } }
Source:
private void replicateDiskStart() { if (Guid.Empty.equals(getParameters().getVdsId())) { throw new EngineException(EngineError.down, "VM " + getParameters().getVmId() + " is not running on any VDS"); } StorageType targetType = storageDomainDao.get(getParameters().getStorageDomainId()).getStorageStaticData().getStorageType(); Optional<String> diskType = vmInfoBuildUtils.getNetworkDiskType(getVm(), targetType); VmReplicateDiskParameters migrationStartParams = new VmReplicateDiskParameters(getParameters().getVdsId(), getParameters().getVmId(), getParameters().getStoragePoolId(), getParameters().getSourceStorageDomainId(), getParameters().getTargetStorageDomainId(), getParameters().getImageGroupID(), getParameters().getDestinationImageId(), diskType.orElse(null)); VDSReturnValue ret = resourceManager.runVdsCommand(VDSCommandType.VmReplicateDiskStart, migrationStartParams); if (!ret.getSucceeded()) { log.error("Failed VmReplicateDiskStart (Disk '{}' , VM '{}')", getParameters().getImageGroupID(), getParameters().getVmId()); throw new EngineException(ret.getVdsError().getCode(), ret.getVdsError().getMessage()); } }

Target:
private void replicateDiskStart() { if (Guid.Empty.equals(getParameters().getVdsId())) { throw new EngineException(EngineError.down, "VM " + getParameters().getVmId() + " is not running on any VDS"); } StorageType targetType = this.getStorageDomainById(getParameters().getTargetStorageDomainId(), getParameters().getStoragePoolId()).getStorageStaticData().getStorageType(); Optional<String> diskType = vmInfoBuildUtils.getNetworkDiskType(getVm(), targetType); VmReplicateDiskParameters migrationStartParams = new VmReplicateDiskParameters(getParameters().getVdsId(), getParameters().getVmId(), getParameters().getStoragePoolId(), getParameters().getSourceStorageDomainId(), getParameters().getTargetStorageDomainId(), getParameters().getImageGroupID(), getParameters().getDestinationImageId(), diskType.orElse(null)); VDSReturnValue ret = resourceManager.runVdsCommand(VDSCommandType.VmReplicateDiskStart, migrationStartParams); if (!ret.getSucceeded()) { log.error("Failed VmReplicateDiskStart (Disk '{}' , VM '{}')", getParameters().getImageGroupID(), getParameters().getVmId()); throw new EngineException(ret.getVdsError().getCode(), ret.getVdsError().getMessage()); } }
Source:
public String toString() { return MoreObjects.toStringHelper("") .add("Server", mServer) .add("AuthServerType", mAuthServer.getClass().getSimpleName()) .toString(); }

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("InternalServer", mServer) .add("AuthServerType", mAuthServer.getClass().getSimpleName()) .toString(); }
Source:
private void injectJsonPayload(Axis2MessageContext messageContext, Map<String, Object> data) { org.apache.axis2.context.MessageContext axis2MessageContext = messageContext.getAxis2MessageContext(); String jsonPayloadString = JsonUtil.jsonPayloadToString(axis2MessageContext); if (JsonUtil.hasAJsonObject(axis2MessageContext)) { injectJsonObject(data, jsonPayloadString); } else { injectJsonArray(data, jsonPayloadString); } }

Target:
private void injectJsonPayload(Axis2MessageContext messageContext, Map<String, Object> data) { org.apache.axis2.context.MessageContext axis2MessageContext = messageContext.getAxis2MessageContext(); String jsonPayloadString = JsonUtil.jsonPayloadToString(axis2MessageContext); try { JsonElement jsonElement = new JsonParser().parse(jsonPayloadString); if(jsonElement.isJsonObject()){ injectJsonObject(data, jsonElement); }else if(jsonElement.isJsonArray()){ injectJsonArray(data, jsonElement); }else if(jsonElement.isJsonPrimitive()){ injectJsonPrimitive(data, jsonElement); } else if (jsonElement.isJsonNull()) { data.put(PAYLOAD_INJECTING_NAME, "null"); } } catch (JsonSyntaxException e) { handleException("Invalid JSON payload"); } }
Source:
public void afterPropertiesSet() throws Exception { if (this.mongoTemplate == null) { if (this.mappingMongoConverter == null) { this.mappingMongoConverter = new MappingMongoConverter(this.mongoDbFactory, new MongoMappingContext()); this.mappingMongoConverter.setApplicationContext(this.applicationContext); List<Object> customConverters = new ArrayList<Object>(); customConverters.add(new MongoDbMessageBytesConverter()); this.mappingMongoConverter.setCustomConversions(new CustomConversions(customConverters)); this.mappingMongoConverter.afterPropertiesSet(); } this.mongoTemplate = new MongoTemplate(this.mongoDbFactory, this.mappingMongoConverter); if (this.applicationContext != null) { this.mongoTemplate.setApplicationContext(this.applicationContext); } } IndexOperations indexOperations = this.mongoTemplate.indexOps(this.collectionName); indexOperations.ensureIndex(new Index(MESSAGE_ID, Order.ASCENDING)); indexOperations.ensureIndex(new Index(GROUP_ID, Order.ASCENDING) .on(LAST_MODIFIED_TIME, Order.DESCENDING) .on(SEQUENCE, Order.DESCENDING)); }

Target:
public void afterPropertiesSet() throws Exception { if (this.mongoTemplate == null) { if (this.mappingMongoConverter == null) { this.mappingMongoConverter = new MappingMongoConverter(this.mongoDbFactory, new MongoMappingContext()); this.mappingMongoConverter.setApplicationContext(this.applicationContext); List<Object> customConverters = new ArrayList<Object>(); customConverters.add(new MongoDbMessageBytesConverter()); this.mappingMongoConverter.setCustomConversions(new CustomConversions(customConverters)); this.mappingMongoConverter.afterPropertiesSet(); } this.mongoTemplate = new MongoTemplate(this.mongoDbFactory, this.mappingMongoConverter); if (this.applicationContext != null) { this.mongoTemplate.setApplicationContext(this.applicationContext); } } IndexOperations indexOperations = this.mongoTemplate.indexOps(this.collectionName); indexOperations.ensureIndex(new Index(MessageDocumentFields.MESSAGE_ID, Order.ASCENDING)); indexOperations.ensureIndex(new Index(MessageDocumentFields.GROUP_ID, Order.ASCENDING) .on(MessageDocumentFields.LAST_MODIFIED_TIME, Order.DESCENDING) .on(MessageDocumentFields.SEQUENCE, Order.DESCENDING)); }
Source:
public boolean configureDefaultNetworkRulesForSystemVm(final Connect conn, final String vmName) { if (!_canBridgeFirewall) { return false; } final Script cmd = new Script(_securityGroupPath, _timeout.getMillis(), s_logger); cmd.add("default_network_rules_systemvm"); cmd.add("--vmname", vmName); cmd.add("--localbrname", _linkLocalBridgeName); final String result = cmd.execute(); if (result != null) { return false; } return true; }

Target:
public boolean configureDefaultNetworkRulesForSystemVm(final Connect conn, final String vmName) { if (!_canBridgeFirewall) { return false; } final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("default_network_rules_systemvm"); cmd.add("--vmname", vmName); cmd.add("--localbrname", _linkLocalBridgeName); final String result = cmd.execute(); if (result != null) { return false; } return true; }
Source:
private void verifyVersion(String aBundleStr) { final Bundle bdleCurrent = Platform.getBundle(aBundleStr); if (bdleCurrent != null) { Version ver = bdleCurrent.getVersion(); if (ver.getQualifier().equals(DASHBOARD_VERSION_QUALIFIER)) { Ftracer.traceDebug("In a runtime environment for " + aBundleStr + Messages.GerritPlugin_Version + ver.toString()); return; } } IBundleGroupProvider[] grpprovider = Platform.getBundleGroupProviders(); for (IBundleGroupProvider element : grpprovider) { IBundleGroup[] bdlgrp = element.getBundleGroups(); Ftracer.traceDebug("bundle group count: " + bdlgrp.length); for (int j = 0; j < bdlgrp.length; j++) { if (bdlgrp[j].getIdentifier().contains(aBundleStr)) { Ftracer.traceDebug("\t bdlgrp[" + j + "] : " + bdlgrp[j].getName() + "\t : " + bdlgrp[j].getProviderName() + "\t version: " + bdlgrp[j].getVersion() + "\t : " + bdlgrp[j].getIdentifier()); break; } } } }

Target:
private void verifyVersion(String aBundleStr) { final Bundle bdleCurrent = Platform.getBundle(aBundleStr); if (bdleCurrent != null) { Version ver = bdleCurrent.getVersion(); if (ver.getQualifier().equals(DASHBOARD_VERSION_QUALIFIER)) { Ftracer.traceDebug(NLS.bind(Messages.GerritPlugin_Version, aBundleStr, ver.toString())); return; } } IBundleGroupProvider[] grpprovider = Platform.getBundleGroupProviders(); for (IBundleGroupProvider element : grpprovider) { IBundleGroup[] bdlgrp = element.getBundleGroups(); Ftracer.traceDebug("bundle group count: " + bdlgrp.length); for (int j = 0; j < bdlgrp.length; j++) { if (bdlgrp[j].getIdentifier().contains(aBundleStr)) { Ftracer.traceDebug("\t bdlgrp[" + j + "] : " + bdlgrp[j].getName() + "\t : " + bdlgrp[j].getProviderName() + "\t version: " + bdlgrp[j].getVersion() + "\t : " + bdlgrp[j].getIdentifier()); break; } } } }
Source:
public void updateEntry(@RequestBody EntryDTO entryDTO) { Entry entry = entryService.getEntryById(entryDTO.getId()); entry.updateEntry(entryDTO); if (UserServiceImpl.hasRole(0)) { smtpMailSender.sendToParticipants(entry, "Trainings", emailMessages.modifyEntry(entry)); } else { entry.getTraining().setStatus(TrainingStatus.DRAFTED); trainingService.updateTraining(entry.getTraining()); trainingEventService.addEvent(new TrainingEvent(entryDTO)); } }

Target:
public void updateEntry(@RequestBody EntryDTO entryDTO) { Entry entry = entryService.getEntryById(entryDTO.getId()); entry.updateEntry(entryDTO); if (UserUtil.hasRole(0)) { smtpMailSender.sendToUsers(trainingService.getTrainingById(entry.getTraining().getId()).getParticipants(), "Trainings", emailMessages.modifyEntry(entry)); } else { entry.getTraining().setStatus(TrainingStatus.DRAFTED); trainingService.updateTraining(entry.getTraining()); trainingEventService.addEvent(new TrainingEvent(entryDTO)); smtpMailSender.sendToUsers(userService.getUsersByRole(UserRole.ADMIN), "Changes in training", entryDTO.getEventDescription()); } }
Source:
public void register(CraftingRecipe recipe) { if (!(recipe instanceof IRecipe)) { recipe = new DelegateSpongeCraftingRecipe(recipe); } recipes.add((IRecipe) recipe); SpongeImplHooks.onCraftingRecipeRegister(recipe); }

Target:
public void register(CraftingRecipe recipe) { if (!(recipe instanceof IRecipe)) { recipe = new DelegateSpongeCraftingRecipe(recipe); } this.recipes.add((IRecipe) recipe); SpongeImplHooks.onCraftingRecipeRegister(recipe); }
Source:
private PingResult getPingResultFromLegacyEndpoint(LeaderPingerContext<PingableLeader> leader) { boolean isLeader = leader.pinger().ping(); return PingResult.builder().isLeader(isLeader).build(); }

Target:
private PingResult getPingResultFromLegacyEndpoint(LeaderPingerContext<PingableLeader> leader) { return PingResult.builder().isLeader(leader.pinger().ping()).build(); }
Source:
private Optional<Node> retrieveNode(RMContainer container) { String hostname = container.getContainer().getNodeId().getHost(); return Optional.fromNullable(nodeStore.getNode(hostname)); }

Target:
private Node retrieveNode(RMContainer container) { String hostname = container.getContainer().getNodeId().getHost(); return nodeStore.getNode(hostname); }
Source:
public void scan(ScanContext context) throws InterruptedException { InetAddress agentAddress = context.getAgentAddress("SNMP"); String location = context.getSysLocation(); if (agentAddress == null) { return; } SnmpAgentConfig agentConfig = m_snmpAgentConfigFactory.getAgentConfig(agentAddress, location); SnmpWalker walker = SnmpUtils.createWalker(agentConfig, getName(), createCollectionTracker(context)); walker.start(); walker.waitFor(); }

Target:
public void scan(ScanContext context) throws InterruptedException { InetAddress agentAddress = context.getAgentAddress("SNMP"); if (agentAddress == null) { return; } SnmpAgentConfig agentConfig = m_snmpAgentConfigFactory.getAgentConfig(agentAddress, null); SnmpWalker walker = SnmpUtils.createWalker(agentConfig, getName(), createCollectionTracker(context)); walker.start(); walker.waitFor(); }
Source:
public ValidationResult snapshotAlreadyExists(Map<Guid, Guid> diskToImageIds) { Set<Guid> diskIds = diskImages.stream() .flatMap(diskImage -> getDiskImageDao().getAllSnapshotsForImageGroup(diskImage.getId()).stream()) .map(diskImage -> diskImage.getImageId()) .collect(Collectors.toSet()); Set<Guid> passedImageIds = new HashSet(diskToImageIds.values()); Set<Guid> existingGuids = passedImageIds.stream().filter(diskIds::contains).collect(Collectors.toSet()); if (!existingGuids.isEmpty()) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_IMAGE_ALREADY_EXISTS, ReplacementUtils.createSetVariableString("ImageId", existingGuids)); } return ValidationResult.VALID; }

Target:
public ValidationResult snapshotAlreadyExists(Map<Guid, Guid> diskToImageIds) { Set<Guid> diskIds = diskImages.stream() .flatMap(diskImage -> getDiskImageDao().getAllSnapshotsForImageGroup(diskImage.getId()).stream()) .map(DiskImage::getImageId) .collect(Collectors.toSet()); Set<Guid> providedImageIds = new HashSet(diskToImageIds.values()); Set<Guid> existingGuids = providedImageIds.stream().filter(diskIds::contains).collect(Collectors.toSet()); if (!existingGuids.isEmpty()) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_IMAGE_ALREADY_EXISTS, ReplacementUtils.replaceWith("ImageIds", existingGuids)); } return ValidationResult.VALID; }
Source:
public DistinctCountAggregator( DimensionSelector selector, MutableBitmap mutableBitmap ) { this.selector = selector; this.mutableBitmap = mutableBitmap; this.idForNull = selector.nameLookupPossibleInAdvance() ? selector.idLookup().lookupId(null) : -1; }

Target:
public DistinctCountAggregator( DimensionSelector selector, MutableBitmap mutableBitmap ) { this.selector = selector; this.mutableBitmap = mutableBitmap; Preconditions.checkArgument( selector.nameLookupPossibleInAdvance() || selector.getValueCardinality() != DimensionSelector.CARDINALITY_UNKNOWN, "DistinctCountAggregator not supported for selector" ); this.idForNull = selector.nameLookupPossibleInAdvance() ? selector.idLookup().lookupId(null) : UNKNOWN; }
Source:
public void loadCMISpawn() { File cmiFolder = pluginHookService.getCMIDataFolder(); if (cmiFolder == null) { return; } File cmiConfig = new File(cmiFolder, "config.yml"); if (cmiConfig.exists()) { cmiSpawn = getLocationFromConfigurationUpper( YamlConfiguration.loadConfiguration(cmiConfig), "Spawn.Main"); } else { cmiSpawn = null; ConsoleLogger.info("CMI config file not found: '" + cmiConfig.getAbsolutePath() + "'"); } }

Target:
public void loadCMISpawn() { File cmiFolder = pluginHookService.getCmiDataFolder(); if (cmiFolder == null) { return; } File cmiConfig = new File(cmiFolder, "config.yml"); if (cmiConfig.exists()) { cmiSpawn = getLocationFromConfigurationUpper( YamlConfiguration.loadConfiguration(cmiConfig), "Spawn.Main"); } else { cmiSpawn = null; ConsoleLogger.info("CMI config file not found: '" + cmiConfig.getAbsolutePath() + "'"); } }
Source:
public void patchNetIdMissingValue() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .build(); String newId = "newId"; String token = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/netid", newId); ops.add(replaceOperation); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.netid", Matchers.is(newId)));; List<Operation> ops2 = new ArrayList<Operation>(); ReplaceOperation replaceOperation2 = new ReplaceOperation("/netid", null); ops2.add(replaceOperation2); patchBody = getPatchContent(ops2); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isBadRequest()); getClient(token).perform(get("/api/eperson/epersons/" + ePerson.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.netid", Matchers.is(newId))); }

Target:
public void patchNetIdMissingValue() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .withNetId("testId") .build(); String newId = "newId"; String token = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/netid", newId); ops.add(replaceOperation); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.netid", Matchers.is(newId))); List<Operation> ops2 = new ArrayList<Operation>(); ReplaceOperation replaceOperation2 = new ReplaceOperation("/netid", null); ops2.add(replaceOperation2); patchBody = getPatchContent(ops2); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isBadRequest()); getClient(token).perform(get("/api/eperson/epersons/" + ePerson.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.netid", Matchers.is(newId))) .andExpect(jsonPath("$.email", Matchers.is("johndoe@fake-email.com"))) .andExpect(jsonPath("$.canLogIn", Matchers.is(false))); }
Source:
public Job jobStatus(String projectId, String jobId) throws IOException { return client.jobs() .get(projectId, jobId) .execute(); }

Target:
Job jobStatus(String projectId, String jobId) throws IOException { return client.jobs() .get(projectId, jobId) .execute(); }
Source:
public double getFailRate() { double failed = this.failed.get(); if(failed == 0.0 && this.passed.get() == 0) { return 0.0; } return failed / (this.passed.get() + failed); }

Target:
public double getFailRate() { double failed = this.failed.get(); double passed = this.passed.get(); if(failed == 0.0 && passed == 0) { return 0.0; } return failed / (passed + failed); }
Source:
private void setStatusIfNotTheSame(InstanceMetaData instanceMetaData, InstanceStatus newStatus) { if (instanceMetaData.getInstanceStatus() != newStatus) { if (updateStatus) { instanceMetaData.setInstanceStatus(newStatus); instanceMetaDataService.save(instanceMetaData); LOGGER.info(":::Auto sync::: The instance status updated from to {}", instanceMetaData.getInstanceStatus(), newStatus); } else { LOGGER.info(":::Auto sync::: The instance status would be had to update from to {}", instanceMetaData.getInstanceStatus(), newStatus); } } }

Target:
private void setStatusIfNotTheSame(InstanceMetaData instanceMetaData, InstanceStatus newStatus) { if (instanceMetaData.getInstanceStatus() != newStatus) { if (updateStatus) { instanceMetaData.setInstanceStatus(newStatus); LOGGER.info(":::Auto sync::: The instance status updated from to {}", instanceMetaData.getInstanceStatus(), newStatus); } else { LOGGER.info(":::Auto sync::: The instance status would be had to update from to {}", instanceMetaData.getInstanceStatus(), newStatus); } } }
Source:
public void resumeNode(String id) { waitServerUntilAvailable.apply(getNode(id)); api.serverApi().updateStatus(id, Server.UpdateStatus.create(Types.ServerAction.POWER_ON, Types.ServerActionMethod.HARDWARE)); }

Target:
public void resumeNode(String id) { api.serverApi().updateStatus(id, Server.UpdateStatus.create(Types.ServerAction.POWER_ON, Types.ServerActionMethod.HARDWARE)); }
Source:
public Object transcode(Object content, MediaType contentType, MediaType destinationType) { if (destinationType.match(APPLICATION_JSON)) { try { return ProtobufUtil.toCanonicalJSON(ctx, (byte[]) content); } catch (IOException e) { throw new CacheException(e); } } else { if (destinationType.match(APPLICATION_PROTOSTREAM)) { try { Reader reader = new InputStreamReader(new ByteArrayInputStream((byte[]) content)); return ProtobufUtil.fromCanonicalJSON(ctx, reader); } catch (IOException e) { e.printStackTrace(); } } } throw new IllegalArgumentException("Not supported"); }

Target:
public Object transcode(Object content, MediaType contentType, MediaType destinationType) { try { if (destinationType.match(APPLICATION_JSON)) { return ProtobufUtil.toCanonicalJSON(ctx, (byte[]) content); } if (destinationType.match(APPLICATION_PROTOSTREAM)) { Reader reader = new InputStreamReader(new ByteArrayInputStream((byte[]) content)); return ProtobufUtil.fromCanonicalJSON(ctx, reader); } } catch (IOException e) { throw log.errorTranscoding(e); } throw log.unsupportedContent(content); }
Source:
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { List<ScalingPolicy> scalingPoliciesRequest = (List<ScalingPolicy>) postParams.get("scalingPolicies"); List<Map<String, Object>> scalingPoliciesList = Lists.newArrayList(); for(ScalingPolicy scalingPolicy : scalingPoliciesRequest) { Map<String,Object> scalingPolicyMap = Maps.newHashMap(); scalingPoliciesList.add(scalingPolicyMap); scalingPolicyMap.put("cooldown", scalingPolicy.getCooldown()); scalingPolicyMap.put("type", scalingPolicy.getType().toString()); scalingPolicyMap.put("name", scalingPolicy.getName()); String targetString = scalingPolicy.getTarget(); Integer targetInt = Ints.tryParse(targetString); Float targetFloat; if (targetInt != null) { scalingPolicyMap.put(scalingPolicy.getTargetType().toString(), targetInt); } else if ((targetFloat = Floats.tryParse(targetString)) != null) { scalingPolicyMap.put(scalingPolicy.getTargetType().toString(), targetFloat); } else { scalingPolicyMap.put(scalingPolicy.getTargetType().toString(), targetString); } } return jsonBinder.bindToRequest(request, scalingPoliciesList); }

Target:
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { return jsonBinder.bindToRequest(request, ParseHelper.buildScalingPoliciesRequestList(postParams)); }
Source:
private List<BrickDetails> getBrickDetails() { List<BrickDetails> brickDetialsList = new ArrayList<BrickDetails>(); BrickDetails brickDetails = new BrickDetails(); brickDetails.setBrickProperties(getBrickProperties()); brickDetails.setClients(getClientInfo()); brickDetails.setMemoryStatus(getMemoryStatus()); brickDetialsList.add(brickDetails); return brickDetialsList; }

Target:
private List<BrickDetails> getBrickDetails() { BrickDetails brickDetails = new BrickDetails(); brickDetails.setBrickProperties(getBrickProperties()); brickDetails.setClients(getClientInfo()); brickDetails.setMemoryStatus(getMemoryStatus()); return Collections.singletonList(brickDetails); }
Source:
private QueryResult executeQueryTest() { Query query = queryPair.getTest(); QueryResult setupResult = null; QueryResult queryResult = null; try { setupResult = setup(query, testPreQueryResults, testPrequery -> executeQuery(testGateway, testUsername, testPassword, queryPair.getTest(), testPrequery, testTimeout, sessionProperties)); if (setupResult.getState() == State.SUCCESS) { queryResult = executeQuery(testGateway, testUsername, testPassword, queryPair.getTest(), query.getQuery(), testTimeout, sessionProperties); } } finally { int retry = 0; QueryResult tearDownResult; do { tearDownResult = tearDown(query, testPostQueryResults, testPostquery -> executeQuery(testGateway, testUsername, testPassword, queryPair.getTest(), testPostquery, testTimeout, sessionProperties)); if (tearDownResult.getState() == State.SUCCESS) { break; } try { TimeUnit.MINUTES.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } retry++; } while (retry < testTeardownRetries); if (tearDownResult.getState() != State.SUCCESS) { queryResult = tearDownResult; if (tearDownResult.getException() != null) { if (setupResult.getException() != null) { tearDownResult.addSuppressed(setupResult.getException()); } if (queryResult.getException() != null) { tearDownResult.addSuppressed(queryResult.getException()); } } } } return queryResult; }

Target:
private QueryResult executeQueryTest() { Query query = queryPair.getTest(); QueryResult setupResult = null; QueryResult queryResult = null; try { setupResult = setup(query, testPreQueryResults, testPrequery -> executeQuery(testGateway, testUsername, testPassword, queryPair.getTest(), testPrequery, testTimeout, sessionProperties)); if (setupResult.getState() == State.SUCCESS) { queryResult = executeQuery(testGateway, testUsername, testPassword, queryPair.getTest(), query.getQuery(), testTimeout, sessionProperties); } } finally { int retry = 0; QueryResult tearDownResult; do { tearDownResult = tearDown(query, testPostQueryResults, testPostquery -> executeQuery(testGateway, testUsername, testPassword, queryPair.getTest(), testPostquery, testTimeout, sessionProperties)); if (tearDownResult.getState() == State.SUCCESS) { break; } try { TimeUnit.MINUTES.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } retry++; } while (retry < testTeardownRetries); if (tearDownResult.getState() != State.SUCCESS) { if (tearDownResult.getException() != null) { if (setupResult.getException() != null) { tearDownResult.addSuppressed(setupResult.getException()); } if (queryResult.getException() != null) { tearDownResult.addSuppressed(queryResult.getException()); } } queryResult = tearDownResult; } } return queryResult; }
Source:
public void asyncAndAwait() { setRootRule(PythonGrammar.FUNCDEF); assertThat(p).matches("async def fun(): pass"); setRootRule(PythonGrammar.ASYNC_STMT); assertThat(p).matches("async with x.bar() as foo: pass"); assertThat(p).matches("async for var in x: pass"); setRootRule(PythonGrammar.STATEMENT); assertThat(p).matches("async = 2"); assertThat(p).matches("await async_func"); }

Target:
public void asyncAndAwait() { setRootRule(PythonGrammar.FUNCDEF); assertThat(p).matches("async def fun(): pass"); assertThat(p).matches("@someAnnotation\nasync def fun(): pass"); setRootRule(PythonGrammar.ASYNC_STMT); assertThat(p).matches("async with x.bar() as foo: pass"); assertThat(p).matches("async for var in x: pass"); setRootRule(PythonGrammar.EXPRESSION_STMT); assertThat(p).matches("await async_func()"); setRootRule(PythonGrammar.STATEMENT); assertThat(p).matches("async = 1"); assertThat(p).matches("await = 1"); setRootRule(PythonGrammar.FUNCDEF); assertThat(p).matches("def async(args): pass"); assertThat(p).matches("def await(args): pass"); }
Source:
private Frame decode() { if (headerCnt < HEADER_SIZE) { int headerCount = read(header, headerCnt, HEADER_SIZE - headerCnt); if (headerCount == 0) { return null; } headerCnt += headerCount; if (headerCnt < HEADER_SIZE) return null; streamType = streamType(header[0]); if (streamType.equals(StreamType.RAW)) { return new Frame(streamType, header); } } if (streamType.equals(StreamType.RAW)) { if (payloadCnt == 0) payload = new byte[rawBuffer.readableBytes()]; int count = read(payload, payloadCnt, rawBuffer.readableBytes()); if (count == 0) return null; payloadCnt = 0; return new Frame(StreamType.RAW, payload); } else { int payloadSize = ((header[4] & 0xff) << 24) + ((header[5] & 0xff) << 16) + ((header[6] & 0xff) << 8) + (header[7] & 0xff); if (payloadCnt == 0) payload = new byte[payloadSize]; int count = read(payload, payloadCnt, payloadSize - payloadCnt); if (count == 0) return null; payloadCnt += count; if (payloadCnt < payloadSize) return null; headerCnt = 0; payloadCnt = 0; return new Frame(streamType, payload); } }

Target:
private Frame decode() { if (headerCnt < HEADER_SIZE) { int headerCount = read(header, headerCnt, HEADER_SIZE - headerCnt); if (headerCount == 0) { return null; } headerCnt += headerCount; if (headerCnt < HEADER_SIZE) { return null; } streamType = streamType(header[0]); if (streamType.equals(StreamType.RAW)) { return new Frame(streamType, header); } } if (streamType.equals(StreamType.RAW)) { if (payloadCnt == 0) payload = new byte[rawBuffer.readableBytes()]; int count = read(payload, payloadCnt, rawBuffer.readableBytes()); if (count == 0) { return null; } payloadCnt = 0; return new Frame(StreamType.RAW, payload); } else { int payloadSize = ((header[4] & 0xff) << 24) + ((header[5] & 0xff) << 16) + ((header[6] & 0xff) << 8) + (header[7] & 0xff); if (payloadCnt == 0) { payload = new byte[payloadSize]; } int count = read(payload, payloadCnt, payloadSize - payloadCnt); if (count == 0) { return null; } payloadCnt += count; if (payloadCnt < payloadSize) { return null; } headerCnt = 0; payloadCnt = 0; return new Frame(streamType, payload); } }
Source:
public void start() throws IOException { if (server != null) { server.start(); } }

Target:
public void start() throws IOException { server.start(); }
Source:
private static void setInfoIncoming(OSCoreCtx oscoreCtx, Message message) { if (message.getSourceContext() instanceof MapBasedEndpointContext == false) { return; } MapBasedEndpointContext endpointContext = (MapBasedEndpointContext) message.getSourceContext(); MapBasedEndpointContext newEndpointContext = setInfo(oscoreCtx, endpointContext); message.setSourceContext(newEndpointContext); }

Target:
private static void setInfoIncoming(OSCoreCtx oscoreCtx, Message message) { EndpointContext newEndpointContext = setInfo(oscoreCtx, message.getSourceContext()); message.setSourceContext(newEndpointContext); }
Source:
public QuotaTypes(Integer quotaType, String name, String unit, String description) { this.quotaType = quotaType; this.description = description; this.quotaName = name; this.quotaUnit = unit; this.discriminator = "None"; }

Target:
private QuotaTypes(Integer quotaType, String name, String unit, String description) { this.quotaType = quotaType; this.description = description; this.quotaName = name; this.quotaUnit = unit; this.discriminator = "None"; }
Source:
public void work() { log.warn(getTitle() + " is running"); if (veryLongString.length() != size) { throw new IllegalStateException("Invalid string size: " + veryLongString.length() + " instead of: " + size); } }

Target:
public void work() { log.debug(getTitle() + " is running"); if (veryLongString.length() != size) { throw new IllegalStateException("Invalid string size: " + veryLongString.length() + " instead of: " + size); } }
Source:
public DeviceModel(final Manufacturer manufacturer, final String code, final String name) { super(); this.manufacturer = manufacturer; this.code = code; this.name = name; }

Target:
public DeviceModel(final Manufacturer manufacturer, final String code, final String name) { this.manufacturer = manufacturer; this.code = code; this.name = name; }
Source:
private boolean removeVmsInPool() { VdcReturnValueBase result; for (VM vm : getVmsInPool()) { RemoveVmFromPoolParameters removeVmFromPoolParameters = new RemoveVmFromPoolParameters(vm.getId()); removeVmFromPoolParameters.setTransactionScopeOption(TransactionScopeOption.Suppress); result = runInternalActionWithTasksContext( VdcActionType.RemoveVmFromPool, removeVmFromPoolParameters); if (!result.getSucceeded()) { return false; } result = runInternalAction( VdcActionType.RemoveVm, withRootCommandInfo(new RemoveVmParameters(vm.getId(), false), getActionType()), createRemoveVmStepContext(vm)); if (!result.getSucceeded()) { return false; } } return true; }

Target:
private boolean removeVmsInPool() { for (VM vm : getCachedVmsInPool()) { RemoveVmFromPoolParameters removeVmFromPoolParameters = new RemoveVmFromPoolParameters(vm.getId()); removeVmFromPoolParameters.setTransactionScopeOption(TransactionScopeOption.Suppress); VdcReturnValueBase result = runInternalActionWithTasksContext( VdcActionType.RemoveVmFromPool, removeVmFromPoolParameters); if (!result.getSucceeded()) { return false; } result = runInternalAction( VdcActionType.RemoveVm, withRootCommandInfo(new RemoveVmParameters(vm.getId(), false), getActionType()), createRemoveVmStepContext(vm)); if (!result.getSucceeded()) { return false; } } return true; }
Source:
public void deleteGroupTest() throws Exception { GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); Group parentGroup = null; try { context.turnOffAuthorisationSystem(); parentGroup = groupService.create(context); context.commit(); parentGroup = context.reloadEntity(parentGroup); String authToken = getAuthToken(admin.getEmail(), password); getClient(authToken).perform( get("/api/eperson/groups/" + parentGroup.getID()) ).andExpect(status().isOk()); getClient(authToken).perform( delete("/api/eperson/groups/" + parentGroup.getID()) ).andExpect(status().isNoContent()); getClient(authToken).perform( get("/api/eperson/groups/" + parentGroup.getID()) ).andExpect(status().isNotFound()); } finally { if (parentGroup != null) { GroupBuilder.deleteGroup(parentGroup.getID()); } } }

Target:
public void deleteGroupTest() throws Exception { context.turnOffAuthorisationSystem(); Group parentGroup = GroupBuilder.createGroup(context) .withName("test group") .build(); context.restoreAuthSystemState(); String authToken = getAuthToken(admin.getEmail(), password); getClient(authToken).perform( get("/api/eperson/groups/" + parentGroup.getID()) ).andExpect(status().isOk()); getClient(authToken).perform( delete("/api/eperson/groups/" + parentGroup.getID()) ).andExpect(status().isNoContent()); getClient(authToken).perform( get("/api/eperson/groups/" + parentGroup.getID()) ).andExpect(status().isNotFound()); }
Source:
public void getActivity_shouldCreateIntentForActivity() throws Exception { Intent intent = new Intent(); PendingIntent pendingIntent = PendingIntent.getActivity(RuntimeEnvironment.application, 99, intent, 100); ShadowPendingIntent shadow = shadowOf(pendingIntent); assertThat(shadow.isActivityIntent()).isTrue(); assertThat(shadow.isBroadcastIntent()).isFalse(); assertThat(shadow.isServiceIntent()).isFalse(); assertThat((Context) RuntimeEnvironment.application).isEqualTo(shadow.getSavedContext()); assertThat(shadow.getRequestCode()).isEqualTo(99); assertThat(shadow.getFlags()).isEqualTo(100); }

Target:
public void getActivity_shouldCreateIntentForActivity() throws Exception { Intent intent = new Intent("ACTION"); PendingIntent pendingIntent = PendingIntent.getActivity(RuntimeEnvironment.application, 99, intent, 100); ShadowPendingIntent shadow = shadowOf(pendingIntent); assertThat(shadow.isActivityIntent()).isTrue(); assertThat(shadow.isBroadcastIntent()).isFalse(); assertThat(shadow.isServiceIntent()).isFalse(); assertThat(shadow.getSavedIntent().filterEquals(intent)).isTrue(); assertThat((Context) RuntimeEnvironment.application).isEqualTo(shadow.getSavedContext()); assertThat(shadow.getRequestCode()).isEqualTo(99); assertThat(shadow.getFlags()).isEqualTo(100); }
Source:
public synchronized void terminateTest(String testID) { logger.info("terminateTest: " + testID); try { BenchFlowTestState testState = testModelDAO.getTestState(testID); switch (testState) { case READY: readyQueue.remove(testID); testModelDAO.setTestState(testID, BenchFlowTestState.TERMINATED); testModelDAO.setTestTerminatedState(testID, TestTerminatedState.PARTIALLY_COMPLETE); handleTestState(testID); break; case WAITING: case START: testModelDAO.setTestState(testID, BenchFlowTestState.TERMINATED); testModelDAO.setTestTerminatedState(testID, TestTerminatedState.PARTIALLY_COMPLETE); handleTestState(testID); break; case RUNNING: TestRunningState runningState = testModelDAO.getTestRunningState(testID); testModelDAO.setTestState(testID, BenchFlowTestState.TERMINATED); testModelDAO.setTestTerminatedState(testID, TestTerminatedState.PARTIALLY_COMPLETE); Future runningTaskFuture = testTasks.get(testID); if (runningTaskFuture != null) { try { runningTaskFuture.get(); } catch (InterruptedException | ExecutionException e) { } } if (runningState == HANDLE_EXPERIMENT_RESULT || runningState == DETERMINE_EXECUTE_VALIDATION_SET) { AbortRunningTestTask abortRunningTestTask = new AbortRunningTestTask(testID); Future abortRunningTestTaskFuture = taskExecutorService.submit(abortRunningTestTask); try { abortRunningTestTaskFuture.get(); } catch (InterruptedException | ExecutionException e) { } } handleTestState(testID); break; case TERMINATED: break; default: break; } } catch (BenchFlowTestIDDoesNotExistException e) { e.printStackTrace(); } }

Target:
public void terminateTest(String testID) { logger.info("terminateTest: " + testID); try { BenchFlowTestState testState = testModelDAO.getTestState(testID); logger.info("Current status: " + testState); switch (testState) { case READY: readyQueue.remove(testID); cancelTask(testID); break; case WAITING: case START: cancelTask(testID); break; case RUNNING: TestRunningState runningState = testModelDAO.getTestRunningState(testID); cancelTask(testID); if (runningState == HANDLE_EXPERIMENT_RESULT || runningState == DETERMINE_EXECUTE_VALIDATION_SET) { logger.info("Need to execute AbortRunningTask"); AbortRunningTestTask abortRunningTestTask = new AbortRunningTestTask(testID); Future abortRunningTestTaskFuture = taskExecutorService.submit(abortRunningTestTask); try { abortRunningTestTaskFuture.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } break; case TERMINATED: break; default: break; } } catch (BenchFlowTestIDDoesNotExistException e) { e.printStackTrace(); } }
Source:
public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { for (TraceTypeHelper helper : TmfTraceType.getInstance().getTraceTypeHelpers()) { if (appliesToTraceType(helper.getTraceClass())) { try { return newModule(helper.getTrace()).getAnalysisRequirements(); } catch (TmfAnalysisException e) { Activator.logError("Error in get analysis requirements", e); } } } return new ArrayList<>(); }

Target:
public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { for (TraceTypeHelper helper : TmfTraceType.getInstance().getTraceTypeHelpers()) { if (appliesToTraceType(helper.getTraceClass())) { try { return newModule(helper.getTrace()).getAnalysisRequirements(); } catch (TmfAnalysisException e) { Activator.logError("Error in get analysis requirements", e); } } } return Collections.EMPTY_SET; }