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:no.sesat.search.http.servlet.BoomerangServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse res)
        throws ServletException, IOException {

    // clients must not cache these requests
    res.setHeader("Cache-Control", "no-cache, must-revalidate, post-check=0, pre-check=0");
    res.setHeader("Pragma", "no-cache"); // for old browsers
    res.setDateHeader("Expires", 0); // to be double-safe

    // entrails is the map of logging information
    final Map<String, Object> entrails = new HashMap<String, Object>();

    // request attribute to keep
    entrails.put("referer", req.getHeader("Referer"));
    entrails.put("method", req.getMethod());
    entrails.put("ipaddress", req.getRemoteAddr());
    entrails.put("user-agent", req.getHeader("User-Agent"));
    entrails.put("user-id", SearchServlet.getCookieValue(req, "SesamID"));
    entrails.put("user", SearchServlet.getCookieValue(req, "SesamUser"));

    if (req.getRequestURI().startsWith(CEREMONIAL)) {

        // ceremonial boomerang
        final StringBuffer url = req.getRequestURL();
        if (null != req.getQueryString()) {
            url.append('?' + req.getQueryString());
        }/*from  w ww  .j a  v  a  2 s  .com*/

        // pick out the entrails
        final int boomerangStart = url.indexOf(CEREMONIAL) + CEREMONIAL.length();

        try {
            final String grub = url.substring(boomerangStart, url.indexOf("/", boomerangStart));
            LOG.debug(grub);

            // the url to return to
            final String destination = url
                    .substring(url.indexOf("/", url.indexOf(CEREMONIAL) + CEREMONIAL.length() + 1) + 1);

            // the grub details to add
            if (0 < grub.length()) {
                final StringTokenizer tokeniser = new StringTokenizer(grub, ";");
                while (tokeniser.hasMoreTokens()) {
                    final String[] entry = tokeniser.nextToken().split("=");
                    entrails.put(entry[0], 1 < entry.length ? entry[1] : entry[0]);
                }
            }
            entrails.put("boomerang", destination);
            kangerooGrub(entrails);

            LOG.debug("Ceremonial boomerang to " + destination.toString());

            if (ROBOTS.matcher(req.getHeader("User-agent")).find()) {
                // robots like permanent redirects. and we're not interested in their clicks so ok to cache.
                res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
                res.setHeader("Location", destination.toString());
                res.setHeader("Connection", "close");

            } else {
                // default behaviour for users.
                res.sendRedirect(destination.toString());
            }

        } catch (StringIndexOutOfBoundsException sioobe) {
            // SEARCH-4668
            LOG.error("Boomerang url not to standard --> " + url);
            LOG.debug(sioobe.getMessage(), sioobe);
        }

    } else {

        // hunting boomerang, just grub, and the grub comes as clean parameters.
        final DataModel datamodel = (DataModel) req.getSession().getAttribute(DataModel.KEY);
        entrails.putAll(datamodel.getParameters().getValues());
        kangerooGrub(entrails);

    }

}

From source file:hydrograph.ui.expression.editor.datastructure.MethodDetails.java

private void createPlaceHolderFromSource(IMethod iMethod, String className) throws JavaModelException {
    StringBuffer buffer = new StringBuffer(iMethod.getSource());
    int indexOfPlaceHolder = buffer.lastIndexOf("@see");
    if (indexOfPlaceHolder != -1 && iMethod.getParameterNames() != null
            && iMethod.getParameterNames().length > 0) {
        buffer = buffer.delete(0, indexOfPlaceHolder + 4);
        buffer = buffer.delete(buffer.indexOf("\n") + 1, buffer.capacity());
        if (StringUtils.contains(buffer.toString(), className + Constants.DOT + iMethod.getElementName())) {
            placeHolder = StringUtils.trim(buffer.toString());
        } else//from w  w  w.  j a v  a 2  s  .  c  o  m
            placeHolder = createDefaultPlaceHolder(iMethod, className);
    } else {
        placeHolder = createDefaultPlaceHolder(iMethod, className);
    }
}

From source file:com.hyron.poscafe.service.action.RecallAction.java

@Override
public boolean parseParams(List<VirtualKey> params) {
    StringBuffer tmpBuf = new StringBuffer();
    for (VirtualKey vk : params) {
        tmpBuf.append(vk.getValue().isEmpty() ? vk.getKeyType().getType() : vk.getValue());
    }//from   w  w  w.  j a  v  a  2s. c o m

    Pattern pattern = Pattern.compile(regexp);
    Matcher matcher = pattern.matcher(tmpBuf);
    if (!matcher.matches()) {
        return false;
    }

    int pos = tmpBuf.indexOf("RECALL");
    String tmpStr = tmpBuf.substring(0, pos);
    recallTransNo = Long.valueOf(tmpStr);
    return true;
}

