Example usage for java.lang StringBuilder replace

List of usage examples for java.lang StringBuilder replace

Introduction

In this page you can find the example usage for java.lang StringBuilder replace.

Prototype

@Override
public StringBuilder replace(int start, int end, String str) 

Source Link

Usage

From source file:org.exoplatform.calendar.ws.RestEventQuery.java

@Override
public String getQueryStatement() throws Exception {
    // events from user, groups, public calendars, and events that contains
    // specific participant
    StringBuilder sql = new StringBuilder("SELECT " + Utils.EXO_ID + " FROM ");
    sql.append(Utils.EXO_CALENDAR_EVENT);
    sql.append(" WHERE");

    //    if (getCalendarPath() != null) {
    //      sql.append(" jcr:path LIKE '").append(getCalendarPath()).append("/%' AND NOT jcr:path LIKE '");
    //      sql.append(getCalendarPath()).append("/%/%'");
    //    }//from   www.j a  v a  2s . c  o  m

    if (getCalendarId() != null || getParticipants() != null) {
        sql.append(" AND (");
        // calendarIds: public and groups, shared calendars
        if (getCalendarId() != null) {
            for (String calId : getCalendarId()) {
                sql.append(" OR ").append(Utils.EXO_CALENDAR_ID).append(" = '").append(calId).append("'");
            }
        }
        // participant
        if (getParticipants() != null) {
            for (String participant : getParticipants()) {
                //workaround for case calendarRestApi.findEventsByCalendar
                if (getCalendarPath() != null) {
                    sql.append(" AND ");
                } else {
                    sql.append(" OR ");
                }

                if (CalendarEvent.TYPE_TASK.equals(getEventType())) {
                    sql.append("CONTAINS(").append(Utils.EXO_TASK_DELEGATOR);
                    sql.append(",'").append(participant).append("')");
                } else {
                    sql.append(Utils.EXO_PARTICIPANT).append(" = '").append(participant).append("'");
                }
            }
        }
        sql.append(")");
    }

    // date time
    if (getFromDate() != null) {
        sql.append(" AND (").append(Utils.EXO_FROM_DATE_TIME).append(" >= TIMESTAMP '")
                .append(ISO8601.format(getFromDate())).append("')");
    }
    if (getToDate() != null) {
        sql.append(" AND (").append(Utils.EXO_TO_DATE_TIME).append(" <= TIMESTAMP '")
                .append(ISO8601.format(getToDate())).append("')");
    }
    // category
    String[] categoryIds = getCategoryId();
    if (categoryIds != null && categoryIds.length > 0) {
        sql.append(" AND (");
        for (int i = 0; i < categoryIds.length; i++) {
            sql.append(Utils.EXO_EVENT_CATEGORYID);
            sql.append(" = '").append(categoryIds[i]).append("'");
            if (i < categoryIds.length - 1) {
                sql.append(" OR ");
            }
        }
        sql.append(")");
    }
    // event or task
    if (!Utils.isEmpty(getEventType())) {
        sql.append(" AND ").append(Utils.EXO_EVENT_TYPE).append("='");
        sql.append(getEventType()).append("'");
    }

    int i = sql.indexOf("WHERE AND");
    if (i != -1) {
        sql.replace(i, i + 9, "WHERE");
    }
    if ((i = sql.indexOf("( OR")) != -1) {
        sql.replace(i, i + 4, "(");
    }
    if ((i = sql.indexOf("( AND")) != -1) {
        sql.replace(i, i + 5, "(");
    }

    String[] orderBy = getOrderBy();
    String orderType = " " + getOrderType();
    if (orderBy != null && orderBy.length > 0) {
        sql.append(" ORDER BY ");

        for (int j = 0; j < orderBy.length; j++) {
            orderBy[j] = orderBy[j] + orderType;
        }
        sql.append(StringUtils.join(orderBy, ","));
    }
    return sql.toString();
}

