Example usage for org.springframework.util StringUtils hasLength

List of usage examples for org.springframework.util StringUtils hasLength

Introduction

In this page you can find the example usage for org.springframework.util StringUtils hasLength.

Prototype

public static boolean hasLength(@Nullable String str) 

Source Link

Document

Check that the given String is neither null nor of length 0.

Usage

From source file:org.cleverbus.core.common.ws.ErrorCodeAwareSoapExceptionResolver.java

@Override
protected final boolean resolveExceptionInternal(MessageContext messageContext, Object endpoint, Exception ex) {
    Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse(),
            "SimpleSoapExceptionResolver requires a SoapMessage");

    if (throttlingAsServerError && ex instanceof ThrottlingExceededException) {
        // no SOAP fault => server error
        return false;
    } else {/* ww  w  .  j a  va 2s . com*/
        SoapMessage response = (SoapMessage) messageContext.getResponse();
        String faultString = StringUtils.hasLength(ex.getMessage()) ? ex.getMessage() : ex.toString();
        SoapBody body = response.getSoapBody();
        SoapFault fault = body.addServerOrReceiverFault(faultString, getLocale());
        customizeFault(messageContext, endpoint, ex, fault);

        return true;
    }
}

From source file:org.openmrs.module.reportingrest.web.resource.EvaluatedDataSetResource.java

@Override
public Object retrieve(String uuid, RequestContext requestContext) throws ResponseException {

    DataSetDefinitionService dataSetDefinitionService = DefinitionContext.getDataSetDefinitionService();

    // the passed in uuid is the DataSetDefinition uuid
    DataSetDefinition definition = dataSetDefinitionService.getDefinitionByUuid(uuid);

    EvaluationContext evalContext = getEvaluationContextWithParameters(definition, requestContext);

    HttpServletRequest httpRequest = requestContext.getRequest();

    // if there is a "cohort" parameter, use that to look for a CohortDefinition to run against, otherwise all patients
    String cohortUuid = httpRequest.getParameter("cohort");
    if (StringUtils.hasLength(cohortUuid)) {
        EvaluatedCohort cohort = new EvaluatedCohortResource().getEvaluatedCohort(cohortUuid, requestContext,
                "cohort.");
        evalContext.setBaseCohort(cohort);
    }/*from  www.j a va2 s .com*/

    // actually do the evaluation
    DataSet dataSet = null;
    try {
        dataSet = dataSetDefinitionService.evaluate(definition, evalContext);
        // there seems to be a bug in the underlying reporting module that doesn't set this
        if (dataSet.getDefinition().getUuid() == null)
            dataSet.getDefinition().setUuid(definition.getUuid());
        if (dataSet.getDefinition().getName() == null)
            dataSet.getDefinition().setName(definition.getName());
        if (dataSet.getDefinition().getDescription() == null)
            dataSet.getDefinition().setDescription(definition.getDescription());
    } catch (EvaluationException e) {
        log.error("Unable to evaluate definition with uuid: " + uuid);
    }

    return asRepresentation(dataSet, requestContext.getRepresentation());
}

From source file:org.openmrs.api.impl.ConditionServiceImpl.java

@Override
public Condition voidCondition(Condition condition, String voidReason) {
    if (!StringUtils.hasLength(voidReason)) {
        throw new IllegalArgumentException("voidReason cannot be empty or null");
    }//from  w  ww.  j  av  a 2 s.  c  o m
    return conditionDAO.saveOrUpdate(condition);
}

From source file:org.cloudfoundry.tools.env.CloudEnvironment.java

@SuppressWarnings("unchecked")
private Map<String, Object> getValueAsMap(String name) {
    String value = getValue(name);
    if (StringUtils.hasLength(value)) {
        try {/*  ww w .  j  a v a2 s .  com*/
            return this.objectMapper.readValue(value, Map.class);
        } catch (Exception e) {
            throw new IllegalStateException("Unable to read value '" + name + "' as a map", e);
        }
    }
    return Collections.emptyMap();
}

