Example usage for org.springframework.context ConfigurableApplicationContext getBean

List of usage examples for org.springframework.context ConfigurableApplicationContext getBean

Introduction

In this page you can find the example usage for org.springframework.context ConfigurableApplicationContext getBean.

Prototype

Object getBean(String name) throws BeansException;

Source Link

Document

Return an instance, which may be shared or independent, of the specified bean.

Usage

From source file:org.apache.syncope.core.misc.MappingUtils.java

/**
 * Prepare attributes for sending to a connector instance.
 *
 * @param any given any object/*w ww .j a v  a 2 s  . com*/
 * @param password clear-text password
 * @param changePwd whether password should be included for propagation attributes or not
 * @param vAttrsToBeRemoved virtual attributes to be removed
 * @param vAttrsToBeUpdated virtual attributes to be added
 * @param enable whether any object must be enabled or not
 * @param provision provision information
 * @return connObjectLink + prepared attributes
 */
public static Pair<String, Set<Attribute>> prepareAttrs(final Any<?, ?, ?> any, final String password,
        final boolean changePwd, final Set<String> vAttrsToBeRemoved,
        final Map<String, AttrMod> vAttrsToBeUpdated, final Boolean enable, final Provision provision) {

    LOG.debug("Preparing resource attributes for {} with provision {} for attributes {}", any, provision,
            any.getPlainAttrs());

    ConfigurableApplicationContext context = ApplicationContextProvider.getApplicationContext();
    VirAttrCache virAttrCache = context.getBean(VirAttrCache.class);
    PasswordGenerator passwordGenerator = context.getBean(PasswordGenerator.class);

    Set<Attribute> attributes = new HashSet<>();
    String connObjectKey = null;

    for (MappingItem mapping : getMappingItems(provision, MappingPurpose.PROPAGATION)) {
        LOG.debug("Processing schema {}", mapping.getIntAttrName());

        try {
            if (mapping.getIntMappingType() == IntMappingType.UserVirtualSchema
                    || mapping.getIntMappingType() == IntMappingType.GroupVirtualSchema
                    || mapping.getIntMappingType() == IntMappingType.AnyObjectVirtualSchema) {

                LOG.debug("Expire entry cache {}-{}", any.getKey(), mapping.getIntAttrName());
                virAttrCache.expire(any.getType().getKey(), any.getKey(), mapping.getIntAttrName());
            }

            Pair<String, Attribute> preparedAttr = prepareAttr(provision, mapping, any, password,
                    passwordGenerator, vAttrsToBeRemoved, vAttrsToBeUpdated);

            if (preparedAttr != null && preparedAttr.getKey() != null) {
                connObjectKey = preparedAttr.getKey();
            }

            if (preparedAttr != null && preparedAttr.getValue() != null) {
                Attribute alreadyAdded = AttributeUtil.find(preparedAttr.getValue().getName(), attributes);

                if (alreadyAdded == null) {
                    attributes.add(preparedAttr.getValue());
                } else {
                    attributes.remove(alreadyAdded);

                    Set<Object> values = new HashSet<>(alreadyAdded.getValue());
                    values.addAll(preparedAttr.getValue().getValue());

                    attributes.add(AttributeBuilder.build(preparedAttr.getValue().getName(), values));
                }
            }
        } catch (Exception e) {
            LOG.debug("Attribute '{}' processing failed", mapping.getIntAttrName(), e);
        }
    }

    Attribute connObjectKeyExtAttr = AttributeUtil.find(getConnObjectKeyItem(provision).getExtAttrName(),
            attributes);
    if (connObjectKeyExtAttr != null) {
        attributes.remove(connObjectKeyExtAttr);
        attributes.add(AttributeBuilder.build(getConnObjectKeyItem(provision).getExtAttrName(), connObjectKey));
    }
    attributes.add(evaluateNAME(any, provision, connObjectKey));

    if (enable != null) {
        attributes.add(AttributeBuilder.buildEnabled(enable));
    }
    if (!changePwd) {
        Attribute pwdAttr = AttributeUtil.find(OperationalAttributes.PASSWORD_NAME, attributes);
        if (pwdAttr != null) {
            attributes.remove(pwdAttr);
        }
    }

    return new ImmutablePair<>(connObjectKey, attributes);
}

From source file:org.apache.syncope.core.misc.MappingUtils.java

/**
 * Prepare an attribute to be sent to a connector instance.
 *
 * @param provision external resource//from  w w w .  j  a  va 2 s  .  c om
 * @param mapItem mapping item for the given attribute
 * @param any any object
 * @param password clear-text password
 * @param passwordGenerator password generator
 * @param vAttrsToBeRemoved virtual attributes to be removed
 * @param vAttrsToBeUpdated virtual attributes to be added
 * @return connObjectLink + prepared attribute
 */
