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.openmrs.validator.LocationValidator.java

/**
 * Checks the form object for any inconsistencies/errors
 * //from w  w w .j  a  va2  s .  c om
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should fail validation if name is null or empty
 * @should fail validation if retired and retireReason is null or empty
 * @should set retired to false if retireReason is null or empty
 * @should pass validation if all fields are correct
 * @should pass validation if retired location is given retired reason
 * @should fail validation if parent location creates a loop
 * @should fail validation if name is exist in non retired locations
 * @should pass validation if field lengths are correct
 * @should fail validation if field lengths are not correct
 */
public void validate(Object obj, Errors errors) {
    Location location = (Location) obj;
    if (location == null) {
        errors.rejectValue("location", "error.general");
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "error.name");

        if (location.isRetired() && !StringUtils.hasLength(location.getRetireReason())) {
            location.setRetired(false); // so that the jsp page displays
            // properly again
            errors.rejectValue("retireReason", "error.null");
        }

        Location exist = Context.getLocationService().getLocation(location.getName());
        if (exist != null && !exist.isRetired()
                && !OpenmrsUtil.nullSafeEquals(location.getUuid(), exist.getUuid())) {
            errors.rejectValue("name", "location.duplicate.name");
        }

        // Traverse all the way up (down?) to the root and check if it
        // equals the root.
        Location root = location;
        while (root.getParentLocation() != null) {
            root = root.getParentLocation();
            if (root.equals(location)) { // Have gone in a circle
                errors.rejectValue("parentLocation", "Location.parentLocation.error");
                break;
            }
        }
        ValidateUtil.validateFieldLengths(errors, obj.getClass(), "name", "description", "address1", "address2",
                "cityVillage", "stateProvince", "country", "postalCode", "latitude", "longitude",
                "countyDistrict", "address3", "address4", "address5", "address6", "retireReason");
        super.validateAttributes(location, errors, Context.getLocationService().getAllLocationAttributeTypes());
    }

}

From source file:org.openmrs.web.controller.order.OrderListByPatientController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db// www . ja  v  a 2 s  .  com
 * 
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();
    if (Context.isAuthenticated()) {
        String[] orderList = ServletRequestUtils.getStringParameters(request, "orderId");
        OrderService os = Context.getOrderService();

        String success = "";
        String error = "";

        MessageSourceAccessor msa = getMessageSourceAccessor();
        String deleted = msa.getMessage("general.deleted");
        String notDeleted = msa.getMessage("general.cannot.delete");
        String ord = msa.getMessage("Order.title");
        String voidReason = ServletRequestUtils.getRequiredStringParameter(request, "voidReason");
        if (!StringUtils.hasLength(voidReason)) {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "general.voidReason.empty");
            return showForm(request, response, errors);
        }
        for (String p : orderList) {
            try {
                os.voidOrder(os.getOrder(Integer.valueOf(p)), voidReason);
                if (!success.equals(""))
                    success += "<br/>";
                success += ord + " " + p + " " + deleted;
            } catch (APIException e) {
                log.warn("Error deleting order", e);
                if (!error.equals(""))
                    error += "<br/>";
                error += ord + " " + p + " " + notDeleted;
            }
        }

        view = getSuccessView();
        if (ServletRequestUtils.getIntParameter(request, "patientId") != null)
            view += "?patientId=" + ServletRequestUtils.getIntParameter(request, "patientId");
        if (!success.equals(""))
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success);
        if (!error.equals(""))
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error);
    }

    return new ModelAndView(new RedirectView(view));
}

