Example usage for java.lang StringBuffer substring

List of usage examples for java.lang StringBuffer substring

Introduction

In this page you can find the example usage for java.lang StringBuffer substring.

Prototype

@Override
public synchronized String substring(int start, int end) 

Source Link

Usage

From source file:org.apache.axis2.builder.XFormURLEncodedBuilder.java

/**
 * Here is what I will try to do here. I will first try to identify the location of the first
 * template element in the request URI. I am trying to deduce the location of that location
 * using the httpLocation element of the binding (it is passed in to this
 * method).//from w w  w  . j  a  va 2 s .c  o m
 * If there is a contant part in the httpLocation, then I will identify it. For this, I get
 * the index of {, from httpLocation param, and whatever to the left of it is the contant part.
 * Then I search for this constant part inside the url. This will give us the access to the first
 * template parameter.
 * To find the end of this parameter, we need to get the index of the next constant, from
 * httpLocation attribute. Likewise we keep on discovering parameters.
 * <p/>
 * Assumptions :
 * 1. User will always append the value of httpLocation to the address given in the
 * endpoint.
 * 2. I was talking about the constants in the httpLocation. Those constants will not occur,
 * to a reasonable extend, before the constant we are looking for.
 *
 * @param templatedPath
 * @param parameterMap
 */
protected String extractParametersUsingHttpLocation(String templatedPath, MultipleEntryHashMap parameterMap,
        String requestURL, String queryParameterSeparator) throws AxisFault, UnsupportedEncodingException {

    if (templatedPath != null && !"".equals(templatedPath) && templatedPath.indexOf("{") > -1) {
        StringBuffer pathTemplate = new StringBuffer(templatedPath);

        // this will hold the index, from which we need to process the request URI
        int startIndex = 0;
        int templateStartIndex = 0;
        int templateEndIndex = 0;
        int indexOfNextConstant = 0;

        StringBuffer requestURIBuffer = new StringBuffer(requestURL);

        while (startIndex < requestURIBuffer.length()) {
            // this will always hold the starting index of a template parameter
            templateStartIndex = pathTemplate.indexOf("{", templateStartIndex);

            if (templateStartIndex > 0) {
                // get the preceding constant part from the template
                String constantPart = pathTemplate.substring(templateEndIndex + 1, templateStartIndex);
                constantPart = constantPart.replaceAll("\\{\\{", "{");
                constantPart = constantPart.replaceAll("}}", "}");

                // get the index of the end of this template param
                templateEndIndex = pathTemplate.indexOf("}", templateStartIndex);
                if ((pathTemplate.length() - 1) > templateEndIndex
                        && pathTemplate.charAt(templateEndIndex + 1) == '}') {
                    templateEndIndex = pathTemplate.indexOf("}", templateEndIndex + 2);
                }

                String parameterName = pathTemplate.substring(templateStartIndex + 1, templateEndIndex);
                // next try to find the next constant
                templateStartIndex = pathTemplate.indexOf("{", templateEndIndex);
                if (pathTemplate.charAt(templateStartIndex + 1) == '{') {
                    templateStartIndex = pathTemplate.indexOf("{", templateStartIndex + 2);
                }

                int endIndexOfConstant = requestURIBuffer.indexOf(constantPart, indexOfNextConstant)
                        + constantPart.length();

                if (templateStartIndex == -1) {
                    if (templateEndIndex == pathTemplate.length() - 1) {

                        // We may have occations where we have templates of the form foo/{name}.
                        // In this case the next connstant will be ? and not the
                        // queryParameterSeparator
                        indexOfNextConstant = requestURIBuffer.indexOf("?", endIndexOfConstant);
                        if (indexOfNextConstant == -1) {
                            indexOfNextConstant = requestURIBuffer.indexOf(queryParameterSeparator,
                                    endIndexOfConstant);
                        }
                        if (indexOfNextConstant > 0) {
                            addParameterToMap(parameterMap, parameterName,
                                    requestURIBuffer.substring(endIndexOfConstant, indexOfNextConstant));
                            return requestURL.substring(indexOfNextConstant);
                        } else {

                            addParameterToMap(parameterMap, parameterName,
                                    requestURIBuffer.substring(endIndexOfConstant));
                            return "";
                        }

                    } else {

                        constantPart = pathTemplate.substring(templateEndIndex + 1, pathTemplate.length());
                        constantPart = constantPart.replaceAll("\\{\\{", "{");
                        constantPart = constantPart.replaceAll("}}", "}");
                        indexOfNextConstant = requestURIBuffer.indexOf(constantPart, endIndexOfConstant);

                        addParameterToMap(parameterMap, parameterName,
                                requestURIBuffer.substring(endIndexOfConstant, indexOfNextConstant));

                        if (requestURIBuffer.length() > indexOfNextConstant + 1) {
                            return requestURIBuffer.substring(indexOfNextConstant + 1);
                        }
                        return "";
                    }
                } else {

                    // this is the next constant from the template
                    constantPart = pathTemplate.substring(templateEndIndex + 1, templateStartIndex);
                    constantPart = constantPart.replaceAll("\\{\\{", "{");
                    constantPart = constantPart.replaceAll("}}", "}");

                    indexOfNextConstant = requestURIBuffer.indexOf(constantPart, endIndexOfConstant);
                    addParameterToMap(parameterMap, parameterName,
                            requestURIBuffer.substring(endIndexOfConstant, indexOfNextConstant));
                    startIndex = indexOfNextConstant;

                }

            }

        }
    }

    return requestURL;
}

