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

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

Introduction

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

Prototype

public static String substring(String str, int start, int end) 

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

Usage

From source file:com.adobe.acs.commons.contentfinder.querybuilder.impl.ContentFinderHitBuilder.java

/**
 * Derives and adds Page related information to the map representing the hit.
 *
 * @param hit//from w w w .  java 2s . c  o m
 * @param map
 * @return
 * @throws javax.jcr.RepositoryException
 */
private static Map<String, Object> addPageData(final Page page, final Hit hit, Map<String, Object> map)
        throws RepositoryException {

    // Title
    String title = page.getName();

    if (StringUtils.isNotBlank(page.getTitle())) {
        title = page.getTitle();
    } else if (StringUtils.isNotBlank(page.getPageTitle())) {
        title = page.getPageTitle();
    } else if (StringUtils.isNotBlank(page.getNavigationTitle())) {
        title = page.getNavigationTitle();
    }

    // Excerpt
    String excerpt = hit.getExcerpt();
    if (StringUtils.isBlank(hit.getExcerpt())) {
        excerpt = StringUtils.stripToEmpty(page.getDescription());
        if (excerpt.length() > MAX_EXCERPT_LENGTH) {
            excerpt = StringUtils.substring(excerpt, 0, (MAX_EXCERPT_LENGTH - ELLIPSE_LENGTH)) + "...";
        }
    }

    map.put(CF_PATH, page.getPath());
    map.put(CF_NAME, page.getName());
    map.put(CF_TITLE, title);
    map.put(CF_EXCERPT, excerpt);
    map.put(CF_DD_GROUPS, "page");
    map.put(CF_TYPE, "Page");
    map.put(CF_LAST_MODIFIED, getLastModified(page));

    return map;
}

From source file:jamm.webapp.InitServlet.java

/**
 * Loads the jamm.properties file and uses it to initalize the
 * Globals object./*from   www  .  j  a  v a  2  s. c o m*/
 *
 * @see jamm.webapp.Globals
 *
 * @param config The configuration from the servlet container.
 *
 * @throws ServletException when their is an IOException loading
 *                          the properties file
 */
private void loadProperties(ServletConfig config) throws ServletException {
    String path;
    Properties properties;

    try {
        path = config.getServletContext().getRealPath("WEB-INF/" + "jamm.properties");
        properties = new Properties();
        properties.load(new FileInputStream(path));

        Globals.setLdapHost(getStringProperty(properties, "ldap.host", "localhost"));
        Globals.setLdapPort(getIntProperty(properties, "ldap.port", 389));
        Globals.setLdapSearchBase(getStringProperty(properties, "ldap.search_base", ""));
        LdapPassword
                .setRandomClass(getStringProperty(properties, "random_class", "java.security.SecureRandom"));

        // Strip out leading and trailing quotes (common problem)
        String rootDn = getStringProperty(properties, "ldap.root_dn", "");
        if (rootDn.startsWith("\"") && rootDn.endsWith("\"")) {
            rootDn = StringUtils.substring(rootDn, 1, -1);
        }
        Globals.setRootDn(rootDn);
        Globals.setRootLogin(getStringProperty(properties, "ldap.root_login", "root"));
        MailManagerOptions.setUsePasswordExOp(getBooleanProperty(properties, "password.exop", true));
        MailManagerOptions
                .setVmailHomedir(getStringProperty(properties, "vmail.homedir", "/home/vmail/domains"));
    } catch (IOException e) {
        throw new ServletException(e);
    }

}

From source file:com.pearson.openideas.cq5.components.content.RelatedArticles.java

/**
 * This method goes through the list of theme resources found in the init function and creates a list of article
 * objects.//from   w w w .jav a2s .c o  m
 */
public final void populateListOfArticles() {
    Article article;
    listOfArticles = new ArrayList<Article>();
    String path;
    Resource resource;
    while (themeResources.hasNext()) {
        resource = themeResources.next();
        path = resource.getPath();
        String articleUrl = StringUtils.substring(path, 0, path.lastIndexOf("/"));
        article = new Article();
        article.setUrl(articleUrl);
        if (!(getCurrentPage().getContentResource().getPath().equals(resource.getPath()))) {

            article = ArticleUtils.createArticleObject(resource, article, tagManager);

            listOfArticles.add(article);
        }
    }

}

From source file:com.mmj.app.lucene.analyzer.AbstractWordAnalyzer.java

