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.digitalpebble.behemoth.io.warc.HttpResponse.java

private int parseStatusLine(PushbackInputStream in, StringBuilder line) throws IOException {
    // skip first character if "\n"
    if (peek(in) == '\n') {
        in.read();/*from   w  w  w.  j  a  va2 s. c  o m*/
    }
    readLine(in, line, false);

    int codeStart = line.indexOf(" ");
    int codeEnd = line.indexOf(" ", codeStart + 1);

    // handle lines with no plaintext result code, ie:
    // "HTTP/1.1 200" vs "HTTP/1.1 200 OK"
    if (codeEnd == -1)
        codeEnd = line.length();

    int code;
    try {
        code = Integer.parseInt(line.substring(codeStart + 1, codeEnd));
    } catch (NumberFormatException e) {
        throw new IOException("bad status line '" + line + "': " + e.getMessage(), e);
    }

    return code;
}

From source file:net.yacy.search.query.QueryParams.java

/**
 * Remove from the URL builder any query modifiers with the same name that the new modifier 
 * @param sb//from  w ww . j av a  2s .  c  o m
 *            a StringBuilder holding the search URL navigation being built.
 *            Must not be null and contain the URL base and the query string
 *            with its eventual modifiers
 * @param newModifier
 *            a new modifier of form key:value. Must not be null.
 */
protected static void removeOldModifiersFromNavUrl(final StringBuilder sb, final String newModifier) {
    int nmpi = newModifier.indexOf(":");
    if (nmpi > 0) {
        final String newModifierKey = newModifier.substring(0, nmpi) + ":";
        int sameModifierIndex = sb.indexOf(newModifierKey);
        while (sameModifierIndex > 0) {
            final int spaceModifierIndex = sb.indexOf(" ", sameModifierIndex);
            if (spaceModifierIndex > sameModifierIndex) {
                /* There are other modifiers after the matching one : we only remove the old matching modifier */
                sb.delete(sameModifierIndex, spaceModifierIndex + 1);
            } else {
                /* The matching modifier is the last : we truncate the builder */
                sb.setLength(sameModifierIndex);
            }
            sameModifierIndex = sb.indexOf(newModifierKey);
        }
        if (sb.charAt(sb.length() - 1) == '+') {
            sb.setLength(sb.length() - 1);
        }
        if (sb.charAt(sb.length() - 1) == ' ') {
            sb.setLength(sb.length() - 1);
        }
    }
}

From source file:com.digitalpebble.behemoth.io.warc.HttpResponse.java

private void parseHeaders(PushbackInputStream in, StringBuilder line) throws IOException {

    while (readLine(in, line, true) != 0) {

        // handle HTTP responses with missing blank line after headers
        int pos;/*from ww  w.  ja v a  2s .c o m*/
        if (((pos = line.indexOf("<!DOCTYPE")) != -1) || ((pos = line.indexOf("<HTML")) != -1)
                || ((pos = line.indexOf("<html")) != -1)) {

            in.unread(line.substring(pos).getBytes("UTF-8"));
            line.setLength(pos);

            try {
                // TODO: (CM) We don't know the header names here
                // since we're just handling them generically. It would
                // be nice to provide some sort of mapping function here
                // for the returned header names to the standard metadata
                // names in the ParseData class
                processHeaderLine(line);
            } catch (Exception e) {

            }
            return;
        }

        processHeaderLine(line);
    }
}

From source file:chibi.gemmaanalysis.OutlierDetectionTestCli.java

/*** Return names of platforms used in the experiment as string, separated by "/" ***/
private String getPlatforms(ExpressionExperiment ee) {

    StringBuilder buffer = new StringBuilder(32);
    String platforms;//from  ww w . j av a2 s . c o  m

    for (BioAssay bioAssay : ee.getBioAssays()) {
        if (buffer.indexOf(bioAssay.getArrayDesignUsed().getShortName()) == -1) {
            buffer.append(bioAssay.getArrayDesignUsed().getShortName() + "/");
            buffer.ensureCapacity(10);
        }
    }

    platforms = buffer.substring(0, buffer.length() - 1);

    return platforms;
}

From source file:org.callimachusproject.server.chain.CacheHandler.java