From source file:org.openmrs.web.controller.order.OrderListController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db//from   ww  w  .  j  a  va  2s .c  o  m
 * 
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();
    if (Context.isAuthenticated()) {
        String[] orderList = ServletRequestUtils.getStringParameters(request, "orderId");
        OrderService os = Context.getOrderService();

        String success = "";
        String error = "";

        MessageSourceAccessor msa = getMessageSourceAccessor();
        String deleted = msa.getMessage("general.deleted");
        String notDeleted = msa.getMessage("general.cannot.delete");
        String ord = msa.getMessage("Order.title");
        String voidReason = ServletRequestUtils.getRequiredStringParameter(request, "voidReason");
        if (!StringUtils.hasLength(voidReason)) {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "general.voidReason.empty");
            return showForm(request, response, errors);
        }
        for (String p : orderList) {
            try {
                os.voidOrder(os.getOrder(Integer.valueOf(p)), voidReason);
                if (!success.equals(""))
                    success += "<br/>";
                success += ord + " " + p + " " + deleted;
            } catch (APIException e) {
                log.warn("Error deleting order", e);
                if (!error.equals(""))
                    error += "<br/>";
                error += ord + " " + p + " " + notDeleted;
            }
        }

        view = getSuccessView();
        if (!success.equals(""))
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success);
        if (!error.equals(""))
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error);
    }

    return new ModelAndView(new RedirectView(view));
}

From source file:org.openmrs.web.controller.PortletController.java

