Example usage for java.util Set containsAll

List of usage examples for java.util Set containsAll

Introduction

In this page you can find the example usage for java.util Set containsAll.

Prototype

boolean containsAll(Collection<?> c);

Source Link

Document

Returns true if this set contains all of the elements of the specified collection.

Usage

From source file:org.mitre.openid.connect.service.impl.TestMITREidDataService_1_2.java

@Test
public void testExportBlacklistedSites() throws IOException {
    BlacklistedSite site1 = new BlacklistedSite();
    site1.setId(1L);/*from   w  ww  .  j av  a  2s. c o m*/
    site1.setUri("http://foo.com");

    BlacklistedSite site2 = new BlacklistedSite();
    site2.setId(2L);
    site2.setUri("http://bar.com");

    BlacklistedSite site3 = new BlacklistedSite();
    site3.setId(3L);
    site3.setUri("http://baz.com");

    Set<BlacklistedSite> allBlacklistedSites = ImmutableSet.of(site1, site2, site3);

    Mockito.when(clientRepository.getAllClients()).thenReturn(new HashSet<ClientDetailsEntity>());
    Mockito.when(approvedSiteRepository.getAll()).thenReturn(new HashSet<ApprovedSite>());
    Mockito.when(wlSiteRepository.getAll()).thenReturn(new HashSet<WhitelistedSite>());
    Mockito.when(blSiteRepository.getAll()).thenReturn(allBlacklistedSites);
    Mockito.when(authHolderRepository.getAll()).thenReturn(new ArrayList<AuthenticationHolderEntity>());
    Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet<OAuth2AccessTokenEntity>());
    Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet<OAuth2RefreshTokenEntity>());
    Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet<SystemScope>());

    // do the data export
    StringWriter stringWriter = new StringWriter();
    JsonWriter writer = new JsonWriter(stringWriter);
    writer.beginObject();
    dataService.exportData(writer);
    writer.endObject();
    writer.close();

    // parse the output as a JSON object for testing
    JsonElement elem = new JsonParser().parse(stringWriter.toString());
    JsonObject root = elem.getAsJsonObject();

    // make sure the root is there
    assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_2), is(true));

    JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_2).getAsJsonObject();

    // make sure all the root elements are there
    assertThat(config.has(MITREidDataService.CLIENTS), is(true));
    assertThat(config.has(MITREidDataService.GRANTS), is(true));
    assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true));
    assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true));
    assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true));
    assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true));

    // make sure the root elements are all arrays
    assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true));

    // check our scope list (this test)
    JsonArray sites = config.get(MITREidDataService.BLACKLISTEDSITES).getAsJsonArray();

    assertThat(sites.size(), is(3));
    // check for both of our sites in turn
    Set<BlacklistedSite> checked = new HashSet<>();
    for (JsonElement e : sites) {
        assertThat(e.isJsonObject(), is(true));
        JsonObject site = e.getAsJsonObject();

        BlacklistedSite compare = null;
        if (site.get("id").getAsLong() == site1.getId().longValue()) {
            compare = site1;
        } else if (site.get("id").getAsLong() == site2.getId().longValue()) {
            compare = site2;
        } else if (site.get("id").getAsLong() == site3.getId().longValue()) {
            compare = site3;
        }

        if (compare == null) {
            fail("Could not find matching blacklisted site id: " + site.get("id").getAsString());
        } else {
            assertThat(site.get("uri").getAsString(), equalTo(compare.getUri()));
            checked.add(compare);
        }
    }
    // make sure all of our clients were found
    assertThat(checked.containsAll(allBlacklistedSites), is(true));

}

