auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void removeImageMapping() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getImageStorageDomainMapDao().remove( new ImageStorageDomainMapId(getParameters().getImageId(), getParameters().getStorageDomainId())); ImagesHandler.updateAllDiskImageSnapshotsStatusWithCompensation(getRelevantDiskImage().getId(), getRelevantDiskImage().getImageStatus(), null, null); return null; }}); }

Target:
private void removeImageMapping() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getImageStorageDomainMapDao().remove( new ImageStorageDomainMapId(getParameters().getImageId(), getParameters().getStorageDomainId())); ImagesHandler.updateAllDiskImageSnapshotsStatus(getRelevantDiskImage().getId(), getRelevantDiskImage().getImageStatus()); return null; }}); }
Source:
public void not_analyse_minified_files_default_config() throws Exception { settings.setProperty(JavaScriptPlugin.EXCLUDE_MINIFIED_FILES, true); InputFile inputFile = inputFile("test_minified/file.js"); fileSystem.add(inputFile); fileSystem.add(inputFile("test_minified/file.min.js")); fileSystem.add(inputFile("test_minified/file-min.js")); SensorContext context = mock(SensorContext.class); mockInputFile(inputFile, context); createSensor().analyse(project, context); verify(context, times(1)).saveMeasure(any(InputFile.class), eq(CoreMetrics.NCLOC), anyDouble()); }

Target:
public void not_analyse_minified_files_default_config() throws Exception { testExcludeMinifiedFileProperty(true); }
Source:
protected boolean domainIsValidDestination(storage_domains domain) { return !(domain.getstorage_domain_type() == StorageDomainType.ISO || domain.getstorage_domain_type() == StorageDomainType.ImportExport); }

Target:
protected boolean domainIsValidDestination(storage_domains domain) { StorageDomainValidator validator = new StorageDomainValidator(domain); return validator.domainIsValidDestination(); }
Source:
public void save(PageRequestContext requestContext) throws SetupWizardException { String username = requestContext.getString("username"); String password = requestContext.getString("password1"); String firstName = requestContext.getString("firstName"); String lastName = requestContext.getString("lastName"); String passwordMD5 = DigestUtils.md5Hex(password); StaffMemberDAO userDAO = DAOFactory.getInstance().getStaffMemberDAO(); InternalAuthDAO internalAuthDAO = DAOFactory.getInstance().getInternalAuthDAO(); PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO(); UserIdentificationDAO userIdentificationDAO = DAOFactory.getInstance().getUserIdentificationDAO(); InternalAuth internalAuth = internalAuthDAO.create(username, passwordMD5); Person person = personDAO.create(null, null, null, null, Boolean.FALSE); userIdentificationDAO.create(person, "internal", String.valueOf(internalAuth.getId())); Organization organization = null; User user = userDAO.create(organization, firstName, lastName, Role.ADMINISTRATOR, person, false); personDAO.updateDefaultUser(person, user); }

Target:
public void save(PageRequestContext requestContext) throws SetupWizardException { String username = requestContext.getString("username"); String password = requestContext.getString("password1"); String firstName = requestContext.getString("firstName"); String lastName = requestContext.getString("lastName"); String passwordMD5 = DigestUtils.md5Hex(password); StaffMemberDAO userDAO = DAOFactory.getInstance().getStaffMemberDAO(); InternalAuthDAO internalAuthDAO = DAOFactory.getInstance().getInternalAuthDAO(); PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO(); UserIdentificationDAO userIdentificationDAO = DAOFactory.getInstance().getUserIdentificationDAO(); DefaultsDAO defaultsDAO = DAOFactory.getInstance().getDefaultsDAO(); Defaults defaults = defaultsDAO.getDefaults(); InternalAuth internalAuth = internalAuthDAO.create(username, passwordMD5); Person person = personDAO.create(null, null, null, null, Boolean.FALSE); userIdentificationDAO.create(person, "internal", String.valueOf(internalAuth.getId())); User user = userDAO.create(defaults.getOrganization(), firstName, lastName, Role.ADMINISTRATOR, person, false); personDAO.updateDefaultUser(person, user); }
Source:
public InputStream getContent() throws IOException, IllegalStateException { return null; }

Target:
public InputStream getContent() throws IOException, IllegalStateException { throw new UnsupportedOperationException("Reading from the entity is not supported"); }
Source:
protected boolean canAlleleFrequenciesBeCalculated(VariantSourceEntry variantSourceEntry) { boolean frequenciesCanBeCalculated = false; if (variantSourceEntry.hasAttribute("GTS") && variantSourceEntry.hasAttribute("GTC")) { frequenciesCanBeCalculated = true; } return frequenciesCanBeCalculated; }

Target:
protected boolean canAlleleFrequenciesBeCalculated(VariantSourceEntry variantSourceEntry) { return variantSourceEntry.hasAttribute(GENOTYPE_STRING) && variantSourceEntry.hasAttribute(GENOTYPE_COUNT); }
Source:
public void evaluate_shouldReturnAllPatientsTakingDrugsAfterSpecifiedDate() throws Exception { cohortDefinition.setActivatedOnOrAfter(DateUtil.getDateTime(2008, 8, 10)); Cohort cohort = Context.getService(CohortDefinitionService.class).evaluate(cohortDefinition, null); System.out.println("Taking Drugs before " + cohort.getMemberIds() + " " + cohortDefinition); Assert.assertTrue(cohort.contains(2)); Assert.assertEquals(1, cohort.size()); }

Target:
public void evaluate_shouldReturnAllPatientsTakingDrugsAfterSpecifiedDate() throws Exception { cohortDefinition.setActivatedOnOrAfter(DateUtil.getDateTime(2008, 8, 10)); Cohort cohort = Context.getService(CohortDefinitionService.class).evaluate(cohortDefinition, null); Assert.assertTrue(cohort.contains(2)); Assert.assertTrue(cohort.contains(7)); Assert.assertEquals(2, cohort.size()); }
Source:
public int compareTo(@NonNull Category category) { return customOrderId - category.getCustomOrderId(); }

Target:
public int compareTo(@NonNull Category category) { if (customOrderId == 0 && category.getCustomOrderId() == 0) { return name.compareTo(category.getName()); } else { return customOrderId - category.getCustomOrderId(); } }
Source:
public static TenantId getTenantId(Event event) { final Optional<CommandContext> commandContext = getCommandContext(event); if (!commandContext.isPresent()) { return TenantId.getDefaultInstance(); } final TenantId result = getTenantId(commandContext.get()); return result; }

