Example usage for java.lang StringBuffer indexOf

List of usage examples for java.lang StringBuffer indexOf

Introduction

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

Prototype

@Override
public int indexOf(String str) 

Source Link

Usage

From source file:com.seajas.search.contender.service.modifier.AbstractModifierService.java

/**
 * Create a StringBuffer out of the given reader content.
 * //from  ww w  .j a v a 2s  . c  o m
 * @param buffer
 * @param reader
 * @param cleanFromProlog
 * @return Reader
 */
protected Reader readerToBuffer(final StringBuffer buffer, final Reader reader, final boolean cleanFromProlog) {
    Integer lastProlog = -1;

    try {
        char[] characterBuffer = new char[8192];

        for (int count; (count = reader.read(characterBuffer)) > 0;) {
            buffer.append(characterBuffer, 0, count);

            // When cleaning by prolog, we stop writing out the buffer after the second prolog

            if (cleanFromProlog) {
                if (lastProlog == -1)
                    lastProlog = buffer.indexOf("<?xml");
                if (lastProlog != -1 && (lastProlog = buffer.indexOf("<?xml", lastProlog + 1)) != -1) {
                    logger.warn("Input document contains more than one XML prolog. Stripping any extra ones.");

                    buffer.replace(lastProlog, buffer.length(), "");

                    break;
                }
            }
        }

        reader.close();

        return new StringReader(buffer.toString().trim());
    } catch (IOException e) {
        logger.error("Could not convert the given reader to a buffer", e);

        return null;
    }
}

From source file:ut.ee.mh.WebServer.java

private void handleLocationRequest(DefaultHttpServerConnection serverConnection, HttpRequest request,
        RequestLine requestLine) throws HttpException, IOException {

    BasicHttpEntityEnclosingRequest enclosingRequest = new BasicHttpEntityEnclosingRequest(
            request.getRequestLine());/*w  w  w  . j a  v  a2  s  .  c  o m*/
    serverConnection.receiveRequestEntity(enclosingRequest);

    InputStream input = enclosingRequest.getEntity().getContent();
    InputStreamReader reader = new InputStreamReader(input);

    StringBuffer form = new StringBuffer();
    while (reader.ready()) {
        form.append((char) reader.read());
    }
    String password = form.substring(form.indexOf("=") + 1);

    if (password.equals(mSharedPreferences.getString(FileSharingService.PREFS_PASSWORD, ""))) {
        HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 302, "Found");
        response.addHeader("Location", "/");
        response.addHeader("Set-Cookie", "id=" + createCookie());
        response.setEntity(new StringEntity(getHTMLHeader() + "Success!" + getHTMLFooter()));
        serverConnection.sendResponseHeader(response);
        serverConnection.sendResponseEntity(response);
    } else {
        HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 401, "Unauthorized");
        response.setEntity(
                new StringEntity(getHTMLHeader() + "<p>Login failed.</p>" + getLoginForm() + getHTMLFooter()));
        serverConnection.sendResponseHeader(response);
        serverConnection.sendResponseEntity(response);
    }
}

From source file:org.apache.nutch.protocol.htmlunit.HttpResponse.java

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

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

        // handle HTTP responses with missing blank line after headers
        int pos;// www.j a  v a2 s  .c om
        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) {
                // fixme:
                Http.LOG.warn("Error: ", e);
            }
            return;
        }

        processHeaderLine(line);
    }
}

From source file:com.india.arunava.network.httpProxy.HTTPProxyThreadBrowser.java