From source file:com.gst.portfolio.loanaccount.service.LoanApplicationWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*from   www.  ja  v  a 2s. c om*/
public CommandProcessingResult modifyApplication(final Long loanId, final JsonCommand command) {

    try {
        AppUser currentUser = getAppUserIfPresent();
        final Loan existingLoanApplication = retrieveLoanBy(loanId);
        if (!existingLoanApplication.isSubmittedAndPendingApproval()) {
            throw new LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeModified(loanId);
        }

        final String productIdParamName = "productId";
        LoanProduct newLoanProduct = null;
        if (command.isChangeInLongParameterNamed(productIdParamName,
                existingLoanApplication.loanProduct().getId())) {
            final Long productId = command.longValueOfParameterNamed(productIdParamName);
            newLoanProduct = this.loanProductRepository.findOne(productId);
            if (newLoanProduct == null) {
                throw new LoanProductNotFoundException(productId);
            }
        }

        LoanProduct loanProductForValidations = newLoanProduct == null ? existingLoanApplication.loanProduct()
                : newLoanProduct;

        this.fromApiJsonDeserializer.validateForModify(command.json(), loanProductForValidations,
                existingLoanApplication);

        checkClientOrGroupActive(existingLoanApplication);

        final Set<LoanCharge> existingCharges = existingLoanApplication.charges();
        Map<Long, LoanChargeData> chargesMap = new HashMap<>();
        for (LoanCharge charge : existingCharges) {
            LoanChargeData chargeData = new LoanChargeData(charge.getId(), charge.getDueLocalDate(),
                    charge.amountOrPercentage());
            chargesMap.put(charge.getId(), chargeData);
        }
        List<LoanDisbursementDetails> disbursementDetails = this.loanUtilService
                .fetchDisbursementData(command.parsedJson().getAsJsonObject());

        /**
         * Stores all charges which are passed in during modify loan
         * application
         **/
        final Set<LoanCharge> possiblyModifedLoanCharges = this.loanChargeAssembler
                .fromParsedJson(command.parsedJson(), disbursementDetails);
        /** Boolean determines if any charge has been modified **/
        boolean isChargeModified = false;

        Set<Charge> newTrancheChages = this.loanChargeAssembler.getNewLoanTrancheCharges(command.parsedJson());
        for (Charge charge : newTrancheChages) {
            existingLoanApplication.addTrancheLoanCharge(charge);
        }

        /**
         * If there are any charges already present, which are now not
         * passed in as a part of the request, deem the charges as modified
         **/
        if (!possiblyModifedLoanCharges.isEmpty()) {
            if (!possiblyModifedLoanCharges.containsAll(existingCharges)) {
                isChargeModified = true;
            }
        }

        /**
         * If any new charges are added or values of existing charges are
         * modified
         **/
        for (LoanCharge loanCharge : possiblyModifedLoanCharges) {
            if (loanCharge.getId() == null) {
                isChargeModified = true;
            } else {
                LoanChargeData chargeData = chargesMap.get(loanCharge.getId());
                if (loanCharge.amountOrPercentage().compareTo(chargeData.amountOrPercentage()) != 0
                        || (loanCharge.isSpecifiedDueDate()
                                && !loanCharge.getDueLocalDate().equals(chargeData.getDueDate()))) {
                    isChargeModified = true;
                }
            }
        }

        final Set<LoanCollateral> possiblyModifedLoanCollateralItems = this.loanCollateralAssembler
                .fromParsedJson(command.parsedJson());

        final Map<String, Object> changes = existingLoanApplication.loanApplicationModification(command,
                possiblyModifedLoanCharges, possiblyModifedLoanCollateralItems, this.aprCalculator,
                isChargeModified);

        if (changes.containsKey("expectedDisbursementDate")) {
            this.loanAssembler.validateExpectedDisbursementForHolidayAndNonWorkingDay(existingLoanApplication);
        }

        final String clientIdParamName = "clientId";
        if (changes.containsKey(clientIdParamName)) {
            final Long clientId = command.longValueOfParameterNamed(clientIdParamName);
            final Client client = this.clientRepository.findOneWithNotFoundDetection(clientId);
            if (client.isNotActive()) {
                throw new ClientNotActiveException(clientId);
            }

            existingLoanApplication.updateClient(client);
        }

        final String groupIdParamName = "groupId";
        if (changes.containsKey(groupIdParamName)) {
            final Long groupId = command.longValueOfParameterNamed(groupIdParamName);
            final Group group = this.groupRepository.findOneWithNotFoundDetection(groupId);
            if (group.isNotActive()) {
                throw new GroupNotActiveException(groupId);
            }

            existingLoanApplication.updateGroup(group);
        }

        if (newLoanProduct != null) {
            existingLoanApplication.updateLoanProduct(newLoanProduct);
            if (!changes.containsKey("interestRateFrequencyType")) {
                existingLoanApplication.updateInterestRateFrequencyType();
            }
            final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
            final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
                    .resource("loan");
            if (newLoanProduct.useBorrowerCycle()) {
                final Long clientId = this.fromJsonHelper.extractLongNamed("clientId", command.parsedJson());
                final Long groupId = this.fromJsonHelper.extractLongNamed("groupId", command.parsedJson());
                Integer cycleNumber = 0;
                if (clientId != null) {
                    cycleNumber = this.loanReadPlatformService.retriveLoanCounter(clientId,
                            newLoanProduct.getId());
                } else if (groupId != null) {
                    cycleNumber = this.loanReadPlatformService.retriveLoanCounter(groupId,
                            AccountType.GROUP.getValue(), newLoanProduct.getId());
                }
                this.loanProductCommandFromApiJsonDeserializer.validateMinMaxConstraints(command.parsedJson(),
                        baseDataValidator, newLoanProduct, cycleNumber);
            } else {
                this.loanProductCommandFromApiJsonDeserializer.validateMinMaxConstraints(command.parsedJson(),
                        baseDataValidator, newLoanProduct);
            }
            if (newLoanProduct.isLinkedToFloatingInterestRate()) {
                existingLoanApplication.getLoanProductRelatedDetail().updateForFloatingInterestRates();
            } else {
                existingLoanApplication.setInterestRateDifferential(null);
                existingLoanApplication.setIsFloatingInterestRate(null);
            }
            if (!dataValidationErrors.isEmpty()) {
                throw new PlatformApiDataValidationException(dataValidationErrors);
            }
        }

        existingLoanApplication.updateIsInterestRecalculationEnabled();
        validateSubmittedOnDate(existingLoanApplication);

        final LoanProductRelatedDetail productRelatedDetail = existingLoanApplication.repaymentScheduleDetail();
        if (existingLoanApplication.loanProduct().getLoanProductConfigurableAttributes() != null) {
            updateProductRelatedDetails(productRelatedDetail, existingLoanApplication);
        }

        if (existingLoanApplication.getLoanProduct().canUseForTopup()
                && existingLoanApplication.getClientId() != null) {
            final Boolean isTopup = command.booleanObjectValueOfParameterNamed(LoanApiConstants.isTopup);
            if (command.isChangeInBooleanParameterNamed(LoanApiConstants.isTopup,
                    existingLoanApplication.isTopup())) {
                existingLoanApplication.setIsTopup(isTopup);
                changes.put(LoanApiConstants.isTopup, isTopup);
            }

            if (existingLoanApplication.isTopup()) {
                final Long loanIdToClose = command.longValueOfParameterNamed(LoanApiConstants.loanIdToClose);
                LoanTopupDetails existingLoanTopupDetails = existingLoanApplication.getTopupLoanDetails();
                if (existingLoanTopupDetails == null
                        || (existingLoanTopupDetails != null
                                && existingLoanTopupDetails.getLoanIdToClose() != loanIdToClose)
                        || changes.containsKey("submittedOnDate")
                        || changes.containsKey("expectedDisbursementDate") || changes.containsKey("principal")
                        || changes.containsKey(LoanApiConstants.disbursementDataParameterName)) {
                    Long existingLoanIdToClose = null;
                    if (existingLoanTopupDetails != null) {
                        existingLoanIdToClose = existingLoanTopupDetails.getLoanIdToClose();
                    }
                    final Loan loanToClose = this.loanRepositoryWrapper.findNonClosedLoanThatBelongsToClient(
                            loanIdToClose, existingLoanApplication.getClientId());
                    if (loanToClose == null) {
                        throw new GeneralPlatformDomainRuleException(
                                "error.msg.loan.loanIdToClose.no.active.loan.associated.to.client.found",
                                "loanIdToClose is invalid, No Active Loan associated with the given Client ID found.");
                    }
                    if (loanToClose.isMultiDisburmentLoan()
                            && !loanToClose.isInterestRecalculationEnabledForProduct()) {
                        throw new GeneralPlatformDomainRuleException(
                                "error.msg.loan.topup.on.multi.tranche.loan.without.interest.recalculation.not.supported",
                                "Topup on loan with multi-tranche disbursal and without interest recalculation is not supported.");
                    }
                    final LocalDate disbursalDateOfLoanToClose = loanToClose.getDisbursementDate();
                    if (!existingLoanApplication.getSubmittedOnDate().isAfter(disbursalDateOfLoanToClose)) {
                        throw new GeneralPlatformDomainRuleException(
                                "error.msg.loan.submitted.date.should.be.after.topup.loan.disbursal.date",
                                "Submitted date of this loan application "
                                        + existingLoanApplication.getSubmittedOnDate()
                                        + " should be after the disbursed date of loan to be closed "
                                        + disbursalDateOfLoanToClose);
                    }
                    if (!loanToClose.getCurrencyCode().equals(existingLoanApplication.getCurrencyCode())) {
                        throw new GeneralPlatformDomainRuleException(
                                "error.msg.loan.to.be.closed.has.different.currency",
                                "loanIdToClose is invalid, Currency code is different.");
                    }
                    final LocalDate lastUserTransactionOnLoanToClose = loanToClose.getLastUserTransactionDate();
                    if (!existingLoanApplication.getDisbursementDate()
                            .isAfter(lastUserTransactionOnLoanToClose)) {
                        throw new GeneralPlatformDomainRuleException(
                                "error.msg.loan.disbursal.date.should.be.after.last.transaction.date.of.loan.to.be.closed",
                                "Disbursal date of this loan application "
                                        + existingLoanApplication.getDisbursementDate()
                                        + " should be after last transaction date of loan to be closed "
                                        + lastUserTransactionOnLoanToClose);
                    }
                    BigDecimal loanOutstanding = this.loanReadPlatformService.retrieveLoanPrePaymentTemplate(
                            loanIdToClose, existingLoanApplication.getDisbursementDate()).getAmount();
                    final BigDecimal firstDisbursalAmount = existingLoanApplication.getFirstDisbursalAmount();
                    if (loanOutstanding.compareTo(firstDisbursalAmount) > 0) {
                        throw new GeneralPlatformDomainRuleException(
                                "error.msg.loan.amount.less.than.outstanding.of.loan.to.be.closed",
                                "Topup loan amount should be greater than outstanding amount of loan to be closed.");
                    }

                    if (existingLoanIdToClose != loanIdToClose) {
                        final LoanTopupDetails topupDetails = new LoanTopupDetails(existingLoanApplication,
                                loanIdToClose);
                        existingLoanApplication.setTopupLoanDetails(topupDetails);
                        changes.put(LoanApiConstants.loanIdToClose, loanIdToClose);
                    }
                }
            } else {
                existingLoanApplication.setTopupLoanDetails(null);
            }
        } else {
            if (existingLoanApplication.isTopup()) {
                existingLoanApplication.setIsTopup(false);
                existingLoanApplication.setTopupLoanDetails(null);
                changes.put(LoanApiConstants.isTopup, false);
            }
        }

        final String fundIdParamName = "fundId";
        if (changes.containsKey(fundIdParamName)) {
            final Long fundId = command.longValueOfParameterNamed(fundIdParamName);
            final Fund fund = this.loanAssembler.findFundByIdIfProvided(fundId);

            existingLoanApplication.updateFund(fund);
        }

        final String loanPurposeIdParamName = "loanPurposeId";
        if (changes.containsKey(loanPurposeIdParamName)) {
            final Long loanPurposeId = command.longValueOfParameterNamed(loanPurposeIdParamName);
            final CodeValue loanPurpose = this.loanAssembler.findCodeValueByIdIfProvided(loanPurposeId);
            existingLoanApplication.updateLoanPurpose(loanPurpose);
        }

        final String loanOfficerIdParamName = "loanOfficerId";
        if (changes.containsKey(loanOfficerIdParamName)) {
            final Long loanOfficerId = command.longValueOfParameterNamed(loanOfficerIdParamName);
            final Staff newValue = this.loanAssembler.findLoanOfficerByIdIfProvided(loanOfficerId);
            existingLoanApplication.updateLoanOfficerOnLoanApplication(newValue);
        }

        final String strategyIdParamName = "transactionProcessingStrategyId";
        if (changes.containsKey(strategyIdParamName)) {
            final Long strategyId = command.longValueOfParameterNamed(strategyIdParamName);
            final LoanTransactionProcessingStrategy strategy = this.loanAssembler
                    .findStrategyByIdIfProvided(strategyId);

            existingLoanApplication.updateTransactionProcessingStrategy(strategy);
        }

        final String collateralParamName = "collateral";
        if (changes.containsKey(collateralParamName)) {
            final Set<LoanCollateral> loanCollateral = this.loanCollateralAssembler
                    .fromParsedJson(command.parsedJson());
            existingLoanApplication.updateLoanCollateral(loanCollateral);
        }

        final String chargesParamName = "charges";
        if (changes.containsKey(chargesParamName)) {
            existingLoanApplication.updateLoanCharges(possiblyModifedLoanCharges);
        }

        if (changes.containsKey("recalculateLoanSchedule")) {
            changes.remove("recalculateLoanSchedule");

            final JsonElement parsedQuery = this.fromJsonHelper.parse(command.json());
            final JsonQuery query = JsonQuery.from(command.json(), parsedQuery, this.fromJsonHelper);

            final LoanScheduleModel loanSchedule = this.calculationPlatformService.calculateLoanSchedule(query,
                    false);
            existingLoanApplication.updateLoanSchedule(loanSchedule, currentUser);
            existingLoanApplication.recalculateAllCharges();
        }

        this.fromApiJsonDeserializer.validateLoanTermAndRepaidEveryValues(
                existingLoanApplication.getTermFrequency(),
                existingLoanApplication.getTermPeriodFrequencyType(),
                productRelatedDetail.getNumberOfRepayments(), productRelatedDetail.getRepayEvery(),
                productRelatedDetail.getRepaymentPeriodFrequencyType().getValue(), existingLoanApplication);

        saveAndFlushLoanWithDataIntegrityViolationChecks(existingLoanApplication);

        final String submittedOnNote = command.stringValueOfParameterNamed("submittedOnNote");
        if (StringUtils.isNotBlank(submittedOnNote)) {
            final Note note = Note.loanNote(existingLoanApplication, submittedOnNote);
            this.noteRepository.save(note);
        }

        final Long calendarId = command.longValueOfParameterNamed("calendarId");
        Calendar calendar = null;
        if (calendarId != null && calendarId != 0) {
            calendar = this.calendarRepository.findOne(calendarId);
            if (calendar == null) {
                throw new CalendarNotFoundException(calendarId);
            }
        }

        final List<CalendarInstance> ciList = (List<CalendarInstance>) this.calendarInstanceRepository
                .findByEntityIdAndEntityTypeId(loanId, CalendarEntityType.LOANS.getValue());
        if (calendar != null) {

            // For loans, allow to attach only one calendar instance per
            // loan
            if (ciList != null && !ciList.isEmpty()) {
                final CalendarInstance calendarInstance = ciList.get(0);
                final boolean isCalendarAssociatedWithEntity = this.calendarReadPlatformService
                        .isCalendarAssociatedWithEntity(calendarInstance.getEntityId(),
                                calendarInstance.getCalendar().getId(),
                                CalendarEntityType.LOANS.getValue().longValue());
                if (isCalendarAssociatedWithEntity) {
                    this.calendarRepository.delete(calendarInstance.getCalendar());
                }
                if (calendarInstance.getCalendar().getId() != calendar.getId()) {
                    calendarInstance.updateCalendar(calendar);
                    this.calendarInstanceRepository.saveAndFlush(calendarInstance);
                }
            } else {
                // attaching new calendar
                final CalendarInstance calendarInstance = new CalendarInstance(calendar,
                        existingLoanApplication.getId(), CalendarEntityType.LOANS.getValue());
                this.calendarInstanceRepository.save(calendarInstance);
            }

        } else {
            if (ciList != null && !ciList.isEmpty()) {
                final CalendarInstance existingCalendarInstance = ciList.get(0);
                final boolean isCalendarAssociatedWithEntity = this.calendarReadPlatformService
                        .isCalendarAssociatedWithEntity(existingCalendarInstance.getEntityId(),
                                existingCalendarInstance.getCalendar().getId(),
                                CalendarEntityType.GROUPS.getValue().longValue());
                if (isCalendarAssociatedWithEntity) {
                    this.calendarInstanceRepository.delete(existingCalendarInstance);
                }
            }
            if (changes.containsKey("repaymentFrequencyNthDayType")
                    || changes.containsKey("repaymentFrequencyDayOfWeekType")) {
                if (changes.get("repaymentFrequencyNthDayType") == null) {
                    if (ciList != null && !ciList.isEmpty()) {
                        final CalendarInstance calendarInstance = ciList.get(0);
                        final boolean isCalendarAssociatedWithEntity = this.calendarReadPlatformService
                                .isCalendarAssociatedWithEntity(calendarInstance.getEntityId(),
                                        calendarInstance.getCalendar().getId(),
                                        CalendarEntityType.LOANS.getValue().longValue());
                        if (isCalendarAssociatedWithEntity) {
                            this.calendarInstanceRepository.delete(calendarInstance);
                            this.calendarRepository.delete(calendarInstance.getCalendar());
                        }
                    }
                } else {
                    Integer repaymentFrequencyTypeInt = command
                            .integerValueOfParameterNamed("repaymentFrequencyType");
                    if (repaymentFrequencyTypeInt != null) {
                        if (PeriodFrequencyType
                                .fromInt(repaymentFrequencyTypeInt) == PeriodFrequencyType.MONTHS) {
                            final String title = "loan_schedule_" + existingLoanApplication.getId();
                            final Integer typeId = CalendarType.COLLECTION.getValue();
                            final CalendarFrequencyType repaymentFrequencyType = CalendarFrequencyType.MONTHLY;
                            final Integer interval = command.integerValueOfParameterNamed("repaymentEvery");
                            LocalDate startDate = command
                                    .localDateValueOfParameterNamed("repaymentsStartingFromDate");
                            if (startDate == null)
                                startDate = command.localDateValueOfParameterNamed("expectedDisbursementDate");
                            final Calendar newCalendar = Calendar.createRepeatingCalendar(title, startDate,
                                    typeId, repaymentFrequencyType, interval,
                                    (Integer) changes.get("repaymentFrequencyDayOfWeekType"),
                                    (Integer) changes.get("repaymentFrequencyNthDayType"));
                            if (ciList != null && !ciList.isEmpty()) {
                                final CalendarInstance calendarInstance = ciList.get(0);
                                final boolean isCalendarAssociatedWithEntity = this.calendarReadPlatformService
                                        .isCalendarAssociatedWithEntity(calendarInstance.getEntityId(),
                                                calendarInstance.getCalendar().getId(),
                                                CalendarEntityType.LOANS.getValue().longValue());
                                if (isCalendarAssociatedWithEntity) {
                                    final Calendar existingCalendar = calendarInstance.getCalendar();
                                    if (existingCalendar != null) {
                                        String existingRecurrence = existingCalendar.getRecurrence();
                                        if (!existingRecurrence.equals(newCalendar.getRecurrence())) {
                                            existingCalendar.setRecurrence(newCalendar.getRecurrence());
                                            this.calendarRepository.save(existingCalendar);
                                        }
                                    }
                                }
                            } else {
                                this.calendarRepository.save(newCalendar);
                                final Integer calendarEntityType = CalendarEntityType.LOANS.getValue();
                                final CalendarInstance calendarInstance = new CalendarInstance(newCalendar,
                                        existingLoanApplication.getId(), calendarEntityType);
                                this.calendarInstanceRepository.save(calendarInstance);
                            }
                        }
                    }
                }
            }
        }

        // Save linked account information
        final String linkAccountIdParamName = "linkAccountId";
        final Long savingsAccountId = command.longValueOfParameterNamed(linkAccountIdParamName);
        AccountAssociations accountAssociations = this.accountAssociationsRepository.findByLoanIdAndType(loanId,
                AccountAssociationType.LINKED_ACCOUNT_ASSOCIATION.getValue());
        boolean isLinkedAccPresent = false;
        if (savingsAccountId == null) {
            if (accountAssociations != null) {
                if (this.fromJsonHelper.parameterExists(linkAccountIdParamName, command.parsedJson())) {
                    this.accountAssociationsRepository.delete(accountAssociations);
                    changes.put(linkAccountIdParamName, null);
                } else {
                    isLinkedAccPresent = true;
                }
            }
        } else {
            isLinkedAccPresent = true;
            boolean isModified = false;
            if (accountAssociations == null) {
                isModified = true;
            } else {
                final SavingsAccount savingsAccount = accountAssociations.linkedSavingsAccount();
                if (savingsAccount == null || !savingsAccount.getId().equals(savingsAccountId)) {
                    isModified = true;
                }
            }
            if (isModified) {
                final SavingsAccount savingsAccount = this.savingsAccountAssembler
                        .assembleFrom(savingsAccountId);
                this.fromApiJsonDeserializer.validatelinkedSavingsAccount(savingsAccount,
                        existingLoanApplication);
                if (accountAssociations == null) {
                    boolean isActive = true;
                    accountAssociations = AccountAssociations.associateSavingsAccount(existingLoanApplication,
                            savingsAccount, AccountAssociationType.LINKED_ACCOUNT_ASSOCIATION.getValue(),
                            isActive);
                } else {
                    accountAssociations.updateLinkedSavingsAccount(savingsAccount);
                }
                changes.put(linkAccountIdParamName, savingsAccountId);
                this.accountAssociationsRepository.save(accountAssociations);
            }
        }

        if (!isLinkedAccPresent) {
            final Set<LoanCharge> charges = existingLoanApplication.charges();
            for (final LoanCharge loanCharge : charges) {
                if (loanCharge.getChargePaymentMode().isPaymentModeAccountTransfer()) {
                    final String errorMessage = "one of the charges requires linked savings account for payment";
                    throw new LinkedAccountRequiredException("loanCharge", errorMessage);
                }
            }
        }

        if ((command.longValueOfParameterNamed(productIdParamName) != null)
                || (command.longValueOfParameterNamed(clientIdParamName) != null)
                || (command.longValueOfParameterNamed(groupIdParamName) != null)) {
            Long OfficeId = null;
            if (existingLoanApplication.getClient() != null) {
                OfficeId = existingLoanApplication.getClient().getOffice().getId();
            } else if (existingLoanApplication.getGroup() != null) {
                OfficeId = existingLoanApplication.getGroup().getOffice().getId();
            }
            officeSpecificLoanProductValidation(existingLoanApplication.getLoanProduct().getId(), OfficeId);
        }

        // updating loan interest recalculation details throwing null
        // pointer exception after saveAndFlush
        // http://stackoverflow.com/questions/17151757/hibernate-cascade-update-gives-null-pointer/17334374#17334374
        this.loanRepositoryWrapper.save(existingLoanApplication);

        if (productRelatedDetail.isInterestRecalculationEnabled()) {
            this.fromApiJsonDeserializer.validateLoanForInterestRecalculation(existingLoanApplication);
            if (changes.containsKey(LoanProductConstants.isInterestRecalculationEnabledParameterName)) {
                createAndPersistCalendarInstanceForInterestRecalculation(existingLoanApplication);

            }

        }

        return new CommandProcessingResultBuilder() //
                .withEntityId(loanId) //
                .withOfficeId(existingLoanApplication.getOfficeId()) //
                .withClientId(existingLoanApplication.getClientId()) //
                .withGroupId(existingLoanApplication.getGroupId()) //
                .withLoanId(existingLoanApplication.getId()) //
                .with(changes).build();
    } catch (final DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }
}