Target:
public static TenantId getTenantId(Event event) { checkNotNull(event); final Optional<CommandContext> commandContext = getOriginCommandContext(event); if (!commandContext.isPresent()) { return TenantId.getDefaultInstance(); } final TenantId result = Commands.getTenantId(commandContext.get()); return result; }
Source:
public RepositorySelectionPage(final boolean sourceSelection, final List<RemoteConfig> configuredRemotes, String presetUri) { super(RepositorySelectionPage.class.getName()); this.uri = new URIish(); this.sourceSelection = sourceSelection; String preset = null; if (presetUri == null) { Clipboard clippy = new Clipboard(Display.getCurrent()); String text = (String) clippy.getContents(TextTransfer.getInstance()); try { if(text != null) { text = text.trim(); if(Transport.canHandleProtocol(new URIish(text))) { preset = text; } } } catch (URISyntaxException e) { preset = null; } clippy.dispose(); } this.presetUri = preset; this.configuredRemotes = getUsableConfigs(configuredRemotes); this.remoteConfig = selectDefaultRemoteConfig(); selection = RepositorySelection.INVALID_SELECTION; if (sourceSelection) { setTitle(UIText.RepositorySelectionPage_sourceSelectionTitle); setDescription(UIText.RepositorySelectionPage_sourceSelectionDescription); } else { setTitle(UIText.RepositorySelectionPage_destinationSelectionTitle); setDescription(UIText.RepositorySelectionPage_destinationSelectionDescription); } }

Target:
public RepositorySelectionPage(final boolean sourceSelection, final List<RemoteConfig> configuredRemotes, String presetUri) { super(RepositorySelectionPage.class.getName()); this.uri = new URIish(); this.sourceSelection = sourceSelection; String preset = null; if (presetUri == null) { Clipboard clippy = new Clipboard(Display.getCurrent()); String text = (String) clippy.getContents(TextTransfer.getInstance()); try { if(text != null) { text = text.trim(); if(Transport.canHandleProtocol(new URIish(text))) preset = text; } } catch (URISyntaxException e) { preset = null; } clippy.dispose(); } this.presetUri = preset; this.configuredRemotes = getUsableConfigs(configuredRemotes); this.remoteConfig = selectDefaultRemoteConfig(); selection = RepositorySelection.INVALID_SELECTION; if (sourceSelection) { setTitle(UIText.RepositorySelectionPage_sourceSelectionTitle); setDescription(UIText.RepositorySelectionPage_sourceSelectionDescription); } else { setTitle(UIText.RepositorySelectionPage_destinationSelectionTitle); setDescription(UIText.RepositorySelectionPage_destinationSelectionDescription); } }
Source:
public static Set<GeneNumber> getGeneNumberList(Set<Gene> genes) { Map<Gene, Set<Evidence>> evidences = EvidenceUtils.getEvidenceByGenes(genes); Set<GeneNumber> geneNumbers = new HashSet<>(); Iterator it = evidences.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Gene, Set<Evidence>> pair = (Map.Entry) it.next(); GeneNumber geneNumber = new GeneNumber(); geneNumber.setGene(pair.getKey()); LevelOfEvidence highestSensitiveLevel = LevelUtils.getHighestLevelFromEvidenceByLevels(pair.getValue(), LevelUtils.getPublicSensitiveLevels()); LevelOfEvidence highestResistanceLevel = LevelUtils.getHighestLevelFromEvidenceByLevels(pair.getValue(), LevelUtils.getPublicResistanceLevels()); geneNumber.setHighestSensitiveLevel(highestSensitiveLevel != null ? highestSensitiveLevel.name() : null); geneNumber.setHighestResistenceLevel(highestResistanceLevel != null ? highestSensitiveLevel.name() : null); Set<Alteration> alterations = AlterationUtils.getAllAlterations(pair.getKey()); List<Alteration> excludeVUS = AlterationUtils.excludeVUS(pair.getKey(), new ArrayList<>(alterations)); geneNumber.setAlteration(excludeVUS.size()); geneNumbers.add(geneNumber); } return geneNumbers; }

Target:
public static Set<GeneNumber> getGeneNumberList(Set<Gene> genes) { Map<Gene, Set<Evidence>> evidences = EvidenceUtils.getEvidenceByGenes(genes); Set<GeneNumber> geneNumbers = new HashSet<>(); Iterator it = evidences.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Gene, Set<Evidence>> pair = (Map.Entry) it.next(); GeneNumber geneNumber = new GeneNumber(); geneNumber.setGene(pair.getKey()); LevelOfEvidence highestSensitiveLevel = LevelUtils.getHighestLevelFromEvidenceByLevels(pair.getValue(), LevelUtils.getPublicSensitiveLevels()); LevelOfEvidence highestResistanceLevel = LevelUtils.getHighestLevelFromEvidenceByLevels(pair.getValue(), LevelUtils.getPublicResistanceLevels()); geneNumber.setHighestSensitiveLevel(highestSensitiveLevel != null ? highestSensitiveLevel.name() : null); geneNumber.setHighestResistenceLevel(highestResistanceLevel != null ? highestResistanceLevel.name() : null); Set<Alteration> alterations = AlterationUtils.getAllAlterations(pair.getKey()); List<Alteration> excludeVUS = AlterationUtils.excludeVUS(pair.getKey(), new ArrayList<>(alterations)); geneNumber.setAlteration(excludeVUS.size()); geneNumbers.add(geneNumber); } return geneNumbers; }
Source:
private void populateChangeRow(final int row, final ChangeInfo c, final ChangeRowFormatter changeRowFormatter) { ChangeCache cache = ChangeCache.get(c.getId()); cache.getChangeInfoCache().set(c); table.setWidget(row, C_ARROW, null); if (Gerrit.isSignedIn()) { table.setWidget(row, C_STAR, StarredChanges.createIcon(c.getId(), c.isStarred())); } String s = Util.cropSubject(c.getSubject()); if (c.getStatus() != null && c.getStatus() != Change.Status.NEW) { s += " (" + c.getStatus().name() + ")"; } if (changeRowFormatter != null) { removeChangeStyle(row, changeRowFormatter); final String rowStyle = changeRowFormatter.getRowStyle(c); if (rowStyle != null) { table.getRowFormatter().addStyleName(row, rowStyle); } s = changeRowFormatter.getDisplayText(c, s); } table.setWidget(row, C_SUBJECT, new TableChangeLink(s, c)); table.setWidget(row, C_OWNER, link(c.getOwner())); table.setWidget(row, C_PROJECT, new ProjectLink(c.getProject().getKey(), c .getStatus())); table.setWidget(row, C_BRANCH, new BranchLink(c.getProject().getKey(), c .getStatus(), c.getBranch(), c.getTopic())); table.setText(row, C_PATCHSET_NUM, String.format("%d", c.getPatchSetId().get())); table.setText(row, C_LAST_UPDATE, shortFormat(c.getLastUpdatedOn())); setRowItem(row, c); }