@SuppressWarnings("unchecked")
private static Pair<String, Attribute> prepareAttr(final Provision provision, final MappingItem mapItem,
        final Any<?, ?, ?> any, final String password, final PasswordGenerator passwordGenerator,
        final Set<String> vAttrsToBeRemoved, final Map<String, AttrMod> vAttrsToBeUpdated) {

    List<Any<?, ?, ?>> anys = new ArrayList<>();

    ConfigurableApplicationContext context = ApplicationContextProvider.getApplicationContext();
    AnyUtilsFactory anyUtilsFactory = context.getBean(AnyUtilsFactory.class);
    VirAttrHandler virAttrHandler = context.getBean(VirAttrHandler.class);

    switch (mapItem.getIntMappingType().getAnyTypeKind()) {
    case USER:
        if (any instanceof User) {
            anys.add(any);
        }
        break;

    case GROUP:
        if (any instanceof User) {
            UserDAO userDAO = context.getBean(UserDAO.class);
            for (Group group : userDAO.findAllGroups((User) any)) {
                virAttrHandler.retrieveVirAttrValues(group);
                anys.add(group);
            }
        } else if (any instanceof Group) {
            anys.add(any);
        }
        break;

    case ANY_OBJECT:
        if (any instanceof AnyObject) {
            anys.add(any);
        }
        break;

    default:
    }

    List<PlainAttrValue> values = getIntValues(provision, mapItem, anys, vAttrsToBeRemoved, vAttrsToBeUpdated);

    PlainSchema schema = null;
    boolean readOnlyVirSchema = false;
    AttrSchemaType schemaType;
    Pair<String, Attribute> result;

    switch (mapItem.getIntMappingType()) {
    case UserPlainSchema:
    case GroupPlainSchema:
    case AnyObjectPlainSchema:
        final PlainSchemaDAO plainSchemaDAO = context.getBean(PlainSchemaDAO.class);
        schema = plainSchemaDAO.find(mapItem.getIntAttrName());
        schemaType = schema == null ? AttrSchemaType.String : schema.getType();
        break;

    case UserVirtualSchema:
    case GroupVirtualSchema:
    case AnyObjectVirtualSchema:
        VirSchemaDAO virSchemaDAO = context.getBean(VirSchemaDAO.class);
        VirSchema virSchema = virSchemaDAO.find(mapItem.getIntAttrName());
        readOnlyVirSchema = (virSchema != null && virSchema.isReadonly());
        schemaType = AttrSchemaType.String;
        break;

    default:
        schemaType = AttrSchemaType.String;
    }

    String extAttrName = mapItem.getExtAttrName();

    LOG.debug("Define mapping for: " + "\n* ExtAttrName " + extAttrName + "\n* is connObjectKey "
            + mapItem.isConnObjectKey() + "\n* is password "
            + (mapItem.isPassword() || mapItem.getIntMappingType() == IntMappingType.Password)
            + "\n* mandatory condition " + mapItem.getMandatoryCondition() + "\n* Schema "
            + mapItem.getIntAttrName() + "\n* IntMappingType " + mapItem.getIntMappingType().toString()
            + "\n* ClassType " + schemaType.getType().getName() + "\n* Values " + values);

    if (readOnlyVirSchema) {
        result = null;
    } else {
        List<Object> objValues = new ArrayList<>();

        for (PlainAttrValue value : values) {
            if (FrameworkUtil.isSupportedAttributeType(schemaType.getType())) {
                objValues.add(value.getValue());
            } else {
                objValues.add(value.getValueAsString());
            }
        }

        if (mapItem.isConnObjectKey()) {
            result = new ImmutablePair<>(objValues.iterator().next().toString(), null);
        } else if (mapItem.isPassword() && any instanceof User) {
            String passwordAttrValue = password;
            if (StringUtils.isBlank(passwordAttrValue)) {
                User user = (User) any;
                if (user.canDecodePassword()) {
                    try {
                        passwordAttrValue = ENCRYPTOR.decode(user.getPassword(), user.getCipherAlgorithm());
                    } catch (Exception e) {
                        LOG.error("Could not decode password for {}", user, e);
                    }
                } else if (provision.getResource().isRandomPwdIfNotProvided()) {
                    try {
                        passwordAttrValue = passwordGenerator.generate(user);
                    } catch (InvalidPasswordPolicySpecException e) {
                        LOG.error("Could not generate policy-compliant random password for {}", user, e);
                    }
                }
            }

            if (passwordAttrValue == null) {
                result = null;
            } else {
                result = new ImmutablePair<>(null,
                        AttributeBuilder.buildPassword(passwordAttrValue.toCharArray()));
            }
        } else {
            if ((schema != null && schema.isMultivalue()) || anyUtilsFactory.getInstance(any)
                    .getAnyTypeKind() != mapItem.getIntMappingType().getAnyTypeKind()) {

                result = new ImmutablePair<>(null, AttributeBuilder.build(extAttrName, objValues));
            } else {
                result = new ImmutablePair<>(null, objValues.isEmpty() ? AttributeBuilder.build(extAttrName)
                        : AttributeBuilder.build(extAttrName, objValues.iterator().next()));
            }
        }
    }

    return result;
}

