Example usage for java.lang StringBuilder indexOf

List of usage examples for java.lang StringBuilder indexOf

Introduction

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

Prototype

@Override
    public int indexOf(String str) 

Source Link

Usage

From source file:com.jaspersoft.studio.community.utils.CommunityAPIUtils.java

/**
 * Returns the contents of '/etc/lsb-release' (and/or others).
 *///from  w  w  w. j  a  v a2  s. c  om
private static String getLinuxDescription() {
    StringBuilder result = new StringBuilder();
    if (EnvironmentUtils.IS_LINUX) {
        String[] files = new String[] { "/etc/lsb-release", //$NON-NLS-1$
                "/etc/lsb_release", "/etc/system-release", //$NON-NLS-1$ //$NON-NLS-2$
                "/etc/fedora-release", "/etc/SuSE-release", //$NON-NLS-1$ //$NON-NLS-2$
                "/etc/redhat-release", "/etc/release", //$NON-NLS-1$ //$NON-NLS-2$
                "/proc/version_signature", "/proc/version", "/etc/issue", }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        for (int i = 0; i < files.length; i++) {
            File file = new File(files[i]);
            if (file.exists() && file.canRead()) {
                try {
                    String version = IOUtils2.readString(file).trim();
                    if (version != null && result.indexOf(version) == -1) {
                        result.append(version);
                        result.append("\n"); //$NON-NLS-1$
                    }
                } catch (IOException e) {
                    JSSCommunityActivator.getDefault()
                            .logError(MessageFormat.format(Messages.CommunityAPIUtils_ErrorMsgReadingFile,
                                    new Object[] { file.getAbsolutePath() }), e);
                }
            }
        }
    }
    return result.toString();
}

From source file:org.apache.commons.digester3.examples.plugins.pipeline.SubstituteTransform.java

public String transform(String s) {
    StringBuilder buf = new StringBuilder(s);
    while (true) {
        int idx = buf.indexOf(from);
        if (idx == -1) {
            break;
        }/*from  ww  w .ja v a  2  s. c om*/

        buf.replace(idx, idx + from.length(), to);
    }
    return buf.toString();
}

From source file:org.pentaho.di.trans.steps.csvinput.CsvInput.java

/**
 * This method is borrowed from TextFileInput
 *
 * @param log//from  w ww  .j  a  v a 2  s  . c o  m
 *          logger
 * @param line
 *          line to analyze
 * @param delimiter
 *          delimiter used
 * @param enclosure
 *          enclosure used
 * @param escapeCharacter
 *          escape character used
 * @return list of string detected
 * @throws KettleException
 */