Target:
private void populateChangeRow(final int row, final ChangeInfo c, final ChangeRowFormatter changeRowFormatter) { ChangeCache cache = ChangeCache.get(c.getId()); cache.getChangeInfoCache().set(c); table.setWidget(row, C_ARROW, null); if (Gerrit.isSignedIn()) { table.setWidget(row, C_STAR, StarredChanges.createIcon(c.getId(), c.isStarred())); } String s = Util.cropSubject(c.getSubject()); if (c.getStatus() != null && c.getStatus() != Change.Status.NEW) { s += " (" + c.getStatus().name() + ")"; } if (changeRowFormatter != null) { removeChangeStyle(row, changeRowFormatter); final String rowStyle = changeRowFormatter.getRowStyle(c); if (rowStyle != null) { table.getRowFormatter().addStyleName(row, rowStyle); } s = changeRowFormatter.getDisplayText(c, s); } table.setWidget(row, C_SUBJECT, new TableChangeLink(s, c)); table.setWidget(row, C_OWNER, link(c.getOwner())); table.setWidget(row, C_PROJECT, new ProjectLink(c.getProject().getKey(), c .getStatus())); table.setWidget(row, C_BRANCH, new BranchLink(c.getProject().getKey(), c .getStatus(), c.getBranch(), c.getTopic())); table.setText(row, C_PATCHSET_NUM, "" + c.getPatchSetId().get()); table.setText(row, C_LAST_UPDATE, shortFormat(c.getLastUpdatedOn())); setRowItem(row, c); }
Source:
public Set<IMarketplaceRating> getAllRatingsInLastXDays(int numberOfDaysBack) { final Calendar queryDate = Calendar.getInstance(); queryDate.add(Calendar.DAY_OF_YEAR, 0 - numberOfDaysBack); final TypedQuery<MarketplaceRatingImpl> query = this.createQuery( this.createCriteriaQuery( new Function< CriteriaBuilder, CriteriaQuery<MarketplaceRatingImpl>>() { @Override public CriteriaQuery<MarketplaceRatingImpl> apply( CriteriaBuilder input) { final CriteriaQuery<MarketplaceRatingImpl> criteriaQuery = input.createQuery(MarketplaceRatingImpl.class); final Root<MarketplaceRatingImpl> definitionRoot = criteriaQuery.from(MarketplaceRatingImpl.class); Predicate ratingDatePredicate = input.greaterThanOrEqualTo( definitionRoot.<java.util.Date>get( "ratingDate"), queryDate.getTime()); criteriaQuery .select(definitionRoot) .where(ratingDatePredicate); return criteriaQuery; } })); return new HashSet<IMarketplaceRating>(query.getResultList()); }

Target:
public Set<IMarketplaceRating> getAllRatingsInLastXDays(int numberOfDaysBack) { LocalDateTime todayMinusNumberOfDaysBack = LocalDateTime.now().minusDays(numberOfDaysBack); final TypedQuery<MarketplaceRatingImpl> query = this.createQuery( this.createCriteriaQuery( new Function< CriteriaBuilder, CriteriaQuery<MarketplaceRatingImpl>>() { @Override public CriteriaQuery<MarketplaceRatingImpl> apply( CriteriaBuilder input) { final CriteriaQuery<MarketplaceRatingImpl> criteriaQuery = input.createQuery(MarketplaceRatingImpl.class); final Root<MarketplaceRatingImpl> definitionRoot = criteriaQuery.from(MarketplaceRatingImpl.class); Predicate ratingDatePredicate = input.greaterThanOrEqualTo( definitionRoot.<java.util.Date>get( "ratingDate"), todayMinusNumberOfDaysBack.toDate()); criteriaQuery .select(definitionRoot) .where(ratingDatePredicate); return criteriaQuery; } })); return new HashSet<IMarketplaceRating>(query.getResultList()); }
Source:
private void addTaskByName(Project p, String name, List<Task> allCompileTasks) { try { allCompileTasks.add(p.getTasks().getByName(name)); } catch (UnknownTaskException e) { } }

Target:
private static void addTaskByName(Project p, String name, List<Task> allCompileTasks) { try { allCompileTasks.add(p.getTasks().getByName(name)); } catch (UnknownTaskException e) { } }
Source:
public void serializeCollectionsSingletonMap() { MoveOrCopyParameters params = new MoveOrCopyParameters( Guid.createGuidFromString("f455686a-79cc-11e6-8c65-54ee755c6cc7"), Guid.createGuidFromString("f970c5f6-79cc-11e6-bc8f-54ee755c6cc7")); params.setImageToDestinationDomainMap( Collections.singletonMap(Guid.createGuidFromString("9edb6526-7ab5-11e6-b829-54ee755c6cc7"), Guid.createGuidFromString("c097a788-7ab5-11e6-849b-54ee755c6cc7"))); JsonObjectSerializer serializer = new JsonObjectSerializer(); String json = serializer.serialize(params); assertTrue(json.length() > 0); MoveOrCopyParameters deserializedParams = new JsonObjectDeserializer().deserialize( json, MoveOrCopyParameters.class); assertEquals(params.getContainerId(), deserializedParams.getContainerId()); assertEquals(params.getExecutionReason(), deserializedParams.getExecutionReason()); }

