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:pt.ist.maidSyncher.api.activeCollab.ACTask.java

public ACCategory getCategory() throws IOException {
    if (this._categoryId == -1 || this._categoryId == 0)
        return null;
    String decodedUrl = URLDecoder.decode(getUrl(), "UTF-8");
    int lastIndexOfSlash = StringUtils.lastIndexOf(decodedUrl, "/");
    String urlToUse = StringUtils.substring(decodedUrl, 0, lastIndexOfSlash);
    return new ACCategory(
            (JSONObject) getRequestProcessor().processGet(urlToUse + "/categories/" + _categoryId));

}

From source file:pt.webdetails.cda.dataaccess.AbstractDataAccess.java

/**
 * Get a value iterator from a $FOREACH directive
 *
 * @return Iterable over values, or null if no results
 *///from  w w  w  .  j a  v  a2  s  . co  m
private Iterable<String> expandParameterIteration(String dataAccessId, int outColumnIdx,
        String[] dataAccessParameters) throws QueryException {
    final String EXC_TEXT = "Unable to expand parameter iteration. ";

    QueryOptions queryOptions = new QueryOptions();
    queryOptions.setDataAccessId(dataAccessId);

    //set query parameters
    if (dataAccessParameters != null) {
        for (String paramDef : dataAccessParameters) {
            int attribIdx = StringUtils.indexOf(paramDef, '=');
            if (attribIdx > 0) {
                String paramName = StringUtils.trim(StringUtils.substring(paramDef, 0, attribIdx));
                String paramValue = StringUtils.trim(StringUtils.substring(paramDef, attribIdx + 1));
                queryOptions.addParameter(paramName, paramValue);
            } else {
                logger.error("Bad parameter definition, skipping: " + paramDef);
            }
        }
    }

    //do query and get selected columns
    logger.debug("expandParameterIteration: Doing inner query on CdaSettings [ " + cdaSettings.getId() + " ("
            + queryOptions.getDataAccessId() + ")]");
    try {

        DataAccess dataAccess = getCdaSettings().getDataAccess(queryOptions.getDataAccessId());
        TableModel tableModel = dataAccess.doQuery(queryOptions);

        if (outColumnIdx < 0 || outColumnIdx >= tableModel.getColumnCount()) {
            throw new QueryException(EXC_TEXT,
                    new IllegalArgumentException("Output column index " + outColumnIdx + " out of range."));
        }

        if (tableModel.getRowCount() < 1) {
            return null;
        }
        return new StringColumnIterable(tableModel, outColumnIdx);

    } catch (UnknownDataAccessException e) {
        throw new QueryException(EXC_TEXT, e);
    }

}

From source file:pt.webdetails.cda.dataaccess.Parameter.java

private String getValueAsString(Object value) {
    String separator = getSeparator();

    if (value == null) {
        if (getDefaultValue() != null)
            return getDefaultValue().toString();
        else// w ww.j  av  a  2s.  co  m
            return null;
    } else if (value instanceof String) {
        return (String) value;
    } else if (type != null) {
        switch (type) {
        case STRING_ARRAY://csvTokenizer compatible

            if (value instanceof List) {
                value = ((List) value).toArray();
            }

            if (!(value instanceof String[]) && (value instanceof Object[])) {
                Object[] oldVal = (Object[]) value;
                String[] newVal = new String[oldVal.length];
                for (int i = 0; i < oldVal.length; i++) {
                    //force toString()
                    newVal[i] = "" + oldVal[i];
                }
                value = newVal;
            }

            String[] strArr = (String[]) value;
            int i = 0;
            StringBuilder strBuild = new StringBuilder();
            for (String s : strArr) {
                if (i++ > 0)
                    strBuild.append(separator);

                strBuild.append('"');
                int lastWritten = 0;
                for (int sepIdx = StringUtils.indexOf(s, "'"); sepIdx >= 0; sepIdx = StringUtils.indexOf(s, "'",
                        sepIdx)) {//quote separator
                    strBuild.append(s.substring(lastWritten, sepIdx));
                    strBuild.append('"');
                    strBuild.append(separator);
                    strBuild.append('"');
                    lastWritten = ++sepIdx;
                }
                strBuild.append(StringUtils.substring(s, lastWritten, s.length()));
                strBuild.append('"');
            }
            return strBuild.toString();
        case DATE:
            try {
                Date dt = (Date) getValue();
                return (dt == null) ? null : "" + dt.getTime();
            } catch (InvalidParameterException e) {
                logger.error("Parameter of date type " + getName() + " does not yield date.", e);
            }
            break;
        case DATE_ARRAY:
        case INTEGER_ARRAY:
        case NUMERIC_ARRAY:
        default://also handle whan we want a string and have an array
            if (value instanceof Object[]) {
                Object[] arr = (Object[]) value;
                i = 0;
                strBuild = new StringBuilder();
                for (Object o : arr) {
                    if (i++ > 0)
                        strBuild.append(separator);
                    if (o instanceof Date)
                        strBuild.append(((Date) o).getTime());
                    else
                        strBuild.append(o);
                }
                return strBuild.toString();
            } //else toString
        }
    }
    return value.toString();
}

