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.google.code.maven.plugin.http.client.Request.java

/**
 * url getter./*from  www .ja  v  a  2  s. c  om*/
 * 
 * @return the url
 * @throws MalformedURLException
 * @throws
 */
private void parseUrl() throws MojoExecutionException {
    if (finalUrl == null) {
        StringBuilder builder = new StringBuilder(url);
        if ("get".equalsIgnoreCase(method) && parameters != null && parameters.length > 0) {
            for (int i = 0; i < parameters.length; i++) {
                if (i == 0 && builder.indexOf("?") < 0) {
                    builder.append("?");
                } else {
                    builder.append("&");
                }
                try {
                    builder.append(parameters[i].toUrlParameter());
                } catch (EncoderException ee) {
                    throw new MojoExecutionException("malformed parameter " + parameters[i], ee);
                }
            }
        }
        try {
            finalUrl = new URL(builder.toString());
        } catch (MalformedURLException mue) {
            throw new MojoExecutionException("failed to parse url " + url, mue);
        }
    }
}

From source file:org.wso2.carbon.identity.mgt.store.InMemoryIdentityDataStore.java

@Override
public UserIdentityClaimsDO load(String userName, UserStoreManager userStoreManager) {

    Cache<String, UserIdentityClaimsDO> cache = getCache();
    if (userName != null && cache != null) {
        if (userStoreManager instanceof org.wso2.carbon.user.core.UserStoreManager) {
            if (!IdentityUtil
                    .isUserStoreCaseSensitive((org.wso2.carbon.user.core.UserStoreManager) userStoreManager)) {
                if (log.isDebugEnabled()) {
                    log.debug("Case insensitive user store found. Changing username from : " + userName
                            + " to : " + userName.toLowerCase());
                }/*www  .j  ava  2s . c om*/
                userName = userName.toLowerCase();
            }
        }

        org.wso2.carbon.user.core.UserStoreManager store = (org.wso2.carbon.user.core.UserStoreManager) userStoreManager;

        String domainName = store.getRealmConfiguration()
                .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);

        UserIdentityClaimsDO userIdentityDTO = (UserIdentityClaimsDO) cache
                .get(domainName + CarbonContext.getThreadLocalCarbonContext().getTenantId() + userName);

        if (userIdentityDTO != null && log.isDebugEnabled()) {
            StringBuilder data = new StringBuilder("{");
            if (userIdentityDTO.getUserIdentityDataMap() != null) {
                for (Map.Entry<String, String> entry : userIdentityDTO.getUserIdentityDataMap().entrySet()) {
                    data.append("[" + entry.getKey() + " = " + entry.getValue() + "], ");
                }
            }
            if (data.indexOf(",") >= 0) {
                data.deleteCharAt(data.lastIndexOf(","));
            }
            data.append("}");
            log.debug("Loaded UserIdentityClaimsDO from cache for user :" + userName + " with claims: " + data);

        }
        return userIdentityDTO;
    }
    return null;
}

From source file:com.gargoylesoftware.htmlunit.WebConsole.java

/**
 * This method is used by all the public method to process the passed
 * parameters./*from  ww  w.ja  v a  2  s.co  m*/
 *
 * If the last parameter implements the Formatter interface, it will be
 * used to format the parameters and print the object.
 * @param objs the logging parameters
 * @return a String to be printed using the logger
 */
private String process(final Object[] objs) {
    if (objs == null) {
        return "null";
    }

    final StringBuffer sb = new StringBuffer();
    final LinkedList<Object> args = new LinkedList<>(Arrays.asList(objs));

    final Formatter formatter = getFormatter();

    if (args.size() > 1 && args.get(0) instanceof String) {
        final StringBuilder msg = new StringBuilder((String) args.remove(0));
        int startPos = msg.indexOf("%");

        while (startPos > -1 && startPos < msg.length() - 1 && args.size() > 0) {
            if (startPos != 0 && msg.charAt(startPos - 1) == '%') {
                // double %
                msg.replace(startPos, startPos + 1, "");
            } else {
                final char type = msg.charAt(startPos + 1);
                String replacement = null;
                switch (type) {
                case 'o':
                case 's':
                    replacement = formatter.parameterAsString(pop(args));
                    break;
                case 'd':
                case 'i':
                    replacement = formatter.parameterAsInteger(pop(args));
                    break;
                case 'f':
                    replacement = formatter.parameterAsFloat(pop(args));
                    break;
                default:
                    break;
                }
                if (replacement != null) {
                    msg.replace(startPos, startPos + 2, replacement);
                    startPos = startPos + replacement.length();
                } else {
                    startPos++;
                }
            }
            startPos = msg.indexOf("%", startPos);
        }
        sb.append(msg);
    }

    for (final Object o : args) {
        if (sb.length() != 0) {
            sb.append(' ');
        }
        sb.append(formatter.printObject(o));
    }
    return sb.toString();
}