Target:
public void serializeCollectionsSingletonMap() { MoveOrCopyParameters params = new MoveOrCopyParameters(Guid.newGuid(), Guid.newGuid()); params.setImageToDestinationDomainMap( Collections.singletonMap(Guid.createGuidFromString("9edb6526-7ab5-11e6-b829-54ee755c6cc7"), Guid.createGuidFromString("c097a788-7ab5-11e6-849b-54ee755c6cc7"))); JsonObjectSerializer serializer = new JsonObjectSerializer(); String json = serializer.serialize(params); assertTrue(json.length() > 0); MoveOrCopyParameters deserializedParams = new JsonObjectDeserializer().deserialize( json, MoveOrCopyParameters.class); assertEquals(params.getContainerId(), deserializedParams.getContainerId()); assertEquals(params.getExecutionReason(), deserializedParams.getExecutionReason()); }
Source:
public void handle(OutgoingSms sms, String response, Header[] headers) { String messageId = getTemplateOutgoingResponse().extractSingleSuccessMessageId(response); if (messageId == null) { Integer failureCount = sms.getFailureCount() + 1; String failureMessage = getTemplateOutgoingResponse().extractSingleFailureMessage(response); if (failureMessage == null) { failureMessage = response; } getEvents().add(outboundEvent(getConfig().retryOrAbortSubject(failureCount), getConfig().getName(), sms.getRecipients(), sms.getMessage(), sms.getMotechId(), null, failureCount, null, null, sms.getCustomParams())); getLogger().info("Failed to send SMS: {}", failureMessage); getAuditRecords().add(new SmsRecord(getConfig().getName(), OUTBOUND, sms.getRecipients().get(0), sms.getMessage(), now(), getConfig().retryOrAbortStatus(failureCount), null, sms.getMotechId(), null, failureMessage)); } else { getLogger().info(String.format("Sent messageId %s '%s' to %s", messageId, messageForLog(sms), sms.getRecipients().get(0))); getAuditRecords().add(new SmsRecord(getConfig().getName(), OUTBOUND, sms.getRecipients().get(0), sms.getMessage(), now(), DISPATCHED, null, sms.getMotechId(), messageId, null)); getEvents().add(outboundEvent(SmsEventSubjects.DISPATCHED, getConfig().getName(), sms.getRecipients(), sms.getMessage(), sms.getMotechId(), messageId, null, null, null, sms.getCustomParams())); } }

Target:
public void handle(OutgoingSms sms, String response, Header[] headers) { String messageId = getTemplateOutgoingResponse().extractSingleSuccessMessageId(response); if (messageId == null) { Integer failureCount = sms.getFailureCount() + 1; String failureMessage = getTemplateOutgoingResponse().extractSingleFailureMessage(response); if (failureMessage == null) { failureMessage = response; } getEvents().add(outboundEvent(getConfig().retryOrAbortSubject(failureCount), getConfig().getName(), sms.getRecipients(), sms.getMessage(), sms.getMotechId(), null, failureCount, null, null, sms.getCustomParams())); getLogger().info("Failed to send SMS: {}", failureMessage); getAuditRecords().add(new SmsRecord(getConfig().getName(), OUTBOUND, sms.getRecipients().get(0), sms.getMessage(), now(), getConfig().retryOrAbortStatus(failureCount), null, sms.getMotechId(), null, failureMessage)); } else { getLogger().info(String.format("Sent messageId %s '%s' to %s", messageId, messageForLog(sms), sms.getRecipients().get(0))); getAuditRecords().add(new SmsRecord(getConfig().getName(), OUTBOUND, sms.getRecipients().get(0), sms.getMessage(), now(), DeliveryStatuses.DISPATCHED, null, sms.getMotechId(), messageId, null)); getEvents().add(outboundEvent(SmsEventSubjects.DISPATCHED, getConfig().getName(), sms.getRecipients(), sms.getMessage(), sms.getMotechId(), messageId, null, null, null, sms.getCustomParams())); } }
Source:
public PreviousPeriodDateDataSet( @JsonProperty("dataSet") final ObjQualifier dataSet, @JsonProperty("periodsAgo") final Integer periodsAgo) { this.dataSet = notNull(dataSet, "'dataSet' must not be null!"); this.periodsAgo = notNull(periodsAgo, "'periodsAgo' must not be null!"); }

Target:
public PreviousPeriodDateDataSet( @JsonProperty("dataSet") final ObjQualifier dataSet, @JsonProperty("periodsAgo") final Integer periodsAgo) { this.dataSet = notNull(dataSet, "dataSet"); this.periodsAgo = notNull(periodsAgo, "periodsAgo"); }
Source:
public void setup() { MockLogAppender.setupLogging(); System.setProperty("opennms.home", "src/test/resources"); categoryMap = new HashMap<>(); addCategory("Foo"); addCategory("Bar"); addCategory("Xyz"); nodeMap = new HashMap<>(); addNode(1, "Node1", "Foo"); addNode(2, "Node2", "Foo", "Bar"); addNode(3, "Node3", "Bar"); addNode(4, "Node4", "Foo", "Bar"); addNode(5, "Node5", "Bar"); addNode(6, "Node6", "Xyz"); alarmMap = new HashMap<>(); addAlarm(1, 1, OnmsSeverity.NORMAL); addAlarm(2, 2, OnmsSeverity.INDETERMINATE); addAlarm(3, 3, OnmsSeverity.MINOR); addAlarm(4, 4, OnmsSeverity.WARNING); addAlarm(5, 5, OnmsSeverity.CLEARED); addAlarm(6, 6, OnmsSeverity.CRITICAL); addAlarm(7, 1, OnmsSeverity.MINOR); addAlarm(8, 2, OnmsSeverity.WARNING); addAlarm(9, 3, OnmsSeverity.MINOR); addAlarm(10, null, OnmsSeverity.CRITICAL); addAlarm(11, 2, OnmsSeverity.CRITICAL, true); }

Target:
public void setup() { MockLogAppender.setupLogging(); categoryMap = new HashMap<>(); addCategory("Foo"); addCategory("Bar"); addCategory("Xyz"); nodeMap = new HashMap<>(); addNode(1, "Node1", "Foo"); addNode(2, "Node2", "Foo", "Bar"); addNode(3, "Node3", "Bar"); addNode(4, "Node4", "Foo", "Bar"); addNode(5, "Node5", "Bar"); addNode(6, "Node6", "Xyz"); alarmMap = new HashMap<>(); addAlarm(1, 1, OnmsSeverity.NORMAL); addAlarm(2, 2, OnmsSeverity.INDETERMINATE); addAlarm(3, 3, OnmsSeverity.MINOR); addAlarm(4, 4, OnmsSeverity.WARNING); addAlarm(5, 5, OnmsSeverity.CLEARED); addAlarm(6, 6, OnmsSeverity.CRITICAL); addAlarm(7, 1, OnmsSeverity.MINOR); addAlarm(8, 2, OnmsSeverity.WARNING); addAlarm(9, 3, OnmsSeverity.MINOR); addAlarm(10, null, OnmsSeverity.CRITICAL); addAlarm(11, 2, OnmsSeverity.CRITICAL, true); }
Source:
public String dumpState() { int num = state.get(); String routeState = stateAsString(num); if (failures.get() > 0) { return String.format("*** State %s, failures %d, last failure %d ms ago", routeState, failures.get(), System.currentTimeMillis() - lastFailure); } else { return String.format("*** State %s, failures %d", routeState, failures.get()); } }

