Example usage for org.springframework.util Assert notEmpty

List of usage examples for org.springframework.util Assert notEmpty

Introduction

In this page you can find the example usage for org.springframework.util Assert notEmpty.

Prototype

public static void notEmpty(@Nullable Map<?, ?> map, Supplier<String> messageSupplier) 

Source Link

Document

Assert that a Map contains entries; that is, it must not be null and must contain at least one entry.

Usage

From source file:net.sf.gazpachoquest.services.core.impl.ResearchServiceImpl.java

@Override
@Transactional(readOnly = false)/*w  w w . j  av  a2s  .c  o m*/
public Research save(Research research, Set<QuestionnaireDefinition> questionnaireDefinitions,
        Set<User> respondents) {
    research = saveOld(research);
    if (ResearchAccessType.BY_INVITATION.equals(research.getType())) {
        for (QuestionnaireDefinition questionnaireDefinition : questionnaireDefinitions) {

            questionnaireDefinition = questionnaireDefinitionRepository
                    .findOne(questionnaireDefinition.getId());

            Map<MailMessageTemplateType, MailMessageTemplate> templates = questionnaireDefinition
                    .getMailTemplates();
            MailMessageTemplate invitationTemplate = templates.get(MailMessageTemplateType.INVITATION);

            Group example = Group.with().name("Respondents").build();
            Group respondentsGroup = groupRepository.findOneByExample(example, new SearchParameters())
                    .orElseThrow(() -> new EmptyResultDataAccessException(
                            String.format("No %s entity with name %s found!", Group.class, "Respondents"), 1));

            for (User respondent : respondents) {
                Assert.state(!respondent.isNew(), "Persist all respondents before starting a research.");
                Questionnaire questionnaire = Questionnaire.with().status(EntityStatus.CONFIRMED)
                        .research(research).questionnaireDefinition(questionnaireDefinition)
                        .respondent(respondent).build();
                questionnaire = questionnaireRepository.save(questionnaire);
                // Create answers holder
                QuestionnaireAnswers questionnaireAnswers = new QuestionnaireAnswers();
                questionnaireAnswers = questionnaireAnswersRepository
                        .save(questionnaire.getQuestionnaireDefinition().getId(), questionnaireAnswers);
                questionnaire.setAnswersId(questionnaireAnswers.getId());

                String token = tokenGenerator.generate();

                respondent = userRepository.findOne(respondent.getId());
                // Grant permissions over questionnaire to respondent
                QuestionnairePermission permission = QuestionnairePermission.with().addPerm(Perm.READ)
                        .addPerm(Perm.UPDATE).user(respondent).target(questionnaire).build();
                questionnairePermissionRepository.save(permission);

                PersonalInvitation personalInvitation = PersonalInvitation.with().research(research)
                        .token(token).status(InvitationStatus.ACTIVE).respondent(respondent).build();
                invitationRepository.save(personalInvitation);

                MailMessage mailMessage = composeMailMessage(invitationTemplate, respondent, token);
                mailMessageRepository.save(mailMessage);

                if (groupRepository.isUserInGroup(respondent.getId(), "Respondents") == 0) {
                    respondentsGroup.assignUser(respondent);
                }
            }
        }
    } else {
        Assert.notEmpty(questionnaireDefinitions, "questionnairDefinitions required");
        Assert.state(questionnaireDefinitions.size() == 1,
                "Only one questionnairDefinitions supported for Open Access researches");
        String token = tokenGenerator.generate();

        AnonymousInvitation anonymousInvitation = AnonymousInvitation.with().research(research).token(token)
                .status(InvitationStatus.ACTIVE).build();
        invitationRepository.save(anonymousInvitation);
    }
    ResearchPermission permission = ResearchPermission.with().addPerm(Perm.READ).addPerm(Perm.UPDATE)
            .addPerm(Perm.DELETE).user(getAuthenticatedUser()).target(research).build();
    researchPermissionRepository.save(permission);
    return research;
}

From source file:fr.mby.saml2.sp.opensaml.query.engine.AuthnResponseQueryProcessor.java

/**
 * Extract the authentications informations from opensaml Authn Response.
 * /*from w  w w. ja  va 2 s  .  c om*/
 * @param authnResponse
 * @param idpConnector
 * @param responseSigned
 * @return a list of authentications embeded in the Authn Response
 * @throws UnsupportedSamlOperation
 * @throws SamlSecurityException
 * @throws SamlProcessingException
 */
