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:com.taobao.diamond.server.controller.BaseStoneController.java

@RequestMapping(params = "method=updateAll", method = RequestMethod.POST)
public String updateConfigAll(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("dataId") String dataId, @RequestParam("group") String group,
        @RequestParam("content") String content) {
    response.setCharacterEncoding("GBK");

    String remoteIp = getRemoteIp(request);

    boolean checkSuccess = true;
    String errorMessage = "";
    if (!StringUtils.hasLength(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) {
        checkSuccess = false;/*from  w ww . j  a  v a  2s .  c om*/
        errorMessage = "DataId";
    }
    if (!StringUtils.hasLength(group) || DiamondUtils.hasInvalidChar(group.trim())) {
        checkSuccess = false;
        errorMessage = "";
    }
    if (!StringUtils.hasLength(content)) {
        checkSuccess = false;
        errorMessage = "";
    }
    if (!checkSuccess) {
        try {
            response.sendError(INVALID_PARAM, errorMessage);
        } catch (IOException e) {
            log.error("response", e);
        }
        return "536";
    }

    // 
    this.updateAllConfigInfo(dataId, group, content);
    try {
        // ipdataIdredis
        this.addIpToDataIdAndGroup(remoteIp, dataId, group);
    } catch (Exception e) {
        log.error("redis", e);
    }
    return "200";
}

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

/**
 * This method produces a model containing the following mappings:
 * /* w ww  . java2s. 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<Obs>) patientObs
 *          (List<Encounter>) patientEncounters
 *          (List<DrugOrder>) patientDrugOrders
 *          (List<DrugOrder>) currentDrugOrders
 *          (List<DrugOrder>) completedDrugOrders
 *          (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 patient has any obs for the concept in the global property 'concept.reasonExitedCare')
 *              (Obs) patientReasonForExit
 *     (if the request has a personId or patientId attribute)
 *          (Person) person
 *          (List<Relationship>) personRelationships
 *          (Map<RelationshipType, List<Relationship>>) personRelationshipsByType
 *     (if the request has an encounterId attribute)
 *          (Integer) encounterId
 *          (Encounter) encounter
 *          (Set<Obs>) 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<Integer, Concept>) conceptMap
 *          (Map<String, Concept>) conceptMapByStringIds
 * </pre>
 * 
 * @should calculate bmi into patientBmiAsString
 * @should not fail with empty height and weight properties
 */
@Override
@SuppressWarnings("unchecked")
public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    this.log.warn("Entering PortletController.handleRequest");
    String portletPath = "";
    Map<String, Object> model = null;
    Integer personId = null;

    try {
        //Add temporary privilege
        //PersonalhrUtil.addTemporayPrivileges();

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

        // find the portlet that was identified in the openmrs:portlet taglib
        final Object uri = request.getAttribute("javax.servlet.include.servlet_path");

        {
            final HttpSession session = request.getSession();
            final String uniqueRequestId = (String) request.getAttribute(WebConstants.INIT_REQ_UNIQUE_ID);
            final 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 
                final List<String> parameterKeys = (List<String>) model.get("parameterKeys");
                for (final String key : parameterKeys) {
                    model.remove(key);
                }
            }
            if (model == null) {
                this.log.warn("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);
            }
        }

        this.log.warn("PortletController.handleRequest: uri=" + uri);
        if (uri != null) {
            final 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'");
            }

            this.log.warn("Loading portlet: " + portletPath);

            final String id = (String) request.getAttribute("org.openmrs.portlet.id");
            final String size = (String) request.getAttribute("org.openmrs.portlet.size");
            final Map<String, Object> params = (Map<String, Object>) request
                    .getAttribute("org.openmrs.portlet.parameters");
            final 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("-", ""));
            final 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());
            }

            // 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) {
                request.getSession().setAttribute("org.openmrs.portlet.patientId", o);

                String patientVariation = "";
                final Integer patientId = (Integer) o;
                if (!model.containsKey("patient")) {
                    // we can't continue if the user can't view patients
                    if (Context.hasPrivilege(OpenmrsConstants.PRIV_VIEW_PATIENTS)) {
                        final Patient p = Context.getPatientService().getPatient(patientId);
                        model.put("patient", p);

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

                        if (Context.hasPrivilege(OpenmrsConstants.PRIV_VIEW_OBS)) {
                            final List<Obs> patientObs = Context.getObsService().getObservationsByPerson(p);
                            model.put("patientObs", patientObs);
                            Obs latestWeight = null;
                            Obs latestHeight = null;
                            String bmiAsString = "?";
                            try {
                                final String weightString = as.getGlobalProperty("concept.weight");
                                ConceptNumeric weightConcept = null;
                                if (StringUtils.hasLength(weightString)) {
                                    weightConcept = cs.getConceptNumeric(
                                            cs.getConcept(Integer.valueOf(weightString)).getConceptId());
                                }
                                final String heightString = as.getGlobalProperty("concept.height");
                                ConceptNumeric heightConcept = null;
                                if (StringUtils.hasLength(heightString)) {
                                    heightConcept = cs.getConceptNumeric(
                                            cs.getConcept(Integer.valueOf(heightString)).getConceptId());
                                }
                                for (final 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)) {
                                        if ((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());
                                    }
                                    final double bmi = weightInKg / (heightInM * heightInM);
                                    model.put("patientBmi", bmi);
                                    final String temp = "" + bmi;
                                    bmiAsString = temp.substring(0, temp.indexOf('.') + 2);
                                }
                            } catch (final Exception ex) {
                                if ((latestWeight != null) && (latestHeight != null)) {
                                    this.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>());
                        }

                        // information about whether or not the patient has exited care
                        Obs reasonForExitObs = null;
                        final String reasonForExitConceptString = as
                                .getGlobalProperty("concept.reasonExitedCare");
                        if (StringUtils.hasLength(reasonForExitConceptString)) {
                            final Concept reasonForExitConcept = cs.getConcept(reasonForExitConceptString);
                            if (reasonForExitConcept != null) {
                                final List<Obs> patientExitObs = Context.getObsService()
                                        .getObservationsByPersonAndConcept(p, reasonForExitConcept);
                                if (patientExitObs != null) {
                                    this.log.debug("Exit obs is size " + patientExitObs.size());
                                    if (patientExitObs.size() == 1) {
                                        reasonForExitObs = patientExitObs.iterator().next();
                                        final Concept exitReason = reasonForExitObs.getValueCoded();
                                        final Date exitDate = reasonForExitObs.getObsDatetime();
                                        if ((exitReason != null) && (exitDate != null)) {
                                            patientVariation = "Exited";
                                        }
                                    } else {
                                        if (patientExitObs.size() == 0) {
                                            this.log.debug("Patient has no reason for exit");
                                        } else {
                                            this.log.error(
                                                    "Too many reasons for exit - not putting data into model");
                                        }
                                    }
                                }
                            }
                        }
                        model.put("patientReasonForExit", reasonForExitObs);

                        if (Context.hasPrivilege(OpenmrsConstants.PRIV_VIEW_ORDERS)) {
                            final List<DrugOrder> drugOrderList = Context.getOrderService()
                                    .getDrugOrdersByPatient(p);
                            model.put("patientDrugOrders", drugOrderList);
                            final List<DrugOrder> currentDrugOrders = new ArrayList<DrugOrder>();
                            final List<DrugOrder> discontinuedDrugOrders = new ArrayList<DrugOrder>();
                            final Date rightNow = new Date();
                            for (final DrugOrder next : drugOrderList) {
                                if (next.isCurrent() || next.isFuture()) {
                                    currentDrugOrders.add(next);
                                }
                                if (next.isDiscontinued(rightNow)) {
                                    discontinuedDrugOrders.add(next);
                                }
                            }
                            model.put("currentDrugOrders", currentDrugOrders);
                            model.put("completedDrugOrders", discontinuedDrugOrders);

                            final List<RegimenSuggestion> standardRegimens = Context.getOrderService()
                                    .getStandardRegimens();
                            if (standardRegimens != null) {
                                model.put("standardRegimens", standardRegimens);
                            }
                        }

                        if (Context.hasPrivilege(OpenmrsConstants.PRIV_VIEW_PROGRAMS)
                                && Context.hasPrivilege(OpenmrsConstants.PRIV_VIEW_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);
                        if (p != null) {
                            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) {
                if (!model.containsKey("person")) {
                    Person p = (Person) model.get("patient");
                    if (p == null) {
                        p = Context.getPersonService().getPerson(personId);
                    }
                    model.put("person", p);

                    if (Context.hasPrivilege(OpenmrsConstants.PRIV_VIEW_RELATIONSHIPS)) {
                        final List<Relationship> relationships = new ArrayList<Relationship>();
                        relationships.addAll(Context.getPersonService().getRelationshipsByPerson(p));
                        final Map<RelationshipType, List<Relationship>> relationshipsByType = new HashMap<RelationshipType, List<Relationship>>();
                        for (final 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")) {
                    if (Context.hasPrivilege(OpenmrsConstants.PRIV_VIEW_ENCOUNTERS)) {
                        final Encounter e = Context.getEncounterService().getEncounter((Integer) o);
                        model.put("encounter", e);
                        if (Context.hasPrivilege(OpenmrsConstants.PRIV_VIEW_OBS)) {
                            model.put("encounterObs", e.getObs());
                        }
                    }
                    model.put("encounterId", o);
                }
            }

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

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

            o = model.get("conceptIds");
            if ((o != null) && !"".equals(o)) {
                if (!model.containsKey("conceptMap")) {
                    this.log.debug("Found conceptIds parameter: " + o);
                    final Map<Integer, Concept> concepts = new HashMap<Integer, Concept>();
                    final Map<String, Concept> conceptsByStringIds = new HashMap<String, Concept>();
                    final String conceptIds = (String) o;
                    final String[] ids = conceptIds.split(",");
                    for (final String cId : ids) {
                        try {
                            final Integer i = Integer.valueOf(cId);
                            final Concept c = cs.getConcept(i);
                            concepts.put(i, c);
                            conceptsByStringIds.put(i.toString(), c);
                        } catch (final Exception ex) {
                        }
                    }
                    model.put("conceptMap", concepts);
                    model.put("conceptMapByStringIds", conceptsByStringIds);
                }
            }

            populateModel(request, model);
            this.log.warn(portletPath + " took " + (System.currentTimeMillis() - timeAtStart) + " ms");
        }
    } finally {
        //PersonalhrUtil.removeTemporayPrivileges();
    }
    return new ModelAndView(portletPath, "model", model);
}

From source file:org.openmrs.module.peer.api.db.hibernate.HibernatePeerDAO.java

/**
 * Utility method to add identifier expression to an existing criteria
 *
 * @param criteria//from   ww w.  ja v  a 2 s  .co m
 * @param identifier
 * @param identifierTypes
 * @param matchIdentifierExactly
 */
private void addIdentifierCriterias(Criteria criteria, String identifier,
        List<PatientIdentifierType> identifierTypes, boolean matchIdentifierExactly) {
    // TODO add junit test for searching on voided identifiers

    // add the join on the identifiers table
    criteria.createAlias("identifiers", "ids");
    criteria.add(Expression.eq("ids.voided", false));

    // do the identifier restriction
    if (identifier != null) {
        // if the user wants an exact search, match on that.
        if (matchIdentifierExactly) {
            criteria.add(Expression.eq("ids.identifier", identifier));
        } else {
            AdministrationService adminService = Context.getAdministrationService();
            String regex = adminService
                    .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX, "");
            String patternSearch = adminService
                    .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SEARCH_PATTERN, "");

            // remove padding from identifier search string
            if (Pattern.matches("^\\^.{1}\\*.*$", regex)) {
                identifier = removePadding(identifier, regex);
            }

            if (StringUtils.hasLength(patternSearch)) {
                //splitAndAddSearchPattern(criteria, identifier, patternSearch);
            }
            // if the regex is empty, default to a simple "like" search or if
            // we're in hsql world, also only do the simple like search (because
            // hsql doesn't know how to deal with 'regexp'
            else if (regex.equals("") || HibernateUtil.isHSQLDialect(sessionFactory)) {
                addCriterionForSimpleSearch(criteria, identifier, adminService);
            }
            // if the regex is present, search on that
            else {
                //                    regex = replaceSearchString(regex, identifier);
                //                    criteria.add(Restrictions.sqlRestriction("identifier regexp ?", regex, Hibernate.STRING));
            }
        }
    }

    // TODO add a junit test for patientIdentifierType restrictions

    // do the type restriction
    if (identifierTypes.size() > 0) {
        criteria.add(Expression.in("ids.identifierType", identifierTypes));
    }
}