From source file:com.meiah.core.util.StringUtil.java

/**
  * /*from  w  ww.j  a v a2 s.  c  o m*/
  * @description ?strSplit
  * @author zhangj
  * @date Jun 15, 2012
  */
 public static void insertEngKeyword(List<String> engKeyword, StringBuffer sb, String strSplit) {
     if (Validator.isNull(strSplit)) {
         strSplit = "\"";
     }
     int index = 0, i = 0, increase = 0, count = 1;
     int start = sb.indexOf(strSplit);
     while (index != -1) {
         index = sb.indexOf(strSplit, index + increase);
         if (index != -1) {
             if (count % 2 != 0) {
                 start = index;
                 if (engKeyword.size() > i) {
                     String keyword = engKeyword.get(i++);
                     increase = keyword.length();
                     sb.insert(start + 1, keyword);
                 }
             } else {
                 increase = 1;
             }
         }
         count++;
     }
 }

From source file:org.vfny.geoserver.wfs.servlets.TestWfsPost.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w w w. j  av a  2s.  c om
 *
 * @param request servlet request
 * @param response servlet response
 *
 * @throws ServletException DOCUMENT ME!
 * @throws IOException DOCUMENT ME!
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestString = request.getParameter("body");
    String urlString = request.getParameter("url");
    boolean doGet = (requestString == null) || requestString.trim().equals("");

    if ((urlString == null)) {
        PrintWriter out = response.getWriter();
        StringBuffer urlInfo = request.getRequestURL();

        if (urlInfo.indexOf("?") != -1) {
            urlInfo.delete(urlInfo.indexOf("?"), urlInfo.length());
        }

        String geoserverUrl = urlInfo.substring(0, urlInfo.indexOf("/", 8)) + request.getContextPath();
        response.setContentType("text/html");
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>TestWfsPost</title>");
        out.println("</head>");
        out.println("<script language=\"JavaScript\">");
        out.println("function doNothing() {");
        out.println("}");
        out.println("function sendRequest() {");
        out.println("  if (checkURL()==true) {");
        out.print("    document.frm.action = \"");
        out.print(urlInfo.toString());
        out.print("\";\n");
        out.println("    document.frm.target = \"_blank\";");
        out.println("    document.frm.submit();");
        out.println("  }");
        out.println("}");
        out.println("function checkURL() {");
        out.println("  if (document.frm.url.value==\"\") {");
        out.println("    alert(\"Please give URL before you sumbit this form!\");");
        out.println("    return false;");
        out.println("  } else {");
        out.println("    return true;");
        out.println("  }");
        out.println("}");
        out.println("function clearRequest() {");
        out.println("document.frm.body.value = \"\";");
        out.println("}");
        out.println("</script>");
        out.println("<body>");
        out.println("<form name=\"frm\" action=\"JavaScript:doNothing()\" method=\"POST\">");
        out.println("<table align=\"center\" cellspacing=\"2\" cellpadding=\"2\" border=\"0\">");
        out.println("<tr>");
        out.println("<td><b>URL:</b></td>");
        out.print("<td><input name=\"url\" value=\"");
        out.print(geoserverUrl);
        out.print("/wfs/GetFeature\" size=\"70\" MAXLENGTH=\"100\"/></td>\n");
        out.println("</tr>");
        out.println("<tr>");
        out.println("<td><b>Request:</b></td>");
        out.println("<td><textarea cols=\"60\" rows=\"24\" name=\"body\"></textarea></td>");
        out.println("</tr>");
        out.println("</table>");
        out.println("<table align=\"center\">");
        out.println("<tr>");
        out.println("<td><input type=\"button\" value=\"Clear\" onclick=\"clearRequest()\"></td>");
        out.println("<td><input type=\"button\" value=\"Submit\" onclick=\"sendRequest()\"></td>");
        out.println("<td></td>");
        out.println("</tr>");
        out.println("</table>");
        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
        out.close();
    } else {
        response.setContentType("application/xml");

        BufferedReader xmlIn = null;
        PrintWriter xmlOut = null;
        StringBuffer sbf = new StringBuffer();
        String resp = null;

        try {
            URL u = new URL(urlString);
            java.net.HttpURLConnection acon = (java.net.HttpURLConnection) u.openConnection();
            acon.setAllowUserInteraction(false);

            if (!doGet) {
                //System.out.println("set to post");
                acon.setRequestMethod("POST");
                acon.setRequestProperty("Content-Type", "application/xml");
            } else {
                //System.out.println("set to get");
                acon.setRequestMethod("GET");
            }

            acon.setDoOutput(true);
            acon.setDoInput(true);
            acon.setUseCaches(false);

            //SISfixed - if there was authentication info in the request,
            //           Pass it along the way to the target URL
            //DJB: applied patch in GEOS-335
            String authHeader = request.getHeader("Authorization");

            String username = request.getParameter("username");

            if ((username != null) && !username.trim().equals("")) {
                String password = request.getParameter("password");
                String up = username + ":" + password;
                byte[] encoded = Base64.encodeBase64(up.getBytes());
                authHeader = "Basic " + new String(encoded);
            }

            if (authHeader != null) {
                acon.setRequestProperty("Authorization", authHeader);
            }

            if (!doGet) {
                xmlOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(acon.getOutputStream())));
                xmlOut = new java.io.PrintWriter(acon.getOutputStream());

                xmlOut.write(requestString);
                xmlOut.flush();
            }

            // Above 400 they're all error codes, see:
            // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
            if (acon.getResponseCode() >= 400) {
                PrintWriter out = response.getWriter();
                out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                out.println("<servlet-exception>");
                out.println("HTTP response: " + acon.getResponseCode() + "\n"
                        + URLDecoder.decode(acon.getResponseMessage(), "UTF-8"));
                out.println("</servlet-exception>");
                out.close();
            } else {
                // xmlIn = new BufferedReader(new InputStreamReader(
                // acon.getInputStream()));
                // String line;

                // System.out.println("got encoding from acon: "
                // + acon.getContentType());
                response.setContentType(acon.getContentType());
                response.setHeader("Content-disposition", acon.getHeaderField("Content-disposition"));

                OutputStream output = response.getOutputStream();
                int c;
                InputStream in = acon.getInputStream();

                while ((c = in.read()) != -1)
                    output.write(c);

                in.close();
                output.close();
            }

            //while ((line = xmlIn.readLine()) != null) {
            //    out.print(line);
            //}
        } catch (Exception e) {
            PrintWriter out = response.getWriter();
            out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            out.println("<servlet-exception>");
            out.println(e.toString());
            out.println("</servlet-exception>");
            out.close();
        } finally {
            try {
                if (xmlIn != null) {
                    xmlIn.close();
                }
            } catch (Exception e1) {
                PrintWriter out = response.getWriter();
                out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                out.println("<servlet-exception>");
                out.println(e1.toString());
                out.println("</servlet-exception>");
                out.close();
            }

            try {
                if (xmlOut != null) {
                    xmlOut.close();
                }
            } catch (Exception e2) {
                PrintWriter out = response.getWriter();
                out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                out.println("<servlet-exception>");
                out.println(e2.toString());
                out.println("</servlet-exception>");
                out.close();
            }
        }
    }
}