From source file:sapience.injectors.stax.inject.StringBasedStaxStreamInjector.java

/**
 * Helper method, takes an XML reference with local namespace definitions, and returns the namespaces as QNames
 * @param xml// w w w  .  ja v  a2s  . c  o  m
 * @return
 */
private List<QName> extractNamespaces(String xml) {
    List<QName> res = new ArrayList<QName>();

    Matcher nsMatcher = nsPattern.matcher(xml);
    while (nsMatcher.find()) {
        int start = nsMatcher.start();
        int end = nsMatcher.end();
        StringBuilder sbu = new StringBuilder(xml.substring(start, end));
        String prefix = sbu.substring(sbu.indexOf(":") + 1, sbu.lastIndexOf("="));
        String uri = sbu.substring(sbu.indexOf("\"") + 1, sbu.lastIndexOf("\""));
        res.add(new QName(uri, prefix));
    }
    return res;
}

From source file:com.admc.jcreole.JCreole.java

/**
 * Generates clean html-expanded HTML with specified EOL type.
 * If 'pageBoilerPlate' is set for this JCreole instance, then will return
 * an html-expanded, eol-converted merge of the page boilerplate with
 * embedded HTML fragment.//from  ww  w . j  ava2 s . c om
 * Otherwise will just return the supplied fragment with the Eols converted
 * as necessary and html variable expansion.
 * <p>
 * Call like <PRE>
 *    postProcess(htmlFrag, System.getProperty("line.separator"));
 * to have output match your local platform default.
 * </p> <p>
 * Input htmlFrag doesn't need to worry about line delimiters, because it
 * will be cleaned up as required.
 * </p> <p>
 * If you are using no boilerplate and want \n line delimiters in output,
 * then it is more efficient to just call htmlExpand() instead of this
 * method.
 * </p> <p>
 * This method implementation has dependencies on the provide boilerplates
 * or others that follow its conventions.
 * </p>
 *
 * @param outputEol  Line delimiters for output.  Null to leave as \n's.
 * @throws if can not generate output, or if the run generates 0 output.
 *         If the problem is due to input formatting, in most cases you
 *         will get a CreoleParseException, which is a RuntimException, and
 *         CreoleParseException has getters for locations in the source
 *         data (though they will be offset for \r's in the provided
 *         Creole source, if any).
 */
public String postProcess(String htmlFrag, String outputEol) throws IOException {
    String htmlString = null;
    if (pageBoilerPlate == null) {
        htmlString = htmlFrag;
    } else {
        StringBuilder html = new StringBuilder(pageBoilerPlate);
        if (html.indexOf("$(pageHeaders)") > -1 || html.indexOf("$(!pageHeaders)") > -1) {
            StringBuilder sb = new StringBuilder();
            int count = 0;
            for (String href : getCssHrefs())
                sb.append(String.format("<link id=\"auto%02d\" class=\"auto\" " + "rel=\"stylesheet\" "
                        + "type=\"text/css\" href=\"%s\" />\n", ++count, href));
            framingExpander.put("pageHeaders", sb.toString(), false);
        } else if (getCssHrefs().size() > 0) {
            throw new CreoleParseException(
                    "Author-supplied style-sheets, but boilerplate has no " + "'pageHeaders' insertion-point");
        }
        framingExpander.put("pageContent", htmlFrag, false);
        htmlString = framingExpander.expand(html).toString();
    }
    if (outputEol != null && !outputEol.equals("\n"))
        htmlString = htmlString.replace("\n", outputEol);
    // Amazing that StringBuilder can't do a multi-replace like this
    return htmlExpand(htmlString);
}

From source file:org.schemaspy.view.StyleSheet.java