From source file:org.apache.syncope.core.util.MappingUtil.java

/**
 * Prepare attributes for sending to a connector instance.
 *
 * @param <T> user / role/*w ww .  j av  a2 s  .c  o m*/
 * @param attrUtil user / role
 * @param subject given user / role
 * @param password clear-text password
 * @param changePwd whether password should be included for propagation attributes or not
 * @param vAttrsToBeRemoved virtual attributes to be removed
 * @param vAttrsToBeUpdated virtual attributes to be added
 * @param membVAttrsToBeRemoved membership virtual attributes to be removed
 * @param membVAttrsToBeUpdated membership virtual attributes to be added
 * @param enable whether user must be enabled or not
 * @param resource target resource
 * @return account link + prepared attributes
 */
public static <T extends AbstractSubject> Map.Entry<String, Set<Attribute>> prepareAttributes(
        final AttributableUtil attrUtil, final T subject, final String password, final boolean changePwd,
        final Set<String> vAttrsToBeRemoved, final Map<String, AttributeMod> vAttrsToBeUpdated,
        final Set<String> membVAttrsToBeRemoved, final Map<String, AttributeMod> membVAttrsToBeUpdated,
        final Boolean enable, final ExternalResource resource) {

    LOG.debug("Preparing resource attributes for {} on resource {} with attributes {}", subject, resource,
            subject.getAttrs());

    final ConfigurableApplicationContext context = ApplicationContextProvider.getApplicationContext();
    final VirAttrCache virAttrCache = context.getBean(VirAttrCache.class);
    final PasswordGenerator passwordGenerator = context.getBean(PasswordGenerator.class);

    Set<Attribute> attributes = new HashSet<Attribute>();
    String accountId = null;

    for (AbstractMappingItem mapping : attrUtil.getMappingItems(resource, MappingPurpose.PROPAGATION)) {
        LOG.debug("Processing schema {}", mapping.getIntAttrName());

        try {
            if ((attrUtil.getType() == AttributableType.USER
                    && mapping.getIntMappingType() == IntMappingType.UserVirtualSchema)
                    || (attrUtil.getType() == AttributableType.ROLE
                            && mapping.getIntMappingType() == IntMappingType.RoleVirtualSchema)) {

                LOG.debug("Expire entry cache {}-{}", subject.getId(), mapping.getIntAttrName());
                virAttrCache.expire(attrUtil.getType(), subject.getId(), mapping.getIntAttrName());
            }

            // SYNCOPE-458 expire cache also for membership virtual schemas
            if (attrUtil.getType() == AttributableType.USER
                    && mapping.getIntMappingType() == IntMappingType.MembershipVirtualSchema
                    && (subject instanceof SyncopeUser)) {
                final SyncopeUser user = (SyncopeUser) subject;
                for (Membership membership : user.getMemberships()) {
                    LOG.debug("Expire entry cache {}-{} for membership {}", subject.getId(),
                            mapping.getIntAttrName(), membership);
                    virAttrCache.expire(AttributableType.MEMBERSHIP, membership.getId(),
                            mapping.getIntAttrName());
                }
            }

            Map.Entry<String, Attribute> preparedAttribute = prepareAttribute(resource, mapping, subject,
                    password, passwordGenerator, vAttrsToBeRemoved, vAttrsToBeUpdated, membVAttrsToBeRemoved,
                    membVAttrsToBeUpdated);

            if (preparedAttribute != null && preparedAttribute.getKey() != null) {
                accountId = preparedAttribute.getKey();
            }

            if (preparedAttribute != null && preparedAttribute.getValue() != null) {
                Attribute alreadyAdded = AttributeUtil.find(preparedAttribute.getValue().getName(), attributes);

                if (alreadyAdded == null) {
                    attributes.add(preparedAttribute.getValue());
                } else {
                    attributes.remove(alreadyAdded);

                    Set<Object> values = new HashSet<Object>(alreadyAdded.getValue());
                    values.addAll(preparedAttribute.getValue().getValue());

                    attributes.add(AttributeBuilder.build(preparedAttribute.getValue().getName(), values));
                }
            }
        } catch (Exception e) {
            LOG.debug("Attribute '{}' processing failed", mapping.getIntAttrName(), e);
        }
    }

    attributes.add(MappingUtil.evaluateNAME(subject, resource, accountId));

    if (enable != null) {
        attributes.add(AttributeBuilder.buildEnabled(enable));
    }
    if (!changePwd) {
        Attribute pwdAttr = AttributeUtil.find(OperationalAttributes.PASSWORD_NAME, attributes);
        if (pwdAttr != null) {
            attributes.remove(pwdAttr);
        }
    }

    return new AbstractMap.SimpleEntry<String, Set<Attribute>>(accountId, attributes);
}