From source file:es.ehu.si.ixa.pipe.convert.Convert.java

public void absaSemEvalToNER2015(String fileName) {
    SAXBuilder sax = new SAXBuilder();
    XPathFactory xFactory = XPathFactory.instance();
    try {/* w  ww. j  a  v a2 s.  c  o  m*/
        Document doc = sax.build(fileName);
        XPathExpression<Element> expr = xFactory.compile("//sentence", Filters.element());
        List<Element> sentences = expr.evaluate(doc);
        for (Element sent : sentences) {

            String sentString = sent.getChildText("text");
            StringBuilder sb = new StringBuilder();
            sb = sb.append(sentString);
            Element opinionsElement = sent.getChild("Opinions");
            if (opinionsElement != null) {
                List<List<Integer>> offsetList = new ArrayList<List<Integer>>();
                List<Integer> offsets = new ArrayList<Integer>();
                List<Element> oteList = opinionsElement.getChildren();
                for (Element aspectElem : oteList) {
                    if (!aspectElem.getAttributeValue("target").equals("NULL")) {
                        Integer offsetFrom = Integer.parseInt(aspectElem.getAttributeValue("from"));
                        Integer offsetTo = Integer.parseInt(aspectElem.getAttributeValue("to"));
                        offsets.add(offsetFrom);
                        offsets.add(offsetTo);
                    }
                }
                List<Integer> offsetsWithoutDuplicates = new ArrayList<Integer>(new HashSet<Integer>(offsets));
                Collections.sort(offsetsWithoutDuplicates);

                for (int i = 0; i < offsetsWithoutDuplicates.size(); i++) {
                    List<Integer> offsetArray = new ArrayList<Integer>();
                    offsetArray.add(offsetsWithoutDuplicates.get(i++));
                    if (offsetsWithoutDuplicates.size() > i) {
                        offsetArray.add(offsetsWithoutDuplicates.get(i));
                    }
                    offsetList.add(offsetArray);
                }
                int counter = 0;
                for (List<Integer> offsetSent : offsetList) {
                    Integer offsetFrom = offsetSent.get(0);
                    Integer offsetTo = offsetSent.get(1);
                    String aspectString = sentString.substring(offsetFrom, offsetTo);
                    sb.replace(offsetFrom + counter, offsetTo + counter,
                            "<START:target> " + aspectString + " <END>");
                    counter += 21;
                }
                System.out.println(sb.toString());
            }
        }
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
    }
}

From source file:net.sourceforge.processdash.ev.ui.EVReport.java