From source file:org.mitre.openid.connect.service.impl.TestMITREidDataService_1_2.java

@Test
public void testExportWhitelistedSites() throws IOException {
    WhitelistedSite site1 = new WhitelistedSite();
    site1.setId(1L);// www  . j a va 2 s .  c  o  m
    site1.setClientId("foo");

    WhitelistedSite site2 = new WhitelistedSite();
    site2.setId(2L);
    site2.setClientId("bar");

    WhitelistedSite site3 = new WhitelistedSite();
    site3.setId(3L);
    site3.setClientId("baz");

    Set<WhitelistedSite> allWhitelistedSites = ImmutableSet.of(site1, site2, site3);

    Mockito.when(clientRepository.getAllClients()).thenReturn(new HashSet<ClientDetailsEntity>());
    Mockito.when(approvedSiteRepository.getAll()).thenReturn(new HashSet<ApprovedSite>());
    Mockito.when(blSiteRepository.getAll()).thenReturn(new HashSet<BlacklistedSite>());
    Mockito.when(wlSiteRepository.getAll()).thenReturn(allWhitelistedSites);
    Mockito.when(authHolderRepository.getAll()).thenReturn(new ArrayList<AuthenticationHolderEntity>());
    Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet<OAuth2AccessTokenEntity>());
    Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet<OAuth2RefreshTokenEntity>());
    Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet<SystemScope>());

    // do the data export
    StringWriter stringWriter = new StringWriter();
    JsonWriter writer = new JsonWriter(stringWriter);
    writer.beginObject();
    dataService.exportData(writer);
    writer.endObject();
    writer.close();

    // parse the output as a JSON object for testing
    JsonElement elem = new JsonParser().parse(stringWriter.toString());
    JsonObject root = elem.getAsJsonObject();

    // make sure the root is there
    assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_2), is(true));

    JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_2).getAsJsonObject();

    // make sure all the root elements are there
    assertThat(config.has(MITREidDataService.CLIENTS), is(true));
    assertThat(config.has(MITREidDataService.GRANTS), is(true));
    assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true));
    assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true));
    assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true));
    assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true));

    // make sure the root elements are all arrays
    assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true));

    // check our scope list (this test)
    JsonArray sites = config.get(MITREidDataService.WHITELISTEDSITES).getAsJsonArray();

    assertThat(sites.size(), is(3));
    // check for both of our sites in turn
    Set<WhitelistedSite> checked = new HashSet<>();
    for (JsonElement e : sites) {
        assertThat(e.isJsonObject(), is(true));
        JsonObject site = e.getAsJsonObject();

        WhitelistedSite compare = null;
        if (site.get("id").getAsLong() == site1.getId().longValue()) {
            compare = site1;
        } else if (site.get("id").getAsLong() == site2.getId().longValue()) {
            compare = site2;
        } else if (site.get("id").getAsLong() == site3.getId().longValue()) {
            compare = site3;
        }

        if (compare == null) {
            fail("Could not find matching whitelisted site id: " + site.get("id").getAsString());
        } else {
            assertThat(site.get("clientId").getAsString(), equalTo(compare.getClientId()));
            checked.add(compare);
        }
    }
    // make sure all of our clients were found
    assertThat(checked.containsAll(allWhitelistedSites), is(true));

}

