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

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

Introduction

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

Prototype

public static String mid(String str, int pos, int len) 

Source Link

Document

Gets len characters from the middle of a String.

Usage

From source file:com.alibaba.intl.bcds.goldroom.util.ImageUtilImpl.java

private String isbnTopath(String isbn, String separator) {
    StringBuilder sb = new StringBuilder();
    sb.append(separator).append(StringUtils.left(isbn, 2));
    sb.append(separator).append(StringUtils.mid(isbn, 2, 2));
    sb.append(separator).append(StringUtils.mid(isbn, 4, 2));
    sb.append(separator);/* ww w . j  a  v a2  s.c o m*/
    return sb.toString();
}

From source file:opennlp.tools.similarity.apps.solr.NLProgram2CodeRequestHandler.java

public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) {
    // get query string
    String requestExpression = req.getParamString();
    String[] exprParts = requestExpression.split("&");
    String[] text = new String[exprParts.length];
    int count = 0;
    for (String val : exprParts) {
        if (val.startsWith("line=")) {
            val = StringUtils.mid(val, 5, val.length());
            text[count] = val;
            count++;//from   w w w. j  ava2  s.c o m
        }

    }

    StringBuffer buf = new StringBuffer();
    for (String sent : text) {
        ObjectPhraseListForSentence opls = null;
        try {
            opls = compiler.convertSentenceToControlObjectPhrase(sent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(sent + "\n" + opls + "\n");
        buf.append(sent + "\n |=> " + opls + "\n");
    }

    LOG.info("re-ranking results: " + buf.toString());
    NamedList<Object> values = rsp.getValues();
    values.remove("response");
    values.add("response", buf.toString().trim());
    rsp.setAllValues(values);

}

From source file:opennlp.tools.similarity.apps.solr.SearchResultsReRankerRequestHandler.java

public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) {
    // get query string
    String requestExpression = req.getParamString();
    String[] exprParts = requestExpression.split("&");
    for (String part : exprParts) {
        if (part.startsWith("q="))
            requestExpression = part;//  w w  w .j  a  v a  2s .co  m
    }
    String query = StringUtils.substringAfter(requestExpression, ":");
    LOG.info(requestExpression);

    SolrParams ps = req.getOriginalParams();
    Iterator<String> iter = ps.getParameterNamesIterator();
    List<String> keys = new ArrayList<String>();
    while (iter.hasNext()) {
        keys.add(iter.next());
    }

    List<HitBase> searchResults = new ArrayList<HitBase>();

    for (Integer i = 0; i < MAX_SEARCH_RESULTS; i++) {
        String title = req.getParams().get("t" + i.toString());
        String descr = req.getParams().get("d" + i.toString());

        if (title == null || descr == null)
            continue;

        HitBase hit = new HitBase();
        hit.setTitle(title);
        hit.setAbstractText(descr);
        hit.setSource(i.toString());
        searchResults.add(hit);
    }

    /*
     * http://173.255.254.250:8983/solr/collection1/reranker/?
     * q=search_keywords:design+iphone+cases&fields=spend+a+day+with+a+custom+iPhone+case&fields=Add+style+to+your+every+day+fresh+design+with+a+custom+iPhone+case&fields=Add+style+to+your+every+day+with+mobile+case+for+your+family&fields=Add+style+to+your+iPhone+and+iPad&fields=Add+Apple+fashion+to+your+iPhone+and+iPad
     * 
     */

    if (searchResults.size() < 1) {
        int count = 0;
        for (String val : exprParts) {
            if (val.startsWith("fields=")) {
                val = StringUtils.mid(val, 7, val.length());
                HitBase hit = new HitBase();
                hit.setTitle("");
                hit.setAbstractText(val);
                hit.setSource(new Integer(count).toString());
                searchResults.add(hit);
                count++;
            }

        }
    }

    List<HitBase> reRankedResults = null;
    query = query.replace('+', ' ');
    if (tooFewKeywords(query) || orQuery(query)) {
        reRankedResults = searchResults;
        LOG.info("No re-ranking for " + query);
    } else
        reRankedResults = calculateMatchScoreResortHits(searchResults, query);
    /*
     * <scores>
    <score index="2">3.0005</score>
    <score index="1">2.101</score>
    <score index="3">2.1003333333333334</score>
    <score index="4">2.00025</score>
    <score index="5">1.1002</score>
    </scores>
     * 
     * 
     */
    StringBuffer buf = new StringBuffer();
    buf.append("<scores>");
    for (HitBase hit : reRankedResults) {
        buf.append("<score index=\"" + hit.getSource() + "\">" + hit.getGenerWithQueryScore() + "</score>");
    }
    buf.append("</scores>");

    NamedList<Object> scoreNum = new NamedList<Object>();
    for (HitBase hit : reRankedResults) {
        scoreNum.add(hit.getSource(), hit.getGenerWithQueryScore());
    }

    StringBuffer bufNums = new StringBuffer();
    bufNums.append("order>");
    for (HitBase hit : reRankedResults) {
        bufNums.append(hit.getSource() + "_");
    }
    bufNums.append("/order>");

    LOG.info("re-ranking results: " + buf.toString());
    NamedList<Object> values = rsp.getValues();
    values.remove("response");
    values.add("response", scoreNum);
    //values.add("new_order", bufNums.toString().trim());
    rsp.setAllValues(values);

}

From source file:opennlp.tools.similarity.apps.solr.SearchResultsReRankerStanfRequestHandler.java

public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) {
    // get query string
    String requestExpression = req.getParamString();
    String[] exprParts = requestExpression.split("&");
    for (String part : exprParts) {
        if (part.startsWith("q="))
            requestExpression = part;/*w w w.  j  a  va  2 s  .  com*/
    }
    String query = StringUtils.substringAfter(requestExpression, ":");
    LOG.info(requestExpression);

    SolrParams ps = req.getOriginalParams();
    Iterator<String> iter = ps.getParameterNamesIterator();
    List<String> keys = new ArrayList<String>();
    while (iter.hasNext()) {
        keys.add(iter.next());
    }

    List<HitBase> searchResults = new ArrayList<HitBase>();

    for (Integer i = 0; i < MAX_SEARCH_RESULTS; i++) {
        String title = req.getParams().get("t" + i.toString());
        String descr = req.getParams().get("d" + i.toString());

        if (title == null || descr == null)
            continue;

        HitBase hit = new HitBase();
        hit.setTitle(title);
        hit.setAbstractText(descr);
        hit.setSource(i.toString());
        searchResults.add(hit);
    }

    /*
     * http://173.255.254.250:8983/solr/collection1/reranker/?
     * q=search_keywords:design+iphone+cases&fields=spend+a+day+with+a+
     * custom+iPhone+case&fields=Add+style+to+your+every+day+fresh+design+
     * with+a+custom+iPhone+case&fields=Add+style+to+your+every+day+with+
     * mobile+case+for+your+family&fields=Add+style+to+your+iPhone+and+iPad&
     * fields=Add+Apple+fashion+to+your+iPhone+and+iPad
     * 
     */

    if (searchResults.size() < 1) {
        int count = 0;
        for (String val : exprParts) {
            if (val.startsWith("fields=")) {
                val = StringUtils.mid(val, 7, val.length());
                HitBase hit = new HitBase();
                hit.setTitle("");
                hit.setAbstractText(val);
                hit.setSource(new Integer(count).toString());
                searchResults.add(hit);
                count++;
            }

        }
    }

    List<HitBase> reRankedResults = null;
    query = query.replace('+', ' ');
    if (tooFewKeywords(query) || orQuery(query)) {
        reRankedResults = searchResults;
        LOG.info("No re-ranking for " + query);
    } else
        reRankedResults = calculateMatchScoreResortHits(searchResults, query);
    /*
     * <scores> <score index="2">3.0005</score> <score
     * index="1">2.101</score> <score index="3">2.1003333333333334</score>
     * <score index="4">2.00025</score> <score index="5">1.1002</score>
     * </scores>
     * 
     * 
     */
    StringBuffer buf = new StringBuffer();
    buf.append("<scores>");
    for (HitBase hit : reRankedResults) {
        buf.append("<score index=\"" + hit.getSource() + "\">" + hit.getGenerWithQueryScore() + "</score>");
    }
    buf.append("</scores>");

    NamedList<Object> scoreNum = new NamedList<Object>();
    for (HitBase hit : reRankedResults) {
        scoreNum.add(hit.getSource(), hit.getGenerWithQueryScore());
    }

    StringBuffer bufNums = new StringBuffer();
    bufNums.append("order>");
    for (HitBase hit : reRankedResults) {
        bufNums.append(hit.getSource() + "_");
    }
    bufNums.append("/order>");

    LOG.info("re-ranking results: " + buf.toString());
    NamedList<Object> values = rsp.getValues();
    values.remove("response");
    values.add("response", scoreNum);
    values.add("new_order", bufNums.toString().trim());
    rsp.setAllValues(values);

}

