Example usage for org.apache.commons.collections4 MapUtils isNotEmpty

List of usage examples for org.apache.commons.collections4 MapUtils isNotEmpty

Introduction

In this page you can find the example usage for org.apache.commons.collections4 MapUtils isNotEmpty.

Prototype

public static boolean isNotEmpty(final Map<?, ?> map) 

Source Link

Document

Null-safe check if the specified map is not empty.

Usage

From source file:org.craftercms.commons.rest.RestClientUtils.java

/**
 * Converts a map of params to a query string.
 *
 * @param params the params to convert to a query string
 * @param encode if the param values should be encoded
 * @return the params as a query string//from  w w w.  jav a 2s  . c  o m
 */
public static String createQueryStringFromParams(MultiValueMap<String, String> params, boolean encode) {
    StringBuilder queryString = new StringBuilder();

    if (MapUtils.isNotEmpty(params)) {
        for (Map.Entry<String, List<String>> entry : params.entrySet()) {
            String paramName;
            try {
                paramName = URLEncoder.encode(entry.getKey(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // Should NEVER happen
                throw new RuntimeException(e);
            }

            for (String paramValue : entry.getValue()) {
                if (queryString.length() > 0) {
                    queryString.append('&');
                }

                if (encode) {
                    try {
                        paramValue = URLEncoder.encode(paramValue, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        // Should NEVER happen
                        throw new RuntimeException(e);
                    }
                }

                queryString.append(paramName).append('=').append(paramValue);
            }
        }

        queryString.insert(0, '?');
    }

    return queryString.toString();
}

From source file:org.craftercms.commons.validation.ValidationResult.java

@JsonIgnore
public boolean hasErrors() {
    return MapUtils.isNotEmpty(errors);
}

From source file:org.craftercms.core.controller.rest.ContentStoreRestController.java

@RequestMapping(value = URL_DESCRIPTOR, method = RequestMethod.GET)
public Map<String, Object> getDescriptor(WebRequest request, HttpServletResponse response,
        @RequestParam(REQUEST_PARAM_CONTEXT_ID) String contextId, @RequestParam(REQUEST_PARAM_URL) String url)
        throws InvalidContextException, StoreException, PathNotFoundException, ItemProcessingException,
        XmlMergeException, XmlFileParseException {
    Map<String, Object> model = getItem(request, response, contextId, url);

    if (MapUtils.isNotEmpty(model)) {
        Item item = (Item) model.remove(MODEL_ATTR_ITEM);
        model.put(MODEL_ATTR_DESCRIPTOR, item.getDescriptorDom());
    }//  www.  ja  v  a 2s  . co m

    return model;
}

From source file:org.craftercms.core.util.HttpServletUtils.java

public static String getQueryStringFromParams(Map<String, Object> queryParams, String charset)
        throws UnsupportedEncodingException {
    StringBuilder queryString = new StringBuilder();

    if (MapUtils.isNotEmpty(queryParams)) {
        for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
            String paramName = URLEncoder.encode(entry.getKey(), charset);

            if (entry.getValue() instanceof List) {
                for (String paramValue : (List<String>) entry.getValue()) {
                    if (queryString.length() > 0) {
                        queryString.append('&');
                    }// w w  w .  j a v a 2  s.com

                    paramValue = URLEncoder.encode(paramValue, charset);

                    queryString.append(paramName).append('=').append(paramValue);
                }
            } else {
                if (queryString.length() > 0) {
                    queryString.append('&');
                }

                String paramValue = URLEncoder.encode((String) entry.getValue(), charset);

                queryString.append(paramName).append('=').append(paramValue);
            }
        }

        queryString.insert(0, '?');
    }

    return queryString.toString();
}

From source file:org.craftercms.deployer.impl.rest.TargetController.java

/**
 * Deploys the {@link Target} with the specified environment and site name.
 *
 * @param env       the target's environment
 * @param siteName  the target's site name
 * @param params    any additional parameters that can be used by the {@link org.craftercms.deployer.api.DeploymentProcessor}s, for
 *                  example {@code reprocess_all_files}
 *
 * @return the response entity with a 200 OK status
 *
 * @throws DeployerException if an error occurred
 *//*from  w  w w.  j  ava2  s  .c  om*/
@RequestMapping(value = DEPLOY_TARGET_URL, method = RequestMethod.POST)
public ResponseEntity<Result> deployTarget(@PathVariable(ENV_PATH_VAR_NAME) String env,
        @PathVariable(SITE_NAME_PATH_VAR_NAME) String siteName,
        @RequestBody(required = false) Map<String, Object> params)
        throws DeployerException, ExecutionException, InterruptedException {
    if (params == null) {
        params = new HashMap<>();
    }

    boolean waitTillDone = false;
    if (MapUtils.isNotEmpty(params)) {
        waitTillDone = BooleanUtils.toBoolean(params.remove(WAIT_TILL_DONE_PARAM_NAME));
    }

    deploymentService.deployTarget(env, siteName, waitTillDone, params);

    return ResponseEntity.status(HttpStatus.ACCEPTED).body(Result.OK);
}

From source file:org.craftercms.deployer.impl.rest.TargetController.java

/**
 * Deploys all current {@link Target}s./*  ww w.  java  2s.  c  o  m*/
 *
 * @param params    any additional parameters that can be used by the {@link org.craftercms.deployer.api.DeploymentProcessor}s, for
 *                  example {@code reprocess_all_files}
 *
 * @return the response entity with a 200 OK status
 *
 * @throws DeployerException if an error occurred
 */
@RequestMapping(value = DEPLOY_ALL_TARGETS_URL, method = RequestMethod.POST)
public ResponseEntity<Result> deployAllTargets(@RequestBody(required = false) Map<String, Object> params)
        throws DeployerException {
    if (params == null) {
        params = new HashMap<>();
    }

    boolean waitTillDone = false;
    if (MapUtils.isNotEmpty(params)) {
        waitTillDone = BooleanUtils.toBoolean(params.remove(WAIT_TILL_DONE_PARAM_NAME));
    }

    deploymentService.deployAllTargets(waitTillDone, params);

    return ResponseEntity.status(HttpStatus.ACCEPTED).body(Result.OK);
}

From source file:org.craftercms.deployer.impl.TargetServiceImpl.java

protected void createConfigFromTemplate(String env, String siteName, String targetId, String templateName,
        Map<String, Object> templateParameters, File configFile) throws TargetServiceException {
    if (StringUtils.isEmpty(templateName)) {
        templateName = defaultTargetConfigTemplateName;
    }/*from   w ww  . j av  a  2s.c  om*/

    Map<String, Object> templateModel = new HashMap<>();
    templateModel.put(TARGET_ENV_MODEL_KEY, env);
    templateModel.put(TARGET_SITE_NAME_MODEL_KEY, siteName);
    templateModel.put(TARGET_ID_MODEL_KEY, targetId);

    if (MapUtils.isNotEmpty(templateParameters)) {
        templateModel.putAll(templateParameters);
    }

    logger.info("Creating new target YAML configuration at {} using template '{}'", configFile, templateName);

    try (Writer out = new BufferedWriter(new FileWriter(configFile))) {
        processConfigTemplate(templateName, templateModel, out);

        out.flush();
    } catch (IOException e) {
        throw new TargetServiceException("Unable to open writer to YAML configuration file " + configFile, e);
    } catch (TargetServiceException e) {
        FileUtils.deleteQuietly(configFile);

        throw e;
    }
}

From source file:org.craftercms.engine.macro.impl.MacroResolverImpl.java

@Override
public String resolveMacros(String str, Map<String, ?> macroValues) {
    if (MapUtils.isNotEmpty(macroValues)) {
        for (Map.Entry<String, ?> entry : macroValues.entrySet()) {
            String macroName = "{" + entry.getKey() + "}";
            Object macroValue = entry.getValue();

            str = str.replace(macroName, macroValue.toString());
        }/*from  w  w  w .j a  v a 2  s  . c  o  m*/
    }

    for (Macro macro : macros) {
        str = macro.resolve(str);
    }

    return str;
}

From source file:org.craftercms.engine.security.PreviewCurrentAuthenticationResolvingProcessor.java

@Override
@SuppressWarnings("unchecked")
public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain)
        throws Exception {
    HttpServletRequest request = context.getRequest();
    Map<String, String> attributes = (Map<String, String>) request.getSession(true)
            .getAttribute(ProfileRestController.PROFILE_SESSION_ATTRIBUTE);

    if (MapUtils.isNotEmpty(attributes)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Non-anonymous persona set: " + attributes);
        }/* ww  w.j a  v a2s . c  o m*/

        Profile profile = new Profile();
        profile.setUsername("preview");
        profile.setEnabled(true);
        profile.setCreatedOn(new Date());
        profile.setLastModified(new Date());
        profile.setTenant("preview");

        String rolesStr = attributes.get("roles");
        if (rolesStr != null) {
            String[] roles = rolesStr.split(",");
            profile.getRoles().addAll(Arrays.asList(roles));
        }

        Map<String, Object> attributesNoUsernameNoRoles = new HashMap<String, Object>(attributes);
        attributesNoUsernameNoRoles.remove("username");
        attributesNoUsernameNoRoles.remove("roles");

        profile.setAttributes(attributesNoUsernameNoRoles);

        SecurityUtils.setAuthentication(request, new PersonaAuthentication(profile));

        processorChain.processRequest(context);
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("No persona set. Trying to resolve authentication normally");
        }

        super.processRequest(context, processorChain);
    }
}