private List<String> wiselySplit(String str, SegMode segMode, Boolean wiselyCombineSingleWord) {
    List<String> result = new ArrayList<String>();
    int index = 0;
    for (int i = 0, len = str.length(), lastIndex = len - 1; i < len; i++) {
        if (isDelimeter(str.charAt(i))) {
            if (index < i) {
                String word = StringUtils.substring(str, index, i);
                _wiselySplit(result, segMode, wiselyCombineSingleWord, word);
            }/* w  w w.ja v  a2  s .  co  m*/
            index = i + 1;
        }
        // ?
        if (i == lastIndex) {
            String word = StringUtils.substring(str, index);
            _wiselySplit(result, segMode, wiselyCombineSingleWord, word);
        }
    }
    return result;
}

From source file:hydrograph.ui.expression.editor.datastructure.ClassDetails.java

private String getJavaDoc(IClassFile classFile) throws JavaModelException {
    BinaryType binaryType = (BinaryType) classFile.getType();
    if (binaryType.getSource() != null && binaryType.getJavadocRange() != null) {
        String javaDoc = Constants.EMPTY_STRING;
        javaDoc = StringUtils.substring(binaryType.getSource().toString(), 0,
                binaryType.getJavadocRange().getLength());
        javaDoc = StringUtils.replaceEachRepeatedly(javaDoc, new String[] { "/*", "*/", "*" },
                new String[] { Constants.EMPTY_STRING, Constants.EMPTY_STRING, Constants.EMPTY_STRING });
    }/*from   w  w w .  j  a  v a  2s  . c om*/
    return javaDoc;
}

From source file:info.magnolia.cms.gui.controlx.list.util.ValueProvider.java

/**
 * get value - first check for property in this object - then look for the getter for this name - else search in
 * MetaData//  w ww . ja  v  a  2  s  . co  m
 * @param name
 * @param obj
 */
public Object getValue(String name, Object obj) {
    Object value = null;
    try {
        if (obj instanceof Content) {
            Content node = (Content) obj;
            if (node.hasNodeData(name)) {
                NodeData nd = node.getNodeData(name);
                if (nd.getType() == PropertyType.DATE) {
                    value = nd.getDate();
                } else {
                    value = nd.getString();
                }
            }

            if (value == null) {
                try {
                    value = PropertyUtils.getProperty(node.getMetaData(), name);
                } catch (NoSuchMethodException e) {
                    value = node.getMetaData().getStringProperty(name);
                    if (StringUtils.isEmpty((String) value)) {
                        value = null;
                    }
                }
            }
        }

        if (value == null) {
            // is this a property of the object
            try {
                value = PropertyUtils.getProperty(obj, name);
            } catch (NoSuchMethodException e1) {
                // check if getter exist for this name
                try {
                    String methodName = "get" + StringUtils.substring(name, 0, 1).toUpperCase()
                            + StringUtils.substring(name, 1);
                    value = MethodUtils.invokeMethod(this, methodName, obj);
                } catch (NoSuchMethodException e2) {
                    value = StringUtils.EMPTY;
                }
            }
        }
    } catch (Exception e) {
        log.error("can't get value", e);
        value = StringUtils.EMPTY;
    }

    if (value instanceof Calendar) {
        value = new Date(((Calendar) value).getTimeInMillis());
    }

    return value;
}

From source file:info.magnolia.cms.filters.RepositoryMappingFilter.java

@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    String uri = MgnlContext.getAggregationState().getCurrentURI();
    int firstSelectorDelimiterPos = StringUtils.indexOf(uri, Path.SELECTOR_DELIMITER,
            StringUtils.lastIndexOf(uri, '/'));
    String path;// w w  w .  j  a  v  a 2s.  c  o m
    // TODO Warning - this might change in the future - see MAGNOLIA-2343 for details.
    String selector;
    if (firstSelectorDelimiterPos > -1) {
        int lastSelectorDelimiterPos = StringUtils.lastIndexOf(uri, Path.SELECTOR_DELIMITER);
        path = StringUtils.substring(uri, 0, firstSelectorDelimiterPos);
        selector = StringUtils.substring(uri, firstSelectorDelimiterPos + 1, lastSelectorDelimiterPos);
    } else {
        // no tilde (and no extension)
        path = uri;
        selector = "";
    }

    URI2RepositoryMapping mapping = uri2RepositoryManager.getMapping(uri);

    // remove prefix if any
    path = mapping.getHandle(path);

    final AggregationState aggregationState = MgnlContext.getAggregationState();
    aggregationState.setRepository(mapping.getRepository());
    aggregationState.setHandle(path);

    // selector could potentially be set from some other place, but we have no better idea for now :)
    aggregationState.setSelector(selector);

    chain.doFilter(request, response);
}

From source file:com.ms.commons.test.classloader.util.VelocityTemplateUtil.java