From source file:org.apache.cocoon.acting.DatabaseAddAction.java

/**
 * Inserts a row or a set of rows into the given table based on the
 * request parameters//ww  w  . j a  v  a2s .  co m
 *
 * @param table the table's configuration
 * @param conn the database connection
 * @param request the request
 */
void processTable(Configuration table, Connection conn, Request request, Map results)
        throws SQLException, ConfigurationException, Exception {
    PreparedStatement statement = null;
    try {
        String query = this.getAddQuery(table);
        getLogger().debug("Add query: " + query);
        statement = conn.prepareStatement(query);
        Configuration[] keys = table.getChild("keys").getChildren("key");
        Configuration[] values = table.getChild("values").getChildren("value");
        int currentIndex = 1;
        boolean manyrows = false;
        int wildcardIndex = -1;
        String wildcardParam = null;
        for (int i = 0; i < keys.length; i++) {
            wildcardParam = keys[i].getAttribute("param");
            if ((wildcardIndex = wildcardParam.indexOf('*')) != -1) {
                manyrows = true;
                break;
            }
        }
        if (manyrows) {
            /**
             * This table has a column with a wildcard, so we're going
             * to be inserting n rows, where 0 <= n
             */
            String prefix = wildcardParam.substring(0, wildcardIndex);
            String suffix = StringUtils.substring(wildcardParam, wildcardIndex + 1);
            Enumeration names = request.getParameterNames();
            SortedSet matchset = new TreeSet();
            int prefixLength = prefix.length();
            int length = prefixLength + suffix.length();
            while (names.hasMoreElements()) {
                String name = (String) names.nextElement();
                if (name.startsWith(prefix) && name.endsWith(suffix)) {
                    String wildcard = StringUtils.mid(name, prefixLength, name.length() - length);
                    matchset.add(wildcard);
                }
            }
            int rowIndex = 1;
            Iterator iterator = matchset.iterator();
            while (iterator.hasNext()) {
                String wildcard = (String) iterator.next();
                currentIndex = 1;
                for (int j = 0; j < keys.length; j++) {
                    String myparam = getActualParam(keys[j].getAttribute("param"), wildcard);
                    currentIndex += setKey(table, keys[j], conn, statement, currentIndex, request, myparam,
                            results);
                }
                for (int j = 0; j < values.length; j++) {
                    String myparam = getActualParam(values[j].getAttribute("param"), wildcard);
                    this.setColumn(statement, currentIndex, request, values[j], myparam,
                            request.getParameter(myparam), rowIndex);
                    currentIndex++;
                }
                statement.execute();
                rowIndex++;
            }
        } else {
            /**
             * This table has no wildcard columns, so we're going to
             * be inserting 1 row.
             */
            for (int i = 0; i < keys.length; i++) {
                currentIndex += setKey(table, keys[i], conn, statement, currentIndex, request,
                        keys[i].getAttribute("param", ""), results);
            }
            for (int i = 0; i < values.length; i++, currentIndex++) {
                this.setColumn(statement, currentIndex, request, values[i]);
            }
            statement.execute();
            /** Done processing table **/
        }
    } finally {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
        }
    }
}