From source file:org.apache.syncope.core.util.MappingUtil.java

/**
 * Prepare an attribute to be sent to a connector instance.
 *
 * @param resource target resource/* w  w  w.jav a  2  s  .co  m*/
 * @param <T> user / role
 * @param mapItem mapping item for the given attribute
 * @param subject given user
 * @param password clear-text password
 * @param passwordGenerator password generator
 * @param vAttrsToBeRemoved virtual attributes to be removed
 * @param vAttrsToBeUpdated virtual attributes to be added
 * @return account link + prepared attribute
 */
@SuppressWarnings("unchecked")
private static <T extends AbstractAttributable> Map.Entry<String, Attribute> prepareAttribute(
        final ExternalResource resource, final AbstractMappingItem mapItem, final T subject,
        final String password, final PasswordGenerator passwordGenerator, final Set<String> vAttrsToBeRemoved,
        final Map<String, AttributeMod> vAttrsToBeUpdated, final Set<String> membVAttrsToBeRemoved,
        final Map<String, AttributeMod> membVAttrsToBeUpdated) {

    final List<AbstractAttributable> attributables = new ArrayList<AbstractAttributable>();

    final ConfigurableApplicationContext context = ApplicationContextProvider.getApplicationContext();
    final ConnObjectUtil connObjectUtil = context.getBean(ConnObjectUtil.class);

    switch (mapItem.getIntMappingType().getAttributableType()) {
    case USER:
        if (subject instanceof SyncopeUser) {
            attributables.add(subject);
        }
        break;

    case ROLE:
        if (subject instanceof SyncopeUser) {
            for (SyncopeRole role : ((SyncopeUser) subject).getRoles()) {
                connObjectUtil.retrieveVirAttrValues(role, AttributableUtil.getInstance(role));
                attributables.add(role);
            }
        }
        if (subject instanceof SyncopeRole) {
            attributables.add(subject);
        }
        break;

    case MEMBERSHIP:
        if (subject instanceof SyncopeUser) {
            attributables.addAll(((SyncopeUser) subject).getMemberships());
        }
        break;

    default:
    }

    List<AbstractAttrValue> values = getIntValues(resource, mapItem, attributables, vAttrsToBeRemoved,
            vAttrsToBeUpdated, membVAttrsToBeRemoved, membVAttrsToBeUpdated);

    AbstractNormalSchema schema = null;
    boolean readOnlyVirSchema = false;
    AttributeSchemaType schemaType;
    final Map.Entry<String, Attribute> result;

    switch (mapItem.getIntMappingType()) {
    case UserSchema:
    case RoleSchema:
    case MembershipSchema:
        final SchemaDAO schemaDAO = context.getBean(SchemaDAO.class);
        schema = schemaDAO.find(mapItem.getIntAttrName(),
                MappingUtil.getIntMappingTypeClass(mapItem.getIntMappingType()));
        schemaType = schema == null ? AttributeSchemaType.String : schema.getType();
        break;

    case UserVirtualSchema:
    case RoleVirtualSchema:
    case MembershipVirtualSchema:
        VirSchemaDAO virSchemaDAO = context.getBean(VirSchemaDAO.class);
        AbstractVirSchema virSchema = virSchemaDAO.find(mapItem.getIntAttrName(),
                MappingUtil.getIntMappingTypeClass(mapItem.getIntMappingType()));
        readOnlyVirSchema = (virSchema != null && virSchema.isReadonly());
        schemaType = AttributeSchemaType.String;
        break;

    default:
        schemaType = AttributeSchemaType.String;
    }

    final String extAttrName = mapItem.getExtAttrName();

    LOG.debug("Define mapping for: " + "\n* ExtAttrName " + extAttrName + "\n* is accountId "
            + mapItem.isAccountid() + "\n* is password "
            + (mapItem.isPassword() || mapItem.getIntMappingType() == IntMappingType.Password)
            + "\n* mandatory condition " + mapItem.getMandatoryCondition() + "\n* Schema "
            + mapItem.getIntAttrName() + "\n* IntMappingType " + mapItem.getIntMappingType().toString()
            + "\n* ClassType " + schemaType.getType().getName() + "\n* Values " + values);

    if (readOnlyVirSchema) {
        result = null;
    } else {
        final List<Object> objValues = new ArrayList<Object>();

        for (AbstractAttrValue value : values) {
            if (FrameworkUtil.isSupportedAttributeType(schemaType.getType())) {
                objValues.add(value.getValue());
            } else {
                objValues.add(value.getValueAsString());
            }
        }

        if (mapItem.isAccountid()) {
            result = new AbstractMap.SimpleEntry<String, Attribute>(objValues.iterator().next().toString(),
                    null);
        } else if (mapItem.isPassword() && subject instanceof SyncopeUser) {
            String passwordAttrValue = password;
            if (StringUtils.isBlank(passwordAttrValue)) {
                SyncopeUser user = (SyncopeUser) subject;
                if (user.canDecodePassword()) {
                    try {
                        passwordAttrValue = ENCRYPTOR.decode(user.getPassword(), user.getCipherAlgorithm());
                    } catch (Exception e) {
                        LOG.error("Could not decode password for {}", user, e);
                    }
                } else if (resource.isRandomPwdIfNotProvided()) {
                    try {
                        passwordAttrValue = passwordGenerator.generate(user);
                    } catch (InvalidPasswordPolicySpecException e) {
                        LOG.error("Could not generate policy-compliant random password for {}", user, e);

                        passwordAttrValue = SecureRandomUtil.generateRandomPassword(16);
                    }
                }
            }

            if (passwordAttrValue == null) {
                result = null;
            } else {
                result = new AbstractMap.SimpleEntry<String, Attribute>(null,
                        AttributeBuilder.buildPassword(passwordAttrValue.toCharArray()));
            }
        } else {
            if ((schema != null && schema.isMultivalue()) || AttributableUtil.getInstance(subject)
                    .getType() != mapItem.getIntMappingType().getAttributableType()) {
                result = new AbstractMap.SimpleEntry<String, Attribute>(null,
                        AttributeBuilder.build(extAttrName, objValues));
            } else {
                result = new AbstractMap.SimpleEntry<String, Attribute>(null,
                        objValues.isEmpty() ? AttributeBuilder.build(extAttrName)
                                : AttributeBuilder.build(extAttrName, objValues.iterator().next()));
            }
        }
    }

    return result;
}