/**
 * This method produces a model containing the following mappings:
 * /*from  w w  w  .ja v  a2 s. c  om*/
 * <pre>
 *     (always)
 *          (java.util.Date) now
 *          (String) size
 *          (Locale) locale
 *          (String) portletUUID // unique for each instance of any portlet
 *          (other parameters)
 *     (if there's currently an authenticated user)
 *          (User) authenticatedUser
 *     (if the request has a patientId attribute)
 *          (Integer) patientId
 *          (Patient) patient
 *          (List&lt;Obs&gt;) patientObs
 *          (List&lt;Encounter&gt;) patientEncounters
 *          (List&lt;Visit&gt;) patientVisits
 *          (List&lt;Visit&gt;) activeVisits
 *          (Obs) patientWeight // most recent weight obs
 *          (Obs) patientHeight // most recent height obs
 *          (Double) patientBmi // BMI derived from most recent weight and most recent height
 *          (String) patientBmiAsString // BMI rounded to one decimal place, or "?" if unknown
 *          (Integer) personId
 *     (if the request has a personId or patientId attribute)
 *          (Person) person
 *          (List&lt;Relationship&gt;) personRelationships
 *          (Map&lt;RelationshipType, List&lt;Relationship&gt;&gt;) personRelationshipsByType
 *     (if the request has an encounterId attribute)
 *          (Integer) encounterId
 *          (Encounter) encounter
 *          (Set&lt;Obs&gt;) encounterObs
 *     (if the request has a userId attribute)
 *          (Integer) userId
 *          (User) user
 *     (if the request has a patientIds attribute, which should be a (String) comma-separated list of patientIds)
 *          (PatientSet) patientSet
 *          (String) patientIds
 *     (if the request has a conceptIds attribute, which should be a (String) commas-separated list of conceptIds)
 *          (Map&lt;Integer, Concept&gt;) conceptMap
 *          (Map&lt;String, Concept&gt;) conceptMapByStringIds
 * </pre>
 * 
 * @should calculate bmi into patientBmiAsString
 * @should not fail with empty height and weight properties
 */
@SuppressWarnings("unchecked")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    AdministrationService as = Context.getAdministrationService();
    ConceptService cs = Context.getConceptService();

    // find the portlet that was identified in the openmrs:portlet taglib
    Object uri = request.getAttribute("javax.servlet.include.servlet_path");
    String portletPath = "";
    Map<String, Object> model = null;
    {
        HttpSession session = request.getSession();
        String uniqueRequestId = (String) request.getAttribute(WebConstants.INIT_REQ_UNIQUE_ID);
        String lastRequestId = (String) session.getAttribute(WebConstants.OPENMRS_PORTLET_LAST_REQ_ID);
        if (uniqueRequestId.equals(lastRequestId)) {
            model = (Map<String, Object>) session.getAttribute(WebConstants.OPENMRS_PORTLET_CACHED_MODEL);

            // remove cached parameters 
            List<String> parameterKeys = (List<String>) model.get("parameterKeys");
            if (parameterKeys != null) {
                for (String key : parameterKeys) {
                    model.remove(key);
                }
            }
        }
        if (model == null) {
            log.debug("creating new portlet model");
            model = new HashMap<String, Object>();
            session.setAttribute(WebConstants.OPENMRS_PORTLET_LAST_REQ_ID, uniqueRequestId);
            session.setAttribute(WebConstants.OPENMRS_PORTLET_CACHED_MODEL, model);
        }
    }

    if (uri != null) {
        long timeAtStart = System.currentTimeMillis();
        portletPath = uri.toString();

        // Allowable extensions are '' (no extension) and '.portlet'
        if (portletPath.endsWith("portlet")) {
            portletPath = portletPath.replace(".portlet", "");
        } else if (portletPath.endsWith("jsp")) {
            throw new ServletException(
                    "Illegal extension used for portlet: '.jsp'. Allowable extensions are '' (no extension) and '.portlet'");
        }

        log.debug("Loading portlet: " + portletPath);

        String id = (String) request.getAttribute("org.openmrs.portlet.id");
        String size = (String) request.getAttribute("org.openmrs.portlet.size");
        Map<String, Object> params = (Map<String, Object>) request
                .getAttribute("org.openmrs.portlet.parameters");
        Map<String, Object> moreParams = (Map<String, Object>) request
                .getAttribute("org.openmrs.portlet.parameterMap");

        model.put("now", new Date());
        model.put("id", id);
        model.put("size", size);
        model.put("locale", Context.getLocale());
        model.put("portletUUID", UUID.randomUUID().toString().replace("-", ""));
        List<String> parameterKeys = new ArrayList<String>(params.keySet());
        model.putAll(params);
        if (moreParams != null) {
            model.putAll(moreParams);
            parameterKeys.addAll(moreParams.keySet());
        }
        model.put("parameterKeys", parameterKeys); // so we can clean these up in the next request

        // if there's an authenticated user, put them, and their patient set, in the model
        if (Context.getAuthenticatedUser() != null) {
            model.put("authenticatedUser", Context.getAuthenticatedUser());
        }

        Integer personId = null;

        // if a patient id is available, put patient data documented above in the model
        Object o = request.getAttribute("org.openmrs.portlet.patientId");
        if (o != null) {
            String patientVariation = "";
            Integer patientId = (Integer) o;
            if (!model.containsKey("patient") && Context.hasPrivilege(PrivilegeConstants.GET_PATIENTS)) {
                // we can't continue if the user can't view patients
                Patient p = Context.getPatientService().getPatient(patientId);
                model.put("patient", p);
                if (p.isDead()) {
                    patientVariation = "Dead";
                }

                // add encounters if this user can view them
                if (Context.hasPrivilege(PrivilegeConstants.GET_ENCOUNTERS)) {
                    model.put("patientEncounters", Context.getEncounterService().getEncountersByPatient(p));
                }

                // add visits if this user can view them
                if (Context.hasPrivilege(PrivilegeConstants.GET_VISITS)) {
                    model.put("person", p);
                    PortletControllerUtil.addFormToEditAndViewUrlMaps(model);
                    model.put("patientVisits", Context.getVisitService().getVisitsByPatient(p));
                    model.put("activeVisits", Context.getVisitService().getActiveVisitsByPatient(p));
                }

                if (Context.hasPrivilege(PrivilegeConstants.GET_OBS)) {
                    List<Obs> patientObs = Context.getObsService().getObservationsByPerson(p);
                    model.put("patientObs", patientObs);
                    Obs latestWeight = null;
                    Obs latestHeight = null;
                    String bmiAsString = "?";
                    try {
                        String weightString = as.getGlobalProperty("concept.weight");
                        ConceptNumeric weightConcept = null;
                        if (StringUtils.hasLength(weightString)) {
                            weightConcept = cs.getConceptNumeric(
                                    cs.getConcept(Integer.valueOf(weightString)).getConceptId());
                        }
                        String heightString = as.getGlobalProperty("concept.height");
                        ConceptNumeric heightConcept = null;
                        if (StringUtils.hasLength(heightString)) {
                            heightConcept = cs.getConceptNumeric(
                                    cs.getConcept(Integer.valueOf(heightString)).getConceptId());
                        }
                        for (Obs obs : patientObs) {
                            if (obs.getConcept().equals(weightConcept)) {
                                if (latestWeight == null
                                        || obs.getObsDatetime().compareTo(latestWeight.getObsDatetime()) > 0) {
                                    latestWeight = obs;
                                }
                            } else if (obs.getConcept().equals(heightConcept) && (latestHeight == null
                                    || obs.getObsDatetime().compareTo(latestHeight.getObsDatetime()) > 0)) {
                                latestHeight = obs;
                            }
                        }
                        if (latestWeight != null) {
                            model.put("patientWeight", latestWeight);
                        }
                        if (latestHeight != null) {
                            model.put("patientHeight", latestHeight);
                        }
                        if (latestWeight != null && latestHeight != null) {
                            double weightInKg;
                            double heightInM;
                            if (weightConcept.getUnits().equals("kg")) {
                                weightInKg = latestWeight.getValueNumeric();
                            } else if (weightConcept.getUnits().equals("lb")) {
                                weightInKg = latestWeight.getValueNumeric() * 0.45359237;
                            } else {
                                throw new IllegalArgumentException(
                                        "Can't handle units of weight concept: " + weightConcept.getUnits());
                            }
                            if (heightConcept.getUnits().equals("cm")) {
                                heightInM = latestHeight.getValueNumeric() / 100;
                            } else if (heightConcept.getUnits().equals("m")) {
                                heightInM = latestHeight.getValueNumeric();
                            } else if (heightConcept.getUnits().equals("in")) {
                                heightInM = latestHeight.getValueNumeric() * 0.0254;
                            } else {
                                throw new IllegalArgumentException(
                                        "Can't handle units of height concept: " + heightConcept.getUnits());
                            }
                            double bmi = weightInKg / (heightInM * heightInM);
                            model.put("patientBmi", bmi);
                            String temp = "" + bmi;
                            bmiAsString = temp.substring(0, temp.indexOf('.') + 2);
                        }
                    } catch (Exception ex) {
                        if (latestWeight != null && latestHeight != null) {
                            log.error("Failed to calculate BMI even though a weight and height were found", ex);
                        }
                    }
                    model.put("patientBmiAsString", bmiAsString);
                } else {
                    model.put("patientObs", new HashSet<Obs>());
                }

                if (Context.hasPrivilege(PrivilegeConstants.GET_PROGRAMS)
                        && Context.hasPrivilege(PrivilegeConstants.GET_PATIENT_PROGRAMS)) {
                    model.put("patientPrograms", Context.getProgramWorkflowService().getPatientPrograms(p, null,
                            null, null, null, null, false));
                    model.put("patientCurrentPrograms", Context.getProgramWorkflowService()
                            .getPatientPrograms(p, null, null, new Date(), new Date(), null, false));
                }

                model.put("patientId", patientId);
                personId = p.getPatientId();
                model.put("personId", personId);

                model.put("patientVariation", patientVariation);
            }
        }

        // if a person id is available, put person and relationships in the model
        if (personId == null) {
            o = request.getAttribute("org.openmrs.portlet.personId");
            if (o != null) {
                personId = (Integer) o;
                model.put("personId", personId);
            }
        }
        if (personId != null) {
            Person p = (Person) model.get("person");
            if (p == null) {
                p = (Person) model.get("patient");
                if (p == null) {
                    p = Context.getPersonService().getPerson(personId);
                }
                model.put("person", p);
            }

            if (!model.containsKey("personRelationships")
                    && Context.hasPrivilege(PrivilegeConstants.GET_RELATIONSHIPS)) {
                List<Relationship> relationships = new ArrayList<Relationship>();
                relationships.addAll(Context.getPersonService().getRelationshipsByPerson(p));
                Map<RelationshipType, List<Relationship>> relationshipsByType = new HashMap<RelationshipType, List<Relationship>>();
                for (Relationship rel : relationships) {
                    List<Relationship> list = relationshipsByType.get(rel.getRelationshipType());
                    if (list == null) {
                        list = new ArrayList<Relationship>();
                        relationshipsByType.put(rel.getRelationshipType(), list);
                    }
                    list.add(rel);
                }

                model.put("personRelationships", relationships);
                model.put("personRelationshipsByType", relationshipsByType);
            }
        }

        // if an encounter id is available, put "encounter" and "encounterObs" in the model
        o = request.getAttribute("org.openmrs.portlet.encounterId");
        if (o != null && !model.containsKey("encounterId")) {
            if (!model.containsKey("encounter") && Context.hasPrivilege(PrivilegeConstants.GET_ENCOUNTERS)) {
                Encounter e = Context.getEncounterService().getEncounter((Integer) o);
                model.put("encounter", e);
                if (Context.hasPrivilege(PrivilegeConstants.GET_OBS)) {
                    model.put("encounterObs", e.getObs());
                }
                model.put("encounterId", (Integer) o);
            }
        }

        // if a user id is available, put "user" in the model
        o = request.getAttribute("org.openmrs.portlet.userId");
        if (o != null && !model.containsKey("user")) {
            if (Context.hasPrivilege(PrivilegeConstants.GET_USERS)) {
                User u = Context.getUserService().getUser((Integer) o);
                model.put("user", u);
            }
            model.put("userId", (Integer) o);
        }

        // if a list of patient ids is available, make a patientset out of it
        o = request.getAttribute("org.openmrs.portlet.patientIds");
        if (!StringUtils.isEmpty(o) && !model.containsKey("patientIds") && !model.containsKey("patientSet")) {
            Cohort ps = new Cohort((String) o);
            model.put("patientSet", ps);
            model.put("patientIds", (String) o);
        }

        o = model.get("conceptIds");

        if (!StringUtils.isEmpty(o) && !model.containsKey("conceptMap")) {
            log.debug("Found conceptIds parameter: " + o);
            Map<Integer, Concept> concepts = new HashMap<Integer, Concept>();
            Map<String, Concept> conceptsByStringIds = new HashMap<String, Concept>();
            String conceptIds = (String) o;
            String[] ids = conceptIds.split(",");
            for (String cId : ids) {
                try {
                    Integer i = Integer.valueOf(cId);
                    Concept c = cs.getConcept(i);
                    concepts.put(i, c);
                    conceptsByStringIds.put(i.toString(), c);
                } catch (Exception ex) {
                    log.error("Error during putting int i into concept c", ex);
                }
            }

            model.put("conceptMap", concepts);
            model.put("conceptMapByStringIds", conceptsByStringIds);
        }

        populateModel(request, model);
        log.debug(portletPath + " took " + (System.currentTimeMillis() - timeAtStart) + " ms");
    }

    return new ModelAndView("/module/legacyui" + portletPath, "model", model);

}