private StyleSheet(BufferedReader cssReader) throws IOException {
    String lineSeparator = System.getProperty("line.separator");
    StringBuilder data = new StringBuilder();
    String line;/*  w w  w .ja  v  a  2s  . co m*/

    while ((line = cssReader.readLine()) != null) {
        data.append(line);
        data.append(lineSeparator);
    }

    css = data.toString();

    int startComment = data.indexOf("/*");
    while (startComment != -1) {
        int endComment = data.indexOf("*/");
        data.replace(startComment, endComment + 2, "");
        startComment = data.indexOf("/*");
    }

    StringTokenizer tokenizer = new StringTokenizer(data.toString(), "{}");
    String id = null;
    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken().trim();
        if (id == null) {
            id = token.toLowerCase();
            ids.add(id);
        } else {
            Map<String, String> attribs = parseAttributes(token);
            if (id.equals(".diagram"))
                bodyBackgroundColor = attribs.get("background");
            else if (id.equals("th.diagram"))
                tableHeadBackgroundColor = attribs.get("background-color");
            else if (id.equals("td.diagram"))
                tableBackgroundColor = attribs.get("background-color");
            else if (id.equals(".diagram .primarykey"))
                primaryKeyBackgroundColor = attribs.get("background");
            else if (id.equals(".diagram .indexedcolumn"))
                indexedColumnBackgroundColor = attribs.get("background");
            else if (id.equals(".selectedtable"))
                selectedTableBackgroundColor = attribs.get("background");
            else if (id.equals(".excludedcolumn"))
                excludedColumnBackgroundColor = attribs.get("background");
            else if (id.equals("a:link"))
                linkColor = attribs.get("color");
            else if (id.equals("a:visited"))
                linkVisitedColor = attribs.get("color");
            id = null;
        }
    }
}

From source file:xyz.monotalk.social.mixcloud.Requester.java

/**
 * get method/*  ww w  .  ja v a  2s  .  co  m*/
 *
 * @return
 */
public R get() {
    // new instance
    HttpClient httpClient = newHttpClient();

    // new HttpGet
    StringBuilder sb = new StringBuilder("");
    String path = pathable.toPath();
    if (path.startsWith("https://api.mixcloud.com/") || path.startsWith("http://api.mixcloud.com/")) {
        sb.append(path);
    } else {
        sb.append("https://api.mixcloud.com/");
        sb.append(path);
    }
    if (appendMetadata) {
        if (sb.indexOf("?") == -1) {
            sb.append("?metadata=1");
        } else {
            sb.append("&metadata=1");
        }
    }
    if (limit != null) {
        if (sb.indexOf("?") == -1) {
            sb.append("?limit=");
            sb.append(limit.toString());

        } else {
            sb.append("&limit=");
            sb.append(limit.toString());
        }
    }

    if (offset != null) {
        if (sb.indexOf("?") == -1) {
            sb.append("?offset=");
            sb.append(offset.toString());

        } else {
            sb.append("&offset=");
            sb.append(offset.toString());
        }
    }

    String url = sb.toString();

    // ------------------------------------
    // Console OUT
    // --------------------------
    println(">>>>>>>>>>>>URL=");
    println(url);
    println("<<<<<<<<<<<<");

    HttpGet httpGet = new HttpGet(url);

    try {
        return httpClient.execute(httpGet, new MixCloudResponseHandler<>(pathable));
    } catch (IOException ex) {
        throw new MixCloudResponseRuntimeException(ex);
    }
}

From source file:com.panet.imeta.trans.steps.textfileinput.TextFileInput.java