private String fixChartHelpContent(String helpContent, String helpBaseUri, Map<String, String> chartHelp) {

    // discard headers and footers from the help content
    int cutStart = helpContent.indexOf("</h1>");
    if (cutStart != -1)
        helpContent = helpContent.substring(cutStart + 5);
    int cutEnd = helpContent.lastIndexOf("</body");
    if (cutEnd != -1)
        helpContent = helpContent.substring(0, cutEnd);

    // create a map of the chart help topics
    Map<String, String> chartUrls = new HashMap<String, String>();
    for (Map.Entry<String, String> e : chartHelp.entrySet()) {
        String chartId = e.getKey();
        String chartUrl = getChartDrillDownUrl(chartId);
        String helpUri = e.getValue();
        String helpName = hrefFileName(helpUri);
        chartUrls.put(helpName, chartUrl);
    }/* ww  w.  jav a2 s.c  om*/

    // find and fix all the hrefs in this help topic:
    //   * If any hrefs point to the help topic for a different chart,
    //     rewrite the href so it actually loads the "drill-down page"
    //     for that chart instead.
    //   * For links that point to some non-chart help topic, rewrite the
    //     href to be absolute (so the help-relative URI won't break)

    StringBuilder html = new StringBuilder(helpContent);
    int pos = 0;
    while (true) {
        // find the next href in the document.
        pos = html.indexOf("href=", pos);
        if (pos == -1)
            break; // no more hrefs to fix

        pos += 6;
        int beg = pos; // the first character of the href value itself
        char delim = html.charAt(beg - 1);
        int end = html.indexOf(String.valueOf(delim), beg);
        if (end == -1)
            continue; // invalid href syntax.  Skip to the next one.

        // extract the href value
        String oneHref = html.substring(beg, end);
        // extract the final portion of the path name
        String oneName = hrefFileName(oneHref);
        // see if that name refers to one of the charts we can display
        String chartUrl = chartUrls.get(oneName);
        if (chartUrl != null) {
            // replace the href with a chart drill-down URL
            html.replace(beg, end, chartUrl);
            pos = beg + chartUrl.length();
        } else {
            try {
                // make the URL absolute, and set a "target" attribute
                // so it will open in another window.
                URI base = new URI(helpBaseUri);
                URI target = base.resolve(oneHref);
                String newUri = target.toString();
                html.replace(beg, end, newUri);
                html.insert(beg - 6, "target='evHelp' ");
                pos = beg + newUri.length() + 16;
            } catch (Exception e) {
                // problems resolving the URI?  Turn the link into an
                // anchor so it can't be clicked on anymore.
                html.replace(beg - 6, beg - 2, "name");
            }
        }
    }

    return html.toString();
}

From source file:org.calrissian.accumulorecipes.commons.iterators.support.QueryEvaluator.java

public StringBuilder rewriteQuery(StringBuilder query, String fieldName, Collection<FieldValue> fieldValues) {
    if (log.isDebugEnabled()) {
        log.debug("rewriteQuery");
    }/*  www .j a v a2s  .c om*/

    if (log.isDebugEnabled()) {
        log.debug("Modifying original criteria: " + query);
    }
    // Pull the values out of the FieldValue object
    String[] values = new String[fieldValues.size()];
    int idx = 0;
    for (FieldValue fv : fieldValues) {
        values[idx] = new String(fv.getValue());
        idx++;
    }
    // Add the array to the context
    ctx.set(fieldName, values);

    Collection<QueryParser.QueryTerm> qt = terms.get(fieldName);

    // Add a script to the beginning of the criteria for this multi-valued field
    StringBuilder script = new StringBuilder();
    script.append("_").append(fieldName).append(" = false;\n");
    script.append("for (field : ").append(fieldName).append(") {\n");

    for (QueryParser.QueryTerm t : qt) {
        if (!t.getOperator().equals(JexlOperatorConstants.getOperator(ParserTreeConstants.JJTFUNCTIONNODE))) {
            script.append("\tif (_").append(fieldName).append(" == false && field ").append(t.getOperator())
                    .append(" ").append(t.getValue()).append(") { \n");
        } else {
            script.append("\tif (_").append(fieldName).append(" == false && ")
                    .append(t.getValue().toString().replace(fieldName, "field")).append(") { \n");
        }
        script.append("\t\t_").append(fieldName).append(" = true;\n");
        script.append("\t}\n");
    }
    script.append("}\n");

    // Add the script to the beginning of the criteria
    query.insert(0, script.toString());

    StringBuilder newPredicate = new StringBuilder();
    newPredicate.append("_").append(fieldName).append(" == true");

    for (QueryParser.QueryTerm t : qt) {
        // Find the location of this term in the criteria
        StringBuilder predicate = new StringBuilder();
        int start = 0;
        if (!t.getOperator().equals(JexlOperatorConstants.getOperator(ParserTreeConstants.JJTFUNCTIONNODE))) {
            predicate.append(fieldName).append(" ").append(t.getOperator()).append(" ").append(t.getValue());
            start = query.indexOf(predicate.toString());
        } else {
            predicate.append(t.getValue().toString());
            // need to find the second occurence of the string.
            start = query.indexOf(predicate.toString());
        }
        if (-1 == start) {
            log.warn("Unable to find predicate: " + predicate.toString() + " in rewritten criteria: "
                    + query.toString());
        }
        int length = predicate.length();

        // Now modify the criteria to check the value of my.fieldName
        query.replace(start, start + length, newPredicate.toString());
    }

    if (log.isDebugEnabled()) {
        log.debug("leaving rewriteQuery with: " + query.toString());
    }
    return query;
}