From source file:org.openmrs.web.controller.user.UserFormController.java

/**
 * @should work for an example//from  w  w w .j  a  va 2  s  .c  om
 */
@RequestMapping(value = "/admin/users/user.form", method = RequestMethod.POST)
public String handleSubmission(WebRequest request, HttpSession httpSession, ModelMap model,
        @RequestParam(required = false, value = "action") String action,
        @RequestParam(required = false, value = "userFormOldPassword") String oldPassword,
        @RequestParam(required = false, value = "userFormPassword") String password,
        @RequestParam(required = false, value = "secretQuestion") String secretQuestion,
        @RequestParam(required = false, value = "secretAnswer") String secretAnswer,
        @RequestParam(required = false, value = "confirm") String confirm,
        @RequestParam(required = false, value = "forcePassword") Boolean forcePassword,
        @RequestParam(required = false, value = "roleStrings") String[] roles,
        @RequestParam(required = false, value = "createNewPerson") String createNewPerson,
        @ModelAttribute("user") User user, BindingResult errors) {

    UserService us = Context.getUserService();
    MessageSourceService mss = Context.getMessageSourceService();

    if (!Context.isAuthenticated()) {
        errors.reject("auth.invalid");
    } else if (mss.getMessage("User.assumeIdentity").equals(action)) {
        Context.becomeUser(user.getSystemId());
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success");
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName());
        return "redirect:/index.htm";

    } else if (mss.getMessage("User.delete").equals(action)) {
        try {
            Context.getUserService().purgeUser(user);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.success");
            return "redirect:users.list";
        } catch (Exception ex) {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "User.delete.failure");
            log.error("Failed to delete user", ex);
            return "redirect:/admin/users/user.form?userId=" + request.getParameter("userId");
        }

    } else if (mss.getMessage("User.retire").equals(action)) {
        String retireReason = request.getParameter("retireReason");
        if (!(StringUtils.hasText(retireReason))) {
            errors.rejectValue("retireReason", "User.disableReason.empty");
            return showForm(user.getUserId(), createNewPerson, user, model);
        } else {
            us.retireUser(user, retireReason);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.retiredMessage");
        }

    } else if (mss.getMessage("User.unRetire").equals(action)) {
        us.unretireUser(user);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.unRetiredMessage");
    } else {

        // check if username is already in the database
        if (us.hasDuplicateUsername(user)) {
            errors.rejectValue("username", "error.username.taken");
        }

        // check if password and password confirm are identical
        if (password == null || password.equals("XXXXXXXXXXXXXXX")) {
            password = "";
        }
        if (confirm == null || confirm.equals("XXXXXXXXXXXXXXX")) {
            confirm = "";
        }

        if (!password.equals(confirm)) {
            errors.reject("error.password.match");
        }

        if (password.length() == 0 && isNewUser(user)) {
            errors.reject("options.login.password.null");
        }

        //check password strength
        if (password.length() > 0) {
            try {
                OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
            } catch (PasswordException e) {
                errors.reject(e.getMessage());
            }
        }

        Set<Role> newRoles = new HashSet<Role>();
        if (roles != null) {
            for (String r : roles) {
                // Make sure that if we already have a detached instance of this role in the
                // user's roles, that we don't fetch a second copy of that same role from
                // the database, or else hibernate will throw a NonUniqueObjectException.
                Role role = null;
                if (user.getRoles() != null) {
                    for (Role test : user.getRoles()) {
                        if (test.getRole().equals(r)) {
                            role = test;
                        }
                    }
                }
                if (role == null) {
                    role = us.getRole(r);
                    user.addRole(role);
                }
                newRoles.add(role);
            }
        }

        if (user.getRoles() == null) {
            newRoles.clear();
        } else {
            user.getRoles().retainAll(newRoles);
        }

        String[] keys = request.getParameterValues("property");
        String[] values = request.getParameterValues("value");

        if (keys != null && values != null) {
            for (int x = 0; x < keys.length; x++) {
                String key = keys[x];
                String val = values[x];
                user.setUserProperty(key, val);
            }
        }

        if (StringUtils.hasLength(secretQuestion) && !StringUtils.hasLength(secretAnswer)) {
            errors.reject("error.User.secretAnswer.empty");
        } else if (!StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) {
            errors.reject("error.User.secretQuestion.empty");
        }

        new UserProperties(user.getUserProperties()).setSupposedToChangePassword(forcePassword);

        userValidator.validate(user, errors);

        if (errors.hasErrors()) {
            return showForm(user.getUserId(), createNewPerson, user, model);
        }

        if (isNewUser(user)) {
            us.createUser(user, password);
        } else {
            us.saveUser(user);

            if (!"".equals(password) && Context.hasPrivilege(PrivilegeConstants.EDIT_USER_PASSWORDS)) {
                if (log.isDebugEnabled()) {
                    log.debug("calling changePassword for user " + user + " by user "
                            + Context.getAuthenticatedUser());
                }
                us.changePassword(user, oldPassword, password);
            }
        }

        if (StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) {
            us.changeQuestionAnswer(user, secretQuestion, secretAnswer);
        }

        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
    }
    return "redirect:users.list";
}