From source file:com.googlecode.ehcache.annotations.config.AnnotationDrivenEhCacheBeanDefinitionParser.java

/**
 * Setup the default cache key generator. 
 * //  w  w w  .ja va 2  s. c o m
 * @return A reference to the default cache key generator. Should never be null.
 */
protected RuntimeBeanReference setupDefaultCacheKeyGenerators(Element element, ParserContext parserContext,
        Object elementSource) {
    //Register all of the default cache key generator types
    this.setupDefaultCacheKeyGenerator(ListCacheKeyGenerator.class, parserContext, elementSource);
    this.setupDefaultCacheKeyGenerator(HashCodeCacheKeyGenerator.class, parserContext, elementSource);
    this.setupDefaultCacheKeyGenerator(MessageDigestCacheKeyGenerator.class, parserContext, elementSource);
    this.setupDefaultCacheKeyGenerator(ReflectionHashCodeCacheKeyGenerator.class, parserContext, elementSource);
    this.setupDefaultCacheKeyGenerator(StringCacheKeyGenerator.class, parserContext, elementSource);

    //If the default cache key generator was specified simply return a bean reference for that
    final String defaultCacheKeyGeneratorName = element.getAttribute(XSD_ATTR__DEFAULT_CACHE_KEY_GENERATOR);
    if (StringUtils.hasLength(defaultCacheKeyGeneratorName)) {
        return new RuntimeBeanReference(defaultCacheKeyGeneratorName);
    }

    //Use the default name for the bean reference
    return new RuntimeBeanReference(DEFAULT_CACHE_KEY_GENERATOR);
}