From source file:org.apache.jackrabbit.jcr2spi.state.TransientItemStateManager.java

/**
 * Create the change log for the tree starting at <code>target</code>. This
 * includes a  check if the ChangeLog to be created is totally 'self-contained'
 * and independent; items within the scope of this update operation (i.e.
 * below the target) must not have dependencies outside of this tree (e.g.
 * moving a node requires that the target node including both old and new
 * parents are saved)./*from   ww  w.j  a va  2s  .  c om*/
 *
 * @param target
 * @param throwOnStale Throws InvalidItemStateException if either the given
 * <code>ItemState</code> or any of its descendants is stale and the flag is true.
 * @return
 * @throws InvalidItemStateException if a stale <code>ItemState</code> is
 * encountered while traversing the state hierarchy. The <code>changeLog</code>
 * might have been populated with some transient item states. A client should
 * therefore not reuse the <code>changeLog</code> if such an exception is thrown.
 * @throws RepositoryException if <code>state</code> is a new item state.
 */
ChangeLog getChangeLog(ItemState target, boolean throwOnStale)
        throws InvalidItemStateException, ConstraintViolationException, RepositoryException {
    // fail-fast test: check status of this item's state
    if (target.getStatus() == Status.NEW) {
        String msg = "Cannot save/revert an item with status NEW (" + target + ").";
        log.debug(msg);
        throw new RepositoryException(msg);
    }
    if (throwOnStale && Status.isStale(target.getStatus())) {
        String msg = "Attempt to save/revert an item, that has been externally modified (" + target + ").";
        log.debug(msg);
        throw new InvalidItemStateException(msg);
    }

    Set<Operation> ops = new LinkedHashSet<Operation>();
    Set<ItemState> affectedStates = new LinkedHashSet<ItemState>();

    HierarchyEntry he = target.getHierarchyEntry();
    if (he.getParent() == null) {
        // the root entry -> the complete change log can be used for
        // simplicity. collecting ops, states can be omitted.
        if (throwOnStale && !staleStates.isEmpty()) {
            String msg = "Cannot save changes: States has been modified externally.";
            log.debug(msg);
            throw new InvalidItemStateException(msg);
        } else {
            affectedStates.addAll(staleStates);
        }
        ops.addAll(operations);
        affectedStates.addAll(addedStates);
        affectedStates.addAll(modifiedStates);
        affectedStates.addAll(removedStates);
    } else {
        // not root entry:
        // - check if there is a stale state in the scope (save only)
        if (throwOnStale) {
            for (ItemState state : staleStates) {
                if (containedInTree(target, state)) {
                    String msg = "Cannot save changes: States has been modified externally.";
                    log.debug(msg);
                    throw new InvalidItemStateException(msg);
                }
            }
        }
        // - collect all affected states within the scope of save/undo
        Iterator[] its = new Iterator[] { addedStates.iterator(), removedStates.iterator(),
                modifiedStates.iterator() };
        IteratorChain chain = new IteratorChain(its);
        if (!throwOnStale) {
            chain.addIterator(staleStates.iterator());
        }
        while (chain.hasNext()) {
            ItemState state = (ItemState) chain.next();
            if (containedInTree(target, state)) {
                affectedStates.add(state);
            }
        }
        // - collect the set of operations and
        //   check if the affected states listed by the operations are all
        //   listed in the modified,removed or added states collected by this
        //   changelog.
        for (Operation op : operations) {
            Collection<ItemState> opStates = op.getAffectedItemStates();
            for (ItemState state : opStates) {
                if (affectedStates.contains(state)) {
                    // operation needs to be included
                    if (!affectedStates.containsAll(opStates)) {
                        // incomplete changelog: need to save a parent as well
                        String msg = "ChangeLog is not self contained.";
                        throw new ConstraintViolationException(msg);
                    }
                    // no violation: add operation an stop iteration over
                    // all affected states present in the operation.
                    ops.add(op);
                    break;
                }
            }
        }
    }

    ChangeLog cl = new ChangeLog(target, ops, affectedStates);
    return cl;
}

