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

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

Introduction

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

Prototype

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

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

A negative start position can be used to start/end n characters from the end of the String.

The returned substring starts with the character in the start position and ends before the end position.

Usage

From source file:de.micromata.genome.db.jpa.logging.entities.BaseLogMasterDO.java

/**
 * Sets the shortmessage./*  w w  w .j a  v  a 2s.com*/
 *
 * @param shortmessage the new shortmessage
 */
public void setShortmessage(String shortmessage) {
    this.shortmessage = StringUtils.substring(shortmessage, 0, MAX_LOG_SHORT_MESSAGE_SIZE);
}

From source file:com.mirth.connect.client.ui.util.SQLParserUtil.java

public String[] Parse() {
    try {/*from  ww w .  j a v  a2  s  . c om*/
        List<String> varList = new ArrayList<String>();

        Pattern pattern = Pattern.compile(SQL_PATTERN, Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(_sqlStatement);
        while (matcher.find()) {
            String key = matcher.group();
            int fromClause = key.toUpperCase().indexOf(" FROM ");

            if (fromClause > 0) {
                String columnText = key.substring(6, fromClause).replaceAll("`", "");
                columnText = removeNestedFunctions(columnText, 0);

                String[] vars = columnText.split(",");

                for (int i = 0; i < vars.length; i++) {
                    if (vars[i].length() > 0) {
                        for (int j = 0; j < keywords.length; j++) {
                            int index = vars[i].toUpperCase().indexOf(keywords[j]);
                            int size = (keywords[j]).length();
                            if (index != -1) {
                                if (index > 0) {
                                    if (vars[i].substring(index - 1, index).equals(" ")
                                            && (vars[i].length() == index + size || vars[i]
                                                    .substring(index + size, index + size + 1).equals(" "))) {
                                        vars[i] = vars[i].replaceAll(vars[i].substring(index, index + size),
                                                "");
                                    }
                                } else if (vars[i].length() == index + size
                                        || vars[i].substring(index + size, index + size + 1).equals(" ")) {
                                    vars[i] = vars[i].replaceAll(vars[i].substring(index, index + size), "");
                                }
                            }
                        }
                        if (vars[i].length() > 0) {
                            String var;

                            if (vars[i].toUpperCase().indexOf(" AS ") != -1) {
                                var = (vars[i].substring(vars[i].toUpperCase().indexOf(" AS ") + 4))
                                        .replaceAll(" ", "").replaceAll("\\(", "").replaceAll("\\)", "");
                            } else if (vars[i].indexOf('(') != -1 || vars[i].indexOf(')') != -1
                                    || vars[i].indexOf('}') != -1 || vars[i].indexOf('{') != -1
                                    || vars[i].indexOf('*') != -1) {
                                continue;
                            } else {
                                vars[i] = vars[i].trim();
                                var = vars[i].replaceAll(" ", "").replaceAll("\\(", "").replaceAll("\\)", "");

                                if (var.lastIndexOf('.') != -1) {
                                    var = var.substring(var.lastIndexOf('.') + 1);
                                }
                            }

                            if ((StringUtils.substring(var, 0, 1).equals("\"")
                                    && StringUtils.substring(var, -1).equals("\""))
                                    || (StringUtils.substring(var, 0, 1).equals("'")
                                            && StringUtils.substring(var, -1).equals("'"))) {
                                var = StringUtils.substring(var, 1, -1);
                            }

                            if ((StringUtils.substring(var, 0, 2).equals("\\\"")
                                    && StringUtils.substring(var, -2).equals("\\\""))
                                    || (StringUtils.substring(var, 0, 2).equals("\\'")
                                            && StringUtils.substring(var, -2).equals("\\'"))) {
                                var = StringUtils.substring(var, 2, -2);
                            }

                            var = StringUtils.lowerCase(var);

                            varList.add(var);
                        }
                    }
                }
            }
        }
        return varList.toArray(new String[varList.size()]);
    } catch (Exception e) {
        logger.error(e);
    }
    return new String[0];
}

From source file:Heuristics.TermLevelHeuristics.java

public String checkFeatures(Heuristic heuristic, String status, String termOrig) {
    this.termHeuristic = heuristic.getTerm();
    this.mapFeatures = heuristic.getMapFeatures();
    this.rule = heuristic.getRule();

    HashMap<String, Boolean> conditions = new HashMap();
    boolean outcome;
    String termOrigCasePreserved = termOrig;
    termOrig = termOrig.toLowerCase();//  ww w .  ja v  a  2  s. co m
    String statusOrigCasePreserved = status;
    status = status.toLowerCase();
    if (mapFeatures == null || mapFeatures.isEmpty()) {
        //            System.out.println("no feature, returning a simple digit");
        return rule;
    }
    int count = 0;
    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    for (Map.Entry<String, Set<String>> feature : mapFeatures.entries()) {
        //            if (termOrig.equals("Learn")) {
        //                System.out.println("feature: " + feature.getKey());
        //                System.out.println("status: " + status);
        //            }
        //            System.out.println("count: " + count);
        boolean opposite = false;
        if (feature.getKey().startsWith("!")) {
            opposite = true;
        }
        if (feature.getKey().contains("isImmediatelyFollowedByAnOpinion")) {
            outcome = opposite ? !isImmediatelyFollowedByAnOpinion(status, termOrig)
                    : isImmediatelyFollowedByAnOpinion(status, termOrig);
            conditions.put(StringUtils.substring(alphabet, count, (count + 1)), outcome);
        } else if (feature.getKey().contains("isFirstTermOfStatus")) {
            outcome = opposite ? !isFirstTermOfStatus(status, termOrig) : isFirstTermOfStatus(status, termOrig);
            conditions.put(StringUtils.substring(alphabet, count, (count + 1)), outcome);
        } else if (feature.getKey().contains("isFollowedByAPositiveOpinion")) {
            outcome = opposite ? !isFollowedByAPositiveOpinion(status, termOrig)
                    : isFollowedByAPositiveOpinion(status, termOrig);
            conditions.put(StringUtils.substring(alphabet, count, (count + 1)), outcome);
        } else if (feature.getKey().contains("isImmediatelyFollowedByAPositiveOpinion")) {
            outcome = opposite ? !isImmediatelyFollowedByAPositiveOpinion(status, termOrig)
                    : isImmediatelyFollowedByAPositiveOpinion(status, termOrig);
            conditions.put(StringUtils.substring(alphabet, count, (count + 1)), outcome);
        } else if (feature.getKey().contains("isImmediatelyFollowedByTimeIndication")) {
            outcome = opposite ? !isImmediatelyFollowedByTimeIndication(status, termOrig)
                    : isImmediatelyFollowedByTimeIndication(status, termOrig);
            conditions.put(StringUtils.substring(alphabet, count, (count + 1)), outcome);
        } else if (feature.getKey().contains("isImmediatelyFollowedByVerbPastTense")) {
            outcome = opposite ? !isImmediatelyFollowedByVerbPastTense(status, termOrig)
                    : !isImmediatelyFollowedByVerbPastTense(status, termOrig);
            conditions.put(StringUtils.substring(alphabet, count, (count + 1)), outcome);
        } else if (feature.getKey().contains("isFollowedBySpecificTerm")) {
            outcome = opposite ? !isFollowedBySpecificTerm(status, termOrig, feature.getValue())
                    : isFollowedBySpecificTerm(status, termOrig, feature.getValue());
            conditions.put(StringUtils.substring(alphabet, count, (count + 1)), outcome);
        } else if (feature.getKey().contains("isImmediatelyFollowedBySpecificTerm")) {
            outcome = opposite ? !isFollowedBySpecificTerm(status, termOrig, feature.getValue())
                    : isFollowedBySpecificTerm(status, termOrig, feature.getValue());
            conditions.put(StringUtils.substring(alphabet, count, (count + 1)), outcome);
        } else if (feature.getKey().contains("isHashtagStart")) {
            outcome = opposite ? !isHashtagStart(termOrig) : isHashtagStart(termOrig);
            conditions.put(StringUtils.substring(alphabet, count, (count + 1)), outcome);
        } else if (feature.getKey().contains("isPrecededBySpecificTerm")) {
            outcome = opposite ? !isPrecededBySpecificTerm(status, termOrig, feature.getValue())
                    : isPrecededBySpecificTerm(status, termOrig, feature.getValue());
            conditions.put(StringUtils.substring(alphabet, count, (count + 1)), outcome);
        } else if (feature.getKey().contains("isQuestionMarkAtEndOfStatus")) {
            outcome = opposite ? !isQuestionMarkAtEndOfStatus(status) : isQuestionMarkAtEndOfStatus(status);
            conditions.put(StringUtils.substring(alphabet, count, (count + 1)), outcome);
        } else if (feature.getKey().contains("isAllCaps")) {
            outcome = opposite ? !isAllCaps(termOrigCasePreserved) : isAllCaps(termOrigCasePreserved);
            conditions.put(StringUtils.substring(alphabet, count, (count + 1)), outcome);
        } else if (feature.getKey().contains("isImmediatelyPrecededByANegation")) {
            outcome = opposite ? !isImmediatelyPrecededByANegation(status, termOrig)
                    : isImmediatelyPrecededByANegation(status, termOrig);
            conditions.put(StringUtils.substring(alphabet, count, (count + 1)), outcome);
        } else if (feature.getKey().contains("isPrecededByStrongWord")) {
            outcome = opposite ? isPrecededByStrongWord(status, termOrig)
                    : isPrecededByStrongWord(status, termOrig);
            conditions.put(StringUtils.substring(alphabet, count, (count + 1)), outcome);
        } else if (feature.getKey().contains("isImmediatelyPrecededByPositive")) {
            outcome = opposite ? !isImmediatelyPrecededByPositive(status, termOrig)
                    : isImmediatelyPrecededByPositive(status, termOrig);
            conditions.put(StringUtils.substring(alphabet, count, (count + 1)), outcome);
        } else if (feature.getKey().contains("isFirstLetterCapitalized")) {
            outcome = opposite ? !isFirstLetterCapitalized(termOrigCasePreserved)
                    : isFirstLetterCapitalized(termOrigCasePreserved);
            conditions.put(StringUtils.substring(alphabet, count, (count + 1)), outcome);
        }
        count++;
    }
    String result = interpreter.interprete(rule, conditions);
    return result;
}

From source file:de.micromata.genome.db.jpa.tabattr.entities.JpaLongValueBaseDO.java

/**
 * Set the value of the attribute./*from   w  w  w .  j  a  va2  s.com*/
 * 
 * if value is longer than VALUE_MAXLENGHT the string will be split and stored in additional data children entities.
 *
 * @param value the new string data
 */
public void setStringData(String value) {
    List<JpaLongValueDataBaseDO<?, PK>> data = getData();
    data.clear();
    int maxValLength = getValueMaxLength();
    if (StringUtils.length(value) > maxValLength) {
        this.value = value.substring(0, maxValLength);
        String rest = value.substring(maxValLength);
        int maxDataLength = getMaxDataLength();
        int rowIdx = 0;
        while (rest.length() > 0) {
            String ds = StringUtils.substring(rest, 0, maxDataLength);
            rest = StringUtils.substring(rest, maxDataLength);
            JpaLongValueDataBaseDO<?, PK> dataDo = createData(ds);
            dataDo.setDatarow(rowIdx++);
            data.add(dataDo);
        }
    } else {
        this.value = value;
    }
}

From source file:com.jkoolcloud.tnt4j.streams.transform.FuncGetObjectName.java

private static String resolveObjectName(String objectName, List<?> args) {
    String option = args.size() > 1 ? (String) args.get(1) : null;
    Options opt;//  w w  w  .ja  va 2 s . c  o m

    try {
        opt = StringUtils.isEmpty(option) ? Options.DEFAULT : Options.valueOf(option.toUpperCase());
    } catch (IllegalArgumentException exc) {
        opt = Options.DEFAULT;
    }

    switch (opt) {
    case FULL:
        break;
    case BEFORE:
        String sSymbol = args.size() > 2 ? (String) args.get(2) : null;
        if (StringUtils.isNotEmpty(sSymbol)) {
            objectName = StringUtils.substringBefore(objectName, sSymbol);
        }
        break;
    case AFTER:
        sSymbol = args.size() > 2 ? (String) args.get(2) : null;
        if (StringUtils.isNotEmpty(sSymbol)) {
            objectName = StringUtils.substringAfter(objectName, sSymbol);
        }
        break;
    case REPLACE:
        sSymbol = args.size() > 2 ? (String) args.get(2) : null;
        if (StringUtils.isNotEmpty(sSymbol)) {
            String rSymbol = args.size() > 3 ? (String) args.get(3) : null;
            objectName = StringUtils.replaceChars(objectName, sSymbol, rSymbol == null ? "" : rSymbol);
        }
        break;
    case SECTION:
        String idxStr = args.size() > 2 ? (String) args.get(2) : null;
        int idx;
        try {
            idx = Integer.parseInt(idxStr);
        } catch (Exception exc) {
            idx = -1;
        }

        if (idx >= 0) {
            sSymbol = args.size() > 3 ? (String) args.get(3) : null;
            String[] onTokens = StringUtils.split(objectName,
                    StringUtils.isEmpty(sSymbol) ? OBJ_NAME_TOKEN_DELIMITERS : sSymbol);
            objectName = idx < ArrayUtils.getLength(onTokens) ? onTokens[idx] : objectName;
        }
        break;
    case DEFAULT:
    default:
        idx = StringUtils.indexOfAny(objectName, OBJ_NAME_TOKEN_DELIMITERS);
        if (idx > 0) {
            objectName = StringUtils.substring(objectName, 0, idx);
        }
        break;
    }

    return objectName;
}

From source file:kenh.expl.impl.ExpLParser.java

/**
 * Parse the expression./*from  www.  j  a va  2 s .co  m*/
 * This method will looking for string in brace, and get the value back.
 * @param express  The expression
 * @return    Return string or non-string object. Return empty string instead of null.
 */
private Object parseExpress(String express) throws UnsupportedExpressionException {
    if (express == null) {
        UnsupportedExpressionException e = new UnsupportedExpressionException("Expression is null.");
        throw e;
    }

    logger.trace("Expr: " + express);

    int left = StringUtils.countMatches(express, "{");
    int right = StringUtils.countMatches(express, "}");

    if (left != right) {
        UnsupportedExpressionException ex = new UnsupportedExpressionException("'{' and '}' does not match.");
        ex.push(express);
        throw ex;
    }

    if (left == 0)
        return express;

    String sResult = null; // String type result
    Object oResult = null; // Non-string type result

    StringBuffer resultBuffer = new StringBuffer();

    try {
        String context = express;
        while (!context.equals("")) {
            String[] s = splitExpression(context);
            if (!s[0].equals(""))
                resultBuffer.append(s[0]);
            if (!s[1].equals("")) {
                String variable = StringUtils.substring(s[1], 1, s[1].length() - 1);
                Object obj = getVariableValue(variable);
                logger.debug(variable + " -> " + ((obj == null) ? "<null>" : obj.toString()));
                try {
                    String str = convertToString(obj);
                    resultBuffer.append(str);
                } catch (UnsupportedExpressionException e) {
                    if (oResult == null)
                        oResult = obj;
                    else {
                        UnsupportedExpressionException ex = new UnsupportedExpressionException(
                                "Multi non-string objects returned. [" + oResult.getClass().getCanonicalName()
                                        + ", " + obj.getClass().getCanonicalName() + "]");
                        ex.push(express);
                        throw ex;
                    }
                }
            }
            context = s[2];
        }

    } catch (UnsupportedExpressionException e) {
        e.push(express);
        throw e;
    } catch (Exception e) {
        UnsupportedExpressionException ex = new UnsupportedExpressionException(e);
        ex.push(express);
        throw ex;
    }

    sResult = resultBuffer.toString();
    Object returnObj = null;
    if (StringUtils.isBlank(sResult)) {
        if (oResult != null)
            returnObj = oResult;
        else
            returnObj = sResult;
    } else {
        if (oResult != null) {
            UnsupportedExpressionException e = new UnsupportedExpressionException(
                    "Non-string object exist. [" + oResult.getClass().getCanonicalName() + "]");
            e.push(express);
            throw e;
        } else
            returnObj = sResult;
    }

    logger.debug(express + " -> " + ((returnObj == null) ? "<null>" : returnObj.toString()));
    return returnObj;
}

From source file:de.micromata.genome.db.jpa.genomecore.chronos.SchedJpaTypeConverter.java

/**
 * To db.//from   ww  w.j  a  v  a  2s  .c o m
 *
 * @param target the target
 * @param source the source
 */
public static void toDb(JpaJobResultDO target, JobResultDO source) {
    jdbc2jpa(target, source);
    target.setDuration(source.getDuration());
    target.setExecutionStart(source.getExecutionStart());
    target.setHostName(source.getHostName());
    target.setJobPk(source.getJobPk());
    target.setResultString(StringUtils.substring(source.getResultString(), 0, 1290));
    target.setRetryCount(source.getRetryCount());
    target.setState(source.getState());
    target.setVm(source.getVm());
}

From source file:com.norconex.collector.http.url.impl.DefaultURLExtractor.java

@Override
public Set<String> extractURLs(Reader document, String documentUrl, ContentType contentType)
        throws IOException {

    // Do not extract if non-HTML
    if (!contentType.equals(ContentType.HTML)) {
        return null;
    }/*from   w  w w .j  a v a  2  s.  c  om*/

    UrlParts urlParts = new UrlParts(documentUrl);

    //TODO HOW TO HANDLE <BASE>????? Is it handled by Tika???

    if (LOG.isDebugEnabled()) {
        LOG.debug("DOCUMENT URL ----> " + documentUrl);
        LOG.debug("  BASE RELATIVE -> " + urlParts.relativeBase);
        LOG.debug("  BASE ABSOLUTE -> " + urlParts.absoluteBase);
    }

    Set<String> urls = new HashSet<String>();

    BufferedReader reader = new BufferedReader(document);
    String line;
    while ((line = reader.readLine()) != null) {
        Matcher matcher = URL_PATTERN.matcher(line);
        while (matcher.find()) {
            String attrName = matcher.group(URL_PATTERN_GROUP_ATTR_NAME);
            String url = matcher.group(URL_PATTERN_GROUP_URL);
            if (StringUtils.startsWithIgnoreCase(url, "mailto:")) {
                continue;
            }
            if (StringUtils.startsWithIgnoreCase(url, "javascript:")) {
                continue;
            }
            if (attrName != null && attrName.equalsIgnoreCase("url")
                    && !META_REFRESH_PATTERN.matcher(line).find()) {
                continue;
            }
            url = extractURL(urlParts, url);
            if (url == null) {
                continue;
            }
            if (url.length() > maxURLLength) {
                LOG.warn("URL length (" + url.length() + ") exeeding " + "maximum length allowed ("
                        + maxURLLength + ") to be extracted. URL (showing first 200 " + "chars): "
                        + StringUtils.substring(url, 0, LOGGING_MAX_URL_LENGTH) + "...");
            } else {
                urls.add(url);
            }
        }
    }
    return urls;
}

From source file:com.pinterest.teletraan.resource.Builds.java

@POST
@ApiOperation(value = "Publish a build", notes = "Publish a build given a build object", response = Response.class)
public Response publish(@Context SecurityContext sc,
        @ApiParam(value = "Build object", required = true) @Valid BuildBean buildBean) throws Exception {
    if (StringUtils.isEmpty(buildBean.getScm())) {
        buildBean.setScm(sourceControlManager.getType());
    }/*from w  ww  . j  a v a 2 s. co  m*/

    if (StringUtils.isEmpty(buildBean.getScm_commit_7())) {
        buildBean.setScm_commit_7(StringUtils.substring(buildBean.getScm_commit(), 0, 7));

    }

    if (StringUtils.isEmpty(buildBean.getScm_info())) {
        buildBean.setScm_info(
                sourceControlManager.generateCommitLink(buildBean.getScm_repo(), buildBean.getScm_commit()));
    }

    if (StringUtils.isEmpty(buildBean.getPublish_info())) {
        buildBean.setPublish_info("UNKNOWN");
    }

    if (buildBean.getPublish_date() == null) {
        buildBean.setPublish_date(System.currentTimeMillis());
    }

    if (buildBean.getCommit_date() == null) {
        buildBean.setCommit_date(System.currentTimeMillis());
    }

    // Set who published the build
    buildBean.setPublisher(sc.getUserPrincipal().getName());

    // We append commit SHA after build id to make build directory name human friendly
    String id = CommonUtils.getBase64UUID();
    String buildId = String.format("%s_%s", id, buildBean.getScm_commit_7());
    buildBean.setBuild_id(buildId);

    buildDAO.insert(buildBean);
    LOG.info("Successfully published build {} by {}.", buildId, sc.getUserPrincipal().getName());

    UriBuilder ub = uriInfo.getAbsolutePathBuilder();
    URI buildUri = ub.path(buildId).build();
    buildBean = buildDAO.getById(buildId);
    return Response.created(buildUri).entity(buildBean).build();
}

From source file:com.jkoolcloud.tnt4j.streams.parsers.ActivityStringParser.java

/**
 * Gets field raw data value resolved by locator.
 *
 * @param locator//  www. ja  v  a2  s  .  c om
 *            activity field locator
 * @param cData
 *            activity data carrier object
 * @param formattingNeeded
 *            flag to set if value formatting is not needed
 * @return substring value resolved by locator, or {@code null} if value is not resolved
 */
@Override
protected Object resolveLocatorValue(ActivityFieldLocator locator, ActivityContext cData,
        AtomicBoolean formattingNeeded) throws ParseException {
    Object val = null;
    String locStr = locator.getLocator();
    try {
        IntRange range = IntRange.getRange(locStr, true);

        val = StringUtils.substring(cData.getData(), range.getFrom(), range.getTo());
    } catch (Exception exc) {
        ParseException pe = new ParseException(StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                "ActivityStringParser.range.exception"), 0);
        pe.initCause(exc);

        throw pe;
    }

    return val;
}