Target:
public String dumpState() { int num = state.get(); String routeState = stateAsString(num); if (failures.get() > 0) { return String.format("State %s, failures %d, last failure %d ms ago", routeState, failures.get(), System.currentTimeMillis() - lastFailure); } else { return String.format("State %s, failures %d", routeState, failures.get()); } }
Source:
public List<String> getNames() { return Lists.newArrayList(name); }

Target:
public List<String> getNames() { return Arrays.asList(name); }
Source:
private TestingLabEntity getAtlEntityById(final Long entityId) throws EntityRetrievalException { TestingLabEntity entity = null; String queryStr = "SELECT atl from TestingLabEntity atl " + "LEFT OUTER JOIN FETCH atl.address " + "WHERE (atl.id = :entityid)" + " AND (atl.deleted = false)"; Query query = entityManager.createQuery(queryStr, TestingLabEntity.class); query.setParameter("entityid", entityId); List<TestingLabEntity> result = query.getResultList(); if (result == null || result.size() == 0) { String msg = String.format(messageSource.getMessage(new DefaultMessageSourceResolvable("acb.notFound"), LocaleContextHolder.getLocale())); throw new EntityRetrievalException(msg); } else if (result.size() > 1) { throw new EntityRetrievalException("Data error. Duplicate certificaiton body id in database."); } else if (result.size() == 1) { entity = result.get(0); } return entity; }

Target:
private TestingLabEntity getAtlEntityById(final Long entityId) throws EntityRetrievalException { TestingLabEntity entity = null; String queryStr = "SELECT atl from TestingLabEntity atl " + "LEFT OUTER JOIN FETCH atl.address " + "WHERE (atl.id = :entityid)" + " AND (atl.deleted = false)"; Query query = entityManager.createQuery(queryStr, TestingLabEntity.class); query.setParameter("entityid", entityId); List<TestingLabEntity> result = query.getResultList(); if (result == null || result.size() == 0) { String msg = errorMessageUtil.getMessage("atl.notFound"); throw new EntityRetrievalException(msg); } else if (result.size() > 1) { throw new EntityRetrievalException("Data error. Duplicate certificaiton body id in database."); } else if (result.size() == 1) { entity = result.get(0); } return entity; }
Source:
Field encodeField( String name, Value value ) { return stringField( name, value.prettyPrint() ); }

Target:
Field encodeField( String name, Value value ) { return new DoubleField( name, Values.coerceToDouble(value), NO ); }
Source:
public void ok() { new OkButton(this).click(); new WaitWhile(new ShellIsAvailable(SHELL_TITLE)); new WaitWhile(new JobIsRunning(), TimePeriod.LONG, false); }

Target:
public void ok() { ok(TimePeriod.LONG); }
Source:
public void onEvent(CarbonDisruptorEvent carbonDisruptorEvent, long l, boolean b) throws Exception { CarbonMessage carbonMessage = (CarbonMessage) carbonDisruptorEvent.getEvent(); Lock lock = carbonMessage.getLock(); if (carbonMessage.getProperty(Constants.DIRECTION) == null) { if (lock.tryLock()) { CarbonCallback carbonCallback = (CarbonCallback) carbonMessage.getProperty(Constants.CALL_BACK); int port = Integer.parseInt(carbonMessage.getHeader("Host").split(":")[1]); NettyTransportContextHolder.getInstance().getMessageProcessor(port) .receive(carbonMessage, carbonCallback); } } else if (carbonMessage.getProperty(Constants.DIRECTION).equals(Constants.DIRECTION_RESPONSE)) { if (lock.tryLock()) { CarbonCallback carbonCallback = (CarbonCallback) carbonMessage.getProperty(Constants.CALL_BACK); carbonCallback.done(carbonMessage); } } }

Target:
public void onEvent(CarbonDisruptorEvent carbonDisruptorEvent, long l, boolean b) throws Exception { CarbonMessage carbonMessage = (CarbonMessage) carbonDisruptorEvent.getEvent(); Lock lock = carbonMessage.getLock(); if (carbonMessage.getProperty(Constants.DIRECTION) == null) { if (lock.tryLock()) { CarbonCallback carbonCallback = (CarbonCallback) carbonMessage.getProperty(Constants.CALL_BACK); int port = Integer.parseInt(carbonMessage.getProperty(Constants.LISTENER_PORT).toString()); NettyTransportContextHolder.getInstance().getMessageProcessor(port) .receive(carbonMessage, carbonCallback); } } else if (carbonMessage.getProperty(Constants.DIRECTION).equals(Constants.DIRECTION_RESPONSE)) { if (lock.tryLock()) { CarbonCallback carbonCallback = (CarbonCallback) carbonMessage.getProperty(Constants.CALL_BACK); carbonCallback.done(carbonMessage); } } }
Source:
public ResponseEntity addRole(@RequestBody @Validated RoleForm roleForm, BindingResult bindingResult, @RequestHeader(HttpHeaders.ACCEPT) String acceptHeader) { if (roleForm == null) { throw new RequestBodyValidationException("Empty request body", bindingResult); } if (bindingResult.hasErrors()) { throw new RequestBodyValidationException(FAILED_ADD_ROLE, bindingResult); } Role role = conversionService.convert(roleForm, Role.class); return processConfig(config -> addRole(config, role), () -> SUCCESSFUL_ADD_ROLE, acceptHeader); }

Target:
public ResponseEntity addRole(@RequestBody @Validated RoleForm roleForm, BindingResult bindingResult, @RequestHeader(HttpHeaders.ACCEPT) String acceptHeader) { if (bindingResult.hasErrors()) { throw new RequestBodyValidationException(FAILED_ADD_ROLE, bindingResult); } Role role = conversionService.convert(roleForm, Role.class); return processConfig(config -> addRole(config, role), () -> SUCCESSFUL_ADD_ROLE, acceptHeader); }
Source:
public LabelSchemaDescriptor( int labelId, int... propertyIds ) { this.labelId = labelId; this.propertyIds = propertyIds; }