@Override
public void run() {

    ByteArrayOutputStream mainBuffer = new ByteArrayOutputStream();

    long count1 = 0;
    long count2 = 0;

    if (ProxyConstants.logLevel >= 1) {
        System.out.println(new Date() + " HTTPProxyThreadBrowser ::Started  " + currentThread());
    }//from  w w w  .  j  a v a2s  .c o m

    final byte[] buffer = new byte[ProxyConstants.MAX_BUFFER];
    int numberRead = 0;
    OutputStream server;
    InputStream client;

    try {

        client = incoming.getInputStream();
        server = outgoing.getOutputStream();
        String proxyAuth = "";
        // If Organization proxy required Authentication
        if (!ProxyConstants.ORGANIZATION_HTTP_PROXY_USER_NAME.equals("")) {
            final String authString = ProxyConstants.ORGANIZATION_HTTP_PROXY_USER_NAME + ":"
                    + ProxyConstants.ORGANIZATION_HTTP_PROXY_USER_PASS;
            proxyAuth = "Basic " + Base64.encodeBase64String(authString.getBytes());
        }

        int rdL;
        final StringBuffer header = new StringBuffer(9999);
        while (true) {
            rdL = client.read();
            if (rdL == -1) {
                break;
            }
            header.append((char) rdL);
            if (header.indexOf("\r\n\r\n") != -1) {
                break;
            }
        }

        if (ProxyConstants.logLevel >= 2) {
            System.out.println(new Date() + " HTTPProxyThreadBrowser :: Request header   = " + currentThread()
                    + " \n" + header);
        }

        final String allInpRequest = header.toString();

        // modify: if it is https request, resend to sslproxy
        if (ProxyConstants.HTTPS_ENABLED && allInpRequest.startsWith("CONNECT ")) {
            new SSLProxy(incoming, incoming.getInputStream(), incoming.getOutputStream(), allInpRequest)
                    .start();
            return;
        }
        // modify end

        String host = "";
        String port = "";
        String tmpHost = "";
        final int indexOf = allInpRequest.toLowerCase().indexOf("host:");
        if (indexOf != -1) {
            final int immediateNeLineChar = allInpRequest.toLowerCase().indexOf("\r\n",
                    allInpRequest.toLowerCase().indexOf("host:"));
            tmpHost = allInpRequest
                    .substring(allInpRequest.toLowerCase().indexOf("host:") + 5, immediateNeLineChar).trim();
            final int isPortThere = tmpHost.indexOf(":");
            if (isPortThere != -1) {
                host = tmpHost.substring(0, tmpHost.indexOf(":"));
                port = tmpHost.substring(tmpHost.indexOf(":") + 1);

            } else {
                port = "80";
                host = tmpHost;
            }
        }

        // ////////////////// Added since rapidshare not opening
        // Making it relative request.

        String modifyGet = header.toString().toLowerCase();

        if (modifyGet.startsWith("get http://")) {
            int i2 = modifyGet.indexOf("/", 11);
            header.replace(4, i2, "");
        }
        if (modifyGet.startsWith("post http://")) {
            int i2 = modifyGet.indexOf("/", 12);
            header.replace(5, i2, "");
        }

        // ///////////////////////////////////////////////

        final String proxyServerURL = ProxyConstants.webPHP_URL_HTTP;
        String isSecure = "";
        final String HeaderHost = ProxyConstants.webPHP_HOST_HTTP;

        if (header.indexOf("X-IS-SSL-RECURSIVE:") == -1) {
            isSecure = "N";
        } else {
            isSecure = "Y";
            // Now detect which Port 443 or 8443 ?
            // Like : abcd X-IS-SSL-RECURSIVE: 8443
            final int p1 = header.indexOf("X-IS-SSL-RECURSIVE: ");
            port = header.substring(p1 + 20, p1 + 20 + 4);
            port = "" + Integer.valueOf(port).intValue();
        }

        if (ProxyConstants.logLevel >= 1) {
            System.out.println(new Date() + " HTTPProxyThreadBrowser ::Started  " + currentThread()
                    + "URL Information :\n" + "Host=" + host + " Port=" + port + " ProxyServerURL="
                    + proxyServerURL + " HeaderHost=" + HeaderHost);
        }

        // Get Content length
        String contentLenght = "";
        final int contIndx = header.toString().toLowerCase().indexOf("content-length: ");
        if (contIndx != -1) {
            final int endI = header.indexOf("\r\n", contIndx + 17);
            contentLenght = header.substring(contIndx + 16, endI);
        }

        String data = header + "";
        data = data.replaceFirst("\r\n\r\n", "\r\nConnection: Close\r\n\r\n");

        // remove the proxy header to become high-anonymous proxy
        data = data.replaceFirst("Proxy-Connection: keep-alive\r\n", "");

        // Replace culprit KeepAlive
        // Should have used Regex
        data = data.replaceFirst("Keep-Alive: ", "X-Dummy-1: ");
        data = data.replaceFirst("keep-alive: ", "X-Dummy-1: ");
        data = data.replaceFirst("Keep-alive: ", "X-Dummy-1: ");
        data = data.replaceFirst("keep-Alive: ", "X-Dummy-1: ");

        data = data.replaceFirst("keep-alive", "Close");
        data = data.replaceFirst("Keep-Alive", "Close");
        data = data.replaceFirst("keep-Alive", "Close");
        data = data.replaceFirst("Keep-alive", "Close");

        int totallength = 0;
        if (!contentLenght.equals("")) {
            totallength = Integer.parseInt(contentLenght.trim()) + (data.length() + 61 + 1);
        } else {
            totallength = (data.length() + 61 + 1);
        }

        String header1 = "";
        header1 = header1 + "POST " + proxyServerURL + " HTTP/1.1\r\n";
        header1 = header1 + "Host: " + HeaderHost + "\r\n";
        header1 = header1 + "Connection: Close\r\n";
        header1 = header1 + "Content-Length: " + totallength + "\r\n";
        header1 = header1 + "Cache-Control: no-cache\r\n";

        if (!ProxyConstants.ORGANIZATION_HTTP_PROXY_USER_NAME.equals("")) {
            header1 = header1 + "Proxy-Authorization: " + proxyAuth + "\r\n";
        }

        count1 = totallength;

        header1 = header1 + "\r\n";
        server.write(header1.getBytes());
        server.flush();

        if (ProxyConstants.ENCRYPTION_ENABLED) {
            // Let know PHP waht are we using
            server.write(("Y".getBytes()));

            server.write(SimpleEncryptDecrypt.enc(host.getBytes()));
            // Padding with space
            for (int i = 0; i < 50 - host.length(); i++) {
                server.write(SimpleEncryptDecrypt.enc(" ".getBytes()));
            }
            server.write(SimpleEncryptDecrypt.enc(port.getBytes()));
            // Padding with space
            for (int i = 0; i < 10 - port.length(); i++) {
                server.write(SimpleEncryptDecrypt.enc(" ".getBytes()));
            }
            // Write fsockopen info
            server.write(SimpleEncryptDecrypt.enc(isSecure.getBytes()));

            // It is destination header
            server.write(SimpleEncryptDecrypt.enc(data.getBytes()));

        } else {
            // Let know PHP waht are we using
            server.write(("N".getBytes()));

            server.write(host.getBytes());
            // Padding with space
            for (int i = 0; i < 50 - host.length(); i++) {
                server.write(" ".getBytes());
            }
            server.write(port.getBytes());
            // Padding with space
            for (int i = 0; i < 10 - port.length(); i++) {
                server.write(" ".getBytes());
            }
            // Write fsockopen info
            server.write(isSecure.getBytes());

            // It is destination header
            server.write(data.getBytes());

        }
        server.flush();

        if (ProxyConstants.logLevel >= 2) {
            System.out.println(new Date() + " HTTPProxyThreadBrowser :: destination header   = "
                    + currentThread() + " \n" + data);
        }

        while (true) {
            numberRead = client.read(buffer);
            count2 = count2 + numberRead;
            if (numberRead == -1) {
                outgoing.close();
                incoming.close();
                break;
            }

            if (ProxyConstants.ENCRYPTION_ENABLED) {
                server.write(SimpleEncryptDecrypt.enc(buffer, numberRead), 0, numberRead);
            } else {
                server.write(buffer, 0, numberRead);
            }
            if (ProxyConstants.logLevel >= 3) {
                final ByteArrayOutputStream bo = new ByteArrayOutputStream();
                bo.write(buffer, 0, numberRead);
                System.out.println("::Readingbody::" + bo + "::Readingbody::");
            }
        }

        if (ProxyConstants.logLevel >= 1) {
            System.out.println(new Date() + " HTTPProxyThreadBrowser :: Finish " + currentThread());
        }
    } catch (final Exception e) {
    }
    synchronized (ProxyConstants.MUTEX) {
        ProxyConstants.TOTAL_TRANSFER = ProxyConstants.TOTAL_TRANSFER + count1 + count2;
    }
}

