Example usage for org.apache.commons.lang StringUtils strip

List of usage examples for org.apache.commons.lang StringUtils strip

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils strip.

Prototype

public static String strip(String str, String stripChars) 

Source Link

Document

Strips any of a set of characters from the start and end of a String.

Usage

From source file:org.nuxeo.ecm.platform.ui.web.validator.DocumentConstraintValidator.java

protected XPathAndField resolveField(FacesContext context, ValueReference vref, ValueExpression ve) {
    Object base = vref.getBase();
    Object propObj = vref.getProperty();
    if (propObj != null && !(propObj instanceof String)) {
        // ignore cases where prop would not be a String
        return null;
    }/*from   w  w w  .j a va2s .c  om*/
    String xpath = null;
    Field field = null;
    String prop = (String) propObj;
    Class<?> baseClass = base.getClass();
    if (DocumentPropertyContext.class.isAssignableFrom(baseClass)) {
        DocumentPropertyContext dc = (DocumentPropertyContext) base;
        xpath = dc.getSchema() + ":" + prop;
        field = getField(xpath);
    } else if (Property.class.isAssignableFrom(baseClass)) {
        xpath = ((Property) base).getPath() + "/" + prop;
        field = getField(((Property) base).getField(), prop);
    } else if (ProtectedEditableModel.class.isAssignableFrom(baseClass)) {
        ProtectedEditableModel model = (ProtectedEditableModel) base;
        ValueExpression listVe = model.getBinding();
        ValueExpressionAnalyzer expressionAnalyzer = new ValueExpressionAnalyzer(listVe);
        ValueReference listRef = expressionAnalyzer.getReference(context.getELContext());
        if (isResolvable(listRef, listVe)) {
            XPathAndField parentField = resolveField(context, listRef, listVe);
            if (parentField != null) {
                field = getField(parentField.field, "*");
                if (parentField.xpath == null) {
                    xpath = field.getName().getLocalName();
                } else {
                    xpath = parentField.xpath + "/" + field.getName().getLocalName();
                }
            }
        }
    } else if (ListItemMapper.class.isAssignableFrom(baseClass)) {
        ListItemMapper mapper = (ListItemMapper) base;
        ProtectedEditableModel model = mapper.getModel();
        ValueExpression listVe;
        if (model.getParent() != null) {
            // move one level up to resolve parent list binding
            listVe = model.getParent().getBinding();
        } else {
            listVe = model.getBinding();
        }
        ValueExpressionAnalyzer expressionAnalyzer = new ValueExpressionAnalyzer(listVe);
        ValueReference listRef = expressionAnalyzer.getReference(context.getELContext());
        if (isResolvable(listRef, listVe)) {
            XPathAndField parentField = resolveField(context, listRef, listVe);
            if (parentField != null) {
                field = getField(parentField.field, prop);
                if (field == null || field.getName() == null) {
                    // it should not happen but still, just in case
                    return null;
                }
                if (parentField.xpath == null) {
                    xpath = field.getName().getLocalName();
                } else {
                    xpath = parentField.xpath + "/" + field.getName().getLocalName();
                }
            }
        }
    } else {
        log.error(String.format("Cannot validate expression '%s, base=%s'", ve.getExpressionString(), base));
    }
    // cleanup / on begin or at end
    if (xpath != null) {
        xpath = StringUtils.strip(xpath, "/");
    } else if (field == null && xpath == null) {
        return null;
    }
    return new XPathAndField(field, xpath);
}

From source file:org.onehippo.forge.solr.indexer.task.JcrUtils.java

/**
 * Get JCR property (nested property if path contains '/')
 * @param node JCR node//  w w w.  j a v a 2  s.  co m
 * @param propertyPath JCR property path
 * @return JCR property (nullable)
 */