Target:
LabelSchemaDescriptor( int labelId, int... propertyIds ) { this.labelId = labelId; this.propertyIds = propertyIds; }
Source:
public void postProcessing() { if (sortGraph) { if (ghStorage.isCHPossible() && isCHPrepared()) throw new IllegalArgumentException("Sorting a prepared CHGraph is not possible yet. See #12"); GraphHopperStorage newGraph = GHUtility.newStorage(ghStorage); GHUtility.sortDFS(ghStorage, newGraph); logger.info("graph sorted (" + Helper.getMemInfo() + ")"); ghStorage = newGraph; } if (hasElevation()) { interpolateBridgesAndOrTunnels(); } initLocationIndex(); if (chFactoryDecorator.isEnabled()) createCHPreparations(); if (!isCHPrepared()) prepareCH(); if (lmFactoryDecorator.isEnabled()) lmFactoryDecorator.createPreparations(ghStorage, traversalMode); prepareLM(); }

Target:
public void postProcessing() { if (sortGraph) { if (ghStorage.isCHPossible() && isCHPrepared()) throw new IllegalArgumentException("Sorting a prepared CHGraph is not possible yet. See #12"); GraphHopperStorage newGraph = GHUtility.newStorage(ghStorage); GHUtility.sortDFS(ghStorage, newGraph); logger.info("graph sorted (" + Helper.getMemInfo() + ")"); ghStorage = newGraph; } if (hasElevation()) { interpolateBridgesAndOrTunnels(); } initLocationIndex(); if (chFactoryDecorator.isEnabled()) chFactoryDecorator.createPreparations(ghStorage, traversalMode); if (!isCHPrepared()) prepareCH(); if (lmFactoryDecorator.isEnabled()) lmFactoryDecorator.createPreparations(ghStorage, traversalMode, locationIndex); loadOrPrepareLM(); }
Source:
public void whenListSubscriptionsThenOk() throws ServiceUnavailableException { final List<Subscription> testSubscriptions = ImmutableList.of( randomSubscription().build(), randomSubscription().build()) .stream() .sorted(SUBSCRIPTION_CREATION_DATE_DESC_COMPARATOR) .collect(toList()); testSubscriptions.forEach(this::insertSubscriptionToDB); final List<Subscription> subscriptions = repository.listSubscriptions(); assertThat(subscriptions, equalTo(testSubscriptions)); }

Target:
public void whenListSubscriptionsThenOk() throws ServiceUnavailableException { final List<Subscription> testSubscriptions = Lists.newArrayList( randomSubscription().build(), randomSubscription().build()); testSubscriptions.sort(SUBSCRIPTION_CREATION_DATE_DESC_COMPARATOR); testSubscriptions.forEach(this::insertSubscriptionToDB); final List<Subscription> subscriptions = repository.listSubscriptions(); assertThat(subscriptions, equalTo(testSubscriptions)); }
Source:
public void contextInitialized(final ServletContextEvent servletContextEvent) { LOGGER.info("===================================================="); LOGGER.info("Scenarioo Viewer is starting up ..."); LOGGER.info("===================================================="); initializeApplicationVersion(servletContextEvent.getServletContext()); loadConfiguration(servletContextEvent); initializeApplicationContext(servletContextEvent.getServletContext()); LOGGER.info(" Updating documentation content directory (will be done asynchronously ...)"); ScenarioDocuBuildsManager.INSTANCE.updateAllBuildsAndSubmitNewBuildsForImport(); LOGGER.info("===================================================="); LOGGER.info("Scenarioo Viewer started succesfully."); LOGGER.info("===================================================="); }

Target:
public void contextInitialized(final ServletContextEvent servletContextEvent) { LOGGER.info("===================================================="); LOGGER.info("Scenarioo Viewer is starting up ..."); LOGGER.info("===================================================="); initializeApplicationVersion(servletContextEvent.getServletContext()); loadConfiguration(servletContextEvent); initializeContextPath(servletContextEvent.getServletContext()); LOGGER.info(" Updating documentation content directory (will be done asynchronously ...)"); ScenarioDocuBuildsManager.INSTANCE.updateAllBuildsAndSubmitNewBuildsForImport(); LOGGER.info("===================================================="); LOGGER.info("Scenarioo Viewer started succesfully."); LOGGER.info("===================================================="); }
Source:
public void run() { log.info("bulk audit logger started"); while (!stopped) { lock.lock(); try { isFilled.await(timeout, TimeUnit.MILLISECONDS); if (queue.isEmpty()) { continue; } try { int count = drain(); if (log.isDebugEnabled()) { log.debug("flushed " + count + " events"); } } catch (RuntimeException cause) { log.error("caught error while draining audit queue", cause); } } catch (InterruptedException cause) { Thread.currentThread().interrupt(); return; } finally { isEmpty.signalAll(); lock.unlock(); } } log.info("bulk audit logger stopped"); }

Target:
public void run() { log.info("bulk audit logger started"); while (!stopped) { lock.lock(); try { isFilled.await(timeout, TimeUnit.MILLISECONDS); if (queue.isEmpty()) { continue; } int count = drain(); if (log.isDebugEnabled()) { log.debug("flushed " + count + " events"); } } catch (InterruptedException cause) { Thread.currentThread().interrupt(); return; } finally { isEmpty.signalAll(); lock.unlock(); } } log.info("bulk audit logger stopped"); }
Source:
public void testImplicitCoercions() throws Exception { assertions.assertQuery( "SELECT GROUPING(k), SUM(v) + 1.0 FROM (VALUES (1, 1)) AS t(k,v) GROUP BY k", "VALUES (0, 2.0)"); assertions.assertQuery( "SELECT\n" + " 1.0 * count(*),\n" + " grouping(x)\n" + "FROM (VALUES 1) t(x)\n" + "GROUP BY GROUPING SETS ((x), ())", "VALUES (1.0, 1), (1.0, 0)"); }