From source file:org.apache.accumulo.test.proxy.SimpleProxyBase.java

@Test
public void userManagement() throws Exception {

    String user;// w  w  w  .  j a v a 2  s.  c om
    ClusterUser otherClient = null;
    ByteBuffer password = s2bb("password");
    if (isKerberosEnabled()) {
        otherClient = getKdc().getClientPrincipal(1);
        user = otherClient.getPrincipal();
    } else {
        user = getUniqueNames(1)[0];
    }

    // create a user
    client.createLocalUser(creds, user, password);
    // change auths
    Set<String> users = client.listLocalUsers(creds);
    Set<String> expectedUsers = new HashSet<String>(Arrays.asList(clientPrincipal, user));
    assertTrue("Did not find all expected users: " + expectedUsers, users.containsAll(expectedUsers));
    HashSet<ByteBuffer> auths = new HashSet<ByteBuffer>(Arrays.asList(s2bb("A"), s2bb("B")));
    client.changeUserAuthorizations(creds, user, auths);
    List<ByteBuffer> update = client.getUserAuthorizations(creds, user);
    assertEquals(auths, new HashSet<ByteBuffer>(update));

    // change password
    if (!isKerberosEnabled()) {
        password = s2bb("");
        client.changeLocalUserPassword(creds, user, password);
        assertTrue(client.authenticateUser(creds, user, s2pp(ByteBufferUtil.toString(password))));
    }

    if (isKerberosEnabled()) {
        UserGroupInformation.loginUserFromKeytab(otherClient.getPrincipal(),
                otherClient.getKeytab().getAbsolutePath());
        final UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
        // Re-login in and make a new connection. Can't use the previous one

        TestProxyClient otherProxyClient = null;
        try {
            otherProxyClient = new TestProxyClient(hostname, proxyPort, factory, proxyPrimary, ugi);
            otherProxyClient.proxy().login(user, Collections.<String, String>emptyMap());
        } finally {
            if (null != otherProxyClient) {
                otherProxyClient.close();
            }
        }
    } else {
        // check login with new password
        client.login(user, s2pp(ByteBufferUtil.toString(password)));
    }
}