public static Property getProperty(Node node, String propertyPath) {
    String propertyPathStripped = StringUtils.strip(propertyPath, PATH_SEPARATOR);
    try {
        if (StringUtils.contains(propertyPathStripped, PATH_SEPARATOR)) {
            String nodePath = StringUtils.split(propertyPathStripped, PATH_SEPARATOR)[0];
            if (node.hasNode(nodePath)) {
                return getProperty(node.getNode(nodePath),
                        StringUtils.removeStart(propertyPathStripped, nodePath));
            }
        } else if (node.hasProperty(propertyPathStripped)) {
            return node.getProperty(propertyPathStripped);
        }
    } catch (RepositoryException e) {
        log.error("Failed to retrieve property " + propertyPath + " for node at " + getPath(node), e);
    }
    return null;
}

From source file:org.onosproject.influxdbmetrics.DefaultInfluxDbMetricsRetriever.java

/**
 * Strips special bracket from the full name.
 *
 * @param fullName full name// w w w  . j a  v  a  2s  .c om
 * @return bracket stripped string
 */
private String strip(String fullName) {
    return StringUtils.strip(StringUtils.strip(fullName, BRACKET_START), BRACKET_END);
}

From source file:org.opencastproject.kernel.security.persistence.OrganizationDatabaseImpl.java

/**
 * @see org.opencastproject.kernel.security.persistence.OrganizationDatabase#getOrganizationByUrl(java.net.URL)
 *///from  w  w w.  j  a  va 2s  . c  o  m