public static String[] guessStringsFromLine(LogChannelInterface log, String line, String delimiter,
        String enclosure, String escapeCharacter) throws KettleException {
    List<String> strings = new ArrayList<String>();

    String pol; // piece of line

    try {
        if (line == null) {
            return null;
        }

        // Split string in pieces, only for CSV!

        int pos = 0;
        int length = line.length();
        boolean dencl = false;

        int len_encl = (enclosure == null ? 0 : enclosure.length());
        int len_esc = (escapeCharacter == null ? 0 : escapeCharacter.length());

        while (pos < length) {
            int from = pos;
            int next;

            boolean encl_found;
            boolean contains_escaped_enclosures = false;
            boolean contains_escaped_separators = false;

            // Is the field beginning with an enclosure?
            // "aa;aa";123;"aaa-aaa";000;...
            if (len_encl > 0 && line.substring(from, from + len_encl).equalsIgnoreCase(enclosure)) {
                if (log.isRowLevel()) {
                    log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"),
                            BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRow",
                                    line.substring(from, from + len_encl)));
                }
                encl_found = true;
                int p = from + len_encl;

                boolean is_enclosure = len_encl > 0 && p + len_encl < length
                        && line.substring(p, p + len_encl).equalsIgnoreCase(enclosure);
                boolean is_escape = len_esc > 0 && p + len_esc < length
                        && line.substring(p, p + len_esc).equalsIgnoreCase(escapeCharacter);

                boolean enclosure_after = false;

                // Is it really an enclosure? See if it's not repeated twice or escaped!
                if ((is_enclosure || is_escape) && p < length - 1) {
                    String strnext = line.substring(p + len_encl, p + 2 * len_encl);
                    if (strnext.equalsIgnoreCase(enclosure)) {
                        p++;
                        enclosure_after = true;
                        dencl = true;

                        // Remember to replace them later on!
                        if (is_escape) {
                            contains_escaped_enclosures = true;
                        }
                    }
                }

                // Look for a closing enclosure!
                while ((!is_enclosure || enclosure_after) && p < line.length()) {
                    p++;
                    enclosure_after = false;
                    is_enclosure = len_encl > 0 && p + len_encl < length
                            && line.substring(p, p + len_encl).equals(enclosure);
                    is_escape = len_esc > 0 && p + len_esc < length
                            && line.substring(p, p + len_esc).equals(escapeCharacter);

                    // Is it really an enclosure? See if it's not repeated twice or escaped!
                    if ((is_enclosure || is_escape) && p < length - 1) {
                        String strnext = line.substring(p + len_encl, p + 2 * len_encl);
                        if (strnext.equals(enclosure)) {
                            p++;
                            enclosure_after = true;
                            dencl = true;

                            // Remember to replace them later on!
                            if (is_escape) {
                                contains_escaped_enclosures = true; // remember
                            }
                        }
                    }
                }

                if (p >= length) {
                    next = p;
                } else {
                    next = p + len_encl;
                }

                if (log.isRowLevel()) {
                    log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"),
                            BaseMessages.getString(PKG, "CsvInput.Log.EndOfEnclosure", "" + p));
                }
            } else {
                encl_found = false;
                boolean found = false;
                int startpoint = from;
                do {
                    next = line.indexOf(delimiter, startpoint);

                    // See if this position is preceded by an escape character.
                    if (len_esc > 0 && next - len_esc > 0) {
                        String before = line.substring(next - len_esc, next);

                        if (escapeCharacter != null && escapeCharacter.equals(before)) {
                            // take the next separator, this one is escaped...
                            startpoint = next + 1;
                            contains_escaped_separators = true;
                        } else {
                            found = true;
                        }
                    } else {
                        found = true;
                    }
                } while (!found && next >= 0);
            }
            if (next == -1) {
                next = length;
            }

            if (encl_found) {
                pol = line.substring(from + len_encl, next - len_encl);
                if (log.isRowLevel()) {
                    log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"),
                            BaseMessages.getString(PKG, "CsvInput.Log.EnclosureFieldFound", "" + pol));
                }
            } else {
                pol = line.substring(from, next);
                if (log.isRowLevel()) {
                    log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"),
                            BaseMessages.getString(PKG, "CsvInput.Log.NormalFieldFound", "" + pol));
                }
            }

            if (dencl) {
                StringBuilder sbpol = new StringBuilder(pol);
                int idx = sbpol.indexOf(enclosure + enclosure);
                while (idx >= 0) {
                    sbpol.delete(idx, idx + (enclosure == null ? 0 : enclosure.length()));
                    idx = sbpol.indexOf(enclosure + enclosure);
                }
                pol = sbpol.toString();
            }

            // replace the escaped enclosures with enclosures...
            if (contains_escaped_enclosures) {
                String replace = escapeCharacter + enclosure;
                pol = Const.replace(pol, replace, enclosure);
            }

            // replace the escaped separators with separators...
            if (contains_escaped_separators) {
                String replace = escapeCharacter + delimiter;
                pol = Const.replace(pol, replace, delimiter);
            }

            // Now add pol to the strings found!
            strings.add(pol);

            pos = next + delimiter.length();
        }
        if (pos == length) {
            if (log.isRowLevel()) {
                log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"),
                        BaseMessages.getString(PKG, "CsvInput.Log.EndOfEmptyLineFound"));
            }
            strings.add("");
        }
    } catch (Exception e) {
        throw new KettleException(
                BaseMessages.getString(PKG, "CsvInput.Log.Error.ErrorConvertingLine", e.toString()), e);
    }

    return strings.toArray(new String[strings.size()]);
}

From source file:com.forerunnergames.tools.common.Strings.java

/**
 * Checks whether the specified string is contained in the specified StringBuilder.
 *
 * @param stringBuilder/*from  www  .  j  a v a2 s.  c  o m*/
 *          The StringBuilder, must not be null.
 * @param s
 *          The string, must not be null.
 *
 * @return true if at least one instance of s is contained within stringBuilder, false otherwise
 */
public static boolean contains(final StringBuilder stringBuilder, final String s) {
    Arguments.checkIsNotNull(stringBuilder, "stringbuilder");
    Arguments.checkIsNotNullOrEmptyOrBlank(s, "s");

    return stringBuilder.indexOf(s) > -1;
}

From source file:de.terministic.serein.core.StatsListener.java