protected List<IAuthentication> extractSamlAuthentications(final Response authnResponse)
        throws SamlSecurityException, UnsupportedSamlOperation, SamlProcessingException {
    final List<IAuthentication> authentications = new ArrayList<IAuthentication>();

    Assert.notEmpty(this.assertions, "Assertions not already processed !");

    try {
        // Our Authn Response could carry multiple assertions, we are interressed only by an AuthnStatement
        // Assertion.
        for (final Assertion assertion : this.assertions) {
            // We look for an AuthnStatement Assertion !
            final List<AuthnStatement> authnStatements = assertion.getAuthnStatements();
            if (authnStatements != null) {
                for (final AuthnStatement authnStatement : authnStatements) {
                    // MBD FIX 2013-04-30 : Loop on all AuthnStatement
                    final Subject subject = this.validateAndRetrieveSubject(assertion);
                    final NameID nameId = subject.getNameID();
                    if (nameId == null) {
                        throw new UnsupportedSamlOperation(
                                "Subject NameID missing other ID types are not supported !");
                    }

                    final BasicSamlAuthentication authn = new BasicSamlAuthentication();
                    authn.setAuthenticationInstant(authnStatement.getAuthnInstant());
                    authn.setSubjectId(nameId.getValue());
                    authn.setSessionIndex(authnStatement.getSessionIndex());

                    this.processAuthnAttributes(assertion, authn);

                    // Add the authentication to the list
                    authn.lock();
                    authentications.add(authn);
                }
            }
        }
    } catch (final SamlValidationException e) {
        throw new SamlProcessingException("Validation of Assertion Subjet failed !", e);
    } catch (final DecryptionException e) {
        throw new SamlProcessingException("Decryption of SAML Assertions failed !", e);
    }

    return authentications;
}

From source file:org.devgateway.ocds.web.rest.controller.AwardsWonLostController.java