From source file:org.owasp.jbrofuzz.graph.canvas.ResponseHeaderSizeChart.java

private int calculateValue(final File inputFile) {

    if (inputFile.isDirectory()) {
        return -1;
    }//from   w ww  . j  a  v  a  2  s  .c o  m

    int headerLength = 0;

    BufferedReader inBuffReader = null;
    try {

        inBuffReader = new BufferedReader(new FileReader(inputFile));

        final StringBuffer one = new StringBuffer();
        int counter = 0;
        int got;
        while (((got = inBuffReader.read()) > 0) && (counter < MAX_CHARS)) {

            one.append((char) got);
            counter++;

        }
        inBuffReader.close();

        one.delete(0, one.indexOf(END_SIGNATURE) + END_SIGNATURE.length());

        headerLength = one.indexOf("\r\n\r\n");

        if (headerLength < 0) {

            headerLength = one.indexOf("\n\n");

        }

    } catch (final IOException e1) {

        return -2;

    } catch (final StringIndexOutOfBoundsException e2) {

        return -3;

    } catch (final NumberFormatException e3) {

        return -4;

    } finally {

        IOUtils.closeQuietly(inBuffReader);

    }

    return headerLength;
}

From source file:com.krawler.common.notification.handlers.NotificationExtractorManager.java

private void replaceExtraPlaceHolders(StringBuffer htmlMsg, Map<String, Object> extraParams) {
    try {/*from  ww  w .j  a v a  2  s. c  om*/
        Set keySets = extraParams.keySet();
        for (Object key : keySets) {
            String value = extraParams.get(key).toString();
            int i1 = htmlMsg.indexOf(key.toString());
            while (i1 >= 0) {
                int i2 = i1 + key.toString().length();
                if (StringUtil.isNullOrEmpty(value)) {
                    value = "";
                }
                htmlMsg.replace(i1, i2, value);
                i1 = htmlMsg.indexOf(key.toString());
            }
        }
    } catch (Exception ex) {
        LOG.info(ex.getMessage(), ex);
        ex.printStackTrace();
    }
}

From source file:org.acegisecurity.captcha.CaptchaEntryPoint.java