From source file:org.nuxeo.ecm.webengine.DefaultWebContext.java

public String getBaseURL() {
    StringBuffer sb = request.getRequestURL();
    int p = sb.indexOf(getBasePath());
    if (p > -1) {
        return sb.substring(0, p);
    }/*from w  w  w  . j  a v  a  2 s  . c  o m*/
    return sb.toString();
}

From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java

private Response execute(CloseableHttpClient http, ServerInfo serverInfo, HttpRequestBase request,
        MessageContext context) throws IOException {
    ensureCertsAreLoaded(context);//ww w. j  a  v a  2s  .c  o  m
    CloseableHttpResponse response = http.execute(request, serverInfo.httpContext);
    if (response == null) {
        return Response.status(Response.Status.BAD_GATEWAY).build();
    }
    Header[] responseHeaders = response.getAllHeaders();
    ResponseBuilder builder = Response.status(response.getStatusLine().getStatusCode());
    for (Header header : responseHeaders) {
        builder.header(header.getName(), header.getValue());
    }
    String strReply = new String(EntityUtils.toByteArray(response.getEntity()));
    HttpServletRequest servletRequest = context.getHttpServletRequest();
    StringBuffer entireRequestUrl = servletRequest.getRequestURL();
    builder.entity(strReply.replaceAll(serverInfo.url.toExternalForm(),
            entireRequestUrl.substring(0, entireRequestUrl.indexOf(servletRequest.getPathInfo())) + "/"
                    + serverInfo.name + "/"));
    return builder.build();
}