From source file:org.openmrs.web.Listener.java

/**
 * Load the openmrs constants with values from web.xml init parameters
 *
 * @param servletContext startup context (web.xml)
 *//*w  ww.  jav  a2s  .  c  o m*/
private void loadConstants(ServletContext servletContext) {
    WebConstants.BUILD_TIMESTAMP = servletContext.getInitParameter("build.timestamp");
    WebConstants.WEBAPP_NAME = getContextPath(servletContext);
    WebConstants.MODULE_REPOSITORY_URL = servletContext.getInitParameter("module.repository.url");
    // note: the below value will be overridden after reading the runtime properties if the
    // "application_data_directory" runtime property is set
    String appDataDir = servletContext.getInitParameter("application.data.directory");
    if (StringUtils.hasLength(appDataDir)) {
        OpenmrsUtil.setApplicationDataDirectory(appDataDir);
    } else if (!"openmrs".equalsIgnoreCase(WebConstants.WEBAPP_NAME)) {
        OpenmrsUtil.setApplicationDataDirectory(
                OpenmrsUtil.getApplicationDataDirectory() + File.separator + WebConstants.WEBAPP_NAME);
    }
}

From source file:org.opennms.protocols.radius.springsecurity.RadiusAuthenticationProvider.java

/** {@inheritDoc} */
@Override//from   w  ww.  ja v a  2 s  .  c o  m
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken token)
        throws AuthenticationException {
    if (!StringUtils.hasLength(username)) {
        logger.info("Authentication attempted with empty username");
        throw new BadCredentialsException(
                messages.getMessage("RadiusAuthenticationProvider.emptyUsername", "Username cannot be empty"));
    }
    String password = (String) token.getCredentials();
    if (!StringUtils.hasLength(password)) {
        logger.info("Authentication attempted with empty password");
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }

    InetAddress serverIP = null;
    serverIP = InetAddressUtils.addr(server);
    if (serverIP == null) {
        logger.error("Could not resolve radius server address " + server);
        throw new AuthenticationServiceException(messages.getMessage(
                "RadiusAuthenticationProvider.unknownServer", "Could not resolve radius server address"));
    }
    AttributeFactory.loadAttributeDictionary("net.jradius.dictionary.AttributeDictionaryImpl");
    AttributeList attributeList = new AttributeList();
    attributeList.add(new Attr_UserName(username));
    attributeList.add(new Attr_UserPassword(password));
    RadiusPacket reply;
    try {
        RadiusClient radiusClient = new RadiusClient(serverIP, secret, port, port + 1, timeout);
        AccessRequest request = new AccessRequest(radiusClient, attributeList);

        logger.debug("Sending AccessRequest message to " + InetAddressUtils.str(serverIP) + ":" + port
                + " using " + (authTypeClass == null ? "PAP" : authTypeClass.getAuthName())
                + " protocol with timeout = " + timeout + ", retries = " + retries + ", attributes:\n"
                + attributeList.toString());
        reply = radiusClient.authenticate(request, authTypeClass, retries);
    } catch (RadiusException e) {
        logger.error("Error connecting to radius server " + server + " : " + e);
        throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.radiusError",
                new Object[] { e }, "Error connecting to radius server: " + e));
    } catch (IOException e) {
        logger.error("Error connecting to radius server " + server + " : " + e);
        throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.radiusError",
                new Object[] { e }, "Error connecting to radius server: " + e));
    }
    if (reply == null) {
        logger.error("Timed out connecting to radius server " + server);
        throw new AuthenticationServiceException(messages.getMessage(
                "RadiusAuthenticationProvider.radiusTimeout", "Timed out connecting to radius server"));
    }
    if (!(reply instanceof AccessAccept)) {
        logger.info("Received a reply other than AccessAccept from radius server " + server + " for user "
                + username + " :\n" + reply.toString());
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
    logger.debug("Received AccessAccept message from " + InetAddressUtils.str(serverIP) + ":" + port
            + " for user " + username + " with attributes:\n" + reply.getAttributes().toString());

    String roles = null;
    if (!StringUtils.hasLength(rolesAttribute)) {
        logger.debug("rolesAttribute not set, using default roles (" + defaultRoles + ") for user " + username);
        roles = new String(defaultRoles);
    } else {
        Iterator<RadiusAttribute> attributes = reply.getAttributes().getAttributeList().iterator();
        while (attributes.hasNext()) {
            RadiusAttribute attribute = attributes.next();
            if (rolesAttribute.equals(attribute.getAttributeName())) {
                roles = new String(attribute.getValue().getBytes());
                break;
            }
        }
        if (roles == null) {
            logger.info("Radius attribute " + rolesAttribute + " not found, using default roles ("
                    + defaultRoles + ") for user " + username);
            roles = new String(defaultRoles);
        }
    }

    String[] rolesArray = roles.replaceAll("\\s*", "").split(",");
    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(rolesArray.length);
    for (String role : rolesArray) {
        authorities.add(new SimpleGrantedAuthority(role));
    }
    if (logger.isDebugEnabled()) {
        StringBuffer readRoles = new StringBuffer();
        for (GrantedAuthority authority : authorities) {
            readRoles.append(authority.toString() + ", ");
        }
        if (readRoles.length() > 0) {
            readRoles.delete(readRoles.length() - 2, readRoles.length());
        }
        logger.debug("Parsed roles " + readRoles + " for user " + username);
    }

    return new User(username, password, true, true, true, true, authorities);
}