From source file:pt.webdetails.cda.utils.FormulaEvaluator.java

public static String replaceFormula(String text, FormulaContext context) throws InvalidParameterException {
    int startIdx = StringUtils.indexOf(text, FORMULA_BEGIN);
    int contentStartIdx = startIdx + FORMULA_BEGIN.length();

    if (startIdx > -1) {
        int contentEndIdx = StringUtils.lastIndexOf(text, FORMULA_END);
        int endIdx = contentEndIdx + FORMULA_END.length();
        if (contentEndIdx >= contentStartIdx) {
            String contents = StringUtils.substring(text, contentStartIdx, contentEndIdx);

            StringBuilder result = new StringBuilder();
            result.append(StringUtils.substring(text, 0, startIdx));
            result.append(processFormula(contents, context));
            result.append(StringUtils.substring(text, endIdx, text.length()));

            return result.toString();
        }//w  w w. j a  v a  2  s .com
        //TODO: else throw something
    }
    return text;
}

From source file:pt.webdetails.cda.utils.NaturalOrderComparator.java

public int compareStrings(String a, String b) {

    if (a == null) {
        if (b == null)
            return 0;
        else//from  w ww  .j a v a  2 s .  c om
            return -1;
    } else if (b == null)
        return 1;

    Matcher matcherA = recognizeNbr.matcher(a);
    Matcher matcherB = recognizeNbr.matcher(b);

    int idxA = 0, idxB = 0;
    while (idxA < a.length() || idxB < b.length()) {
        boolean foundInA = matcherA.find(idxA);
        boolean foundInB = matcherB.find(idxB);

        if (!foundInA || !foundInB) {//then our job is over, return a regular string comparison
            return stringComparator.compare(a.substring(idxA), b.substring(idxB));
        }
        //else found in both

        //1) compare unmatched bit as String
        String preA = StringUtils.substring(a, idxA, matcherA.start());
        String preB = StringUtils.substring(b, idxB, matcherB.start());
        int comparison = stringComparator.compare(preA, preB);

        if (comparison != 0)
            return comparison;//done!

        //2) get the number and compare it
        String matchA = StringUtils.substring(a, matcherA.start(), matcherA.end());
        String matchB = StringUtils.substring(b, matcherB.start(), matcherB.end());

        BigDecimal numberA = new BigDecimal(StringUtils.remove(matchA, ',').trim());
        BigDecimal numberB = new BigDecimal(StringUtils.remove(matchB, ',').trim());

        comparison = numberA.compareTo(numberB);

        if (comparison != 0)
            return comparison;

        //3) if inconclusive process the rest
        idxA = matcherA.end();
        idxB = matcherB.end();
    }

    return 0;
}

From source file:reconf.client.constructors.SimpleConstructor.java

public Object construct(MethodData data) throws Throwable {
    if (data.hasAdapter()) {
        return data.getAdapter().adapt(data.getValue());
    }/*from   ww  w .  java2s . c  o m*/

    Class<?> returnClass = (Class<?>) data.getReturnType();

    String trimmed = StringUtils.defaultString(StringUtils.trim(data.getValue()));
    if (!trimmed.startsWith("'") || !trimmed.endsWith("'")) {
        throw new RuntimeException(msg.format("error.invalid.string", data.getValue(), data.getMethod()));
    }

    String wholeValue = StringUtils.substring(trimmed, 1, trimmed.length() - 1);

    if (String.class.equals(returnClass)) {
        return wholeValue;
    }

    if (null == data.getValue()) {
        return null;
    }

    if (Object.class.equals(returnClass)) {
        returnClass = String.class;
    }

    if (char.class.equals(data.getReturnType()) || Character.class.equals(data.getReturnType())) {
        if (StringUtils.length(wholeValue) == 1) {
            return CharUtils.toChar(wholeValue);
        }
        return CharUtils.toChar(StringUtils.replace(wholeValue, " ", ""));
    }

    if (primitiveBoxing.containsKey(returnClass)) {
        if (StringUtils.isBlank(wholeValue)) {
            return null;
        }
        Method parser = primitiveBoxing.get(returnClass).getMethod(
                "parse" + StringUtils.capitalize(returnClass.getSimpleName()), new Class<?>[] { String.class });
        return parser.invoke(primitiveBoxing.get(returnClass), new Object[] { StringUtils.trim(wholeValue) });
    }

    Method valueOf = null;
    try {
        valueOf = returnClass.getMethod("valueOf", new Class<?>[] { String.class });
    } catch (NoSuchMethodException ignored) {
    }

    if (valueOf == null) {
        try {

            valueOf = returnClass.getMethod("valueOf", new Class<?>[] { Object.class });
        } catch (NoSuchMethodException ignored) {
        }
    }

    if (null != valueOf) {
        if (StringUtils.isEmpty(wholeValue)) {
            return null;
        }
        return valueOf.invoke(data.getReturnType(), new Object[] { StringUtils.trim(wholeValue) });
    }

    Constructor<?> constructor = null;

    try {
        constructor = returnClass.getConstructor(String.class);
        constructor.setAccessible(true);

    } catch (NoSuchMethodException ignored) {
        throw new IllegalStateException(
                msg.format("error.string.constructor", returnClass.getSimpleName(), data.getMethod()));
    }

    try {
        return constructor.newInstance(wholeValue);

    } catch (Exception e) {
        if (e.getCause() != null && e.getCause() instanceof NumberFormatException) {
            return constructor.newInstance(StringUtils.trim(wholeValue));
        }
        throw e;
    }
}