From source file:org.apache.hive.beeline.BeeLine.java

/**
 * This is an internal method used to create !connect command when -p option is used without
 * providing the password on the command line. Connect command returned should be ; separated
 * key-value pairs along with the url. We cannot use space separated !connect url user [password]
 * [driver] here since both password and driver are optional and there would be no way to
 * distinguish if the last string is password or driver
 *
 * @param url connection url passed using -u argument on the command line
 * @param user username passed through command line
 * @param driver driver passed through command line -d option
 * @param stripPasswd when set to true generates a !connect command which strips the password for
 *          logging purposes/*from w ww.  ja  v a2 s  . c o m*/
 * @return !connect command
 */
private String constructCmdUrl(String url, String user, String driver, boolean stripPasswd) {
    StringBuilder command = new StringBuilder("!connect ");
    command.append(url);
    //if the url does not have a database name add the trailing '/'
    if (isTrailingSlashNeeded(url)) {
        command.append('/');
    }
    command.append(';');
    // if the username is not already available in the URL add the one provided
    if (Utils.parsePropertyFromUrl(url, JdbcConnectionParams.AUTH_USER) == null) {
        command.append(JdbcConnectionParams.AUTH_USER);
        command.append('=');
        command.append((user == null || user.length() == 0 ? "''" : user));
    }
    if (stripPasswd) {
        // if password is available in url it needs to be striped
        int startIndex = command.indexOf(JdbcConnectionParams.AUTH_PASSWD + "=")
                + JdbcConnectionParams.AUTH_PASSWD.length() + 2;
        if (startIndex != -1) {
            int endIndex = command.toString().indexOf(";", startIndex);
            command.replace(startIndex, (endIndex == -1 ? command.length() : endIndex), BeeLine.PASSWD_MASK);
        }
    }
    // if the driver is not already available in the URL add the one provided
    if (Utils.parsePropertyFromUrl(url, JdbcConnectionParams.PROPERTY_DRIVER) == null && driver != null) {
        command.append(';');
        command.append(JdbcConnectionParams.PROPERTY_DRIVER);
        command.append("=");
        command.append(driver);
    }
    return command.toString();
}

From source file:com.MainFiles.Functions.java

public String stringBuilder(String s) {
    StringBuilder sb = new StringBuilder(s);

    int i = 0;//from   ww  w . j  a v a  2 s .com
    while ((i = sb.indexOf(" ", i + 30)) != -1) {
        sb.replace(i, i + 1, "#");
    }
    return sb.toString();
}

From source file:mergedoc.core.Comment.java

/**
 * ????????????/*from w w  w. j av  a  2  s .  c  o m*/
 * ?????????
 * <p>
 * @param lineValue 
 * @param resultBuf ?????
 * @param width ??
 */