From source file:org.cbioportal.annotation.AnnotationPipeline.java

private static void launchJob(String[] args, String filename, String outputFilename, String isoformOverride,
        String errorReportLocation, boolean replace, boolean verbose) throws Exception {
    SpringApplication app = new SpringApplication(AnnotationPipeline.class);
    ConfigurableApplicationContext ctx = app.run(args);
    JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);

    Job annotationJob = ctx.getBean(BatchConfiguration.ANNOTATION_JOB, Job.class);
    JobParameters jobParameters = new JobParametersBuilder().addString("filename", filename)
            .addString("outputFilename", outputFilename).addString("replace", String.valueOf(replace))
            .addString("isoformOverride", isoformOverride).addString("errorReportLocation", errorReportLocation)
            .addString("verbose", String.valueOf(verbose)).toJobParameters();
    JobExecution jobExecution = jobLauncher.run(annotationJob, jobParameters);
    if (!jobExecution.getExitStatus().equals(ExitStatus.COMPLETED)) {
        System.exit(2);/*  www .j av a  2 s. com*/
    }
}

From source file:org.fao.geonet.api.registries.vocabularies.KeywordsApi.java

/**
 * Search keywords.//from w w  w. j  a  v  a2  s  .  c  om
 *
 * @param q the q
 * @param lang the lang
 * @param rows the rows
 * @param start the start
 * @param targetLangs the target langs
 * @param thesaurus the thesaurus
 * @param type the type
 * @param uri the uri
 * @param sort the sort
 * @param request the request
 * @param httpSession the http session
 * @return the list
 * @throws Exception the exception
 */