From source file:org.apache.servicemix.jbi.deployer.impl.AdminCommandsImpl.java

/**
 * Prints information about all components (Service Engine or Binding
 * Component) installedServiceReference[] refs = getAdminService().getComponentServiceReferences(filter);
 * if (excludeBCs && excludeSEs) {
 * refs = new ServiceReference[0];//from  ww w .  j  av  a 2 s  .c o  m
 * }
 * List<Component> components = new ArrayList<Component>();
 *
 * @param excludeSEs
 * @param excludeBCs
 * @param requiredState
 * @param sharedLibraryName
 * @param serviceAssemblyName
 * @return list of components in an XML blob
 */
public String listComponents(boolean excludeSEs, boolean excludeBCs, boolean excludePojos, String requiredState,
        String sharedLibraryName, String serviceAssemblyName) throws Exception {
    //validate requiredState
    if (requiredState != null && requiredState.length() > 0
            && !LifeCycleMBean.UNKNOWN.equalsIgnoreCase(requiredState)
            && !LifeCycleMBean.SHUTDOWN.equalsIgnoreCase(requiredState)
            && !LifeCycleMBean.STOPPED.equalsIgnoreCase(requiredState)
            && !LifeCycleMBean.STARTED.equalsIgnoreCase(requiredState)) {
        throw ManagementSupport.failure("listComponents",
                "Required state '" + requiredState + "' is not a valid state.");
    }
    // Get components
    List<Component> components = new ArrayList<Component>();
    for (Component component : deployer.getComponents().values()) {
        // Check type
        if (excludeSEs && Deployer.TYPE_SERVICE_ENGINE.equals(component.getMainType())) {
            continue;
        }
        // Check type
        if (excludeBCs && Deployer.TYPE_BINDING_COMPONENT.equals(component.getMainType())) {
            continue;
        }
        // Check status
        if (requiredState != null && requiredState.length() > 0
                && !requiredState.equalsIgnoreCase(component.getCurrentState())) {
            continue;
        }
        // Check shared library
        if (StringUtils.hasLength(sharedLibraryName)) {
            boolean match = false;
            for (SharedLibrary lib : component.getSharedLibraries()) {
                if (sharedLibraryName.equals(lib.getName())) {
                    match = true;
                    break;
                }
            }
            if (!match) {
                continue;
            }
        }
        // Check deployed service assembly
        if (StringUtils.hasLength(serviceAssemblyName)) {
            boolean match = false;
            for (ServiceUnit su : component.getServiceUnits()) {
                if (serviceAssemblyName.equals(su.getServiceAssembly().getName())) {
                    match = true;
                    break;
                }
            }
            if (!match) {
                continue;
            }
        }
        components.add(component);
    }

    StringBuffer buffer = new StringBuffer();
    buffer.append("<?xml version='1.0'?>\n");
    buffer.append(
            "<component-info-list xmlns='http://java.sun.com/xml/ns/jbi/component-info-list' version='1.0'>\n");
    for (Component component : components) {
        buffer.append("  <component-info");
        buffer.append(" type='").append(component.getMainType()).append("'");
        buffer.append(" name='").append(component.getName()).append("'");
        buffer.append(" state='").append(component.getCurrentState()).append("'>\n");
        buffer.append("    <description>");
        if (component.getDescription() != null) {
            buffer.append(component.getDescription());
        }
        buffer.append("</description>\n");
        buffer.append("  </component-info>\n");
    }
    buffer.append("</component-info-list>");
    return buffer.toString();

}