private void wrap(String lineValue, StringBuilder resultBuf, int width) {

    final int minWidth = width - 10;
    final int maxWidth = width + 10;
    final int ADJUST_SKIP_WIDTH = width + 4;
    final int lastPos = lineValue.length() - 1;
    final String PUNCTS = "??)}";
    final String PARTICLES = "???????";

    StringBuilder buf = new StringBuilder();
    int bufLen = 0;
    for (int pos = 0; pos < lastPos; pos++) {

        if (bufLen == 0) {
            String after = lineValue.substring(pos, lastPos);
            int afterLen = after.getBytes().length;
            if (afterLen <= ADJUST_SKIP_WIDTH) {
                buf.append(after);
                break;
            }
        }

        char c = lineValue.charAt(pos);
        int cLen = String.valueOf(c).getBytes().length;
        bufLen += cLen;
        boolean isChangeLine = false;

        if (bufLen > minWidth) {
            // ???????????

            if (c == ' ') {

                isChangeLine = true;
                buf.append('\n');

            } else if (PUNCTS.indexOf(c) != -1 || PARTICLES.indexOf(c) != -1) {

                char next = lineValue.charAt(pos + 1);
                if (PUNCTS.indexOf(next) == -1 && next != ' ' && next != '.') {

                    isChangeLine = true;
                    buf.append(c);
                    buf.append('\n');
                }

            } else if (bufLen > width) {
                // ??????
                // ???????????

                if (c == '<' || cLen > 1) {

                    isChangeLine = true;
                    buf.append('\n');
                    buf.append(c);

                } else if (bufLen > maxWidth) {
                    // ??????
                    // ????

                    for (int bPos = buf.length() - 1; bPos > 0; bPos--) {
                        char bc = buf.charAt(bPos);

                        if (bc == ' ') {
                            buf.replace(bPos, bPos + 1, "\n");
                            bufLen = buf.substring(bPos + 1).getBytes().length;
                            break;

                        } else {

                            int bcLen = String.valueOf(bc).getBytes().length;
                            if (bcLen > 1) {
                                buf.insert(bPos + 1, '\n');
                                bufLen = buf.substring(bPos + 2).getBytes().length;
                                break;
                            }
                        }
                    }
                }
            }
        }

        if (isChangeLine) {
            resultBuf.append(buf);
            buf = new StringBuilder();
            bufLen = 0;
        } else {
            buf.append(c);
        }
    }
    buf.append(lineValue.charAt(lastPos));

    resultBuf.append(buf);
    resultBuf.append('\n');
}

From source file:ca.nrc.cadc.vos.server.NodeDAO.java

/**
 * The resulting SQL is a simple select statement. The ResultSet can be
 * processed with a NodeMapper.//from  w  w w.  jav  a2s. co m
 *
 * @param parent The node to query for.
 * @param limit
 * @param withStart
 * @return simple SQL statement select for use with NodeMapper
 */
protected String getSelectNodesByParentSQL(ContainerNode parent, Integer limit, boolean withStart) {
    StringBuilder sb = new StringBuilder();
    sb.append("SELECT nodeID");
    for (String col : NODE_COLUMNS) {
        sb.append(",");
        sb.append(col);
    }
    sb.append(" FROM ");
    sb.append(getNodeTableName());
    Long nid = getNodeID(parent);
    if (nid != null) {
        sb.append(" WHERE parentID = ");
        sb.append(getNodeID(parent));
    } else
        sb.append(" WHERE parentID IS NULL");
    if (withStart)
        sb.append(" AND name >= ?");

    if (withStart || limit != null)
        sb.append(" ORDER BY name");

    if (limit != null) {

        if (nodeSchema.limitWithTop) // TOP, eg sybase
            sb.replace(0, 6, "SELECT TOP " + limit);
        else // LIMIT, eg postgresql
        {
            sb.append(" LIMIT ");
            sb.append(limit);
        }
    }
    return sb.toString();
}

From source file:ca.nrc.cadc.vos.server.NodeDAO.java