@ApiOperation(value = "Search keywords", nickname = "searchKeywords", notes = "")
@RequestMapping(path = "/search", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public List<KeywordBean> searchKeywords(
        @ApiParam(value = "Query", required = false) @RequestParam(required = false) String q,
        @ApiParam(value = "Query in that language", required = false) @RequestParam(value = "lang", defaultValue = "eng") String lang,
        @ApiParam(value = "Number of rows", required = false) @RequestParam(required = false, defaultValue = "1000") int rows,
        @ApiParam(value = "Start from", required = false) @RequestParam(defaultValue = "0", required = false) int start,
        @ApiParam(value = "Return keyword information in one or more languages", required = false) @RequestParam(value = XmlParams.pLang, required = false) List<String> targetLangs,
        @ApiParam(value = "Thesaurus identifier", required = false) @RequestParam(required = false) String[] thesaurus,
        //        @ApiParam(
        //            value = "?",
        //            required = false
        //        )
        //        @RequestParam(
        //            required = false
        //        )
        //            String thesauriDomainName,
        @ApiParam(value = "Type of search", required = false) @RequestParam(defaultValue = "CONTAINS") KeywordSearchType type,
        @ApiParam(value = "URI query", required = false) @RequestParam(required = false) String uri,
        @ApiParam(value = "Sort by", required = false) @RequestParam(required = false, defaultValue = "DESC") String sort,
        @ApiIgnore HttpServletRequest request, @ApiIgnore @ApiParam(hidden = true) HttpSession httpSession)
        throws Exception {
    ConfigurableApplicationContext applicationContext = ApplicationContextHolder.get();
    ServiceContext context = ApiUtils.createServiceContext(request);
    UserSession session = ApiUtils.getUserSession(httpSession);

    //        Locale locale = languageUtils.parseAcceptLanguage(request.getLocales());
    //        lang = locale.getISO3Language();

    KeywordsSearcher searcher;
    // perform the search and save search result into session
    ThesaurusManager thesaurusMan = applicationContext.getBean(ThesaurusManager.class);

    if (Log.isDebugEnabled("KeywordsManager")) {
        Log.debug("KeywordsManager", "Creating new keywords searcher");
    }
    searcher = new KeywordsSearcher(context, thesaurusMan);

    IsoLanguagesMapper languagesMapper = applicationContext.getBean(IsoLanguagesMapper.class);
    String thesauriDomainName = null;

    KeywordSearchParamsBuilder builder = parseBuilder(lang, q, rows, start, targetLangs,
            Arrays.asList(thesaurus), thesauriDomainName, type, uri, languagesMapper);

    //            if (checkModified(webRequest, thesaurusMan, builder)) {
    //                return null;
    //            }

    if (q == null || q.trim().isEmpty()) {
        builder.setComparator(KeywordSort.defaultLabelSorter(SortDirection.parse(sort)));
    } else {
        builder.setComparator(KeywordSort.searchResultsSorter(q, SortDirection.parse(sort)));
    }

    searcher.search(builder.build());
    session.setProperty(Geonet.Session.SEARCH_KEYWORDS_RESULT, searcher);

    // get the results
    return searcher.getResults();
}

From source file:org.fao.geonet.api.registries.vocabularies.KeywordsApi.java

/**
 * Parses the builder./*from ww w  .j  av a  2s.  c o  m*/
 *
 * @param uiLang the ui lang
 * @param q the q
 * @param maxResults the max results
 * @param offset the offset
 * @param targetLangs the target langs
 * @param thesauri the thesauri
 * @param thesauriDomainName the thesauri domain name
 * @param typeSearch the type search
 * @param uri the uri
 * @param mapper the mapper
 * @return the keyword search params builder
 */
private KeywordSearchParamsBuilder parseBuilder(String uiLang, String q, int maxResults, int offset,
        List<String> targetLangs, List<String> thesauri, String thesauriDomainName,
        KeywordSearchType typeSearch, String uri, IsoLanguagesMapper mapper) {
    KeywordSearchParamsBuilder parsedParams = new KeywordSearchParamsBuilder(mapper).lenient(true);

    if (q != null) {
        parsedParams.keyword(q, typeSearch, true);
    }

    if (uri != null) {
        parsedParams.uri(uri);
    }

    parsedParams.maxResults(maxResults);
    parsedParams.offset(offset);

    if (thesauriDomainName != null) {
        parsedParams.thesauriDomainName(thesauriDomainName);
    }

    if (thesauri == null) {
        ConfigurableApplicationContext applicationContext = ApplicationContextHolder.get();
        ThesaurusManager thesaurusMan = applicationContext.getBean(ThesaurusManager.class);
        Map<String, Thesaurus> listOfThesaurus = thesaurusMan.getThesauriMap();
        for (String t : listOfThesaurus.keySet()) {
            parsedParams.addThesaurus(listOfThesaurus.get(t).getKey());
        }
    } else {
        for (String thesaurusName : thesauri) {
            if (!thesaurusName.trim().isEmpty()) {
                parsedParams.addThesaurus(thesaurusName.trim());
            }
        }
    }

    boolean addedLang = false;
    if (targetLangs != null) {
        for (String targetLang : targetLangs) {
            if (!targetLang.trim().isEmpty()) {
                parsedParams.addLang(targetLang.trim());
                addedLang = true;
            }
        }
    }
    if (!addedLang) {
        parsedParams.addLang(uiLang);
    }

    return parsedParams;
}

From source file:org.fao.geonet.api.site.SiteApi.java

@ApiOperation(value = "Get settings", notes = "Return public settings for anonymous users, internals are allowed for authenticated.", nickname = "getSettings")
@RequestMapping(path = "/settings", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)// www  .j  av a 2  s.  co  m
@ApiResponses(value = { @ApiResponse(code = 200, message = "Settings.") })
@ResponseBody
public SettingsListResponse getSettingsSet(
        @ApiParam(value = "Setting set. A common set of settings to retrieve.", required = false) @RequestParam(required = false) SettingSet[] set,
        @ApiParam(value = "Setting key", required = false) @RequestParam(required = false) String[] key,
        HttpServletRequest request, @ApiIgnore @ApiParam(hidden = true) HttpSession httpSession)
        throws Exception {
    ConfigurableApplicationContext appContext = ApplicationContextHolder.get();
    SettingManager sm = appContext.getBean(SettingManager.class);
    UserSession session = ApiUtils.getUserSession(httpSession);
    Profile profile = session == null ? null : session.getProfile();

    List<String> settingList = new ArrayList<>();
    if (set == null && key == null) {
        final SettingRepository settingRepository = appContext.getBean(SettingRepository.class);
        final List<org.fao.geonet.domain.Setting> publicSettings = settingRepository.findAllByInternal(false);

        // Add virtual settings based on internal settings.
        // eg. if mail server is defined, allow email interactions ...
        String mailServer = sm.getValue(Settings.SYSTEM_FEEDBACK_MAILSERVER_HOST);
        publicSettings.add(new Setting()
                .setName(Settings.SYSTEM_FEEDBACK_MAILSERVER_HOST + Settings.VIRTUAL_SETTINGS_SUFFIX_ISDEFINED)
                .setDataType(SettingDataType.BOOLEAN).setValue(StringUtils.isNotEmpty(mailServer) + ""));

        SettingsListResponse response = new SettingsListResponse();
        response.setSettings(publicSettings);
        return response;
    } else {
        if (set != null && set.length > 0) {
            for (SettingSet s : set) {
                String[] props = s.getListOfSettings();
                if (props != null) {
                    Collections.addAll(settingList, props);
                }
            }
        }
        if (key != null && key.length > 0) {
            Collections.addAll(settingList, key);
        }
        List<org.fao.geonet.domain.Setting> settings = sm.getSettings(settingList.toArray(new String[0]));
        ListIterator<org.fao.geonet.domain.Setting> iterator = settings.listIterator();

        // Cleanup internal settings for not authenticated users.
        while (iterator.hasNext()) {
            org.fao.geonet.domain.Setting s = iterator.next();
            if (s.isInternal() && profile == null) {
                settings.remove(s);
            }
        }

        SettingsListResponse response = new SettingsListResponse();
        response.setSettings(settings);
        return response;
    }
}

From source file:org.fao.geonet.api.site.SiteApi.java

@ApiOperation(value = "Get settings with details", notes = "Provides also setting properties.", nickname = "getSettingsDetails")
@RequestMapping(path = "/settings/details", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)//from   ww w  .java2  s  .co m
@ApiResponses(value = { @ApiResponse(code = 200, message = "Settings with details.") })
@ResponseBody
@PreAuthorize("hasRole('Administrator')")
public List<Setting> getSettingsDetails(
        @ApiParam(value = "Setting set. A common set of settings to retrieve.", required = false) @RequestParam(required = false) SettingSet[] set,
        @ApiParam(value = "Setting key", required = false) @RequestParam(required = false) String[] key,
        HttpServletRequest request, @ApiIgnore @ApiParam(hidden = true) HttpSession httpSession)
        throws Exception {
    ConfigurableApplicationContext appContext = ApplicationContextHolder.get();
    SettingManager sm = appContext.getBean(SettingManager.class);
    UserSession session = ApiUtils.getUserSession(httpSession);
    Profile profile = session == null ? null : session.getProfile();

    List<String> settingList = new ArrayList<>();
    if (set == null && key == null) {
        return sm.getAll();
    } else {
        if (set != null && set.length > 0) {
            for (SettingSet s : set) {
                String[] props = s.getListOfSettings();
                if (props != null) {
                    Collections.addAll(settingList, props);
                }
            }
        }
        if (key != null && key.length > 0) {
            Collections.addAll(settingList, key);
        }
        List<org.fao.geonet.domain.Setting> settings = sm.getSettings(settingList.toArray(new String[0]));
        ListIterator<org.fao.geonet.domain.Setting> iterator = settings.listIterator();

        // Cleanup internal settings for not authenticated users.
        while (iterator.hasNext()) {
            org.fao.geonet.domain.Setting s = iterator.next();
            if (s.isInternal() && profile == null) {
                settings.remove(s);
            }
        }
        return settings;
    }
}

From source file:org.fao.geonet.api.userfeedback.UserFeedbackAPI.java

@ApiOperation(value = "Send an email to catalogue administrator or record's contact", notes = "", nickname = "sendEmailToContact")
@RequestMapping(value = "/records/{metadataUuid}/alert", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)//  ww w.  ja v  a 2s. c o m
@ResponseBody
public ResponseEntity sendEmailToContact(
        @ApiParam(value = "Metadata record UUID.", required = true) @PathVariable(value = "metadataUuid") final String metadataUuid,
        @ApiParam(value = "Recaptcha validation key.", required = false) @RequestParam(required = false, defaultValue = "") final String recaptcha,
        @ApiParam(value = "User name.", required = true) @RequestParam final String name,
        @ApiParam(value = "User organisation.", required = true) @RequestParam final String org,
        @ApiParam(value = "User email address.", required = true) @RequestParam final String email,
        @ApiParam(value = "A comment or question.", required = true) @RequestParam final String comments,
        @ApiParam(value = "User phone number.", required = false) @RequestParam(required = false, defaultValue = "") final String phone,
        @ApiParam(value = "Email subject.", required = false) @RequestParam(required = false, defaultValue = "User feedback") final String subject,
        @ApiParam(value = "User function.", required = false) @RequestParam(required = false, defaultValue = "-") final String function,
        @ApiParam(value = "Comment type.", required = false) @RequestParam(required = false, defaultValue = "-") final String type,
        @ApiParam(value = "Comment category.", required = false) @RequestParam(required = false, defaultValue = "-") final String category,
        @ApiParam(value = "List of record's contact to send this email.", required = false) @RequestParam(required = false, defaultValue = "") final String metadataEmail,
        @ApiIgnore final HttpServletRequest request) throws IOException {
    ConfigurableApplicationContext applicationContext = ApplicationContextHolder.get();
    SettingManager sm = applicationContext.getBean(SettingManager.class);
    MetadataRepository metadataRepository = applicationContext.getBean(MetadataRepository.class);

    Locale locale = languageUtils.parseAcceptLanguage(request.getLocales());
    ResourceBundle messages = ResourceBundle.getBundle("org.fao.geonet.api.Messages", locale);

    boolean recaptchaEnabled = sm.getValueAsBool(Settings.SYSTEM_USERSELFREGISTRATION_RECAPTCHA_ENABLE);

    if (recaptchaEnabled) {
        boolean validRecaptcha = RecaptchaChecker.verify(recaptcha,
                sm.getValue(Settings.SYSTEM_USERSELFREGISTRATION_RECAPTCHA_SECRETKEY));
        if (!validRecaptcha) {
            return new ResponseEntity<>(messages.getString("recaptcha_not_valid"),
                    HttpStatus.PRECONDITION_FAILED);
        }
    }

    String to = sm.getValue(SYSTEM_FEEDBACK_EMAIL);
    String catalogueName = sm.getValue(SYSTEM_SITE_NAME_PATH);

    List<String> toAddress = new LinkedList<String>();
    toAddress.add(to);
    if (isNotBlank(metadataEmail)) {
        //Check metadata email belongs to metadata security!!
        Metadata md = metadataRepository.findOneByUuid(metadataUuid);
        if (md.getData().indexOf(metadataEmail) > 0) {
            toAddress.add(metadataEmail);
        }
    }

    String title = XslUtil.getIndexField(null, metadataUuid, "title", "");

    MailUtil.sendMail(toAddress,
            String.format(messages.getString("user_feedback_title"), catalogueName, title, subject),
            String.format(messages.getString("user_feedback_text"), name, org, function, email, phone, title,
                    type, category, comments, sm.getNodeURL(), metadataUuid),
            sm);

    return new ResponseEntity(HttpStatus.CREATED);
}