From source file:com.starit.diamond.server.controller.AdminController.java

/**
 * //from   w  w w.j  a  va  2s . co m
 * 
 * @param modelMap
 * @return
 */
@RequestMapping(value = "/deleteUser", method = RequestMethod.GET)
public String deleteUser(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("userName") String userName, ModelMap modelMap) {
    if (!StringUtils.hasLength(userName) || DiamondUtils.hasInvalidChar(userName.trim())) {
        request.getSession().setAttribute("message", "??");
        return "redirect:" + listUser(request, response, modelMap);
    }
    if (this.userService.removeUser(userName)) {
        request.getSession().setAttribute("message", "?!");
    } else {
        request.getSession().setAttribute("message", "!");
    }
    return "redirect:" + listUser(request, response, modelMap);
}

From source file:org.cloudfoundry.identity.uaa.oauth.ClientAdminEndpoints.java

@RequestMapping(value = "/oauth/clients", method = RequestMethod.GET)
@ResponseBody/*from   w ww . ja  va2s.c  o  m*/
public SearchResults<?> listClientDetails(
        @RequestParam(value = "attributes", required = false) String attributesCommaSeparated,
        @RequestParam(required = false, defaultValue = "client_id pr") String filter,
        @RequestParam(required = false, defaultValue = "client_id") String sortBy,
        @RequestParam(required = false, defaultValue = "ascending") String sortOrder,
        @RequestParam(required = false, defaultValue = "1") int startIndex,
        @RequestParam(required = false, defaultValue = "100") int count) throws Exception {
    List<ClientDetails> result = new ArrayList<ClientDetails>();
    List<ClientDetails> clients;
    try {
        clients = clientDetailsService.query(filter, sortBy, "ascending".equalsIgnoreCase(sortOrder));
        if (count > clients.size()) {
            count = clients.size();
        }
    } catch (IllegalArgumentException e) {
        throw new UaaException("Invalid filter expression: [" + filter + "]", HttpStatus.BAD_REQUEST.value());
    }
    for (ClientDetails client : UaaPagingUtils.subList(clients, startIndex, count)) {
        result.add(removeSecret(client));
    }

    if (!StringUtils.hasLength(attributesCommaSeparated)) {
        return new SearchResults<ClientDetails>(Arrays.asList(SCIM_CLIENTS_SCHEMA_URI), result, startIndex,
                count, clients.size());
    }

    String[] attributes = attributesCommaSeparated.split(",");
    try {
        return SearchResultsFactory.buildSearchResultFrom(result, startIndex, count, clients.size(), attributes,
                attributeNameMapper, Arrays.asList(SCIM_CLIENTS_SCHEMA_URI));
    } catch (SpelParseException e) {
        throw new UaaException("Invalid attributes: [" + attributesCommaSeparated + "]",
                HttpStatus.BAD_REQUEST.value());
    } catch (SpelEvaluationException e) {
        throw new UaaException("Invalid attributes: [" + attributesCommaSeparated + "]",
                HttpStatus.BAD_REQUEST.value());
    }
}