From source file:com.appeligo.search.actions.ProgramAction.java

public StringBuffer getRequestURL() {
    StringBuffer requestURL = getServletRequest().getRequestURL();
    int slashes = requestURL.indexOf("//");
    int nextSlash = requestURL.indexOf("/", slashes + 2);
    requestURL.delete(nextSlash, requestURL.length());
    requestURL.append(programInfo.getWebPath());
    return requestURL;
}

From source file:net.duckling.ddl.web.controller.task.TaskBaseController.java

/**
 * Task??/* www .ja  v  a  2s .  com*/
 * 
 * @param userIds
 *            ?? xx1@xx.com,xx2@xx.com....
 * @param site
 *            Site
 * @return string xxName%xxEmail,...,...
 * */
private String convert2TaskNameType(String uIds, Site site) {
    if (StringUtils.isEmpty(uIds)) {
        return "";
    }
    String emails[] = uIds.split(",");
    StringBuffer sb = new StringBuffer();
    for (String email : emails) {
        if (StringUtils.isEmpty(email)) {
            continue;
        }
        sb.append(aoneUserService.getUserNameByID(email)).append("%").append(email).append(",");
    }
    if (sb.indexOf(",") > -1) {
        sb.deleteCharAt(sb.lastIndexOf(","));
    }
    return sb.toString();
}

From source file:org.jboss.dashboard.ui.components.URLMarkupGenerator.java

/**
 * Apply a final post-processing on generated URLs in order to add some extra information such as CSRF tokens or
 * propagate some behavioural parameters via URL-rewriting.
 *///from   w ww  .  j ava  2s  .  co  m
protected StringBuffer postProcessURL(StringBuffer url) {
    // Keep the embedded mode using URL rewriting.
    RequestContext reqCtx = RequestContext.lookup();
    if (reqCtx != null) {
        HttpServletRequest request = reqCtx.getRequest().getRequestObject();
        boolean embeddedMode = Boolean.parseBoolean(request.getParameter(Parameters.PARAM_EMBEDDED));
        String embeddedParam = Parameters.PARAM_EMBEDDED + "=true";
        if (embeddedMode && url.indexOf(embeddedParam) == -1) {
            url.append(url.indexOf("?") != -1 ? PARAM_SEPARATOR : "?");
            url.append(embeddedParam);
        }
    }
    // Add the CSRF protection token
    if (CSRFTokenProcessor.lookup().isEnabled()) {
        CSRFTokenGenerator csrfTokenGenerator = CSRFTokenGenerator.lookup();
        String token = csrfTokenGenerator.getLastToken();
        url.append(url.indexOf("?") != -1 ? PARAM_SEPARATOR : "?");
        url.append(csrfTokenGenerator.getTokenName()).append("=").append(token);
    }
    return url;
}

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

private String mk_header(StringBuffer workingContents) {
    return workingContents.substring(0, workingContents.indexOf("\r\n"));
}