protected static String evalString(Map<Object, Object> context, String str, MutableInt depth) {
    if (depth.intValue() > 5) {
        System.err.println("eval depth > 5 for `" + StringUtils.substring(str, 0, 50) + "`.");
        return str;
    }//from   w  w  w . j ava2  s  .c  o m

    StringBuilder sb = new StringBuilder();
    char[] chars = str.toCharArray();

    boolean in = false;
    StringBuilder tsb = new StringBuilder();
    for (int i = 0; i < chars.length; i++) {
        char c = chars[i];
        char nc = 0;
        if ((i + 1) < chars.length) {
            nc = chars[i + 1];
        }

        if (in) {
            if (c != '}') {
                tsb.append(c);
            } else {
                Object value = context.get(tsb.toString());
                if (value == null) {
                    sb.append("${" + tsb.toString() + "}");
                } else {
                    sb.append(value);
                }
                tsb = new StringBuilder();
                in = false;
            }
        } else {
            if ((c == '$') && (nc == '{')) {
                in = true;
                i++;
            } else {
                sb.append(c);
            }
        }
    }
    if (in) {
        throw new RuntimeException("at last is in");
    }

    String result = sb.toString();

    if (result.contains("${")) {
        depth.add(1);
        return evalString(context, result, depth);
    } else {
        return result;
    }
}

From source file:com.ancientprogramming.fixedformat4j.format.impl.AbstractDecimalFormatter.java

public String asString(T obj, FormatInstructions instructions) {
    BigDecimal roundedValue = null;
    int decimals = instructions.getFixedFormatDecimalData().getDecimals();
    if (obj != null) {
        BigDecimal value = obj instanceof BigDecimal ? (BigDecimal) obj : BigDecimal.valueOf(obj.doubleValue());

        RoundingMode roundingMode = instructions.getFixedFormatDecimalData().getRoundingMode();

        roundedValue = value.setScale(decimals, roundingMode);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Value before rounding = '" + value + "', value after rounding = '" + roundedValue
                    + "', decimals = " + decimals + ", rounding mode = " + roundingMode);
        }//from  www.j  a  v  a  2s  . c  o  m
    }

    DecimalFormat formatter = new DecimalFormat();
    formatter.setDecimalSeparatorAlwaysShown(true);
    formatter.setMaximumFractionDigits(decimals);

    char decimalSeparator = formatter.getDecimalFormatSymbols().getDecimalSeparator();
    char groupingSeparator = formatter.getDecimalFormatSymbols().getGroupingSeparator();
    String zeroString = "0" + decimalSeparator + "0";

    String rawString = roundedValue != null ? formatter.format(roundedValue) : zeroString;
    if (LOG.isDebugEnabled()) {
        LOG.debug("rawString: " + rawString + " - G[" + groupingSeparator + "] D[" + decimalSeparator + "]");
    }
    rawString = rawString.replaceAll("\\" + groupingSeparator, "");
    boolean useDecimalDelimiter = instructions.getFixedFormatDecimalData().isUseDecimalDelimiter();

    String beforeDelimiter = rawString.substring(0, rawString.indexOf(decimalSeparator));
    String afterDelimiter = rawString.substring(rawString.indexOf(decimalSeparator) + 1, rawString.length());
    if (LOG.isDebugEnabled()) {
        LOG.debug("beforeDelimiter[" + beforeDelimiter + "], afterDelimiter[" + afterDelimiter + "]");
    }

    //trim decimals
    afterDelimiter = StringUtils.substring(afterDelimiter, 0, decimals);
    afterDelimiter = StringUtils.rightPad(afterDelimiter, decimals, '0');

    String delimiter = useDecimalDelimiter ? "" + instructions.getFixedFormatDecimalData().getDecimalDelimiter()
            : "";
    String result = beforeDelimiter + delimiter + afterDelimiter;
    if (LOG.isDebugEnabled()) {
        LOG.debug("result[" + result + "]");
    }
    return result;
}

From source file:com.hangum.tadpole.erd.core.part.TableEditPart.java

private ColumnFigure[] createColumnFigure(Table tableModel, Column model) {
    ColumnFigure labelKey = new ColumnFigure(COLUMN_TYPE.KEY);
    ColumnFigure labelName = new ColumnFigure(COLUMN_TYPE.NAME);
    ColumnFigure labelType = new ColumnFigure(COLUMN_TYPE.TYPE);
    ColumnFigure labelNotNull = new ColumnFigure(COLUMN_TYPE.NULL);

    labelKey.setText(StringUtils.substring(model.getKey(), 0, 1));
    labelName.setText(model.getField());
    labelType.setText(model.getType());/*from   w  ww.j  a  v  a2s  .  c o m*/
    labelNotNull.setText(StringUtils.substring(model.getNull(), 0, 1));

    return new ColumnFigure[] { labelKey, labelName, labelType, labelNotNull };
}