private void includeOriginalRequest(StringBuffer redirectUrl, HttpServletRequest req) {
    // add original request to the url
    if (redirectUrl.indexOf("?") >= 0) {
        redirectUrl.append("&");
    } else {/*w  w  w . j  a v a2 s .co m*/
        redirectUrl.append("?");
    }

    redirectUrl.append(originalRequestUrlParameterName);
    redirectUrl.append("=");

    try {
        redirectUrl.append(URLEncoder.encode(req.getRequestURL().toString(), urlEncodingCharset));
    } catch (UnsupportedEncodingException e) {
        logger.warn(e);
    }

    //append method
    redirectUrl.append("&");
    redirectUrl.append(originalRequestMethodParameterName);
    redirectUrl.append("=");
    redirectUrl.append(req.getMethod());

    if (includeOriginalParameters) {
        // append query params
        redirectUrl.append("&");
        redirectUrl.append(originalRequestParametersParameterName);
        redirectUrl.append("=");

        StringBuffer qp = new StringBuffer();
        Enumeration parameters = req.getParameterNames();

        if ((parameters != null) && parameters.hasMoreElements()) {
            //qp.append("?");
            while (parameters.hasMoreElements()) {
                String name = parameters.nextElement().toString();
                String value = req.getParameter(name);
                qp.append(name);
                qp.append(originalRequestParametersNameValueSeparator);
                qp.append(value);

                if (parameters.hasMoreElements()) {
                    qp.append(originalRequestParametersSeparator);
                }
            }
        }

        try {
            redirectUrl.append(URLEncoder.encode(qp.toString(), urlEncodingCharset));
        } catch (Exception e) {
            logger.warn(e);
        }
    }
}

From source file:org.jbpm.formModeler.fieldTypes.document.handling.JBPMDocumentFieldTypeHandler.java

@Override
public Object getValue(Field field, String inputName, Map parametersMap, Map filesMap, String desiredClassName,
        Object previousValue) throws Exception {
    Document oldDoc = (Document) previousValue;

    // Expecting a delete parameter, if we receive that the current file will be deleted from the system
    String[] deleteParam = (String[]) parametersMap.get(inputName + "_delete");
    boolean delete = oldDoc != null && (deleteParam != null && deleteParam.length > 0 && deleteParam[0] != null
            && Boolean.valueOf(deleteParam[0]).booleanValue());

    // if there is an uploaded file for that field we will delete the previous one (if existed) and will return the uploaded file path.
    File file = (File) filesMap.get(inputName);
    if (file != null) {
        // Getting the DocumentMarshallingStrategy for this project if exists any we build the document
        AbstractDocumentMarshallingStrategy marshallingStrategy = getDocumentMarshallingStrategy(inputName);
        if (marshallingStrategy != null) {
            StringBuffer url = RequestContext.getCurrentContext().getRequest().getRequestObject()
                    .getRequestURL();/*from ww w .j  a v a2s .c  o m*/

            Map<String, String> params = new HashMap<String, String>();
            params.put("app.url", url.substring(0, url.indexOf("/Controller")));

            Document doc = marshallingStrategy.buildDocument(file.getName(), file.length(),
                    new Date(file.lastModified()), params);
            doc.setContent(FileUtils.readFileToByteArray(file));
            return doc;
        } else {
            Document doc = new DocumentImpl(file.getName(), file.length(), new Date(file.lastModified()));
            doc.setContent(FileUtils.readFileToByteArray(file));
            return doc;
        }
    }

    // If we receive the delete parameter or we are uploading a new file the current file will be deleted
    if (delete) {
        return null;
    }

    return oldDoc;
}

From source file:org.owasp.jbrofuzz.graph.canvas.ResponseSizeChart.java

private int calculateValue(final File inputFile) {

    if (inputFile.isDirectory()) {
        return -1;
    }/*from   ww  w. j av a2  s .  c o m*/

    long headerLength = 0L;

    BufferedReader inBuffReader = null;
    try {

        inBuffReader = new BufferedReader(new FileReader(inputFile));

        final StringBuffer one = new StringBuffer();
        int counter = 0;
        int got;
        while (((got = inBuffReader.read()) > 0) && (counter < MAX_CHARS)) {

            one.append((char) got);
            counter++;

        }
        inBuffReader.close();

        one.delete(0, 5);
        one.delete(one.indexOf("\n--"), one.length());

        headerLength = (one.indexOf(END_SIGNATURE) + END_SIGNATURE.length());

    } catch (final IOException e1) {

        return -2;

    } catch (final StringIndexOutOfBoundsException e2) {

        return -3;

    } catch (final NumberFormatException e3) {

        return -4;

    } finally {

        IOUtils.closeQuietly(inBuffReader);

    }

    return (int) (inputFile.length() - headerLength);
}