protected String getFindOutstandingPropagationsSQL(int limit, boolean dataNodesOnly) {
    StringBuilder sb = new StringBuilder();
    sb.append("SELECT");
    sb.append(" nodeID, type, parentID FROM ");
    sb.append(getNodeTableName());/*from w w  w .j  a va2  s .c om*/
    if (nodeSchema.deltaIndexName != null) {
        sb.append(" (INDEX ");
        sb.append(nodeSchema.deltaIndexName);
        sb.append(")");
    }
    sb.append(" WHERE delta != 0");
    sb.append(" AND ");
    if (dataNodesOnly) {
        sb.append("type = '");
        sb.append(NODE_TYPE_DATA);
        sb.append("'");
    } else {
        sb.append("type IN ('");
        sb.append(NODE_TYPE_DATA);
        sb.append("', '");
        sb.append(NODE_TYPE_CONTAINER);
        sb.append("')");
    }

    if (nodeSchema.limitWithTop) // TOP, eg sybase
        sb.replace(0, 6, "SELECT TOP " + limit);
    else // LIMIT, eg postgresql
    {
        sb.append(" LIMIT ");
        sb.append(limit);
    }

    return sb.toString();
}

From source file:org.apache.accumulo.examples.wikisearch.parser.QueryEvaluator.java

public StringBuilder rewriteQuery(StringBuilder query, String fieldName, Collection<FieldValue> fieldValues) {
    if (log.isDebugEnabled()) {
        log.debug("rewriteQuery");
    }//from www. j  av  a  2  s.  com
    // Here we have a field that has multiple values. In this case we need to put
    // all values into the jexl context as an array and rewrite the query to account for all
    // of the fields.
    if (caseInsensitive) {
        fieldName = fieldName.toLowerCase();
    }
    if (log.isDebugEnabled()) {
        log.debug("Modifying original query: " + query);
    }
    // Pull the values out of the FieldValue object
    String[] values = new String[fieldValues.size()];
    int idx = 0;
    for (FieldValue fv : fieldValues) {
        if (caseInsensitive) {
            values[idx] = (new String(fv.getValue())).toLowerCase();
        } else {
            values[idx] = new String(fv.getValue());
        }
        idx++;
    }
    // Add the array to the context
    ctx.set(fieldName, values);

    Collection<QueryTerm> qt = terms.get(fieldName);

    // Add a script to the beginning of the query for this multi-valued field
    StringBuilder script = new StringBuilder();
    script.append("_").append(fieldName).append(" = false;\n");
    script.append("for (field : ").append(fieldName).append(") {\n");

    for (QueryTerm t : qt) {
        if (!t.getOperator().equals(JexlOperatorConstants.getOperator(ParserTreeConstants.JJTFUNCTIONNODE))) {
            script.append("\tif (_").append(fieldName).append(" == false && field ").append(t.getOperator())
                    .append(" ").append(t.getValue()).append(") { \n");
        } else {
            script.append("\tif (_").append(fieldName).append(" == false && ")
                    .append(t.getValue().toString().replace(fieldName, "field")).append(") { \n");
        }
        script.append("\t\t_").append(fieldName).append(" = true;\n");
        script.append("\t}\n");
    }
    script.append("}\n");

    // Add the script to the beginning of the query
    query.insert(0, script.toString());

    StringBuilder newPredicate = new StringBuilder();
    newPredicate.append("_").append(fieldName).append(" == true");

    for (QueryTerm t : qt) {
        // Find the location of this term in the query
        StringBuilder predicate = new StringBuilder();
        int start = 0;
        if (!t.getOperator().equals(JexlOperatorConstants.getOperator(ParserTreeConstants.JJTFUNCTIONNODE))) {
            predicate.append(fieldName).append(" ").append(t.getOperator()).append(" ").append(t.getValue());
            start = query.indexOf(predicate.toString());
        } else {
            predicate.append(t.getValue().toString());
            // need to find the second occurence of the string.
            start = query.indexOf(predicate.toString());
        }
        if (-1 == start) {
            log.warn("Unable to find predicate: " + predicate.toString() + " in rewritten query: "
                    + query.toString());
        }
        int length = predicate.length();

        // Now modify the query to check the value of my.fieldName
        query.replace(start, start + length, newPredicate.toString());
    }

    if (log.isDebugEnabled()) {
        log.debug("leaving rewriteQuery with: " + query.toString());
    }
    return query;
}