From source file:org.semispace.SemiSpace.java

/**
 * <p>If this is a read (not a take), then we must confirm that the agent's name
 * is not already in the entry</p>
 * <p>Note that this routine uses <code>Collections.containsAll</code> which means
 * that the {@link ITuple} in question must contain all of the fields and values
 * found in <code>templateSubSet</code></p>
 * @param containerEntrySet//from   w  w  w . j  a v  a 2s.  c  o m
 * @param templateSubSet
 * @param isToTakeTheLease 
 * @param searchMap TODO
 * @param theTuple TODO
 * @return
 */
private boolean hasSubSet(Set<Entry<String, Object>> containerEntrySet, Map<String, Object> templateSubSet,
        boolean isToTakeTheLease, Map<String, Object> searchMap, ISemiSpaceTuple theTuple) {
    if (templateSubSet == null) {
        throw new SemiSpaceUsageException("Did not expect template sub set to be null");
    }
    //HUGE ISSUE: as this code is written, the templates include an ID value
    // which can NEVER be the same as a given tuple.
    templateSubSet.remove(ITupleFields.ID);
    //searchMap is from the tuple itself. In theory, if the tuple is read by an agent,
    //then that agent's name should be in it on the second pass.
    //        log.logDebug("HASSUBSET-0 "+searchMap + " ||| "+templateSubSet);
    //NOTE: template has a String individual agentName whereas tuples
    // accumulate agentName in lists
    String agentName = (String) templateSubSet.get(ITupleFields.AGENT_NAME);
    Set<Entry<String, Object>> templateEntrySet = templateSubSet.entrySet();
    //        log.logDebug("HASSUBSET-1 "+templateEntrySet+" "+agentName+" "+isToTakeTheLease);
    boolean result = false;
    if (!isToTakeTheLease && agentName != null) {
        //has this agent seen this tuple before?
        Object o = searchMap.get(ITupleFields.AGENT_NAME);
        //          log.logDebug("HASSUBSET-2 "+o);
        if (o != null) {
            if (o instanceof String)
                result = ((String) o).equals(agentName);
            else
                result = ((List) o).contains(agentName);
        }

    }
    //        log.logDebug("HASSUBSET-3 "+result);
    //note that "true" means this agent has seen this tuple before
    //so just leave with a "not found" result
    if (result)
        return false;
    //The point here is that agentName is not a content field and, if present
    agentName = (String) templateSubSet.remove(ITupleFields.AGENT_NAME);
    //haven't seen it, is it the one?
    result = containerEntrySet.containsAll(templateEntrySet);
    //MUST PUT IT BACK IN THE TEMPLATE since the template is used in iterations
    if (agentName != null)
        templateSubSet.put(ITupleFields.AGENT_NAME, agentName);
    //        log.logDebug("HASSUBSET-4 "+result+" "+containerEntrySet+" "+templateEntrySet);
    if (result) {
        //We found this tuple, so tell it that "agentName" was here!
        //THIS IS COMPLEX!
        // Just adding the agent name back here doesn't solve the problem
        // since the next time the agent asks, the tuple will be fetched
        // back from the queue (until it is times out or is taken) and the situation
        // remains the same.
        if (theTuple != null)
            theTuple.addAgentName(agentName);
    }
    return result;
}

From source file:amie.keys.CSAKey.java

/**
 * It determines whether there exists a more general version of the given conditional key, a version of the
 * key with the exact same relations but fewer instantiations. For instance
 * if the key states lastname | nationality=French, field=Databases but the map contains a key
 * lastname nationality | field=Databases (here nationality is not instantiated), the method will report 
 * this as a subsumption case and return true. 
 * @param conditionalKey//from  w w  w.  ja va2s  .  c  o  m
 * @param conditionRule
 * @param conditions2Keys2
 * @return
 */