From source file:org.openmrs.module.feedback.web.StatusFormController.java

@Override
protected Map referenceData(HttpServletRequest req) throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();
    Object o = Context.getService(FeedbackService.class);
    FeedbackService service = (FeedbackService) o;
    FeedbackService hService = (FeedbackService) Context.getService(FeedbackService.class);
    String feedbackStatusId = req.getParameter("feedbackStatusId");

    /* Tells wheather the data is deleted or not */
    if (!StringUtils.hasLength(feedbackStatusId)
            || (service.getStatus(Integer.parseInt(feedbackStatusId)) == null)) {
        Status s = new Status();

        map.put("statuses", s);
        req.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, "feedback.notification.status.deleted");

        return map;
    }/*from   w ww. ja  v a 2 s .co  m*/

    /* Otherwise return the data based on the input */
    else {
        Status s = service.getStatus(Integer.parseInt(feedbackStatusId));

        System.out.println(s.getfeedbackStatusId());
        map.put("statuses", s);

        return map;
    }
}

From source file:org.jasig.schedassist.web.security.CustomLDAPAuthenticationProvider.java

/**
 * Incorporates some of the /*from  ww  w  . ja v a  2 s . c om*/
 *  (non-Javadoc)
 * @see org.springframework.security.authentication.dao.DaoAuthenticationProvider#additionalAuthenticationChecks(org.springframework.security.core.userdetails.UserDetails, org.springframework.security.authentication.UsernamePasswordAuthenticationToken)
 */
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    if (logger.isDebugEnabled()) {
        logger.debug("Processing authentication request for user: " + username);
    }

    if (!StringUtils.hasLength(username)) {
        throw new BadCredentialsException(
                messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username"));
    }

    Assert.notNull(password, "Null password was supplied in authentication token");

    try {
        DirContextOperations userData = getAuthenticator().authenticate(authentication);
        if (userData == null) {
            throw new BadCredentialsException(
                    messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    } catch (PasswordPolicyException ppe) {
        // The only reason a ppolicy exception can occur during a bind is that the account is locked.
        throw new LockedException(
                messages.getMessage(ppe.getStatus().getErrorCode(), ppe.getStatus().getDefaultMessage()));
    } catch (UsernameNotFoundException notFound) {
        if (hideUserNotFoundExceptions) {
            throw new BadCredentialsException(
                    messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials"));
        } else {
            throw notFound;
        }
    }
}

From source file:org.openmrs.module.idcards.web.servlet.PrintEmptyIdcardsServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//*from   w  w w .  jav  a2 s .com*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Integer mrnCount = ServletRequestUtils.getRequiredIntParameter(request, "mrn_count");
    Integer templateId = ServletRequestUtils.getIntParameter(request, "templateId", 1);
    String generatedMRNs = ServletRequestUtils.getStringParameter(request, "generated_mrns", "none");
    String password = ServletRequestUtils.getStringParameter(request, "pdf_password");
    if (!StringUtils.hasLength(password))
        throw new ServletException("A non-empty password is required.");

    IdcardsTemplate card = getIdcardsService().getIdcardsTemplate(templateId);

    StringBuffer requestURL = request.getRequestURL();
    String baseURL = requestURL.substring(0, requestURL.indexOf("/moduleServlet"));

    List<Integer> identifiers = null;

    if ("none".equals(generatedMRNs)) {
        identifiers = Collections.nCopies(mrnCount, 0);
    } else if ("pregenerated".equals(generatedMRNs)) {
        identifiers = getIdcardsService().printGeneratedIdentifiers(mrnCount, card);
    } else if ("generateNew".equals(generatedMRNs)) {
        Integer min = Integer
                .valueOf(Context.getAdministrationService().getGlobalProperty("idcards.generateMin"));
        Integer max = Integer
                .valueOf(Context.getAdministrationService().getGlobalProperty("idcards.generateMax"));
        identifiers = getIdcardsService().generateAndPrintIdentifiers(mrnCount, min, max, card);
    } else
        throw new ServletException("Invalid choice for 'generatedMRNs' parameter");

    generateOutput(card, baseURL, response, identifiers, password);

}

From source file:org.springmodules.validation.valang.predicates.BasicValidationRule.java

public void validate(Object target, Errors errors) {
    Object tmpTarget;//ww w.  j a  v  a 2  s .  c  o m

    if (target instanceof BeanWrapper || target instanceof Map) {
        tmpTarget = target;
    } else {
        tmpTarget = new BeanWrapperImpl(target);
    }
    if (!getPredicate().evaluate(tmpTarget)) {

        /*
        * Take into account error key and error args for localization
        */
        if (StringUtils.hasLength(getErrorKey())) {
            if (getErrorArgs() != null && !getErrorArgs().isEmpty()) {
                Collection tmpColl = new ArrayList();
                for (Iterator iter = getErrorArgs().iterator(); iter.hasNext();) {
                    tmpColl.add(((Function) iter.next()).getResult(tmpTarget));
                }
                errors.rejectValue(getField(), getErrorKey(), tmpColl.toArray(), getErrorMessage());
            } else {
                errors.rejectValue(getField(), getErrorKey(), getErrorMessage());
            }
        } else {
            errors.rejectValue(getField(), getField(), getErrorMessage());
        }

    }
}

From source file:org.jasig.portlet.weather.portlet.WeatherEditController.java

@RequestMapping(params = { "action=add" })
public void addCity(@RequestParam(value = "location", required = false) String location,
        @RequestParam(value = "locationCode", required = false) String locationCode,
        @RequestParam(value = "unit", required = false) TemperatureUnit unit, ActionRequest request,
        ActionResponse response) throws Exception {
    PortletPreferences prefs = request.getPreferences();

    Map<String, Object> model = new LinkedHashMap<String, Object>();

    // validate the submitted data
    if (!StringUtils.hasText(location) || !StringUtils.hasLength(locationCode)) {
        model.put("status", "failure");
        this.ajaxPortletSupport.redirectAjaxResponse("ajax/json", model, request, response);
        return;//from  w ww.  j  a v a 2  s  . c o  m
    }

    // make sure this location isn't already in our list
    try {
        final SavedLocation savedLocation = this.weatherService.addWeatherLocation(prefs, locationCode,
                location, unit == null ? TemperatureUnit.F : unit);
        model.put("status", "success");
        model.put("location", savedLocation);
    } catch (DuplicateLocationException dle) {
        model.put("status", "failure");
        model.put("cause", "DUPLICATE_LOCATION");
    }

    this.ajaxPortletSupport.redirectAjaxResponse("ajax/json", model, request, response);
}

From source file:fr.acxio.tools.agia.expression.StandardDataExpressionResolver.java

@Override
public <T> T evaluate(String sExpression, EvaluationContext sEvalContext, Class<T> sTargetType) {
    if (!StringUtils.hasLength(sExpression)) {
        if (sTargetType == null || ClassUtils.isAssignableValue(sTargetType, sExpression)) {
            return (T) sExpression;
        }//from w  w  w.  j  av  a  2  s  . com
        throw new EvaluationException(
                "Cannot convert value '" + sExpression + "' to type '" + sTargetType.getName() + "'");
    }
    try {
        Expression expr = this.expressionCache.get(sExpression);
        if (expr == null) {
            expr = this.expressionParser.parseExpression(sExpression, expressionParserContext);
            this.expressionCache.put(sExpression, expr);
        }
        return expr.getValue(sEvalContext, sTargetType);
    } catch (Exception ex) {
        throw new EvaluationException("Expression parsing failed", ex);
    }
}