@ApiOperation(value = "Number of procurements by tender status for a list of procuring entities")
@RequestMapping(value = "/api/procurementsByTenderStatus", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> procurementsByTenderStatus(@ModelAttribute @Valid final YearFilterPagingRequest filter) {
    Assert.notEmpty(filter.getProcuringEntityId(), "procuringEntityId must not be empty!");

    Aggregation agg = newAggregation(/* w w w . jav  a  2  s . c  o  m*/
            match(where(MongoConstants.FieldNames.TENDER_STATUS).exists(true)
                    .andOperator(getYearDefaultFilterCriteria(filter, TENDER_PERIOD_START_DATE))),
            group(Fields.from(
                    Fields.field("procuringEntityId", MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_ID),
                    Fields.field("procuringEntityName", MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_NAME),
                    Fields.field("tenderStatus", MongoConstants.FieldNames.TENDER_STATUS))).count()
                            .as("count"));

    return releaseAgg(agg);
}

From source file:com.epam.catgenome.manager.vcf.VcfManager.java

/**
 * Loads a single variation with extended info
 *
 * @param query {@code VariationQuery}, defining variation to load
 * @return desired {@code Variation} from VCF file
 *//*from w w w  . j  av  a 2 s  .c  o m*/
public Variation loadVariation(final VariationQuery query) throws FeatureFileReadingException {
    // converts query to a simple track corresponded to a single nucleotide position, where a particular
    // variation should be presented

    final Track<Variation> track = new Track<>();
    track.setScaleFactor(1D);
    track.setId(query.getId());
    track.setEndIndex(query.getPosition());
    track.setStartIndex(query.getPosition());
    track.setChromosome(referenceGenomeManager.loadChromosome(query.getChromosomeId()));

    // tries to load variation
    loadVariations(track, query.getSampleId(), true, false);
    Assert.notEmpty(track.getBlocks(),
            getMessage(MessagesConstants.ERROR_NO_SUCH_VARIATION, query.getPosition()));
    Variation variation = track.getBlocks().get(0);
    extendInfoFields(variation);
    VcfFile vcfFile = vcfFileManager.loadVcfFile(query.getId());
    Reference reference = referenceGenomeManager.loadReferenceGenome(vcfFile.getReferenceId());
    if (reference.getGeneFile() != null) {
        Set<String> geneIds = featureIndexManager.fetchGeneIds(variation.getStartIndex(),
                variation.getEndIndex(), Collections.singletonList(reference.getGeneFile()),
                track.getChromosome());
        variation.setGeneNames(geneIds);
    }

    return variation;
}

From source file:org.devgateway.ocds.web.rest.controller.AwardsWonLostController.java

@ApiOperation(value = "Number of procurements by procurement method for a list of procuring entities")
@RequestMapping(value = "/api/procurementsByProcurementMethod", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> procurementsByProcurementMethod(
        @ModelAttribute @Valid final YearFilterPagingRequest filter) {
    Assert.notEmpty(filter.getProcuringEntityId(), "procuringEntityId must not be empty!");

    Aggregation agg = newAggregation(/* ww w.j  av  a 2s  .co  m*/
            match(where(MongoConstants.FieldNames.TENDER_PROC_METHOD).exists(true)
                    .andOperator(getYearDefaultFilterCriteria(filter, TENDER_PERIOD_START_DATE))),
            group(Fields.from(
                    Fields.field("procuringEntityId", MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_ID),
                    Fields.field("procuringEntityName", MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_NAME),
                    Fields.field("tenderStatus", MongoConstants.FieldNames.TENDER_PROC_METHOD))).count()
                            .as("count"));

    return releaseAgg(agg);
}

From source file:org.bremersee.common.security.acls.jdbc.BasicLookupStrategy.java

/**
 * Looks up a batch of <code>ObjectIdentity</code>s directly from the database.
 * <p>/*  w  w  w  .ja v a 2s .  c  om*/
 * The caller is responsible for optimization issues, such as selecting the identities
 * to lookup, ensuring the cache doesn't contain them already, and adding the returned
 * elements to the cache etc.
 * <p>
 * This subclass is required to return fully valid <code>Acl</code>s, including
 * properly-configured parent ACLs.
 *
 */
private Map<ObjectIdentity, Acl> lookupObjectIdentities(final Collection<ObjectIdentity> objectIdentities,
        List<Sid> sids) {
    Assert.notEmpty(objectIdentities, "Must provide identities to lookup");

    final Map<Serializable, Acl> acls = new HashMap<>(); // contains
    // Acls
    // with
    // StubAclParents

    // Make the "acls" map contain all requested objectIdentities
    // (including markers to each parent in the hierarchy)
    String sql = computeRepeatingSql(lookupObjectIdentitiesWhereClause, objectIdentities.size());

    Set<Long> parentsToLookup = jdbcTemplate.query(sql, new PreparedStatementSetter() { // NOSONAR
        @Override
        public void setValues(PreparedStatement ps) throws SQLException {
            int i = 0;
            for (ObjectIdentity oid : objectIdentities) {
                // Determine prepared statement values for this iteration
                String type = oid.getType();

                // No need to check for nulls, as guaranteed non-null by
                // ObjectIdentity.getIdentifier() interface contract
                String identifier = oid.getIdentifier().toString();
                // Changed by Christian Bremer (cbr)
                //long id = (Long.valueOf(identifier)).longValue(); // NOSONAR

                // Inject values
                //ps.setString((2 * i) + 1, id); // NOSONAR
                ps.setString((2 * i) + 1, identifier);
                ps.setString((2 * i) + 2, type);
                i++;
            }
        }
    }, new ProcessResultSet(acls, sids));

    // Lookup the parents, now that our JdbcTemplate has released the database
    // connection (SEC-547)
    if (!parentsToLookup.isEmpty()) {
        lookupPrimaryKeys(acls, parentsToLookup, sids);
    }

    // Finally, convert our "acls" containing StubAclParents into true Acls
    Map<ObjectIdentity, Acl> resultMap = new HashMap<>();

    for (Acl inputAcl : acls.values()) {
        Assert.isInstanceOf(AclImpl.class, inputAcl, "Map should have contained an AclImpl");
        Assert.isInstanceOf(Long.class, ((AclImpl) inputAcl).getId(), "Acl.getId() must be Long");

        Acl result = convert(acls, (Long) ((AclImpl) inputAcl).getId());
        resultMap.put(result.getObjectIdentity(), result);
    }

    return resultMap;
}

From source file:de.extra.client.core.plugin.dummies.DummyQueryDataResponceOutputPlugin.java

/**
 * Liefert QueryArguments als List/*from w w  w .ja  v a 2s . c om*/
 * 
 * @return
 */
private List<String> getQueryArguments(final RequestTransport requestXml) {
    final RequestTransportBody transportBody = requestXml.getTransportBody();
    Assert.notNull(transportBody, "ResponseTransportBody is null");
    final DataType data = transportBody.getData();
    Assert.notNull(data, "TransportData is null");
    final ElementSequenceType elementSequence = data.getElementSequence();
    Assert.notNull(elementSequence, "TransportData.elementSequence is null");
    final List<Object> any = elementSequence.getAny();
    Assert.notNull(any, "ElementSequence is empty is null");
    Assert.isTrue(any.size() == 1, "ElementSequense beinhaltet mehr als ein Element");
    final Object dataRequestObject = any.get(0);
    Assert.isAssignable(DataRequest.class, dataRequestObject.getClass(),
            "Unexpectede ElementSequence entry" + dataRequestObject.getClass() + " Expected DataRequest.");
    final DataRequest dataRequest = (DataRequest) dataRequestObject;
    final DataRequestQuery query = dataRequest.getQuery();
    Assert.notNull(query, "Query is null");
    final List<DataRequestArgument> argument = query.getArgument();
    Assert.notNull(argument, "DataRequestArgument List is null");
    // Assert.isTrue(argument.size() == 1,
    // "DataRequestArgument List beinhaltet mehr als ein Element");
    final DataRequestArgument dataRequestArgument = argument.get(0);
    Assert.notNull(dataRequestArgument, "DataRequestArgument is null");
    final List<JAXBElement<?>> dataRequestArgumentContent = dataRequestArgument.getContent();
    Assert.notNull(dataRequestArgumentContent, "DataRequestArgument.content is null");
    Assert.isTrue(dataRequestArgumentContent.size() == 1,
            "DataRequestArgument.content  beinhaltet mehr als ein Element");
    final JAXBElement<?> jaxbElement = dataRequestArgumentContent.get(0);

    // TODO MAXRESP (06.11.12)
    boolean assignableOperand = false;
    final Object operandSetObject = jaxbElement.getValue();
    final List<String> queryArgumentList = new ArrayList<String>();
    // OperandSet oder Operand?
    if (operandSetObject.getClass().isAssignableFrom(OperandSet.class)) {
        assignableOperand = true;
        final OperandSet operandSet = (OperandSet) operandSetObject;
        final List<Operand> operandEQ = operandSet.getEQ();
        Assert.notNull(operandEQ, "operandEQ is null");
        Assert.notEmpty(operandEQ, "operandEQ is empty");
        for (final Operand operand : operandEQ) {
            final String operandValue = operand.getValue();
            queryArgumentList.add(operandValue);
        }
    } else if (operandSetObject.getClass().isAssignableFrom(Operand.class)) {
        // Fr Fachverfahren 'Sterbedaten Abgleich'!
        // Als OperandValue wird die maximale ResponseId erwartet (z.B. 31)
        // Als Dummy Server Antwort werden drei aufeinanderfolgende ID'S
        // (z.B. 32,33,34) generiert
        assignableOperand = true;
        final Operand operand = (Operand) operandSetObject;
        final String operandValue = operand.getValue();
        try {
            final long operandValueAsLong = Long.parseLong(operandValue);
            for (long respId = operandValueAsLong + 1; respId <= operandValueAsLong + 3; respId++) {
                queryArgumentList.add(String.valueOf(respId));
            }
        } catch (final NumberFormatException ex) {
            // Anderes Fachverfahren?
            queryArgumentList.add(operandValue);
        }
    }

    Assert.isTrue(assignableOperand, "Unexpected dataRequestArgumentContent entry"
            + dataRequestObject.getClass() + " Expected OperandSet or Operand.");
    return queryArgumentList;
}

From source file:com.epam.catgenome.manager.vcf.VcfManager.java

/**
 * Loads a single variation with extended info
 *
 * @param query {@code VariationQuery}, defining variation to load
 * @param fileUrl URL of VCF file resource
 * @param indexUrl URL of VCF index resource
 * @return desired {@code Variation} from VCF file
 */// w  w w  .j  a  v a2s .c  o m
public Variation loadVariation(final VariationQuery query, String fileUrl, String indexUrl)
        throws FeatureFileReadingException {
    // converts query to a simple track corresponded to a single nucleotide position, where a particular
    // variation should be presented

    final Track<Variation> track = new Track<>();
    track.setScaleFactor(1D);
    track.setEndIndex(query.getPosition());
    track.setStartIndex(query.getPosition());
    track.setChromosome(new Chromosome(query.getChromosomeId()));

    // tries to load variation
    loadVariations(track, fileUrl, indexUrl,
            query.getSampleId() != null ? query.getSampleId().intValue() : null, true, false);
    Assert.notEmpty(track.getBlocks(),
            getMessage(MessagesConstants.ERROR_NO_SUCH_VARIATION, query.getPosition()));
    Variation variation = track.getBlocks().get(0);
    extendInfoFields(variation);
    Reference reference = referenceGenomeManager.loadReferenceGenome(track.getChromosome().getReferenceId());
    if (reference.getGeneFile() != null) {
        Set<String> geneIds = featureIndexManager.fetchGeneIds(variation.getStartIndex(),
                variation.getEndIndex(), Collections.singletonList(reference.getGeneFile()),
                track.getChromosome());
        variation.setGeneNames(geneIds);
    }

    return variation;
}

From source file:org.devgateway.ocds.web.rest.controller.AwardsWonLostController.java

@ApiOperation(value = "List of buyers with releases for the given procuring entities."
        + "procuringEntityId is mandatory")
@RequestMapping(value = "/api/buyersForProcuringEntities", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> buyersProcuringEntities(@ModelAttribute @Valid final YearFilterPagingRequest filter) {
    Assert.notEmpty(filter.getProcuringEntityId(), "procuringEntityId must not be empty!");

    Aggregation agg = newAggregation(//from ww w.j  ava 2 s . co m
            match(where(MongoConstants.FieldNames.BUYER_ID).exists(true)
                    .andOperator(getYearDefaultFilterCriteria(filter, TENDER_PERIOD_START_DATE))),
            group(Fields.from(Fields.field("buyerId", MongoConstants.FieldNames.BUYER_ID),
                    Fields.field("buyerName", MongoConstants.FieldNames.BUYER_NAME),
                    Fields.field("procuringEntityId", MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_ID))));

    return releaseAgg(agg);
}

From source file:org.bremersee.common.security.acls.jdbc.BasicLookupStrategy.java

/**
 * The final phase of converting the <code>Map</code> of <code>AclImpl</code>
 * instances which contain <code>StubAclParent</code>s into proper, valid
 * <code>AclImpl</code>s with correct ACL parents.
 *
 * @param inputMap the unconverted <code>AclImpl</code>s
 * @param currentIdentity the current<code>Acl</code> that we wish to convert (this
 * may be// w  w w .jav a2  s.  c o  m
 *
 */
private AclImpl convert(Map<Serializable, Acl> inputMap, Long currentIdentity) {
    Assert.notEmpty(inputMap, "InputMap required");
    Assert.notNull(currentIdentity, "CurrentIdentity required");

    // Retrieve this Acl from the InputMap
    Acl uncastAcl = inputMap.get(currentIdentity);
    Assert.isInstanceOf(AclImpl.class, uncastAcl, "The inputMap contained a non-AclImpl");

    AclImpl inputAcl = (AclImpl) uncastAcl;

    Acl parent = inputAcl.getParentAcl();

    if ((parent != null) && parent instanceof StubAclParent) {
        // Lookup the parent
        StubAclParent stubAclParent = (StubAclParent) parent;
        parent = convert(inputMap, stubAclParent.getId());
    }

    // Now we have the parent (if there is one), create the true AclImpl
    AclImpl result = new AclImpl(inputAcl.getObjectIdentity(), inputAcl.getId(), aclAuthorizationStrategy,
            grantingStrategy, parent, null, inputAcl.isEntriesInheriting(), inputAcl.getOwner());

    // Copy the "aces" from the input to the destination

    // Obtain the "aces" from the input ACL
    List<AccessControlEntryImpl> aces = readAces(inputAcl);

    // Create a list in which to store the "aces" for the "result" AclImpl instance
    List<AccessControlEntryImpl> acesNew = new ArrayList<>();

    // Iterate over the "aces" input and replace each nested
    // AccessControlEntryImpl.getAcl() with the new "result" AclImpl instance
    // This ensures StubAclParent instances are removed, as per SEC-951
    for (AccessControlEntryImpl ace : aces) {
        setAclOnAce(ace, result);
        acesNew.add(ace);
    }

    // Finally, now that the "aces" have been converted to have the "result" AclImpl
    // instance, modify the "result" AclImpl instance
    setAces(result, acesNew);

    return result;
}