From source file:grails.plugin.cache.web.PageInfo.java

public long getDateHeader(String headerName) {
    String header = getHeader(headerName);
    if (!StringUtils.hasLength(header)) {
        return -1;
    }/*from   w w w  .j av  a2  s .co  m*/

    try {
        return Long.valueOf(header);
    } catch (NumberFormatException e) {
        return httpDateFormatter.parseDateFromHttpDate(header).getTime();
    }
}

From source file:uk.ac.ebi.ep.controller.BrowseTaxonomyController.java

@RequestMapping(value = FILTER_BY_FACETS, method = RequestMethod.GET)
public String filterByFacets(@ModelAttribute("searchModel") SearchModel searchModel,
        @RequestParam(value = "taxId", required = true) Long taxId,
        @RequestParam(value = "organismName", required = false) String organismName, Model model,
        HttpServletRequest request, HttpSession session, RedirectAttributes attributes) {

    List<Species> species = enzymePortalService.findSpeciesByTaxId(taxId);
    List<Compound> compouds = enzymePortalService.findCompoundsByTaxId(taxId);
    List<Disease> diseases = enzymePortalService.findDiseasesByTaxId(taxId);
    List<EcNumber> enzymeFamilies = enzymePortalService.findEnzymeFamiliesByTaxId(taxId);

    SearchFilters filters = new SearchFilters();
    filters.setSpecies(species);/*from  www .  j  a  v a2s . c o  m*/
    filters.setCompounds(compouds);
    filters.setDiseases(diseases);
    filters.setEcNumbers(enzymeFamilies);

    SearchParams searchParams = searchModel.getSearchparams();
    searchParams.setText(organismName);
    searchParams.setSize(SEARCH_PAGESIZE);
    searchModel.setSearchparams(searchParams);

    SearchResults searchResults = new SearchResults();

    searchResults.setSearchfilters(filters);
    searchModel.setSearchresults(searchResults);

    SearchParams searchParameters = searchModel.getSearchparams();

    String compound_autocompleteFilter = request.getParameter("searchparams.compounds");
    String specie_autocompleteFilter = request.getParameter("_ctempList_selected");
    String diseases_autocompleteFilter = request.getParameter("_DtempList_selected");

    // Filter:
    List<String> specieFilter = searchParameters.getSpecies();
    List<String> compoundFilter = searchParameters.getCompounds();
    List<String> diseaseFilter = searchParameters.getDiseases();
    List<Integer> ecFilter = searchParameters.getEcFamilies();

    //remove empty string in the filter to avoid unsual behavior of the filter facets
    if (specieFilter.contains("")) {
        specieFilter.remove("");

    }
    if (compoundFilter.contains("")) {
        compoundFilter.remove("");

    }
    if (diseaseFilter.contains("")) {
        diseaseFilter.remove("");
    }

    //to ensure that the seleted item is used in species filter, add the selected to the list. this is a workaround. different JS were used for auto complete and normal filter
    if ((specie_autocompleteFilter != null && StringUtils.hasLength(specie_autocompleteFilter) == true)
            && StringUtils.isEmpty(compound_autocompleteFilter)
            && StringUtils.isEmpty(diseases_autocompleteFilter)) {
        specieFilter.add(specie_autocompleteFilter);

    }

    if ((diseases_autocompleteFilter != null && StringUtils.hasLength(diseases_autocompleteFilter) == true)
            && StringUtils.isEmpty(compound_autocompleteFilter)
            && StringUtils.isEmpty(specie_autocompleteFilter)) {
        diseaseFilter.add(diseases_autocompleteFilter);

    }

    //both from auto complete and normal selection. selected items are displayed on top the list and returns back to the orignial list when not selected.
    //SearchResults searchResults = resultSet;
    List<Species> defaultSpeciesList = searchResults.getSearchfilters().getSpecies();
    resetSelectedSpecies(defaultSpeciesList);

    searchParameters.getSpecies().stream().forEach((selectedItems) -> {
        defaultSpeciesList.stream()
                .filter((theSpecies) -> (selectedItems.equals(theSpecies.getScientificname())))
                .forEach((theSpecies) -> {
                    theSpecies.setSelected(true);
                });
    });

    List<Compound> defaultCompoundList = searchResults.getSearchfilters().getCompounds();
    resetSelectedCompounds(defaultCompoundList);

    searchParameters.getCompounds().stream().forEach((SelectedCompounds) -> {
        defaultCompoundList.stream().filter((theCompound) -> (SelectedCompounds.equals(theCompound.getName())))
                .forEach((theCompound) -> {
                    theCompound.setSelected(true);
                });
    });

    List<Disease> defaultDiseaseList = searchResults.getSearchfilters().getDiseases();
    resetSelectedDisease(defaultDiseaseList);

    searchParameters.getDiseases().stream().forEach((selectedDisease) -> {
        defaultDiseaseList.stream().filter((disease) -> (selectedDisease.equals(disease.getName())))
                .forEach((disease) -> {
                    disease.setSelected(true);
                });
    });

    List<EcNumber> defaultEcNumberList = searchResults.getSearchfilters().getEcNumbers();

    resetSelectedEcNumber(defaultEcNumberList);

    searchParameters.getEcFamilies().stream().forEach((selectedEcFamily) -> {
        defaultEcNumberList.stream().filter((ec) -> (selectedEcFamily.equals(ec.getEc()))).forEach((ec) -> {
            ec.setSelected(true);
        });
    });

    Pageable pageable = new PageRequest(0, SEARCH_PAGESIZE, Sort.Direction.ASC, "function", "entryType");
    Page<UniprotEntry> page = new PageImpl<>(new ArrayList<>(), pageable, 0);

    //specie only
    if (specieFilter.isEmpty() && compoundFilter.isEmpty() && diseaseFilter.isEmpty()) {
        page = enzymePortalService.filterBySpecie(taxId, pageable);

    }

    //specie only
    if (!specieFilter.isEmpty() && compoundFilter.isEmpty() && diseaseFilter.isEmpty()) {
        page = enzymePortalService.filterBySpecie(taxId, pageable);

    }

    // compounds only
    if (!compoundFilter.isEmpty() && diseaseFilter.isEmpty()) {
        page = enzymePortalService.filterBySpecieAndCompounds(taxId, compoundFilter, pageable);

    }
    // disease only
    if (compoundFilter.isEmpty() && !diseaseFilter.isEmpty()) {
        page = enzymePortalService.filterBySpecieAndDiseases(taxId, diseaseFilter, pageable);

    }

    //ec only
    if (compoundFilter.isEmpty() && diseaseFilter.isEmpty() && !ecFilter.isEmpty()) {
        page = enzymePortalService.filterBySpecieAndEc(taxId, ecFilter, pageable);

    }

    //compound and diseases
    if (!compoundFilter.isEmpty() && !diseaseFilter.isEmpty() && ecFilter.isEmpty()) {
        page = enzymePortalService.filterBySpecieAndCompoundsAndDiseases(taxId, compoundFilter, diseaseFilter,
                pageable);

    }

    //compound and ec
    if (!compoundFilter.isEmpty() && !ecFilter.isEmpty() && diseaseFilter.isEmpty()) {
        page = enzymePortalService.filterBySpecieAndCompoundsAndEc(taxId, compoundFilter, ecFilter, pageable);

    }

    //disease and ec
    if (!ecFilter.isEmpty() && !diseaseFilter.isEmpty() && compoundFilter.isEmpty()) {
        page = enzymePortalService.filterBySpecieAndDiseasesAndEc(taxId, diseaseFilter, ecFilter, pageable);

    }

    //disease and compounds and ec

    if (!ecFilter.isEmpty() && !diseaseFilter.isEmpty() && !compoundFilter.isEmpty()) {
        page = enzymePortalService.filterBySpecieAndCompoundsAndDiseasesAndEc(taxId, compoundFilter,
                diseaseFilter, ecFilter, pageable);

    }
    model.addAttribute("searchFilter", filters);
    List<UniprotEntry> result = page.getContent();

    int current = page.getNumber() + 1;
    int begin = Math.max(1, current - 5);
    int end = Math.min(begin + 10, page.getTotalPages());

    model.addAttribute("page", page);
    model.addAttribute("beginIndex", begin);
    model.addAttribute("endIndex", end);
    model.addAttribute("currentIndex", current);

    model.addAttribute("organismName", organismName);
    model.addAttribute("taxId", taxId);

    model.addAttribute("summaryEntries", result);

    searchResults.setTotalfound(page.getTotalElements());
    searchResults.setSearchfilters(filters);
    searchResults.setSummaryentries(result);
    searchModel.setSearchresults(searchResults);
    model.addAttribute("searchModel", searchModel);
    model.addAttribute("searchConfig", searchConfig);

    String searchKey = getSearchKey(searchModel.getSearchparams());

    cacheSearch(session.getServletContext(), searchKey, searchResults);
    setLastSummaries(session, searchResults.getSummaryentries());

    clearHistory(session);
    addToHistory(session, searchModel.getSearchparams().getType(), searchKey);

    return RESULT;
}