Example usage for java.lang StringBuffer substring

List of usage examples for java.lang StringBuffer substring

Introduction

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

Prototype

@Override
public synchronized String substring(int start) 

Source Link

Usage

From source file:se.simonsoft.cms.testing.svn.SvnTestSetup.java

String trySvnHttpParentUrls() {
    StringBuffer tried = new StringBuffer();
    for (String u : TRY_URLS) {
        tried.append(", ").append(u);
        if (isHttpUrlSvnParent(u))
            return u;
    }//from w  w w  .j  a  v  a 2  s.c  o m
    throw new RuntimeException(
            "Svn test setup failed because none of these URLS were found to be an svn parent path: "
                    + tried.substring(2));
}

From source file:com.edgenius.wiki.render.filter.NewlineFilter.java

@Override
public void replace(StringBuffer buffer, MatchResult matchResult, RenderContext context) {
    String all = matchResult.group(0);
    // space, \t \r etc. 
    String prefix = matchResult.group(1);
    //remove all \r but keep space or \t etc
    prefix = prefix.replaceAll("\\r", "");
    buffer.append(prefix);/*from w  w w .j  a  v a2  s .  c o m*/

    int count = StringUtils.countMatches(all, NEWLINE);
    if (buffer.length() >= WikiConstants.UUID_KEY_SIZE - 1 && context
            .isUniqueKey(buffer.substring(buffer.length() - WikiConstants.UUID_KEY_SIZE + 1) + "\n")) {
        if (count == 1) {
            buffer.append(all);
            return;
        } else {
            buffer.append("\n");
            count--;
        }
    }
    //TODO: bug: if before newline, there is a region, which will be replaced to a string. how to detect isEndByBlockHtmlTag()?

    //if it is after a block HTML, such as after Hr, page needn't append the first br.
    //if following tag is Block html tag or not, it does not matter if there are br or not.
    //I checked in FF3, the Block HTML tag will ignore its the first <br> before it.
    if (RenderUtil.isEndByBlockHtmlTag(buffer)) {
        count--;
        //TinyMCE eat "\n"
        //but, keep this "\n" information to render text, it is useful in RichTag render
        buffer.append(NEWLINE_HIDDEN_TAG).append("</span>");
    }

    int para = count / 2;
    for (int idx = 0; idx < para; idx++) {
        if (buffer.length() == 0) {
            //for any empty new lines on the beginning of content, use <br> instead <p>
            //The reason do so, is, in rich to markup convert, first <p> at text begin will be ignore 
            buffer.append(NEWLINE_TAG).append(NEWLINE_TAG);
        } else {
            //can not user <p class="xxx"/> to replace <p class="xxx"></p>, at least FF show wrong if use <p/> 
            buffer.append(PARAGRAPH_TAG);
        }
    }

    int br = count % 2;
    if (br > 0)
        buffer.append(NEWLINE_TAG);
}

From source file:com.navjagpal.fileshare.WebServer.java

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

    BasicHttpEntityEnclosingRequest enclosingRequest = new BasicHttpEntityEnclosingRequest(
            request.getRequestLine());//from w w  w .  j a  v  a2  s  .  co  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:se.simonsoft.cms.testing.svn.SvnTestSetup.java

File trySvnParentPaths() {
    StringBuffer tried = new StringBuffer();
    for (String p : TRY_PATHS) {
        tried.append(", ").append(p);
        File f = new File(p);
        if (f.exists() && f.isDirectory() && f.canWrite()) {
            return f;
        }/* w  w  w .  j a v a2 s. c o  m*/
    }
    throw new RuntimeException(
            "Svn test setup failed to find a suitable parent path among: " + tried.substring(2));
}

From source file:org.xwiki.rendering.internal.parser.reference.GenericLinkReferenceParser.java

/**
 * Find out the element located to the right of the passed separator.
 * //w  ww. ja va 2  s  .  c o  m
 * @param content the string to parse. This parameter will be modified by the method to remove the parsed content.
 * @param separator the separator string to locate the element
 * @return the parsed element or null if the separator string wasn't found
 */
protected String parseElementAfterString(StringBuffer content, String separator) {
    String element = null;

    // Find the first non escaped separator (starting from the end of the content buffer).
    int index = content.lastIndexOf(separator);
    while (index != -1) {
        // Check if the element is found and it's not escaped.
        if (!shouldEscape(content, index)) {
            element = content.substring(index + separator.length()).trim();
            content.delete(index, content.length());
            break;
        }

        if (index > 0) {
            index = content.lastIndexOf(separator, index - 1);
        } else {
            break;
        }
    }

    return element;
}

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());//from ww w  . ja  v a2s . c om
    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.jsecurity.web.RedirectView.java