From source file:reconf.client.constructors.StringParser.java

public StringParser(MethodData arg) {
    this.data = arg;

    if (StringUtils.isEmpty(data.getValue())) {
        return;//from   w  w w  .j av a2 s  .  co  m
    }

    String trimmed = StringUtils.defaultString(StringUtils.trim(data.getValue()));
    if (!trimmed.startsWith("[") || !trimmed.endsWith("]")) {
        throw new RuntimeException(msg.format("error.complex.type", data.getMethod()));
    }

    String wholeValue = StringUtils.substring(trimmed, 1, trimmed.length() - 1);
    extractTokens(wholeValue);
    if (openClose.size() % 2 != 0) {
        throw new IllegalArgumentException(
                msg.format("error.invalid.string", data.getValue(), data.getMethod()));
    }
}

From source file:se.nrm.dina.dina.inventory.logic.dyntaxa.ExcelLogic.java

private void uploadNewSynonyms(XSSFSheet sheet) {

    int numOfRows = sheet.getLastRowNum();

    theRank = "Species";
    IntStream.range(4, numOfRows + 1).forEach(nbr -> {
        XSSFRow row = sheet.getRow(nbr);
        if (row.getCell(0) != null) {
            genus = row.getCell(0).getStringCellValue().trim();
            species = row.getCell(1).getStringCellValue().trim();
            author = row.getCell(2).getStringCellValue().trim();
            scientificName = row.getCell(5).getStringCellValue().trim();
            synonymOf = row.getCell(6).getStringCellValue().trim();
            source = row.getCell(7).getStringCellValue();
            if (source.length() > 64) {
                source = StringUtils.substring(source, 0, 63);
            }/*from  w w  w .  ja v  a  2s .  c  o  m*/
            agentName = row.getCell(8).getStringCellValue();
            uploadSynonyms();
        }
    });
}

From source file:se.nrm.dina.dina.inventory.logic.util.Util.java

public Date convertStringToDate(int year) {
    try {//ww  w . j  a  v  a 2  s.  c  o  m
        if (year != 0) {
            String strYear = String.valueOf(year);
            if (strYear.length() == 8) {
                strYear = StringUtils.substring(strYear, 0, 3);
            }
            return DATA_FORMAT.parse(strYear + "-01-01");
        } else {
            return null;
        }
    } catch (ParseException ex) {
        return null;
    }
}

From source file:smartcrud.common.orm.PropertyFilter.java

/**
 * @param filterName ,???. //  w w w .  j a  v a 2  s  .c  o  m
 *                   eg. LIKES_NAME_OR_LOGIN_NAME
 * @param value .
 */
public PropertyFilter(final String filterName, final String value) {

    String matchTypeStr = StringUtils.substringBefore(filterName, "_");
    String matchTypeCode = StringUtils.substring(matchTypeStr, 0, matchTypeStr.length() - 1);
    String propertyTypeCode = StringUtils.substring(matchTypeStr, matchTypeStr.length() - 1,
            matchTypeStr.length());
    try {
        matchType = Enum.valueOf(MatchType.class, matchTypeCode);
    } catch (RuntimeException e) {
        throw new IllegalArgumentException(
                "filter??" + filterName + ",.", e);
    }

    try {
        propertyType = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
    } catch (RuntimeException e) {
        throw new IllegalArgumentException(
                "filter??" + filterName + ",.", e);
    }

    String propertyNameStr = StringUtils.substringAfter(filterName, "_");
    propertyNames = StringUtils.split(propertyNameStr, PropertyFilter.OR_SEPARATOR);

    Assert.isTrue(propertyNames.length > 0,
            "filter??" + filterName + ",??.");
    //entity property.
    this.propertyValue = ReflectionUtils.convertStringToObject(value, propertyType);
}