From source file:org.kuali.ext.mm.ObjectUtil.java

/**
 * Tokenize the input line with the given deliminator and populate the given object with values of the tokens
 *
 * @param targetObject the target object
 * @param line the input line//w w w  . j  av  a 2  s.c  o  m
 * @param delim the deminator that separates the fields in the given line
 * @param keyFields the specified fields
 */
public static void convertLineToBusinessObject(Object targetObject, String line, int[] fieldLength,
        List<String> keyFields) {
    String[] tokens = new String[fieldLength.length];

    int currentPosition = 0;
    for (int i = 0; i < fieldLength.length; i++) {
        currentPosition = i <= 0 ? 0 : fieldLength[i - 1] + currentPosition;
        tokens[i] = StringUtils.mid(line, currentPosition, fieldLength[i]).trim();
    }
    ObjectUtil.buildObject(targetObject, tokens, keyFields);
}

From source file:org.kuali.kfs.module.ld.batch.service.impl.LaborBalanceSummaryReportServiceImpl.java

/**
 * determine if the given date is within the upper bound of year end period
 * //from w w  w.  j  a va 2s. c o  m
 * @param runDate the given date
 * @param yearEndPeriodUpperBound the upper bound date of year end period
 * @param lastDayOfFiscalYear the last day of the current fiscal year
 * @return true if the given date is within the upper bound of year end period; otherwise, false
 */