private boolean isSubsumedByKey(Rule conditionalKey, Rule conditionRule,
        MultiMap<Rule, Rule> conditions2Keys2) {
    if (conditionRule.getLength() < 2) {
        return false;
    }

    Set<ByteString> instantiations = new LinkedHashSet<>();
    Set<ByteString> instantiatedRelations = new LinkedHashSet<>();
    Set<ByteString> nonInstantiatedRelations = new LinkedHashSet<>();
    Utilities.parseConditionalKey(conditionalKey, nonInstantiatedRelations, instantiations,
            instantiatedRelations);

    /**
     * Now get all possible simpler versions of the condition If the
     * condition is field=Databases, residence=Paris, gender=female the
     * method returns: field=Databases, residence=Paris field=Database,
     * gender=female residence=Paris, gender=female residence=Paris
     * gender=female field=Databases *
     */
    List<Rule> properSubconditions = getAllProperSubconditions(conditionRule);
    for (Rule subCondition : properSubconditions) {
        List<Rule> potentialParents = conditions2Keys2.get(subCondition);
        if (potentialParents != null) {
            for (Rule potentialParent : potentialParents) {
                if (potentialParent.getLength() != conditionalKey.getLength()) {
                    // System.out.println("potentialParent:" + potentialParent);
                    continue;
                }
                Set<ByteString> instantiatedRelationsParent = new LinkedHashSet<>();
                Set<ByteString> nonInstantiatedRelationsParent = new LinkedHashSet<>();
                Set<ByteString> instantiationsParent = new LinkedHashSet<>();
                Utilities.parseConditionalKey(potentialParent, nonInstantiatedRelationsParent,
                        instantiationsParent, instantiatedRelationsParent);
                Set<ByteString> instansiatedNonInstantiatedRelations = new LinkedHashSet<>();
                instansiatedNonInstantiatedRelations.addAll(instantiatedRelations);
                instansiatedNonInstantiatedRelations.addAll(nonInstantiatedRelations);
                Set<ByteString> instansiatedNonInstantiatedRelationsParent = new LinkedHashSet<>();
                instansiatedNonInstantiatedRelationsParent.addAll(instantiatedRelationsParent);
                instansiatedNonInstantiatedRelationsParent.addAll(nonInstantiatedRelationsParent);
                if (instantiatedRelations.containsAll(instantiatedRelationsParent)
                        && nonInstantiatedRelationsParent.containsAll(nonInstantiatedRelations)
                        && instansiatedNonInstantiatedRelationsParent
                                .containsAll(instansiatedNonInstantiatedRelations)) {
                    return true;
                }
            }
        }
    }

    return false;
}

From source file:org.mitre.openid.connect.service.impl.TestMITREidDataService_1_3.java

@Test
public void testExportRefreshTokens() throws IOException, ParseException {
    String expiration1 = "2014-09-10T22:49:44.090+0000";
    Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH);

    ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class);
    when(mockedClient1.getClientId()).thenReturn("mocked_client_1");

    AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class);
    when(mockedAuthHolder1.getId()).thenReturn(1L);

    OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity();
    token1.setId(1L);//  w  w w  .j av a 2  s  .  com
    token1.setClient(mockedClient1);
    token1.setExpiration(expirationDate1);
    token1.setJwt(JWTParser
            .parse("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."));
    token1.setAuthenticationHolder(mockedAuthHolder1);

    String expiration2 = "2015-01-07T18:31:50.079+0000";
    Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH);

    ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class);
    when(mockedClient2.getClientId()).thenReturn("mocked_client_2");

    AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class);
    when(mockedAuthHolder2.getId()).thenReturn(2L);

    OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity();
    token2.setId(2L);
    token2.setClient(mockedClient2);
    token2.setExpiration(expirationDate2);
    token2.setJwt(JWTParser
            .parse("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."));
    token2.setAuthenticationHolder(mockedAuthHolder2);

    Set<OAuth2RefreshTokenEntity> allRefreshTokens = ImmutableSet.of(token1, token2);

    Mockito.when(clientRepository.getAllClients()).thenReturn(new HashSet<ClientDetailsEntity>());
    Mockito.when(approvedSiteRepository.getAll()).thenReturn(new HashSet<ApprovedSite>());
    Mockito.when(wlSiteRepository.getAll()).thenReturn(new HashSet<WhitelistedSite>());
    Mockito.when(blSiteRepository.getAll()).thenReturn(new HashSet<BlacklistedSite>());
    Mockito.when(authHolderRepository.getAll()).thenReturn(new ArrayList<AuthenticationHolderEntity>());
    Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet<OAuth2AccessTokenEntity>());
    Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(allRefreshTokens);
    Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet<SystemScope>());

    // do the data export
    StringWriter stringWriter = new StringWriter();
    JsonWriter writer = new JsonWriter(stringWriter);
    writer.beginObject();
    dataService.exportData(writer);
    writer.endObject();
    writer.close();

    // parse the output as a JSON object for testing
    JsonElement elem = new JsonParser().parse(stringWriter.toString());
    JsonObject root = elem.getAsJsonObject();

    // make sure the root is there
    assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_3), is(true));

    JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_3).getAsJsonObject();

    // make sure all the root elements are there
    assertThat(config.has(MITREidDataService.CLIENTS), is(true));
    assertThat(config.has(MITREidDataService.GRANTS), is(true));
    assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true));
    assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true));
    assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true));
    assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true));

    // make sure the root elements are all arrays
    assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true));

    // check our refresh token list (this test)
    JsonArray refreshTokens = config.get(MITREidDataService.REFRESHTOKENS).getAsJsonArray();

    assertThat(refreshTokens.size(), is(2));
    // check for both of our refresh tokens in turn
    Set<OAuth2RefreshTokenEntity> checked = new HashSet<>();
    for (JsonElement e : refreshTokens) {
        assertThat(e.isJsonObject(), is(true));
        JsonObject token = e.getAsJsonObject();

        OAuth2RefreshTokenEntity compare = null;
        if (token.get("id").getAsLong() == token1.getId()) {
            compare = token1;
        } else if (token.get("id").getAsLong() == token2.getId()) {
            compare = token2;
        }

        if (compare == null) {
            fail("Could not find matching id: " + token.get("id").getAsString());
        } else {
            assertThat(token.get("id").getAsLong(), equalTo(compare.getId()));
            assertThat(token.get("clientId").getAsString(), equalTo(compare.getClient().getClientId()));
            assertThat(token.get("expiration").getAsString(),
                    equalTo(formatter.print(compare.getExpiration(), Locale.ENGLISH)));
            assertThat(token.get("value").getAsString(), equalTo(compare.getValue()));
            assertThat(token.get("authenticationHolderId").getAsLong(),
                    equalTo(compare.getAuthenticationHolder().getId()));
            checked.add(compare);
        }
    }
    // make sure all of our refresh tokens were found
    assertThat(checked.containsAll(allRefreshTokens), is(true));
}

From source file:org.mitre.openid.connect.service.impl.TestMITREidDataService_1_3.java