private String getCacheControl(Header[] cache, Header lastMod, long now) {
    StringBuilder sb = new StringBuilder();
    for (Header hd : cache) {
        if (sb.length() > 0) {
            sb.append(",");
        }//ww w  .  ja  va  2 s  . c o  m
        sb.append(hd.getValue());
    }
    if (sb.length() == 0 || sb.indexOf("max-age") < 0 && sb.indexOf("s-maxage") < 0
            && sb.indexOf("no-cache") < 0 && sb.indexOf("no-store") < 0) {
        int maxage = getMaxAgeHeuristic(lastMod, now);
        if (maxage > 0) {
            if (sb.length() > 0) {
                sb.append(",");
            }
            sb.append("max-age=").append(maxage);
            return sb.toString();
        }
    }
    return null;
}

From source file:org.olat.core.gui.components.form.flexible.impl.elements.FileElementRenderer.java

@Override
public void render(Renderer renderer, StringOutput sb, Component source, URLBuilder ubu, Translator translator,
        RenderResult renderResult, String[] args) {
    // Use translator with flexi form elements fallback
    Translator trans = Util.createPackageTranslator(FileElementRenderer.class, translator.getLocale(),
            translator);/*from   w  ww  .  jav a  2 s .  c  o  m*/
    //
    FileElementComponent fileComp = (FileElementComponent) source;
    FileElementImpl fileElem = fileComp.getFileElementImpl();
    String id = fileComp.getFormDispatchId();
    // Calculate current file name: either from already uploaded file or
    // from initial file or empty
    String fileName = fileElem.getUploadFileName();
    if (fileName == null) {
        // try fallback: default file
        File initialFile = fileElem.getInitialFile();
        if (initialFile != null) {
            fileName = initialFile.getName();
        } else {
            fileName = "";
        }
    }

    // Read-write view
    if (source.isEnabled()) {
        sb.append("<div class='b_fileinput'>");
        // input.Browse is the real filebrowser, but set to be transparent.
        // the div.b_fileinput_fakechooser is layered below the input.Browse and represents the visual GUI.
        // Since input.Browse is layered above div.b_fileinput_fakechooser, all click events to go input.Browse
        // See http://www.quirksmode.org/dom/inputfile.html
        sb.append("<input type='file' name=\"");
        sb.append(id); // name for form labeling
        sb.append("\" id=\"");
        sb.append(id); // id to make dirty button work
        sb.append("\" class='b_fileinput_realchooser' ");
        // Add on* event handlers
        StringBuilder eventHandlers = FormJSHelper.getRawJSFor(fileElem.getRootForm(), id,
                fileElem.getAction());
        int onChangePos = eventHandlers.indexOf("onchange=");
        if (onChangePos != -1) {
            // add file upload change handler
            sb.append(eventHandlers.substring(0, onChangePos + 10));
            sb.append("b_handleFileUploadFormChange(this, this.form.fake_").append(id)
                    .append(", this.form.upload);");
            sb.append(eventHandlers.substring(onChangePos + 10, eventHandlers.length()));
        } else {
            sb.append(eventHandlers);
            sb.append(" onchange=\"b_handleFileUploadFormChange(this, this.form.fake_").append(id)
                    .append(", this.form.upload)\"");
        }
        // Add mime type restriction
        Set<String> mimeTypes = fileElem.getMimeTypeLimitations();
        if (mimeTypes.size() > 0) {
            sb.append(" accept=\"");
            Iterator iterator = mimeTypes.iterator();
            while (iterator.hasNext()) {
                String type = (String) iterator.next();
                sb.append(type);
                if (iterator.hasNext())
                    sb.append(",");
            }
            sb.append("\"");
        }
        // Add pseudo focus marker on fake file chooser button
        sb.append(" onfocus=\"this.form.fake_").append(id)
                .append(".nextSibling.style.border = '1px dotted black';\"");
        sb.append(" onblur=\"this.form.fake_").append(id).append(".nextSibling.style.border = '0';\"");
        // Add select text (hover)
        sb.append(" title=\"").append(StringEscapeUtils.escapeHtml(trans.translate("file.element.select")))
                .append("\"/>");
        sb.append("<div class='b_fileinput_fakechooser'>");
        // Add the visible but fake input field and a styled faked file chooser button
        sb.append("<input name='fake_").append(id).append("' value=\"")
                .append(StringEscapeUtils.escapeHtml(fileName)).append("\"/>");
        sb.append("<a href='#' class='b_with_small_icon_left b_fileinput_icon'><span>")
                .append(trans.translate("file.element.select")).append("</span></a>");
        // Add Max upload size
        if (fileElem.getMaxUploadSizeKB() != FileElement.UPLOAD_UNLIMITED) {
            String maxUpload = Formatter.roundToString((fileElem.getMaxUploadSizeKB() + 0f) / 1024, 1);
            sb.append("<span class='b_fileinput_maxsize'>(")
                    .append(trans.translate("file.element.select.maxsize", new String[] { maxUpload }))
                    .append(")</span>");
        }
        sb.append("</div></div>");

        // Add IE fix to deal with SSL and server timeouts
        // See http://bugs.olat.org/jira/browse/OLAT-1299
        sb.append("<!--[if lte IE 7]>");
        sb.append("<iframe height='1px' style='visibility:hidden' src='");
        StaticMediaDispatcher.renderStaticURI(sb, "workaround.html");
        sb.append("'></iframe>");
        sb.append("<![endif]-->");

        // Add set dirty form on change
        sb.append(FormJSHelper.getJSStartWithVarDeclaration(fileComp.getFormDispatchId()));
        /*
         * deactivated due OLAT-3094 and OLAT-3040 if(te.hasFocus()){ sb.append(FormJSHelper.getFocusFor(teC.getFormDispatchId())); }
         */
        sb.append(FormJSHelper.getSetFlexiFormDirty(fileElem.getRootForm(), fileComp.getFormDispatchId()));
        sb.append(FormJSHelper.getJSEnd());

    } else {
        //
        // Read only view
        sb.append("<span id=\"");
        sb.append(id);
        sb.append("\" ");
        sb.append(FormJSHelper.getRawJSFor(fileElem.getRootForm(), id, fileElem.getAction()));
        sb.append(" >");
        sb.append("<input disabled=\"disabled\" class=\"b_form_element_disabled\" size=\"");
        sb.append("\" value=\"");
        sb.append(StringEscapeUtils.escapeHtml(fileName));
        sb.append("\" ");
        sb.append("\" />");
        sb.append("</span>");
    }

}