public static final String[] guessStringsFromLine(String line, TextFileInputMeta inf) throws KettleException {
    List<String> strings = new ArrayList<String>();
    int fieldnr;/* ww w . j  av a  2s  .c  om*/

    String pol; // piece of line

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

        if (inf.getFileType().equalsIgnoreCase("CSV")) {
            // Split string in pieces, only for CSV!

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

            int len_encl = (inf.getEnclosure() == null ? 0 : inf.getEnclosure().length());
            int len_esc = (inf.getEscapeCharacter() == null ? 0 : inf.getEscapeCharacter().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(inf.getEnclosure())) {
                    if (log.isRowLevel())
                        log.logRowlevel(Messages.getString("TextFileInput.Log.ConvertLineToRowTitle"),
                                Messages.getString("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(inf.getEnclosure());
                    boolean is_escape = len_esc > 0 && p + len_esc < length
                            && line.substring(p, p + len_esc).equalsIgnoreCase(inf.getEscapeCharacter());

                    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(inf.getEnclosure())) {
                            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(inf.getEnclosure());
                        is_escape = len_esc > 0 && p + len_esc < length
                                && line.substring(p, p + len_esc).equals(inf.getEscapeCharacter());

                        // Is it really an enclosure? See if it's not repeated twice or escaped!
                        if ((is_enclosure || is_escape) && p < length - 1) // Is
                        {
                            String strnext = line.substring(p + len_encl, p + 2 * len_encl);
                            if (strnext.equals(inf.getEnclosure())) {
                                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(Messages.getString("TextFileInput.Log.ConvertLineToRowTitle"),
                                Messages.getString("TextFileInput.Log.EndOfEnclosure", "" + p));
                } else {
                    encl_found = false;
                    boolean found = false;
                    int startpoint = from;
                    int tries = 1;
                    do {
                        next = line.indexOf(inf.getSeparator(), 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 (inf.getEscapeCharacter().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(Messages.getString("TextFileInput.Log.ConvertLineToRowTitle"),
                                Messages.getString("TextFileInput.Log.EnclosureFieldFound", "" + pol));
                } else {
                    pol = line.substring(from, next);
                    if (log.isRowLevel())
                        log.logRowlevel(Messages.getString("TextFileInput.Log.ConvertLineToRowTitle"),
                                Messages.getString("TextFileInput.Log.NormalFieldFound", "" + pol));
                }

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

                //   replace the escaped enclosures with enclosures... 
                if (contains_escaped_enclosures) {
                    String replace = inf.getEscapeCharacter() + inf.getEnclosure();
                    String replaceWith = inf.getEnclosure();

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

                //replace the escaped separators with separators... 
                if (contains_escaped_separators) {
                    String replace = inf.getEscapeCharacter() + inf.getSeparator();
                    String replaceWith = inf.getSeparator();

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

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

                pos = next + inf.getSeparator().length();
                fieldnr++;
            }
            if (pos == length) {
                if (log.isRowLevel())
                    log.logRowlevel(Messages.getString("TextFileInput.Log.ConvertLineToRowTitle"),
                            Messages.getString("TextFileInput.Log.EndOfEmptyLineFound"));
                strings.add("");
                fieldnr++;
            }
        } else {
            // Fixed file format: Simply get the strings at the required positions...
            for (int i = 0; i < inf.getInputFields().length; i++) {
                TextFileInputField field = inf.getInputFields()[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(
                Messages.getString("TextFileInput.Log.Error.ErrorConvertingLine", e.toString()), e);
    }

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

From source file:chat.viska.xmpp.NettyTcpSession.java

private Document preprocessInboundXml(final String xml) throws SAXException {
    final StringBuilder builder = new StringBuilder(xml);
    final String openingPrefixBlock = '<' + serverStreamPrefix + ':';
    final String closingPrefixBlock = "</" + serverStreamPrefix + ':';
    final int openingPrefixBlockIdx = builder.indexOf(openingPrefixBlock);
    final int firstXmlnsIdx = builder.indexOf(" xmlns=") + 1;

    if (openingPrefixBlockIdx == 0) {
        // Remove <stream: prefix and add namespace block
        builder.delete(1, 1 + serverStreamPrefix.length() + 1);
        final int closingPrefixBlockIdx = builder.indexOf(closingPrefixBlock);
        builder.delete(closingPrefixBlockIdx + 2, closingPrefixBlockIdx + 2 + serverStreamPrefix.length() + 1);
        builder.insert(builder.indexOf(">"), String.format(" xmlns=\"%1s\"", CommonXmlns.STREAM_HEADER));
    } else if (firstXmlnsIdx < 0 || firstXmlnsIdx > builder.indexOf(">")) {
        // No xmlns for the root, which means a stanza
        builder.insert(builder.indexOf(">"), String.format(" xmlns=\"%1s\"", CommonXmlns.STANZA_CLIENT));
    }/*from   w w w  .  j  a  va2 s.c  o m*/
    return DomUtils.readDocument(builder.toString());
}

From source file:wicket.protocol.http.request.AbstractWebRequestCodingStrategy.java

/**
 * Adds (shared) resource related parameters (resource key). Any shared
 * resource key mount will override this method; hence if a mount is found,
 * this method will not be called.//from  ww w.  j  av  a  2 s.  co m
 * 
 * If you override this method to behave different then also
 * {@link #encode(RequestCycle, ISharedResourceRequestTarget)} should be
 * overridden to by in sync with that behaviour.
 * 
 * @param request
 *            the incomming request
 * @param parameters
 *            the parameters object to set the found values on
 */
protected void addResourceParameters(Request request, RequestParameters parameters) {
    String pathInfo = request.getPath();
    if (pathInfo != null) {
        if (pathInfo.startsWith("/")) {
            pathInfo = pathInfo.substring(1);
        }
        if (pathInfo.startsWith("resources/")) {
            int ix = "resources/".length();
            if (pathInfo.length() > ix) {
                StringBuilder path = new StringBuilder(pathInfo.substring(ix));
                int ixSemiColon = path.indexOf(";");
                // strip off any jsession id
                if (ixSemiColon != -1) {
                    int ixEnd = path.indexOf("?");
                    if (ixEnd == -1) {
                        ixEnd = path.length();
                    }
                    path.delete(ixSemiColon, ixEnd);
                }
                parameters.setResourceKey(path.toString());
            }
        }
    }
}