Target:
public void testImplicitCoercions() throws Exception { assertions.assertQuery( "SELECT GROUPING(k), SUM(v) + 1.0 FROM (VALUES (1, 1)) AS t(k,v) GROUP BY k", "VALUES (0, 2.0)"); assertions.assertQuery( "SELECT\n" + " 1.0 * count(*), " + " grouping(x) " + "FROM (VALUES 1) t(x) " + "GROUP BY GROUPING SETS ((x), ()) ", "VALUES (1.0, 1), (1.0, 0)"); }
Source:
protected void execute(Context context) throws SQLException { long now = system2.now(); MassUpdate massUpdate = context.prepareMassUpdate(); massUpdate.select("select u.id from users u " + "where u.active = " + falseValue + " and " + "( email is not null or " + " crypted_password is not null or " + " salt is not null or " + " external_identity is not null or " + " external_identity_provider is not null ) "); massUpdate.update("update users set " + " email = null, " + " crypted_password = null, " + " salt = null, " + " external_identity = null, " + " external_identity_provider = null, " + " updated_at = ? " + " where id = ?"); massUpdate.rowPluralName("deactivated users with remaining data"); massUpdate.execute((row, update) -> { update.setLong(1, now); update.setLong(2, row.getLong(1)); return true; }); }

Target:
protected void execute(Context context) throws SQLException { long now = system2.now(); MassUpdate massUpdate = context.prepareMassUpdate(); massUpdate.select("select u.id from users u " + "where u.active = " + falseValue + " and " + "( email is not null or " + " crypted_password is not null or " + " salt is not null or " + " external_identity is not null or " + " external_identity_provider is not null ) "); massUpdate.update("update users set " + " email = null, " + " crypted_password = null, " + " salt = null, " + " external_identity = null, " + " external_identity_provider = null, " + " updated_at = ? " + " where id = ?"); massUpdate.rowPluralName("deactivated users"); massUpdate.execute((row, update) -> { update.setLong(1, now); update.setLong(2, row.getLong(1)); return true; }); }
Source:
public List<Map<String, Object>> getAllDefinitions() throws IOException { PersistentAnalysis getAllDefsRequest = new SavedQueryRequest(HttpMethods.GET, true , null ); List<Object> response = queryClient.getListResponse(getAllDefsRequest); for (Object defObj : response) { if (!(defObj instanceof LinkedHashMap)) { throw new ServerException("Expected list of definitions to be JSON Array of JSON " + "Objects, but encountered this: " + defObj.toString()); } } @SuppressWarnings("unchecked") List<Map<String, Object>> responseMaps = (List)response; return responseMaps; }

Target:
public List<Map<String, Object>> getAllDefinitions() throws IOException { PersistentAnalysis getAllDefsRequest = new SavedQueryRequest(HttpMethods.GET, true , null ); List<Object> response = queryClient.getListResponse(getAllDefsRequest); for (Object defObj : response) { if (!(defObj instanceof Map)) { throw new ServerException("Expected list of definitions to be JSON Array of JSON " + "Objects, but encountered this: " + defObj.toString()); } } @SuppressWarnings("unchecked") List<Map<String, Object>> responseMaps = (List)response; return responseMaps; }
Source:
public DruidQueryGeneratorContext withLimit(long limit) { if (limit <= 0 || limit > Long.MAX_VALUE) { throw new PrestoException(DRUID_QUERY_GENERATOR_FAILURE, "Invalid limit: " + limit); } checkArgument(!hasLimit(), "Limit already exists. Druid doesn't support limit on top of another limit"); return new DruidQueryGeneratorContext( selections, from, filter, OptionalLong.of(limit)); }

Target:
public DruidQueryGeneratorContext withLimit(long limit) { if (limit <= 0 || limit > Long.MAX_VALUE) { throw new PrestoException(DRUID_QUERY_GENERATOR_FAILURE, "Invalid limit: " + limit); } checkState(!hasLimit(), "Limit already exists. Druid doesn't support limit on top of another limit"); return new DruidQueryGeneratorContext( selections, from, filter, OptionalLong.of(limit)); }
Source:
public static ApplicationInfo getApplication( Identifier identifier ) { if ( identifier == null ) { return null; } if ( !isApplicationAdmin() && !isApplicationUser() ) { return null; } String applicationName = null; UUID applicationId = null; BiMap<UUID, String> applications = getApplications(); Set<String> values= applications.values(); if ( applications == null ) { return null; } if ( identifier.isName() ) { applicationName = identifier.getName().toLowerCase(); for (String value: values ){ if(value.toLowerCase().equals( applicationName )){ applicationId = applications.inverse().get( value ); break; } } } else if ( identifier.isUUID() ) { applicationId = identifier.getUUID(); applicationName = applications.get( identifier.getUUID() ); } if ( ( applicationId != null ) && ( applicationName != null ) ) { return new ApplicationInfo( applicationId, applicationName ); } return null; }

Target:
public static ApplicationInfo getApplication( Identifier identifier ) { if ( identifier == null ) { return null; } if ( !isApplicationAdmin() && !isApplicationUser() ) { return null; } String applicationName = null; UUID applicationId = null; BiMap<UUID, String> applications = getApplications(); if ( applications == null ) { return null; } if ( identifier.isName() ) { applicationName = identifier.getName().toLowerCase(); applicationId = applications.inverse().get( applicationName ); } else if ( identifier.isUUID() ) { applicationId = identifier.getUUID(); applicationName = applications.get( identifier.getUUID() ); } if ( ( applicationId != null ) && ( applicationName != null ) ) { return new ApplicationInfo( applicationId, applicationName ); } return null; }
Source:
public STGroup getTemplates() { if (templates == null) { templates = loadTemplates(); String version = getVersion(); if (version == null || !version.equals(Tool.VERSION)) { gen.tool.errMgr.toolError(ErrorType.INCOMPATIBLE_TOOL_AND_TEMPLATES, version, Tool.VERSION, language); } } return templates; }

Target:
public STGroup getTemplates() { if (templates == null) { String version = getVersion(); if (version == null || !version.equals(Tool.VERSION)) { gen.tool.errMgr.toolError(ErrorType.INCOMPATIBLE_TOOL_AND_TEMPLATES, version, Tool.VERSION, language); } templates = loadTemplates(); } return templates; }
Source:
public void setUp() { n = new CacheManagerNotifierImpl(); cl = new CacheManagerListener(); TestingUtil.inject(n, TestingUtil.named(KnownComponentNames.ASYNC_NOTIFICATION_EXECUTOR, new WithinThreadExecutor())); n.start(); n.addListener(cl); }

Target:
public void setUp() { n = new CacheManagerNotifierImpl(); cl = new CacheManagerListener(); n.start(); n.addListener(cl); }
Source:
void handleDataReceived(Buffer data) { if (dataHandler != null) { setContext(); try { if (pause) { if (pendingData == null) { pendingData = new ArrayDeque<>(); } pendingData.add(data); return; } dataHandler.handle(data); } catch (Throwable t) { handleHandlerException(t); } } }