@Override
public Organization getOrganizationByUrl(URL url) throws OrganizationDatabaseException, NotFoundException {
    String requestUrl = StringUtils.strip(url.getHost(), "/");
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("Organization.findByUrl");
        q.setParameter("serverName", requestUrl);
        q.setParameter("port", url.getPort());
        return (JpaOrganization) q.getSingleResult();
    } catch (NoResultException e) {
        throw new NotFoundException();
    } catch (Exception e) {
        throw new OrganizationDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.search.impl.solr.SolrRequester.java

/**
 * Creates a list of <code>MediaSegment</code>s from the given result document.
 * /*w ww .  j a v a  2  s .com*/
 * @param doc
 *          the result document
 * @param query
 *          the original query
 */
private List<MediaSegmentImpl> createSearchResultSegments(SolrDocument doc, SolrQuery query) {
    List<MediaSegmentImpl> segments = new ArrayList<MediaSegmentImpl>();

    // The maximum number of hits in a segment
    int maxHits = 0;

    // Loop over every segment
    for (String fieldName : doc.getFieldNames()) {
        if (!fieldName.startsWith(Schema.SEGMENT_TEXT_PREFIX))
            continue;

        // Ceate a new segment
        int segmentId = Integer.parseInt(fieldName.substring(Schema.SEGMENT_TEXT_PREFIX.length()));
        MediaSegmentImpl segment = new MediaSegmentImpl(segmentId);
        segment.setText(mkString(doc.getFieldValue(fieldName)));

        // Read the hints for this segment
        Properties segmentHints = new Properties();
        try {
            String hintFieldName = Schema.SEGMENT_HINT_PREFIX + segment.getIndex();
            Object hintFieldValue = doc.getFieldValue(hintFieldName);
            segmentHints.load(new ByteArrayInputStream(hintFieldValue.toString().getBytes()));
        } catch (IOException e) {
            logger.warn("Cannot load hint properties.");
        }

        // get segment time
        String segmentTime = segmentHints.getProperty("time");
        if (segmentTime == null)
            throw new IllegalStateException("Found segment without time hint");
        segment.setTime(Long.parseLong(segmentTime));

        // get segment duration
        String segmentDuration = segmentHints.getProperty("duration");
        if (segmentDuration == null)
            throw new IllegalStateException("Found segment without duration hint");
        segment.setDuration(Long.parseLong(segmentDuration));

        // get preview urls
        for (Entry<Object, Object> entry : segmentHints.entrySet()) {
            if (entry.getKey().toString().startsWith("preview.")) {
                String[] parts = entry.getKey().toString().split("\\.");
                segment.addPreview(entry.getValue().toString(), parts[1]);
            }
        }

        // calculate the segment's relevance with respect to the query
        String queryText = query.getQuery();
        String segmentText = segment.getText();
        if (!StringUtils.isBlank(queryText) && !StringUtils.isBlank(segmentText)) {
            segmentText = segmentText.toLowerCase();
            Pattern p = Pattern.compile(".*fulltext:\\(([^)]*)\\).*");
            Matcher m = p.matcher(queryText);
            if (m.matches()) {
                String[] queryTerms = StringUtils.split(m.group(1).toLowerCase());
                int segmentHits = 0;
                int textLength = segmentText.length();
                for (String t : queryTerms) {
                    String strippedTerm = StringUtils.strip(t, "*");
                    int startIndex = 0;
                    while (startIndex < textLength - 1) {
                        int foundAt = segmentText.indexOf(strippedTerm, startIndex);
                        if (foundAt < 0)
                            break;
                        segmentHits++;
                        startIndex = foundAt + strippedTerm.length();
                    }
                }

                // for now, just store the number of hits, but keep track of the maximum hit count
                if (segmentHits > 0) {
                    segment.setHit(true);
                    segment.setRelevance(segmentHits);
                }
                if (segmentHits > maxHits)
                    maxHits = segmentHits;
            }
        }

        segments.add(segment);
    }

    for (MediaSegmentImpl segment : segments) {
        int hitsInSegment = segment.getRelevance();
        if (hitsInSegment > 0)
            segment.setRelevance((int) ((100 * hitsInSegment) / maxHits));
    }

    return segments;
}

From source file:org.opencastproject.security.api.Organization.java

/**
 * Constructs an organization with its attributes.
 * //from   w  ww  .j  a  v a 2  s . c o  m
 * @param id
 *          the unique identifier
 * @param name
 *          the friendly name
 * @param serverName
 *          the host name
 * @param serverPort
 *          the host port
 * @param adminRole
 *          name of the local admin role
 * @param anonymousRole
 *          name of the local anonymous role
 * @param properties
 *          arbitrary properties defined for this organization, which might include branding, etc.
 */
public Organization(String id, String name, String serverName, int serverPort, String adminRole,
        String anonymousRole, Map<String, String> properties) {
    this();
    this.id = id;
    this.name = name;
    this.serverName = StringUtils.strip(serverName, "/");
    this.serverPort = serverPort;
    this.adminRole = adminRole;
    this.anonymousRole = anonymousRole;
    this.properties = new ArrayList<Organization.OrgProperty>();
    if (properties != null && !properties.isEmpty()) {
        for (Entry<String, String> entry : properties.entrySet()) {
            this.properties.add(new OrgProperty(entry.getKey(), entry.getValue()));
        }
    }
}

From source file:org.opencastproject.security.util.SecurityUtil.java

/** Extract hostname and port number from a URL. */
public static Tuple<String, Integer> hostAndPort(URL url) {
    return tuple(StringUtils.strip(url.getHost(), "/"), url.getPort());
}

From source file:org.openlegacy.utils.StringUtil.java

public static String toDisplayName(String text) {
    if (StringUtils.isAllUpperCase(text)) {
        text = text.toLowerCase();/*from   w w  w  . ja v  a2  s .  co m*/
    }
    char[] chars = text.toCharArray();
    StringBuilder sb = new StringBuilder(text.length());
    for (int i = 0; i < chars.length; i++) {
        char c = chars[i];
        if (Character.isLetter(c) || Character.isDigit(c) || c == ' ' || c == '\\' || c == '/' || c == '.') {
            if (i == 0) {
                sb.append(Character.toUpperCase(c));
            } else {
                // add blank current char is upper case, previous char is blank and not upper case
                if (Character.isUpperCase(c) && chars[i - 1] != ' ' && Character.isLetter(chars[i - 1])
                        && !Character.isUpperCase(chars[i - 1])) {
                    sb.append(' ');
                }
                sb.append(c);
            }
        }

    }
    return StringUtils.strip(sb.toString(), " .");
}

From source file:org.openmrs.module.webservices.rest.web.v1_0.search.openmrs1_9.EncounterSearchHandler1_9.java

@Override
public PageableResult search(RequestContext context) throws ResponseException {
    String patientUuid = context.getRequest().getParameter(REQUEST_PARAM_PATIENT);
    String conceptUuid = context.getRequest().getParameter(REQUEST_PARAM_CONCEPT);
    String values = context.getRequest().getParameter(REQUEST_PARAM_VALUES);

    if (StringUtils.isNotBlank(patientUuid) && StringUtils.isNotBlank(conceptUuid)) {
        Patient patient = ((PatientResource1_8) Context.getService(RestService.class)
                .getResourceBySupportedClass(Patient.class)).getByUniqueId(patientUuid);

        // get all encounters matching patient and concept
        if (patient != null) {
            Concept concept = ((ConceptResource1_8) Context.getService(RestService.class)
                    .getResourceBySupportedClass(Concept.class)).getByUniqueId(conceptUuid);
            if (concept != null) {
                List<Obs> obs = Context.getObsService().getObservationsByPersonAndConcept(patient, concept);
                List<Obs> filteredObs = new ArrayList<Obs>();
                Iterator<Obs> obsIterator = obs.iterator();

                // return all encounters matching obs and values, if values are provided
                // filter out all non-matching obs
                if (StringUtils.isNotBlank(values)) {
                    if (!StringUtils.strip(values, ",").trim().equalsIgnoreCase("")) {
                        Obs currentObs;//from   www . j a v  a2  s.  c o  m
                        String[] valueArray = values.split(",");
                        ConceptDatatype datatype = concept.getDatatype();

                        if (datatype.isNumeric()) {
                            while (obsIterator.hasNext()) {
                                currentObs = obsIterator.next();
                                if (this.isNumberInArray(currentObs.getValueNumeric(), valueArray)) {
                                    filteredObs.add(currentObs);
                                }
                            }
                        } else if (datatype.isText()) {
                            while (obsIterator.hasNext()) {
                                currentObs = obsIterator.next();
                                if (OpenmrsUtil.isStringInArray(currentObs.getValueText(), valueArray)) {
                                    filteredObs.add(currentObs);
                                }
                            }
                        } else if (datatype.isCoded()) {
                            while (obsIterator.hasNext()) {
                                currentObs = obsIterator.next();
                                if (OpenmrsUtil.isStringInArray(currentObs.getValueCoded().getUuid(),
                                        valueArray)) {
                                    filteredObs.add(currentObs);
                                }
                            }
                        }

                        // return encounters for filtered obs
                        if (filteredObs.size() > 0) {
                            List<Encounter> encounters = this.getEncountersForObs(filteredObs.iterator());

                            return new NeedsPaging<Encounter>(encounters, context);
                        }
                    }
                } else {
                    // return all encounters with obs matching concept
                    List<Encounter> encounters = this.getEncountersForObs(obsIterator);

                    return new NeedsPaging<Encounter>(encounters, context);
                }
            } else {
                throw new ObjectNotFoundException();
            }
        } else {
            throw new ObjectNotFoundException();
        }

    }

    return new EmptySearchResult();
}

From source file:org.openvpms.report.jasper.JasperTemplateLoader.java

/**
 * Returns the name from a report./*w  ww .j  a v  a 2  s .c  om*/
 *
 * @param report the report
 * @return the report name. May be <tt>null</tt>
 */
private String getReportName(JRDesignSubreport report) {
    JRExpression expression = report.getExpression();
    if (expression != null) {
        String name = expression.getText();
        name = StringUtils.strip(name, " \"");
        return name;
    }
    return null;
}