From source file:com.openedit.BaseWebPageRequest.java

public String getSiteRoot() {
    String site = (String) getPageValue("siteRoot");
    if (site == null) {
        site = getContentProperty("siteRoot");
    }//  ww  w  .j a va  2  s. co m
    if (site == null && getRequest() != null) {
        StringBuffer ctx = getRequest().getRequestURL();
        site = ctx.substring(0, ctx.indexOf("/", 8)); //8 comes from https://
    } else if (site == null) {
        site = getRequestParameter("siteRoot");
    }
    return site;
}

From source file:com.isecpartners.gizmo.HttpRequest.java

public boolean readRequest(Socket clientSock) {
    StringBuffer contents = new StringBuffer();

    try {/*from   www.j a va2 s .  co  m*/
        InputStream input = clientSock.getInputStream();

        contents = readMessage(input);

        if (contents == null) {
            return false;
        }

        setContentEncodings(contents);
        this.interrimContents = contents.toString();
        this.sock = clientSock;

        this.header = contents.substring(0, contents.indexOf("\r\n"));

        workingContents = new StringBuffer(this.interrimContents.toString());

        if (header.contains("CONNECT") && GizmoView.getView().intercepting()) {
            handle_connect_protocol();
            if (!GizmoView.getView().config().terminateSSL()) {
                return false;
            }
            this.header = workingContents.substring(0, workingContents.indexOf("\r\n"));
        }
        if (GizmoView.getView().intercepting()) {
            if (header.contains("http")) {
                url = header.substring(header.indexOf("http"), header.indexOf("HTTP") - 1);
            } else {
                url = header.substring(header.indexOf("/"), header.indexOf("HTTP") - 1);
            }
            if (url.contains("//")) {
                host = url.substring(url.indexOf("//") + 2, url.indexOf("/", url.indexOf("//") + 2));
            } else {
                String upper = workingContents.toString().toUpperCase();
                int host_start = upper.indexOf("HOST:") + 5;
                host = workingContents.substring(host_start, upper.indexOf("\n", host_start)).trim();
            }
        }

        this.addContents(workingContents.toString());

    } catch (Exception e) {
        return false;
    }

    return true;
}

From source file:dk.netarkivet.harvester.datamodel.RunningJobsInfoDBDAO.java