Target:
void handleDataReceived(Buffer data) { if (paused) { if (pendingData == null) { pendingData = new ArrayDeque<>(); } pendingData.add(data); return; } if (dataHandler != null) { setContext(); try { dataHandler.handle(data); } catch (Throwable t) { handleHandlerException(t); } } }
Source:
public int hashCode() { int result = hosts != null ? hosts.hashCode() : 0; result = 31 * result + (configurations != null ? configurations.hashCode() : 0); result = 31 * result + (dependentConfigurations != null ? dependentConfigurations.hashCode() : 0); return result; }

Target:
public int hashCode() { return Objects.hash(hosts, configurations, dependentConfigurations); }
Source:
public static void gatherWithBlockCopying(final List<File> bams, final File output, final boolean createIndex, final boolean createMd5) { try { OutputStream out = new FileOutputStream(output); if (createMd5) out = new Md5CalculatingOutputStream(out, new File(output.getAbsolutePath() + ".md5")); File indexFile = null; if (createIndex) { indexFile = new File(output.getParentFile(), IOUtil.basename(output) + BAMIndex.BAMIndexSuffix); out = new StreamInflatingIndexingOutputStream(out, indexFile); } boolean isFirstFile = true; for (final File f : bams) { blockCopyBamFile(f, out, !isFirstFile, true); isFirstFile = false; } out.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); out.close(); if (createIndex && (output.lastModified() < indexFile.lastModified())) { final boolean success = indexFile.setLastModified(System.currentTimeMillis()); if (!success) { System.err.print(String.format("Index file is newer than BAM file for %s and unable to resolve this", output.getAbsolutePath())); } } } catch (final IOException ioe) { throw new RuntimeIOException(ioe); } }

Target:
public static void gatherWithBlockCopying(final List<File> bams, final File output, final boolean createIndex, final boolean createMd5) { try { OutputStream out = new FileOutputStream(output); if (createMd5) out = new Md5CalculatingOutputStream(out, new File(output.getAbsolutePath() + ".md5")); File indexFile = null; if (createIndex) { indexFile = new File(output.getParentFile(), IOUtil.basename(output) + BAMIndex.BAMIndexSuffix); out = new StreamInflatingIndexingOutputStream(out, indexFile); } boolean isFirstFile = true; for (final File f : bams) { blockCopyBamFile(f, out, !isFirstFile, true); isFirstFile = false; } out.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); out.close(); if (createIndex && (output.lastModified() > indexFile.lastModified())) { final boolean success = indexFile.setLastModified(System.currentTimeMillis()); if (!success) { System.err.print(String.format("Index file is older than BAM file for %s and unable to resolve this", output.getAbsolutePath())); } } } catch (final IOException ioe) { throw new RuntimeIOException(ioe); } }
Source:
void throwsExceptionWhenParameterizedTestIsNotInvokedAtLeastOnce() { ExtensionContext extensionContextWithAnnotatedTestMethod = getExtensionContextReturningSingleMethod( new TestCaseWithAnnotatedMethod()); Stream<TestTemplateInvocationContext> stream = this.parameterizedTestExtension.provideTestTemplateInvocationContexts( extensionContextWithAnnotatedTestMethod); Object[] unused = stream.toArray(); JUnitException exception = assertThrows(JUnitException.class, stream::close); assertThat(exception).hasMessage( "Configuration error: You must provide at least one argument for this @ParameterizedTest"); }

Target:
void throwsExceptionWhenParameterizedTestIsNotInvokedAtLeastOnce() { ExtensionContext extensionContextWithAnnotatedTestMethod = getExtensionContextReturningSingleMethod( new TestCaseWithAnnotatedMethod()); Stream<TestTemplateInvocationContext> stream = this.parameterizedTestExtension.provideTestTemplateInvocationContexts( extensionContextWithAnnotatedTestMethod); stream.toArray(); JUnitException exception = assertThrows(JUnitException.class, stream::close); assertThat(exception).hasMessage( "Configuration error: You must provide at least one argument for this @ParameterizedTest"); }
Source:
private void validateMediumDutySdxEnablement(SdxClusterRequest sdxClusterRequest, DetailedEnvironmentResponse environment) { ValidationResultBuilder validationBuilder = new ValidationResultBuilder(); if (SdxClusterShape.MEDIUM_DUTY_HA.equals(sdxClusterRequest.getClusterShape())) { boolean mediumDutySdxEntitlementEnabled = entitlementService.mediumDutySdxEnabled(environment.getCreator(), Crn.safeFromString(environment.getCreator()).getAccountId()); if (!mediumDutySdxEntitlementEnabled) { validationBuilder.error("Provisioning a Medium Duty SDX shape is not enabled for this account."); } if (!isMediumDutySdxSupported(sdxClusterRequest.getRuntime())) { validationBuilder.error("Provisioning a Medium Duty SDX shape is only valid for CM version > 7.2.2 and not " + sdxClusterRequest.getRuntime()); } } ValidationResult validationResult = validationBuilder.build(); if (validationResult.hasError()) { throw new BadRequestException(validationResult.getFormattedErrors()); } }

Target:
private void validateMediumDutySdxEnablement(SdxClusterRequest sdxClusterRequest, DetailedEnvironmentResponse environment) { ValidationResultBuilder validationBuilder = new ValidationResultBuilder(); if (SdxClusterShape.MEDIUM_DUTY_HA.equals(sdxClusterRequest.getClusterShape())) { boolean mediumDutySdxEntitlementEnabled = entitlementService.mediumDutySdxEnabled(environment.getCreator(), Crn.safeFromString(environment.getCreator()).getAccountId()); if (!mediumDutySdxEntitlementEnabled) { validationBuilder.error("Provisioning a medium duty data lake cluster is not enabled for this account. " + "Contact Cloudera support to enable CDP_MEDIUM_DUTY_SDX entitlement for the account."); } if (!isMediumDutySdxSupported(sdxClusterRequest.getRuntime())) { validationBuilder.error("Provisioning a Medium Duty SDX shape is only valid for CM version >= 7.2.2 and not " + sdxClusterRequest.getRuntime()); } } ValidationResult validationResult = validationBuilder.build(); if (validationResult.hasError()) { throw new BadRequestException(validationResult.getFormattedErrors()); } }