From source file:org.openo.sdnhub.overlayvpndriver.http.OverlayVpnDriverSsoProxy.java

@SuppressWarnings("rawtypes")
private static OverlayVpnDriverResponse parserAcResponse(String content) {
    if (!StringUtils.hasLength(content)) {
        return null;
    }//from   ww w  .  java 2 s.c  o m

    JSONObject respoenJO = JSONObject.fromObject(content);
    if (null == respoenJO) {
        return null;
    }

    return JsonUtil.fromJson(respoenJO.toString(), OverlayVpnDriverResponse.class);
}

From source file:org.openo.sdnhub.overlayvpndriver.http.OverlayVpnDriverSsoProxy.java

/**
 * Send post restful request. <br>
 *
 * @param restUrl restful URL path/*ww w.  jav  a 2 s  .  c om*/
 * @param body message body
 * @return The object of HTTPReturnMessage
 * @since SDNO 0.5
 */
@SuppressWarnings("deprecation")
public HTTPReturnMessage post(final String restUrl, final String body) {
    String postUrl = this.getHttpsUrl() + restUrl;
    LOGGER.info("Post Request url: " + restUrl + "\n Body: " + body);

    HttpPost httpPost = new HttpPost(postUrl);

    if (StringUtils.hasLength(body)) {
        StringEntity reqEntity = new StringEntity(body, HTTP.UTF_8);
        httpPost.setEntity(reqEntity);
    }

    return commonRequest(httpPost);
}

From source file:org.openo.sdnhub.overlayvpndriver.http.OverlayVpnDriverSsoProxy.java

/**
 * Send put restful request. <br>/*from w  w  w. ja va 2  s  .c om*/
 *
 * @param restUrl restful URL path
 * @param body message body
 * @return The object of HTTPReturnMessage
 * @since SDNO 0.5
 */
@SuppressWarnings("deprecation")
public HTTPReturnMessage put(final String restUrl, final String body) {
    HttpPut httpPut = new HttpPut(this.getHttpsUrl() + restUrl);
    LOGGER.info("Put Request url for AC: " + restUrl + "\n Body: " + body);

    if (StringUtils.hasLength(body)) {
        StringEntity reqEntity = new StringEntity(body, HTTP.UTF_8);
        httpPut.setEntity(reqEntity);
    }

    return commonRequest(httpPut);
}