@Test
public void testExportSystemScopes() throws IOException {
    SystemScope scope1 = new SystemScope();
    scope1.setId(1L);/*from   w ww . j  ava2  s.co m*/
    scope1.setValue("scope1");
    scope1.setDescription("Scope 1");
    scope1.setRestricted(true);
    scope1.setDefaultScope(false);
    scope1.setIcon("glass");

    SystemScope scope2 = new SystemScope();
    scope2.setId(2L);
    scope2.setValue("scope2");
    scope2.setDescription("Scope 2");
    scope2.setRestricted(false);
    scope2.setDefaultScope(false);
    scope2.setIcon("ball");

    SystemScope scope3 = new SystemScope();
    scope3.setId(3L);
    scope3.setValue("scope3");
    scope3.setDescription("Scope 3");
    scope3.setRestricted(false);
    scope3.setDefaultScope(true);
    scope3.setIcon("road");

    Set<SystemScope> allScopes = ImmutableSet.of(scope1, scope2, scope3);

    Mockito.when(clientRepository.getAllClients()).thenReturn(new HashSet<ClientDetailsEntity>());
    Mockito.when(approvedSiteRepository.getAll()).thenReturn(new HashSet<ApprovedSite>());
    Mockito.when(wlSiteRepository.getAll()).thenReturn(new HashSet<WhitelistedSite>());
    Mockito.when(blSiteRepository.getAll()).thenReturn(new HashSet<BlacklistedSite>());
    Mockito.when(authHolderRepository.getAll()).thenReturn(new ArrayList<AuthenticationHolderEntity>());
    Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet<OAuth2AccessTokenEntity>());
    Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet<OAuth2RefreshTokenEntity>());
    Mockito.when(sysScopeRepository.getAll()).thenReturn(allScopes);

    // do the data export
    StringWriter stringWriter = new StringWriter();
    JsonWriter writer = new JsonWriter(stringWriter);
    writer.beginObject();
    dataService.exportData(writer);
    writer.endObject();
    writer.close();

    // parse the output as a JSON object for testing
    JsonElement elem = new JsonParser().parse(stringWriter.toString());
    JsonObject root = elem.getAsJsonObject();

    // make sure the root is there
    assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_3), is(true));

    JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_3).getAsJsonObject();

    // make sure all the root elements are there
    assertThat(config.has(MITREidDataService.CLIENTS), is(true));
    assertThat(config.has(MITREidDataService.GRANTS), is(true));
    assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true));
    assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true));
    assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true));
    assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true));

    // make sure the root elements are all arrays
    assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true));

    // check our scope list (this test)
    JsonArray scopes = config.get(MITREidDataService.SYSTEMSCOPES).getAsJsonArray();

    assertThat(scopes.size(), is(3));
    // check for both of our clients in turn
    Set<SystemScope> checked = new HashSet<>();
    for (JsonElement e : scopes) {
        assertThat(e.isJsonObject(), is(true));
        JsonObject scope = e.getAsJsonObject();

        SystemScope compare = null;
        if (scope.get("value").getAsString().equals(scope1.getValue())) {
            compare = scope1;
        } else if (scope.get("value").getAsString().equals(scope2.getValue())) {
            compare = scope2;
        } else if (scope.get("value").getAsString().equals(scope3.getValue())) {
            compare = scope3;
        }

        if (compare == null) {
            fail("Could not find matching scope value: " + scope.get("value").getAsString());
        } else {
            assertThat(scope.get("value").getAsString(), equalTo(compare.getValue()));
            assertThat(scope.get("description").getAsString(), equalTo(compare.getDescription()));
            assertThat(scope.get("icon").getAsString(), equalTo(compare.getIcon()));
            assertThat(scope.get("restricted").getAsBoolean(), equalTo(compare.isRestricted()));
            assertThat(scope.get("defaultScope").getAsBoolean(), equalTo(compare.isDefaultScope()));
            checked.add(compare);
        }
    }
    // make sure all of our clients were found
    assertThat(checked.containsAll(allScopes), is(true));

}

From source file:org.mitre.openid.connect.service.impl.TestMITREidDataService_1_2.java

@Test
public void testExportRefreshTokens() throws IOException, ParseException {
    String expiration1 = "2014-09-10T22:49:44.090+0000";
    Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH);

    ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class);
    when(mockedClient1.getClientId()).thenReturn("mocked_client_1");

    AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class);
    when(mockedAuthHolder1.getId()).thenReturn(1L);

    OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity();
    token1.setId(1L);/*from   w ww  . j  ava2  s .  c o  m*/
    token1.setClient(mockedClient1);
    token1.setExpiration(expirationDate1);
    token1.setJwt(JWTParser
            .parse("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."));
    token1.setAuthenticationHolder(mockedAuthHolder1);

    String expiration2 = "2015-01-07T18:31:50.079+0000";
    Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH);

    ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class);
    when(mockedClient2.getClientId()).thenReturn("mocked_client_2");

    AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class);
    when(mockedAuthHolder2.getId()).thenReturn(2L);

    OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity();
    token2.setId(2L);
    token2.setClient(mockedClient2);
    token2.setExpiration(expirationDate2);
    token2.setJwt(JWTParser
            .parse("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."));
    token2.setAuthenticationHolder(mockedAuthHolder2);

    Set<OAuth2RefreshTokenEntity> allRefreshTokens = ImmutableSet.of(token1, token2);

    Mockito.when(clientRepository.getAllClients()).thenReturn(new HashSet<ClientDetailsEntity>());
    Mockito.when(approvedSiteRepository.getAll()).thenReturn(new HashSet<ApprovedSite>());
    Mockito.when(wlSiteRepository.getAll()).thenReturn(new HashSet<WhitelistedSite>());
    Mockito.when(blSiteRepository.getAll()).thenReturn(new HashSet<BlacklistedSite>());
    Mockito.when(authHolderRepository.getAll()).thenReturn(new ArrayList<AuthenticationHolderEntity>());
    Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet<OAuth2AccessTokenEntity>());
    Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(allRefreshTokens);
    Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet<SystemScope>());

    // do the data export
    StringWriter stringWriter = new StringWriter();
    JsonWriter writer = new JsonWriter(stringWriter);
    writer.beginObject();
    dataService.exportData(writer);
    writer.endObject();
    writer.close();

    // parse the output as a JSON object for testing
    JsonElement elem = new JsonParser().parse(stringWriter.toString());
    JsonObject root = elem.getAsJsonObject();

    // make sure the root is there
    assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_2), is(true));

    JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_2).getAsJsonObject();

    // make sure all the root elements are there
    assertThat(config.has(MITREidDataService.CLIENTS), is(true));
    assertThat(config.has(MITREidDataService.GRANTS), is(true));
    assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true));
    assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true));
    assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true));
    assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true));
    assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true));

    // make sure the root elements are all arrays
    assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true));
    assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true));

    // check our refresh token list (this test)
    JsonArray refreshTokens = config.get(MITREidDataService.REFRESHTOKENS).getAsJsonArray();

    assertThat(refreshTokens.size(), is(2));
    // check for both of our refresh tokens in turn
    Set<OAuth2RefreshTokenEntity> checked = new HashSet<>();
    for (JsonElement e : refreshTokens) {
        assertThat(e.isJsonObject(), is(true));
        JsonObject token = e.getAsJsonObject();

        OAuth2RefreshTokenEntity compare = null;
        if (token.get("id").getAsLong() == token1.getId()) {
            compare = token1;
        } else if (token.get("id").getAsLong() == token2.getId()) {
            compare = token2;
        }

        if (compare == null) {
            fail("Could not find matching id: " + token.get("id").getAsString());
        } else {
            assertThat(token.get("id").getAsLong(), equalTo(compare.getId()));
            assertThat(token.get("clientId").getAsString(), equalTo(compare.getClient().getClientId()));
            assertThat(token.get("expiration").getAsString(),
                    equalTo(formatter.print(compare.getExpiration(), Locale.ENGLISH)));
            assertThat(token.get("value").getAsString(), equalTo(compare.getValue()));
            assertThat(token.get("authenticationHolderId").getAsLong(),
                    equalTo(compare.getAuthenticationHolder().getId()));
            checked.add(compare);
        }
    }
    // make sure all of our refresh tokens were found
    assertThat(checked.containsAll(allRefreshTokens), is(true));
}