From source file:de.itsvs.cwtrpc.security.AbstractRpcProcessingFilter.java

protected boolean matchesFilterProcessesUrl(HttpServletRequest request) throws IOException, ServletException {
    final String contextPath;
    final StringBuilder sb;
    final String uri;

    contextPath = request.getContextPath();
    sb = new StringBuilder(request.getRequestURI());
    if ((contextPath.length() > 0) && (sb.indexOf(contextPath) == 0)) {
        sb.delete(0, contextPath.length());
    }//from ww w.  ja  v a2s .  c  o  m
    if ((sb.length() == 0) || (sb.charAt(0) != '/')) {
        sb.insert(0, '/');
    }
    uri = sb.toString();

    if (log.isDebugEnabled()) {
        log.debug(
                "Checking received URI '" + uri + "' against configured URI '" + getFilterProcessesUrl() + "'");
    }
    return getFilterProcessesUrl().equals(uri);
}

From source file:org.sonatype.nexus.plugins.rrb.MavenRepositoryReader.java

private ArrayList<RepositoryDirectory> parseResult(StringBuilder indata) {
    RemoteRepositoryParser parser = null;
    String baseUrl = "";
    if (proxyRepository != null) {
        baseUrl = proxyRepository.getRemoteUrl();
    }//w ww .j a  v  a 2s  .co m

    if (indata.indexOf("<html ") != -1) {
        // if title="Artifactory" then it is an Artifactory repo...
        if (indata.indexOf("title=\"Artifactory\"") != -1) {
            logger.debug("is Artifactory repository");
            parser = new ArtifactoryRemoteRepositoryParser(remotePath, localUrl, id, baseUrl);
        } else {
            logger.debug("is html repository");
            parser = new HtmlRemoteRepositoryParser(remotePath, localUrl, id, baseUrl);
        }
    } else if (indata.indexOf("xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"") != -1
            || (indata.indexOf("<?xml") != -1 && responseContainsError(indata))) {
        logger.debug("is S3 repository");
        if (responseContainsError(indata) && !responseContainsAccessDenied(indata)) {
            logger.debug("response from S3 repository contains error, need to find rootUrl");
            remoteUrl = findcreateNewUrl(indata);
            indata = getContent();
        } else if (responseContainsError(indata) && responseContainsAccessDenied(indata)) {
            logger.debug("response from S3 repository contains access denied response");
            indata = new StringBuilder();
        }

        parser = new S3RemoteRepositoryParser(remotePath, localUrl, id,
                baseUrl.replace(findRootUrl(indata), ""));
    } else {
        logger.debug("Found no matching parser, using default html parser");

        parser = new HtmlRemoteRepositoryParser(remotePath, localUrl, id, baseUrl);
    }
    return parser.extractLinks(indata);
}

From source file:org.apache.sling.scripting.sightly.impl.utils.PathInfo.java

/**
 * Creates a {@code PathInfo} object based on a request path.
 *
 * @param path the full normalized path (no '.', '..', or double slashes8) of the request, including the query parameters
 * @throws NullPointerException if the supplied {@code path} is null
 *///from  ww w.ja v a2  s.  c o m
public PathInfo(String path) {
    if (path == null) {
        throw new NullPointerException("The path parameter cannot be null.");
    }
    try {
        uri = new URI(path);
    } catch (URISyntaxException e) {
        throw new SightlyException("The provided path does not represent a valid URI: " + path);
    }
    selectors = new LinkedHashSet<String>();
    String processingPath = path;
    if (uri.getPath() != null) {
        processingPath = uri.getPath();
    }
    int lastDot = processingPath.lastIndexOf('.');
    if (lastDot > -1) {
        String afterLastDot = processingPath.substring(lastDot + 1);
        String[] parts = afterLastDot.split("/");
        extension = parts[0];
        if (parts.length > 1) {
            // we have a suffix
            StringBuilder suffixSB = new StringBuilder();
            for (int i = 1; i < parts.length; i++) {
                suffixSB.append("/").append(parts[i]);
            }
            int hashIndex = suffixSB.indexOf("#");
            if (hashIndex > -1) {
                suffix = suffixSB.substring(0, hashIndex);
            } else {
                suffix = suffixSB.toString();
            }
        }
    }
    int firstDot = processingPath.indexOf('.');
    if (firstDot < lastDot) {
        selectorString = processingPath.substring(firstDot + 1, lastDot);
        String[] selectorsArray = selectorString.split("\\.");
        selectors.addAll(Arrays.asList(selectorsArray));
    }
    int pathLength = processingPath.length() - (selectorString == null ? 0 : selectorString.length() + 1)
            - (extension == null ? 0 : extension.length() + 1) - (suffix == null ? 0 : suffix.length());
    if (pathLength == processingPath.length()) {
        this.path = processingPath;
    } else {
        this.path = processingPath.substring(0, pathLength);
    }
    String query = uri.getQuery();
    if (StringUtils.isNotEmpty(query)) {
        String[] keyValuePairs = query.split("&");
        for (int i = 0; i < keyValuePairs.length; i++) {
            String[] pair = keyValuePairs[i].split("=");
            if (pair.length == 2) {
                String param = pair[0];
                String value = pair[1];
                Collection<String> values = parameters.get(param);
                if (values == null) {
                    values = new ArrayList<String>();
                    parameters.put(param, values);
                }
                values.add(value);
            }
        }
    }
}

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

private String preprocessOutboundXml(@UnknownInitialization(NettyTcpSession.class) NettyTcpSession this,
        final Document xml) throws TransformerException {
    final String streamHeaderXmlnsBlock = String.format("xmlns=\"%1s\"", CommonXmlns.STREAM_HEADER);
    final String rootNs = xml.getDocumentElement().getNamespaceURI();
    final String rootName = xml.getDocumentElement().getLocalName();

    if (CommonXmlns.STREAM_OPENING_WEBSOCKET.equals(rootNs)) {
        if ("close".equals(rootName)) {
            return "</stream:stream>";
        } else if ("open".equals(rootName)) {
            return convertToTcpStreamOpening(xml);
        } else {//  ww w  .  ja v a2  s.  c o  m
            throw new IllegalArgumentException("Incorrect stream opening XML.");
        }
    } else if (CommonXmlns.STREAM_HEADER.equals(rootNs)) {
        // Elements with header namespace, which mean should be prefixed "stream:"
        final StringBuilder builder = new StringBuilder(DomUtils.writeString(xml));
        final int streamHeaderNamespaceBlockIdx = builder.indexOf(streamHeaderXmlnsBlock);
        builder.insert(1, serverStreamPrefix + ":");
        builder.delete(streamHeaderNamespaceBlockIdx,
                streamHeaderNamespaceBlockIdx + streamHeaderXmlnsBlock.length());
        return builder.toString();
    } else {
        return DomUtils.writeString(xml);
    }
}