protected boolean isInYearEndUpperBound(Date runDate, String yearEndPeriodUpperBound,
        String lastDayOfFiscalYear) {
    SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
    String today = sdf.format(runDate);

    String month = StringUtils.mid(lastDayOfFiscalYear, 0, 2);
    String date = StringUtils.mid(lastDayOfFiscalYear, 2, 2);

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.MONTH, Integer.parseInt(month) - 1);
    calendar.set(Calendar.DATE, Integer.parseInt(date));
    calendar.add(Calendar.DATE, 1);
    String firstDayOfNewFiscalYear = sdf.format(calendar.getTime());

    return today.compareTo(yearEndPeriodUpperBound) <= 0 && today.compareTo(firstDayOfNewFiscalYear) >= 0;
}

From source file:org.openhab.binding.plugwise.internal.Energy.java

public Energy(String logdate, long l, int interval) {

    if (logdate.length() == 8) {

        if (!logdate.equals("FFFFFFFF")) {

            int year = 0;
            int month = 0;
            long minutes = 0;

            year = Integer.parseInt(StringUtils.left(logdate, 2), 16) + 2000;
            month = Integer.parseInt(StringUtils.mid(logdate, 2, 2), 16);
            minutes = Long.parseLong(StringUtils.right(logdate, 4), 16);

            time = new DateTime(year, month, 1, 0, 0, DateTimeZone.UTC).plusMinutes((int) minutes)
                    .toDateTime(DateTimeZone.getDefault()).minusHours(1);

        } else {/*w w  w. j a  v  a 2s.c o m*/
            time = DateTime.now();
            this.interval = interval;
            this.pulses = 0;
        }

    } else {
        time = DateTime.now();
    }

    this.interval = interval;
    this.pulses = l;

}

From source file:org.openhab.binding.plugwise.protocol.InformationResponseMessage.java

@Override
protected void parsePayLoad() {
    Pattern RESPONSE_PATTERN = Pattern
            .compile("(\\w{16})(\\w{2})(\\w{2})(\\w{4})(\\w{8})(\\w{2})(\\w{2})(\\w{12})(\\w{8})(\\w{2})");

    Matcher matcher = RESPONSE_PATTERN.matcher(payLoad);
    if (matcher.matches()) {
        MAC = matcher.group(1);/*from   ww  w .  ja  v a2 s .c om*/
        year = Integer.parseInt(matcher.group(2), 16) + 2000;
        month = Integer.parseInt(matcher.group(3), 16);
        minutes = Integer.parseInt(matcher.group(4), 16);
        logAddress = (Integer.parseInt(matcher.group(5), 16) - 278528) / 8;
        powerState = (matcher.group(6).equals("01"));
        hertz = Integer.parseInt(matcher.group(7), 16);
        hardwareVersion = StringUtils.left(matcher.group(8), 4) + "-" + StringUtils.mid(matcher.group(8), 4, 4)
                + "-" + StringUtils.right(matcher.group(8), 4);
        firmwareVersion = Integer.parseInt(matcher.group(9), 16);
        unknown = Integer.parseInt(matcher.group(10), 16);
    } else {
        logger.debug("Plugwise protocol RoleCallResponseMessage error: {} does not match", payLoad);
    }
}