private String ArrayToString(double[] array) {
    StringBuilder result = new StringBuilder();
    for (double d : array) {
        StringBuilder str = new StringBuilder("        ");
        str.append(f.format(d));//from   w  w  w. j  ava2 s . c o m
        int i = str.indexOf(".");
        if (i > 0) {
            str.append("0000");
            result.append(str.substring(i - 8, i + 7));
        } else {
            result.append(str.substring(str.length() - 9));
        }
        result.append("\t");
    }
    return result.toString();
}

From source file:org.pentaho.di.trans.steps.fileinput.text.TextFileInputUtils.java

public static final String[] guessStringsFromLine(VariableSpace space, LogChannelInterface log, String line,
        TextFileInputMeta inf, String delimiter, String enclosure, String escapeCharacter)
        throws KettleException {
    List<String> strings = new ArrayList<>();

    String pol; // piece of line

    try {//from  w w w.  ja va  2s.  c  o m
        if (line == null) {
            return null;
        }

        if (inf.content.fileType.equalsIgnoreCase("CSV")) {

            // Split string in pieces, only for CSV!

            int pos = 0;
            int length = line.length();
            boolean dencl = false;

            int len_encl = (enclosure == null ? 0 : enclosure.length());
            int len_esc = (escapeCharacter == null ? 0 : escapeCharacter.length());

            while (pos < length) {
                int from = pos;
                int next;

                boolean encl_found;
                boolean contains_escaped_enclosures = false;
                boolean contains_escaped_separators = false;
                boolean contains_escaped_escape = false;

                // Is the field beginning with an enclosure?
                // "aa;aa";123;"aaa-aaa";000;...
                if (len_encl > 0 && line.substring(from, from + len_encl).equalsIgnoreCase(enclosure)) {
                    if (log.isRowLevel()) {
                        log.logRowlevel(BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRowTitle"),
                                BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRow",
                                        line.substring(from, from + len_encl)));
                    }
                    encl_found = true;
                    int p = from + len_encl;

                    boolean is_enclosure = len_encl > 0 && p + len_encl < length
                            && line.substring(p, p + len_encl).equalsIgnoreCase(enclosure);
                    boolean is_escape = len_esc > 0 && p + len_esc < length
                            && line.substring(p, p + len_esc).equalsIgnoreCase(escapeCharacter);

                    boolean enclosure_after = false;

                    // Is it really an enclosure? See if it's not repeated twice or escaped!
                    if ((is_enclosure || is_escape) && p < length - 1) {
                        String strnext = line.substring(p + len_encl, p + 2 * len_encl);
                        if (strnext.equalsIgnoreCase(enclosure)) {
                            p++;
                            enclosure_after = true;
                            dencl = true;

                            // Remember to replace them later on!
                            if (is_escape) {
                                contains_escaped_enclosures = true;
                            }
                        } else if (strnext.equals(escapeCharacter)) {
                            p++;
                            // Remember to replace them later on!
                            if (is_escape) {
                                contains_escaped_escape = true; // remember
                            }
                        }
                    }

                    // Look for a closing enclosure!
                    while ((!is_enclosure || enclosure_after) && p < line.length()) {
                        p++;
                        enclosure_after = false;
                        is_enclosure = len_encl > 0 && p + len_encl < length
                                && line.substring(p, p + len_encl).equals(enclosure);
                        is_escape = len_esc > 0 && p + len_esc < length
                                && line.substring(p, p + len_esc).equals(escapeCharacter);

                        // Is it really an enclosure? See if it's not repeated twice or escaped!
                        if ((is_enclosure || is_escape) && p < length - 1) {

                            String strnext = line.substring(p + len_encl, p + 2 * len_encl);
                            if (strnext.equals(enclosure)) {
                                p++;
                                enclosure_after = true;
                                dencl = true;

                                // Remember to replace them later on!
                                if (is_escape) {
                                    contains_escaped_enclosures = true; // remember
                                }
                            } else if (strnext.equals(escapeCharacter)) {
                                p++;
                                // Remember to replace them later on!
                                if (is_escape) {
                                    contains_escaped_escape = true; // remember
                                }
                            }
                        }
                    }

                    if (p >= length) {
                        next = p;
                    } else {
                        next = p + len_encl;
                    }

                    if (log.isRowLevel()) {
                        log.logRowlevel(BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRowTitle"),
                                BaseMessages.getString(PKG, "TextFileInput.Log.EndOfEnclosure", "" + p));
                    }
                } else {
                    encl_found = false;
                    boolean found = false;
                    int startpoint = from;
                    // int tries = 1;
                    do {
                        next = line.indexOf(delimiter, startpoint);

                        // See if this position is preceded by an escape character.
                        if (len_esc > 0 && next - len_esc > 0) {
                            String before = line.substring(next - len_esc, next);

                            if (escapeCharacter.equals(before)) {
                                // take the next separator, this one is escaped...
                                startpoint = next + 1;
                                // tries++;
                                contains_escaped_separators = true;
                            } else {
                                found = true;
                            }
                        } else {
                            found = true;
                        }
                    } while (!found && next >= 0);
                }
                if (next == -1) {
                    next = length;
                }

                if (encl_found) {
                    pol = line.substring(from + len_encl, next - len_encl);
                    if (log.isRowLevel()) {
                        log.logRowlevel(BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRowTitle"),
                                BaseMessages.getString(PKG, "TextFileInput.Log.EnclosureFieldFound", "" + pol));
                    }
                } else {
                    pol = line.substring(from, next);
                    if (log.isRowLevel()) {
                        log.logRowlevel(BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRowTitle"),
                                BaseMessages.getString(PKG, "TextFileInput.Log.NormalFieldFound", "" + pol));
                    }
                }

                if (dencl) {
                    StringBuilder sbpol = new StringBuilder(pol);
                    int idx = sbpol.indexOf(enclosure + enclosure);
                    while (idx >= 0) {
                        sbpol.delete(idx, idx + enclosure.length());
                        idx = sbpol.indexOf(enclosure + enclosure);
                    }
                    pol = sbpol.toString();
                }

                // replace the escaped enclosures with enclosures...
                if (contains_escaped_enclosures) {
                    String replace = escapeCharacter + enclosure;
                    String replaceWith = enclosure;

                    pol = Const.replace(pol, replace, replaceWith);
                }

                // replace the escaped separators with separators...
                if (contains_escaped_separators) {
                    String replace = escapeCharacter + delimiter;
                    String replaceWith = delimiter;

                    pol = Const.replace(pol, replace, replaceWith);
                }

                // replace the escaped escape with escape...
                if (contains_escaped_escape) {
                    String replace = escapeCharacter + escapeCharacter;
                    String replaceWith = escapeCharacter;

                    pol = Const.replace(pol, replace, replaceWith);
                }

                // Now add pol to the strings found!
                strings.add(pol);

                pos = next + delimiter.length();
            }
            if (pos == length) {
                if (log.isRowLevel()) {
                    log.logRowlevel(BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRowTitle"),
                            BaseMessages.getString(PKG, "TextFileInput.Log.EndOfEmptyLineFound"));
                }
                strings.add("");
            }
        } else {
            // Fixed file format: Simply get the strings at the required positions...
            for (int i = 0; i < inf.inputFields.length; i++) {
                BaseFileField field = inf.inputFields[i];

                int length = line.length();

                if (field.getPosition() + field.getLength() <= length) {
                    strings.add(line.substring(field.getPosition(), field.getPosition() + field.getLength()));
                } else {
                    if (field.getPosition() < length) {
                        strings.add(line.substring(field.getPosition()));
                    } else {
                        strings.add("");
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new KettleException(
                BaseMessages.getString(PKG, "TextFileInput.Log.Error.ErrorConvertingLine", e.toString()), e);
    }

    return strings.toArray(new String[strings.size()]);
}

From source file:nz.net.orcon.kanban.automation.plugin.TemplatePlugin.java

private void replaceAll(String field, String value, StringBuilder builder) {

    int x = 0;//from   ww  w  . ja  v a2 s.  c  om
    String toFind = "${" + field + "}";
    while (x >= 0) {
        x = builder.indexOf(toFind);
        if (x >= 0) {
            builder.replace(x, x + toFind.length(), value);
        }
    }
}

From source file:org.alfresco.web.app.servlet.BaseServlet.java

/**
 * Redirect to the Login page - saving the current URL which can be redirected back later
 * once the user has successfully completed the authentication process.
 * @param sendRedirect allow a redirect status code to be set? If <code>false</code> redirect
 * will be via markup rather than status code (to allow the status code to be used for handshake
 * responses etc.//from  ww w. j  ava2s .  com
 */
public static void redirectToLoginPage(HttpServletRequest req, HttpServletResponse res, ServletContext sc,
        boolean sendRedirect) throws IOException {
    // Pass the full requested URL as a parameter so the login page knows where to redirect to later
    final String uri = req.getRequestURI();
    String redirectURL = uri;

    // authentication failed - so end servlet execution and redirect to login page
    if (WebApplicationContextUtils.getRequiredWebApplicationContext(sc)
            .containsBean(Application.BEAN_CONFIG_SERVICE)) {
        StringBuilder redirect = new StringBuilder(128).append(req.getContextPath()).append(FACES_SERVLET)
                .append(Application.getLoginPage(sc));

        // if we find a JSF servlet reference in the URI then we need to check if the rest of the
        // JSP specified is valid for a redirect operation after Login has occured.
        int jspIndex;
        if (uri.indexOf(req.getContextPath() + FACES_SERVLET) == -1 || uri
                .length() > (jspIndex = uri.indexOf(BaseServlet.FACES_SERVLET)
                        + BaseServlet.FACES_SERVLET.length())
                && BaseServlet.validRedirectJSP(uri.substring(jspIndex))) {
            if (redirect.indexOf("?") == -1) {
                redirect.append('?');
            } else {
                redirect.append('&');
            }
            redirect.append(LoginOutcomeBean.PARAM_REDIRECT_URL);
            redirect.append('=');
            String url = uri;

            // Append the query string if necessary
            String queryString = req.getQueryString();
            if (queryString != null) {
                // Strip out leading ticket arguments
                queryString = queryString.replaceAll("(?<=^|&)" + ARG_TICKET + "(=[^&=]*)?&", "");
                // Strip out trailing ticket arguments
                queryString = queryString.replaceAll("(^|&)" + ARG_TICKET + "(=[^&=]*)?(?=&|$)", "");
                if (queryString.length() != 0) {
                    url += "?" + queryString;
                }
            }
            redirect.append(URLEncoder.encode(url, "UTF-8"));
        }
        redirectURL = redirect.toString();
    }
    // If external authentication isn't in use (e.g. proxied share authentication), it's safe to return a redirect to the client
    if (sendRedirect) {
        res.sendRedirect(redirectURL);
    }
    // Otherwise, we must signal to the client with an unauthorized status code and rely on a browser refresh to do
    // the redirect for failover login (as we do with NTLM, Kerberos)
    else {
        res.setContentType("text/html; charset=UTF-8");
        res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        final PrintWriter out = res.getWriter();
        out.println("<html><head>");
        out.println("<meta http-equiv=\"Refresh\" content=\"0; url=" + redirectURL + "\">");
        out.println("</head><body><p>Please <a href=\"" + redirectURL + "\">log in</a>.</p>");
        out.println("</body></html>");
        out.close();
    }
}

From source file:raptor.swt.RaptorStyledText.java

@Override
public void copy() {
    if ((getStyle() & SWT.SINGLE) != 0) {
        super.copy();
    } else {//  w  w  w  .  j  a  v a2 s. c om
        String text = getSelectionText();
        if (!StringUtils.isEmpty(text)) {
            // TO DO: This really should be moved down into the connector.
            // Currently, however, that is not needed .
            if (text.startsWith("http")) {
                StringBuilder builder = new StringBuilder(text);
                int newLineIndex = builder.indexOf("\n\\");

                while (newLineIndex != -1) {
                    int cursor = newLineIndex + 2;
                    while (Character.isWhitespace(builder.charAt(cursor))) {
                        cursor++;
                    }
                    if (cursor > newLineIndex + 2) {
                        builder.delete(newLineIndex, cursor);
                    }
                    newLineIndex = builder.indexOf("\n\\", newLineIndex + 1);
                }
                text = builder.toString();

            } else {
                text = IcsUtils.removeLineBreaks(text);
            }

            clipBoard.setContents(new Object[] { text }, new Transfer[] { TextTransfer.getInstance() },
                    DND.CLIPBOARD);
        }
    }
}

From source file:org.glite.lb.NotifParser.java

/**
 * this method creates an XML document out of a provided String
 * note that the string has to be a valid escaped XML document representation,
 * otherwise the process will fail/*from   w  w w. j  a  v a 2  s.c o  m*/
 *
 * @param body a String containing an XML document
 * @return an XML document in the Document format
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws org.xml.sax.SAXException
 * @throws java.io.IOException
 */
private Document createXML(String body) throws ParserConfigurationException, SAXException, IOException {
    String removed = body.substring(0, body.length() - 1);
    String parsed = StringEscapeUtils.unescapeXml(removed);
    //this code removes hexadecimal references from the string (couldn't find
    //a suitable parser for this)
    StringBuilder build = new StringBuilder(parsed);
    int j = build.indexOf("%");
    while (j > 0) {
        if (build.charAt(j - 1) == '>') {
            build.delete(j, j + 3);
            if (build.charAt(j) == '<') {
                j = build.indexOf("%");
            }
        } else {
            j = build.indexOf("%", j + 1);
        }
    }
    parsed = build.toString();
    //ends here
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    return factory.newDocumentBuilder().parse(new InputSource(new StringReader(parsed)));
}