From source file:org.craftercms.profile.services.impl.ProfileServiceImpl.java

@Override
public Profile createProfile(String tenantName, String username, String password, String email, boolean enabled,
        Set<String> roles, Map<String, Object> attributes, String verificationUrl) throws ProfileException {
    checkIfManageProfilesIsAllowed(tenantName);

    if (!EmailUtils.validateEmail(email)) {
        throw new InvalidEmailAddressException(email);
    }/*from ww w  .j  a  va  2s.  c o m*/

    try {
        Tenant tenant = getTenant(tenantName);
        Date now = new Date();

        Profile profile = new Profile();
        profile.setTenant(tenantName);
        profile.setUsername(username);
        profile.setPassword(CryptoUtils.hashPassword(password));
        profile.setEmail(email);
        profile.setCreatedOn(now);
        profile.setLastModified(now);
        profile.setVerified(false);

        boolean emailNewProfiles = tenant.isVerifyNewProfiles();
        if (!emailNewProfiles || StringUtils.isEmpty(verificationUrl)) {
            profile.setEnabled(enabled);
        }

        if (CollectionUtils.isNotEmpty(roles)) {
            profile.setRoles(roles);
        }

        for (AttributeDefinition definition : tenant.getAttributeDefinitions()) {
            if (definition.getDefaultValue() != null) {
                profile.setAttribute(definition.getName(), definition.getDefaultValue());
            }
        }
        if (MapUtils.isNotEmpty(attributes)) {
            rejectAttributesIfActionNotAllowed(tenant, attributes.keySet(), AttributeAction.WRITE_ATTRIBUTE);

            profile.getAttributes().putAll(attributes);
        }

        profileRepository.insert(profile);

        logger.debug(LOG_KEY_PROFILE_CREATED, profile);

        if (emailNewProfiles && StringUtils.isNotEmpty(verificationUrl)) {
            VerificationToken token = verificationService.createToken(profile);
            verificationService.sendEmail(token, profile, verificationUrl, newProfileEmailFromAddress,
                    newProfileEmailSubject, newProfileEmailTemplateName);
        }

        return profile;
    } catch (DuplicateKeyException e) {
        throw new ProfileExistsException(tenantName, username);
    } catch (MongoDataException e) {
        throw new I10nProfileException(ERROR_KEY_CREATE_PROFILE_ERROR, e, username, tenantName);
    }
}