/**
 * Append query properties to the redirect URL.
 * Stringifies, URL-encodes and formats model attributes as query properties.
 *
 * @param targetUrl      the StringBuffer to append the properties to
 * @param model          Map that contains model attributes
 * @param encodingScheme the encoding scheme to use
 * @throws java.io.UnsupportedEncodingException
 *          if string encoding failed/*w  w  w.  jav  a  2  s. c  o  m*/
 * @see #queryProperties
 */
protected void appendQueryProperties(StringBuffer targetUrl, Map model, String encodingScheme)
        throws UnsupportedEncodingException {

    // Extract anchor fragment, if any.
    // The following code does not use JDK 1.4's StringBuffer.indexOf(String)
    // method to retain JDK 1.3 compatibility.
    String fragment = null;
    int anchorIndex = targetUrl.toString().indexOf('#');
    if (anchorIndex > -1) {
        fragment = targetUrl.substring(anchorIndex);
        targetUrl.delete(anchorIndex, targetUrl.length());
    }

    // If there aren't already some parameters, we need a "?".
    boolean first = (getUrl().indexOf('?') < 0);
    Map queryProps = queryProperties(model);

    if (queryProps != null) {
        for (Object o : queryProps.entrySet()) {
            if (first) {
                targetUrl.append('?');
                first = false;
            } else {
                targetUrl.append('&');
            }
            Map.Entry entry = (Map.Entry) o;
            String encodedKey = urlEncode(entry.getKey().toString(), encodingScheme);
            String encodedValue = (entry.getValue() != null
                    ? urlEncode(entry.getValue().toString(), encodingScheme)
                    : "");
            targetUrl.append(encodedKey).append('=').append(encodedValue);
        }
    }

    // Append anchor fragment, if any, to end of URL.
    if (fragment != null) {
        targetUrl.append(fragment);
    }
}

From source file:edu.vt.cs.cnd2xsd.Cnd2XsdConverter.java

private void loadPropertyMap(String path) {
    FileInputStream stream = null;
    try {//  w  ww.  ja  va2 s  .com
        stream = new FileInputStream(path);
        attrMap = new HashMap<String, String[]>();
        byte[] buffer = new byte[512];
        StringBuffer stBuffer = new StringBuffer();
        while (stream.available() > 0) {
            int n = stream.read(buffer, 0, 512);
            stBuffer.append(new String(buffer, 0, n));
        }
        String value = stBuffer.substring(0);
        //now lets split the value into multiple lines
        String[] lines = value.split("\n");
        log.debug("Buffer contains :{} lines", lines.length);

        for (String line : lines) {
            String[] kvs = line.split("#");
            String key = kvs[0];
            String[] values = null;
            if (kvs.length > 1) {
                values = kvs[1].split(",");
                log.debug("Key: {} Value:{}", key, kvs[1]);
            }
            attrMap.put(key, values);

        }

    } catch (IOException ex) {
        log.error("Exception caught:", ex);
    }

    finally {
        try {
            stream.close();
        } catch (IOException ex) {
            log.error("Exception caught:", ex);
        }
    }

}

From source file:com.digitalpebble.storm.crawler.protocol.http.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 ava 2s  . co  m
        if (((pos = line.indexOf("<!DOCTYPE")) != -1) || ((pos = line.indexOf("<HTML")) != -1)
                || ((pos = line.indexOf("<html")) != -1)) {

            in.unread(line.substring(pos).getBytes(StandardCharsets.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:
                HttpProtocol.LOGGER.warn("Error: ", e);
            }
            return;
        }

        processHeaderLine(line);
    }
}

From source file:net.mlw.vlh.adapter.hibernate3.util.StatementBuilder.java

/**
 * Generete optimalized query for focusing large amount of data.
 * /*from ww  w  .  j ava2s .  co m*/
 * @param session
 * @param hql
 * @param whereClause
 * @param isRemoveEmptyStrings
 * @param defaultFocusPropertyObjectAlias
 * @param focusProperty
 * @return
 * @throws HibernateException
 * @throws ParseException
 */
public Query generateForFocus(Session session, StringBuffer hql, Map whereClause, boolean isRemoveEmptyStrings,
        String defaultFocusPropertyObjectAlias, String focusProperty)
        throws HibernateException, ParseException {
    StringBuffer hsqlFocus = new StringBuffer("SELECT ");
    hsqlFocus.append(defaultFocusPropertyObjectAlias);
    hsqlFocus.append(focusProperty);

    int indexOfTextFrom = hql.toString().toLowerCase().indexOf(" from ");
    if (indexOfTextFrom < 0) {
        indexOfTextFrom = hql.toString().toLowerCase().indexOf("from ");
        hsqlFocus.append(" ");
    }
    if (indexOfTextFrom > -1) {
        hsqlFocus.append(hql.substring(indexOfTextFrom));
        return generate(session, hsqlFocus, whereClause, isRemoveEmptyStrings);
    } else {
        LOGGER.error("HQL hasn't command FROM!!");
        return null;
    }
}