/**
 * Stores a {@link StartedJobInfo} record to the persistent storage.
 * The record is stored in the monitor table, and if the elapsed time since
 * the last history sample is equal or superior to the history sample rate,
 * also to the history table./*from  w w w  . jav  a2  s  .  co  m*/
 * @param startedJobInfo the record to store.
 */
@Override
public synchronized void store(StartedJobInfo startedJobInfo) {
    ArgumentNotValid.checkNotNull(startedJobInfo, "StartedJobInfo startedJobInfo");

    Connection c = HarvestDBConnection.get();

    try {
        PreparedStatement stm = null;

        // First is there a record in the monitor table?
        boolean update = false;
        try {
            stm = c.prepareStatement(
                    "SELECT jobId FROM runningJobsMonitor" + " WHERE jobId=? AND harvestName=?");
            stm.setLong(1, startedJobInfo.getJobId());
            stm.setString(2, startedJobInfo.getHarvestName());

            // One row expected, as per PK definition
            update = stm.executeQuery().next();

        } catch (SQLException e) {
            String message = "SQL error checking running jobs monitor table" + "\n"
                    + ExceptionUtils.getSQLExceptionCause(e);
            log.warn(message, e);
            throw new IOFailure(message, e);
        }

        try {
            // Update or insert latest progress information for this job
            c.setAutoCommit(false);

            StringBuffer sql = new StringBuffer();

            if (update) {
                sql.append("UPDATE runningJobsMonitor SET ");

                StringBuffer columns = new StringBuffer();
                for (HM_COLUMN setCol : HM_COLUMN.values()) {
                    columns.append(setCol.name() + "=?, ");
                }
                sql.append(columns.substring(0, columns.lastIndexOf(",")));
                sql.append(" WHERE jobId=? AND harvestName=?");
            } else {
                sql.append("INSERT INTO runningJobsMonitor (");
                sql.append(HM_COLUMN.getColumnsInOrder());
                sql.append(") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            }

            stm = c.prepareStatement(sql.toString());
            stm.setLong(HM_COLUMN.jobId.rank(), startedJobInfo.getJobId());
            stm.setString(HM_COLUMN.harvestName.rank(), startedJobInfo.getHarvestName());
            stm.setLong(HM_COLUMN.elapsedSeconds.rank(), startedJobInfo.getElapsedSeconds());
            stm.setString(HM_COLUMN.hostUrl.rank(), startedJobInfo.getHostUrl());
            stm.setDouble(HM_COLUMN.progress.rank(), startedJobInfo.getProgress());
            stm.setLong(HM_COLUMN.queuedFilesCount.rank(), startedJobInfo.getQueuedFilesCount());
            stm.setLong(HM_COLUMN.totalQueuesCount.rank(), startedJobInfo.getTotalQueuesCount());
            stm.setLong(HM_COLUMN.activeQueuesCount.rank(), startedJobInfo.getActiveQueuesCount());
            stm.setLong(HM_COLUMN.retiredQueuesCount.rank(), startedJobInfo.getRetiredQueuesCount());
            stm.setLong(HM_COLUMN.exhaustedQueuesCount.rank(), startedJobInfo.getExhaustedQueuesCount());
            stm.setLong(HM_COLUMN.alertsCount.rank(), startedJobInfo.getAlertsCount());
            stm.setLong(HM_COLUMN.downloadedFilesCount.rank(), startedJobInfo.getDownloadedFilesCount());
            stm.setLong(HM_COLUMN.currentProcessedKBPerSec.rank(),
                    startedJobInfo.getCurrentProcessedKBPerSec());
            stm.setLong(HM_COLUMN.processedKBPerSec.rank(), startedJobInfo.getProcessedKBPerSec());
            stm.setDouble(HM_COLUMN.currentProcessedDocsPerSec.rank(),
                    startedJobInfo.getCurrentProcessedDocsPerSec());
            stm.setDouble(HM_COLUMN.processedDocsPerSec.rank(), startedJobInfo.getProcessedDocsPerSec());
            stm.setInt(HM_COLUMN.activeToeCount.rank(), startedJobInfo.getActiveToeCount());
            stm.setInt(HM_COLUMN.status.rank(), startedJobInfo.getStatus().ordinal());
            stm.setTimestamp(HM_COLUMN.tstamp.rank(), new Timestamp(startedJobInfo.getTimestamp().getTime()));

            if (update) {
                stm.setLong(HM_COLUMN.values().length + 1, startedJobInfo.getJobId());

                stm.setString(HM_COLUMN.values().length + 2, startedJobInfo.getHarvestName());
            }

            stm.executeUpdate();

            c.commit();
        } catch (SQLException e) {
            String message = "SQL error storing started job info " + startedJobInfo + " in monitor table" + "\n"
                    + ExceptionUtils.getSQLExceptionCause(e);
            log.warn(message, e);
            throw new IOFailure(message, e);
        } finally {
            DBUtils.closeStatementIfOpen(stm);
            DBUtils.rollbackIfNeeded(c, "store started job info", startedJobInfo);
        }

        // Should we store an history record?
        Long lastHistoryStore = lastSampleDateByJobId.get(startedJobInfo.getJobId());

        long time = System.currentTimeMillis();
        boolean shouldSample = lastHistoryStore == null || time >= lastHistoryStore + HISTORY_SAMPLE_RATE;

        if (!shouldSample) {
            return; // we're done
        }

        try {
            c.setAutoCommit(false);

            stm = c.prepareStatement("INSERT INTO runningJobsHistory (" + HM_COLUMN.getColumnsInOrder()
                    + ") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            stm.setLong(HM_COLUMN.jobId.rank(), startedJobInfo.getJobId());
            stm.setString(HM_COLUMN.harvestName.rank(), startedJobInfo.getHarvestName());
            stm.setLong(HM_COLUMN.elapsedSeconds.rank(), startedJobInfo.getElapsedSeconds());
            stm.setString(HM_COLUMN.hostUrl.rank(), startedJobInfo.getHostUrl());
            stm.setDouble(HM_COLUMN.progress.rank(), startedJobInfo.getProgress());
            stm.setLong(HM_COLUMN.queuedFilesCount.rank(), startedJobInfo.getQueuedFilesCount());
            stm.setLong(HM_COLUMN.totalQueuesCount.rank(), startedJobInfo.getTotalQueuesCount());
            stm.setLong(HM_COLUMN.activeQueuesCount.rank(), startedJobInfo.getActiveQueuesCount());
            stm.setLong(HM_COLUMN.retiredQueuesCount.rank(), startedJobInfo.getRetiredQueuesCount());
            stm.setLong(HM_COLUMN.exhaustedQueuesCount.rank(), startedJobInfo.getExhaustedQueuesCount());
            stm.setLong(HM_COLUMN.alertsCount.rank(), startedJobInfo.getAlertsCount());
            stm.setLong(HM_COLUMN.downloadedFilesCount.rank(), startedJobInfo.getDownloadedFilesCount());
            stm.setLong(HM_COLUMN.currentProcessedKBPerSec.rank(),
                    startedJobInfo.getCurrentProcessedKBPerSec());
            stm.setLong(HM_COLUMN.processedKBPerSec.rank(), startedJobInfo.getProcessedKBPerSec());
            stm.setDouble(HM_COLUMN.currentProcessedDocsPerSec.rank(),
                    startedJobInfo.getCurrentProcessedDocsPerSec());
            stm.setDouble(HM_COLUMN.processedDocsPerSec.rank(), startedJobInfo.getProcessedDocsPerSec());
            stm.setInt(HM_COLUMN.activeToeCount.rank(), startedJobInfo.getActiveToeCount());
            stm.setInt(HM_COLUMN.status.rank(), startedJobInfo.getStatus().ordinal());
            stm.setTimestamp(HM_COLUMN.tstamp.rank(), new Timestamp(startedJobInfo.getTimestamp().getTime()));

            stm.executeUpdate();

            c.commit();
        } catch (SQLException e) {
            String message = "SQL error storing started job info " + startedJobInfo + " in history table" + "\n"
                    + ExceptionUtils.getSQLExceptionCause(e);
            log.warn(message, e);
            throw new IOFailure(message, e);
        } finally {
            DBUtils.closeStatementIfOpen(stm);
            DBUtils.rollbackIfNeeded(c, "store started job info", startedJobInfo);
        }

        // Remember last sampling date
        lastSampleDateByJobId.put(startedJobInfo.getJobId(), time);
    } finally {
        HarvestDBConnection.release(c);
    }
}

From source file:org.latticesoft.util.container.VarBean.java

/**
 * Returns the full index including that of the parent(s) separated
 * by the separator String.//from w ww  .j  av a  2  s .c  o m
 * @param separator the separator for the name
 */
public String getHierarchyIndex(String separator) {
    if (separator == null) {
        separator = "-";
    }
    List l = this.getHierarchyList();
    StringBuffer sb = new StringBuffer();
    Iterator iter = l.iterator();
    while (iter.hasNext()) {
        VarBean b = (VarBean) iter.next();
        sb.append(b.getIndex());
        sb.append(separator);
    }
    String retVal = "";
    if (sb.length() > separator.length()) {
        retVal = sb.substring(0, sb.length() - separator.length());
    } else {
        retVal = sb.toString();
    }
    return retVal;
}

From source file:org.etudes.ambrosia.impl.UiPropertyReference.java

/**
 * Write the value./*from w  w  w .j av  a  2s. co m*/
 * 
 * @param entity
 *        The entity to write to.
 * @param property
 *        The property to set.
 * @param value
 *        The value to write.
 */
protected void setValue(Object entity, String property, String[] valueSource) {
    // form a "setFoo()" based setter method name
    StringBuffer setter = new StringBuffer("set" + property);
    setter.setCharAt(3, setter.substring(3, 4).toUpperCase().charAt(0));

    // unformat the values - in any are invalid, give up
    String[] value = null;
    try {
        if (valueSource != null) {
            value = new String[valueSource.length];
            for (int i = 0; i < valueSource.length; i++) {
                value[i] = StringUtil.trimToNull(unFormat(valueSource[i]));
            }
        }
    } catch (IllegalArgumentException e) {
        return;
    }

    try {
        // use this form, providing the setter name and no getter, so we can support properties that are write-only
        PropertyDescriptor pd = new PropertyDescriptor(property, entity.getClass(), null, setter.toString());
        Method write = pd.getWriteMethod();
        Object[] params = new Object[1];
        params[0] = null;

        Class[] paramTypes = write.getParameterTypes();
        if ((paramTypes != null) && (paramTypes.length == 1)) {
            // single value boolean
            if (paramTypes[0] == Boolean.class) {
                params[0] = ((value != null) && (value[0] != null))
                        ? Boolean.valueOf(StringUtil.trimToZero(value[0]))
                        : null;
            }

            // multiple value boolean
            else if (paramTypes[0] == Boolean[].class) {
                if (value != null) {
                    Boolean[] values = new Boolean[value.length];
                    for (int i = 0; i < value.length; i++) {
                        values[i] = Boolean.valueOf(StringUtil.trimToZero(value[i]));
                    }
                    params[0] = values;
                }
            }

            // single value long
            else if (paramTypes[0] == Long.class) {
                params[0] = ((value != null) && (value[0] != null))
                        ? Long.valueOf(StringUtil.trimToZero(value[0]))
                        : null;
            }

            // multiple value long
            else if (paramTypes[0] == Long[].class) {
                if (value != null) {
                    Long[] values = new Long[value.length];
                    for (int i = 0; i < value.length; i++) {
                        values[i] = Long.valueOf(StringUtil.trimToZero(value[i]));
                    }
                    params[0] = values;
                }
            }

            // single value int
            else if (paramTypes[0] == Integer.class) {
                params[0] = ((value != null) && (value[0] != null))
                        ? Integer.valueOf(StringUtil.trimToZero(value[0]))
                        : null;
            }

            // multiple value int
            else if (paramTypes[0] == Integer[].class) {
                if (value != null) {
                    Integer[] values = new Integer[value.length];
                    for (int i = 0; i < value.length; i++) {
                        values[i] = Integer.valueOf(StringUtil.trimToZero(value[i]));
                    }
                    params[0] = values;
                }
            }

            // single value Date
            else if (paramTypes[0] == Date.class) {
                // assume a long ms format
                params[0] = ((value != null) && (value[0] != null)) ? new Date(Long.parseLong(value[0])) : null;
            }

            // multiple value Date
            else if (paramTypes[0] == Date[].class) {
                if (value != null) {
                    Date[] values = new Date[value.length];
                    for (int i = 0; i < value.length; i++) {
                        // assume a long ms format
                        values[i] = new Date(Long.parseLong(value[i]));
                    }
                    params[0] = values;
                }
            }

            // single value string
            else if (paramTypes[0] == String.class) {
                params[0] = ((value != null) && (value[0] != null)) ? StringUtil.trimToNull(value[0]) : null;
            }

            // multiple value string
            else if (paramTypes[0] == String[].class) {
                // trim it
                if (value != null) {
                    for (int i = 0; i < value.length; i++) {
                        value[i] = StringUtil.trimToNull(value[i]);
                    }
                }

                params[0] = value;
            }

            // single value enum
            else if (paramTypes[0].isEnum()) {
                if ((value == null) || (value[0] == null)) {
                    params[0] = null;
                } else {
                    Object[] constants = paramTypes[0].getEnumConstants();
                    if (constants != null) {
                        // see if value matches any of these
                        for (Object o : constants) {
                            if (o.toString().equals(value[0])) {
                                params[0] = o;
                                break;
                            }
                        }
                    }
                }
            }

            // single value float
            else if (paramTypes[0] == Float.class) {
                params[0] = ((value != null) && (value[0] != null))
                        ? Float.valueOf(StringUtil.trimToZero(value[0]))
                        : null;
            }

            // multiple value float
            else if (paramTypes[0] == Float[].class) {
                if (value != null) {
                    Float[] values = new Float[value.length];
                    for (int i = 0; i < value.length; i++) {
                        values[i] = Float.valueOf(StringUtil.trimToZero(value[i]));
                    }
                    params[0] = values;
                }
            }

            // multiple value string in list
            else if (paramTypes[0] == List.class) {
                if (value != null) {
                    // trim it into a List
                    List valueList = new ArrayList(value.length);
                    if (value != null) {
                        for (int i = 0; i < value.length; i++) {
                            String v = StringUtil.trimToNull(value[i]);
                            if (v != null) {
                                valueList.add(v);
                            }
                        }
                    }

                    params[0] = valueList;
                }
            }

            // multiple value string in set
            else if (paramTypes[0] == Set.class) {
                if (value != null) {
                    // trim it into a List
                    Set valueSet = new HashSet(value.length);
                    for (int i = 0; i < value.length; i++) {
                        String v = StringUtil.trimToNull(value[i]);
                        if (v != null) {
                            valueSet.add(v);
                        }
                    }

                    params[0] = valueSet;
                }
            }

            // TODO: other types
            else {
                M_log.warn("setValue: unhandled setter parameter type - not set: " + paramTypes[0]);
                return;
            }

            write.invoke(entity, params);
        } else {
            M_log.warn("setValue: method: " + property + " object: " + entity.getClass()
                    + " : no one parameter setter method defined");
        }
    } catch (NumberFormatException ie) {
    } catch (IntrospectionException ie) {
        M_log.warn("setValue: method: " + property + " object: " + entity.getClass(), ie);
    } catch (IllegalAccessException ie) {
        M_log.warn("setValue: method: " + property + " object: " + entity.getClass(), ie);
    } catch (IllegalArgumentException ie) {
        M_log.warn("setValue: method: " + property + " object: " + entity.getClass(), ie);
    } catch (InvocationTargetException ie) {
        M_log.warn("setValue: method: " + property + " object: " + entity.getClass(), ie);
    }
}

From source file:org.ambraproject.article.service.BrowseServiceImpl.java

/**
 * Returns a list of articles for a given category
 * @param params a collection filters / parameters to browse by
 * @return articles/*from   w  w w.ja  va2s .com*/
 */
private BrowseResult getArticlesBySubjectViaSolr(BrowseParameters params) {
    BrowseResult result = new BrowseResult();
    ArrayList<SearchHit> articles = new ArrayList<SearchHit>();
    long total = 0;

    SolrQuery query = createCommonQuery(params.getJournalKey());

    query.addField("title_display");
    query.addField("author_display");
    query.addField("article_type");
    query.addField("publication_date");
    query.addField("id");
    query.addField("abstract_primary_display");
    query.addField("eissn");

    if (params.getSubjects() != null && params.getSubjects().length > 0) {
        StringBuffer subjectQuery = new StringBuffer();
        for (String subject : params.getSubjects()) {
            subjectQuery.append("\"").append(subject).append("\"").append(" AND ");
        }
        // remove the last " AND "
        query.setQuery("subject_level_1:(" + subjectQuery.substring(0, subjectQuery.length() - 5) + ")");
    }

    // we use subject_level_1 field instead of subject_facet field because
    // we are only interested in the top level subjects
    query.setFacet(true);
    query.addFacetField("subject_level_1");
    query.setFacetMinCount(1);
    query.setFacetSort("index");

    setSort(query, params);

    query.setStart(params.getPageNum() * params.getPageSize());
    query.setRows(params.getPageSize());

    try {
        QueryResponse response = this.serverFactory.getServer().query(query);
        SolrDocumentList documentList = response.getResults();
        total = documentList.getNumFound();

        for (SolrDocument document : documentList) {
            SearchHit sh = createArticleBrowseDisplay(document, query.toString());
            articles.add(sh);
        }

        result.setSubjectFacet(facetCountsToHashMap(response.getFacetField("subject_level_1")));
    } catch (SolrServerException e) {
        log.error("Unable to execute a query on the Solr Server.", e);
    }

    result.setTotal(total);
    result.setArticles(articles);

    return result;
}

From source file:com.avricot.prediction.utils.Steemer.java

/**
  * Retrieve the "R zone" (1 or 2 depending on the buffer) and return the corresponding string<br>
  * "R is the region after the first non-vowel following a vowel
  * or is the null region at the end of the word if there is no such non-vowel"<br>
  * @param buffer java.lang.StringBuffer - the in buffer
  * @return java.lang.String - the resulting string
  *///from   w  w w  .jav a2 s. c  o m
 private String retrieveR(StringBuffer buffer) {
     int len = buffer.length();
     int pos = -1;
     for (int c = 0; c < len; c++) {
         if (isVowel(buffer.charAt(c))) {
             pos = c;
             break;
         }
     }
     if (pos > -1) {
         int consonne = -1;
         for (int c = pos; c < len; c++) {
             if (!isVowel(buffer.charAt(c))) {
                 consonne = c;
                 break;
             }
         }
         if (consonne > -1 && (consonne + 1) < len)
             return buffer.substring(consonne + 1, len);
         else
             return null;
     } else
         return null;
 }

From source file:org.kuali.ole.select.document.OleLineItemReceivingDocument.java

/**
 * This method will set copies into list of copies for LineItem.
 *
 * @param singleItem/*from   w  w w .ja v a 2s.co  m*/
 * @param workBibDocument
 * @return
 */
public List<OleCopies> setCopiesToLineItem(OleLineItemReceivingItem singleItem,
        WorkBibDocument workBibDocument) {
    List<WorkInstanceDocument> instanceDocuments = workBibDocument.getWorkInstanceDocumentList();
    List<OleCopies> copies = new ArrayList<OleCopies>();
    for (WorkInstanceDocument workInstanceDocument : instanceDocuments) {
        List<WorkItemDocument> itemDocuments = workInstanceDocument.getItemDocumentList();
        StringBuffer enumeration = new StringBuffer();
        for (int itemDocs = 0; itemDocs < itemDocuments.size(); itemDocs++) {
            if (itemDocs + 1 == itemDocuments.size()) {
                enumeration = enumeration.append(itemDocuments.get(itemDocs).getEnumeration());
            } else {
                enumeration = enumeration.append(itemDocuments.get(itemDocs).getEnumeration() + ",");
            }

        }
        int startingCopy = 0;
        if (singleItem.getItemReceivedTotalParts().intValue() != 0 && null != enumeration) {
            String enumerationSplit = enumeration.substring(1, 2);
            boolean isint = checkIsEnumerationSplitIsIntegerOrNot(enumerationSplit);
            if (isint) {
                startingCopy = Integer.parseInt(enumerationSplit);
            }
        }

        /*
         * if (singleItem.getItemReceivedTotalQuantity().isGreaterThan(new KualiDecimal(1)) ||
         * singleItem.getItemReceivedTotalParts().isGreaterThan(new KualiDecimal(1))) {
         */
        boolean isValid = checkForEnumeration(enumeration);
        if (isValid) {
            OleRequisitionCopies copy = new OleRequisitionCopies();
            int noOfCopies = 0;
            if (null != singleItem.getItemOrderedQuantity() && null != singleItem.getItemOrderedParts()) {
                noOfCopies = workInstanceDocument.getItemDocumentList().size()
                        / singleItem.getItemOrderedParts().intValue();
                copy.setParts(new KualiInteger(singleItem.getItemOrderedParts().intValue()));
            } else {
                noOfCopies = workInstanceDocument.getItemDocumentList().size()
                        / singleItem.getItemReceivedTotalParts().intValue();
                copy.setParts(new KualiInteger(singleItem.getItemReceivedTotalParts().intValue()));
            }

            copy.setLocationCopies(workInstanceDocument.getHoldingsDocument().getLocationName());
            copy.setItemCopies(new KualiDecimal(noOfCopies));
            copy.setPartEnumeration(enumeration.toString());
            copy.setStartingCopyNumber(new KualiInteger(startingCopy));
            copies.add(copy);
            // }
        }
    }
    return copies;
}

From source file:org.latticesoft.util.common.StringUtil.java

/**
 * Extracts all the parameters from a string.
 * @param source source string to parse//from  ww  w . jav  a 2s. c om
 * @param start starting characters for indicating parameter
 * @param end ending characters for indicating end of parameter
 * @return a collection of parameters
 */
public static List extractParameter(String source, String start, String end) {
    StringBuffer sb = new StringBuffer(source);
    List l = new ArrayList();
    int index1 = -1;
    int index2 = -1;
    String param = null;
    if (log.isDebugEnabled()) {
        StringBuffer disp = new StringBuffer();
        disp.append("source:");
        for (int i = 0; i < source.length(); i++) {
            disp.append(i % 10);
        }
        log.debug(disp.toString());
        log.debug("source:" + source);
    }
    do {
        param = null;
        index1 = sb.toString().indexOf(start, index2);
        index2 = sb.toString().indexOf(end, index1 + start.length());

        if (index1 < index2 && index1 > -1 && index2 > -1) {
            int from = index1 + start.length();
            int to = -1;
            if (index2 > source.length()) {
                to = source.length();
            } else {
                to = index2;// - end.length();
            }
            param = sb.substring(from, to);
            if (log.isDebugEnabled()) {
                log.debug("[" + from + ", " + to + "] " + param);
            }
        }
        if (param != null) {
            index2 += end.length();
            l.add(param);
        }
    } while (param != null);
    if (log.isDebugEnabled()) {
        log.debug("-----");
    }
    return l;
}