Example usage for java.lang StringBuffer setLength

List of usage examples for java.lang StringBuffer setLength

Introduction

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

Prototype

@Override
public synchronized void setLength(int newLength) 

Source Link

Usage

From source file:com.pureinfo.srm.auth.ShowCheckboxGroupFunctionHandler.java

private String doPerform(String _sName, String _sValue, String[] _arrayMaps) {
    String[] values = _sValue == null ? null : _sValue.split("\\$");
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < _arrayMaps.length; i++) {
        String map[] = _arrayMaps[i].split(":");
        if (map == null || map.length < 1) {
            continue;
        }/*from   ww w .  ja v a2  s  . c o m*/
        String sBoxValue = map[0];
        String sBoxShow = map.length > 1 ? map[1] : " ";
        sb.append("<INPUT type=\"checkbox\" name=\"").append(_sName).append("\" value=\"").append(sBoxValue)
                .append("\"");
        if (ArrayUtils.contains(values, sBoxValue)) {
            sb.append(" checked");
        }
        sb.append('>').append(sBoxShow);
    }
    String sResult = new String(sb);
    sb.setLength(0);
    return sResult;
}

From source file:org.eclipse.wst.ws.internal.parser.wsil.WebServicesParser.java

private byte[] getInputStreamAsByteArray(String uriString)
        throws MalformedURLException, IOException, WWWAuthenticationException {
    // Try to get a cached copy of the byte[]
    WebServiceEntity wsEntity = getWebServiceEntityByURI(uriString);
    if (wsEntity != null) {
        byte[] bytes = wsEntity.getBytes();
        if (bytes != null)
            return bytes;
    }/*from  w w w. ja  va  2s. c  om*/
    // Get the byte[] by opening a stream to the URI
    URL url = createURL(uriString);
    URLConnection conn = url.openConnection();
    // proxy server setting
    String proxyUserName = System.getProperty("http.proxyUserName");
    String proxyPassword = System.getProperty("http.proxyPassword");
    if (proxyUserName != null && proxyPassword != null) {
        StringBuffer userNamePassword = new StringBuffer(proxyUserName);
        userNamePassword.append(':').append(proxyPassword);
        Base64 encoder = new Base64();
        String encoding = new String(encoder.encode(userNamePassword.toString().getBytes()));
        userNamePassword.setLength(0);
        userNamePassword.append("Basic ").append(encoding);
        conn.setRequestProperty("Proxy-authorization", userNamePassword.toString());
    }
    // HTTP basic authentication setting
    if (httpBasicAuthUsername_ != null && httpBasicAuthPassword_ != null) {
        StringBuffer sb = new StringBuffer(httpBasicAuthUsername_);
        sb.append(':').append(httpBasicAuthPassword_);
        Base64 encoder = new Base64();
        String encoding = new String(encoder.encode(sb.toString().getBytes()));
        sb.setLength(0);
        sb.append("Basic ").append(encoding);
        conn.setRequestProperty("Authorization", sb.toString());
    }
    InputStream is = null;
    try {
        is = conn.getInputStream();
        String wwwAuthMsg = conn.getHeaderField("WWW-Authenticate");
        if (wwwAuthMsg != null)
            throw new WWWAuthenticationException(new IOException(), wwwAuthMsg, uriString);
    } catch (IOException ioe) {
        String wwwAuthMsg = conn.getHeaderField("WWW-Authenticate");
        if (wwwAuthMsg != null)
            throw new WWWAuthenticationException(ioe, wwwAuthMsg, uriString);
        else
            throw ioe;
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] b = new byte[1024];
    int byteRead = is.read(b);
    while (byteRead != -1) {
        baos.write(b, 0, byteRead);
        byteRead = is.read(b);
    }
    is.close();
    return baos.toByteArray();
}

From source file:org.jahia.modules.filter.WebClippingFilter.java

private String getURLContentWithPostMethod(String urlToClip, RenderContext renderContext, Resource resource,
        RenderChain chain, Map map) {
    String path = urlToClip;/*from w w w . j  a v  a2 s .  c om*/
    Map parameters = (Map) map.get("URL_PARAMS");
    // Get the httpClient
    HttpClient httpClient = new HttpClient();
    Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443));
    httpClient.getParams().setContentCharset("UTF-8");
    // Create a post method for accessing the url.
    PostMethod postMethod = new PostMethod(path);
    // Set a default retry handler (see httpclient doc).
    postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    if (parameters != null) {
        Iterator iterator = parameters.entrySet().iterator();
        StringBuffer buffer = new StringBuffer(4096);
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            if (!entry.getKey().toString().equals("original_method")
                    && !entry.getKey().toString().equals("jahia_url_web_clipping")) {
                final Object value = entry.getValue();
                if (value instanceof String[]) {
                    buffer.setLength(0);
                    String[] strings = (String[]) entry.getValue();
                    for (int i = 0; i < strings.length; i++) {
                        String string = strings[i];
                        buffer.append((i != 0) ? "," : "").append(string);
                    }
                    postMethod.addParameter(entry.getKey().toString(), buffer.toString());
                } else {
                    postMethod.addParameter(entry.getKey().toString(), value.toString());
                }
            }
        }
    }
    String contentCharset = httpClient.getParams().getContentCharset();
    httpClient.getParams().setContentCharset(contentCharset);
    return getResponse(path, renderContext, resource, chain, postMethod, httpClient);
}

From source file:org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport.HTTPTransport.java

private String getWWWAuthentication() {
    if (httpBasicAuthUsername != null && httpBasicAuthPassword != null) {
        StringBuffer sb = new StringBuffer(httpBasicAuthUsername);
        sb.append(COLON);/* w  w w. j  av  a 2s  . c  o  m*/
        sb.append(httpBasicAuthPassword);
        Base64 encoder = new Base64();
        String encodedUserNamePassword = new String(encoder.encode(sb.toString().getBytes()));
        sb.setLength(0);
        sb.append(HTTP_HEADER_AUTH);
        sb.append(COLON);
        sb.append(SPACE);
        sb.append(BASIC);
        sb.append(SPACE);
        sb.append(stripNewLine(encodedUserNamePassword));
        sb.append(NEW_LINE);
        return sb.toString();
    } else
        return EMPTY_STRING;
}

From source file:com.sec.ose.osi.sdk.protexsdk.discovery.report.ReportFactory.java

public static void parser(String projectName, BufferedReader htmlReportReader, UIResponseObserver observer,
        ReportType reportType) {/*w  w  w  .ja  v a 2 s  .  co  m*/
    String tmpLine = null;
    ArrayList<CodeMatchesPrecision> list = new ArrayList<CodeMatchesPrecision>();
    ArrayList<String> data = new ArrayList<String>();
    int insertedCnt = 0;

    if (htmlReportReader == null) {
        log.debug("Fail to generate " + projectName + " " + reportType + " Report");
        observer.setFailMessage("Fail to generate " + projectName + " " + reportType + " Report");
        return;
    }

    String msgHead = " > Creating Report : " + projectName + "\n";
    String pMessage = " >> Parsing [" + reportType.getType() + "] HTML file.";
    log.debug(pMessage);

    try {
        StringBuffer tmpValue = new StringBuffer("");
        while ((tmpLine = htmlReportReader.readLine()) != null) {
            tmpLine = tmpLine.trim();
            if (tmpLine.startsWith("<table border='0' cellspacing='0' cellpadding='0' class='reportTable'")) {
                while ((tmpLine = htmlReportReader.readLine()) != null) {
                    tmpLine = tmpLine.trim();
                    if (tmpLine.startsWith("</thead>")) {
                        break;
                    }
                }
                break;
            }
        }

        while ((tmpLine = htmlReportReader.readLine()) != null) {
            tmpLine = tmpLine.trim();
            if (tmpLine.startsWith("<tr ")) {
                int index = 0;
                while ((tmpLine = htmlReportReader.readLine()) != null) {
                    tmpLine = tmpLine.trim();
                    if (tmpLine.startsWith("<td ")) {
                        while ((tmpLine = htmlReportReader.readLine()) != null) {
                            tmpLine = tmpLine.trim();
                            if (tmpLine.startsWith("</td>")) {
                                String removedTagValue = removeHtmlTag(tmpValue);
                                data.add(removedTagValue);
                                tmpValue.setLength(0);
                                ++index;
                                break;
                            }
                            tmpValue.append(tmpLine);
                        }
                    }
                    if (tmpLine.startsWith("</tr>")) {
                        if (hasNoData(index)) {
                            break;
                        }
                        CodeMatchesPrecision codeMatchesPrecision = new CodeMatchesPrecision();
                        codeMatchesPrecision.setFile(data.get(0));
                        codeMatchesPrecision.setSize(Tools.transStringToInteger(data.get(1)));
                        codeMatchesPrecision.setFileLine(Tools.transStringToInteger(data.get(2)));
                        codeMatchesPrecision.setTotalLines(Tools.transStringToInteger(data.get(3)));
                        codeMatchesPrecision.setComponent(data.get(4));
                        codeMatchesPrecision.setVersion(data.get(5));
                        codeMatchesPrecision.setLicense(data.get(6));
                        codeMatchesPrecision.setUsage(data.get(7));
                        codeMatchesPrecision.setStatus(data.get(8));
                        codeMatchesPrecision.setPercentage(data.get(9));
                        codeMatchesPrecision.setMatchedFile(data.get(10));
                        codeMatchesPrecision.setMatchedFileLine(Tools.transStringToInteger(data.get(11)));
                        codeMatchesPrecision.setFileComment(data.get(12));
                        codeMatchesPrecision.setComponentComment(data.get(13));
                        list.add(codeMatchesPrecision);
                        data.clear();

                        insertedCnt++;
                        if (insertedCnt % 10000 == 0) {
                            log.debug("codeMatchesPrecision insertedCnt: " + insertedCnt);
                            if (observer != null) {
                                observer.pushMessageWithHeader(
                                        msgHead + pMessage + "\n >>> Inserted data count : " + insertedCnt);
                            }
                            insertCodematchTable(projectName, list);
                            list.clear();
                        }
                        break;
                    }
                }
            }
            if (tmpLine.startsWith("</table>")) {
                log.debug("codeMatchesPrecision insertedCnt: " + insertedCnt);
                insertCodematchTable(projectName, list);
                list.clear();
                break;
            }
        }
    } catch (IOException e) {
        ReportAPIWrapper.log.warn(e);
        String[] buttonOK = { "OK" };
        JOptionPane.showOptionDialog(null, "Out Of Memory Error", "Java heap space", JOptionPane.OK_OPTION,
                JOptionPane.ERROR_MESSAGE, null, buttonOK, "OK");
    }
    ReportAPIWrapper.log.debug("codeMatchesPrecision insertedCnt finally : " + insertedCnt);
}

From source file:com.lingxiang2014.entity.Article.java

@Transient
public String[] getPageContents() {
    if (StringUtils.isEmpty(content)) {
        return new String[] { "" };
    }// ww  w  .j av a2  s . com
    if (content.contains(PAGE_BREAK_SEPARATOR)) {
        return content.split(PAGE_BREAK_SEPARATOR);
    } else {
        List<String> pageContents = new ArrayList<String>();
        Document document = Jsoup.parse(content);
        List<Node> children = document.body().childNodes();
        if (children != null) {
            int textLength = 0;
            StringBuffer html = new StringBuffer();
            for (Node node : children) {
                if (node instanceof Element) {
                    Element element = (Element) node;
                    html.append(element.outerHtml());
                    textLength += element.text().length();
                    if (textLength >= PAGE_CONTENT_LENGTH) {
                        pageContents.add(html.toString());
                        textLength = 0;
                        html.setLength(0);
                    }
                } else if (node instanceof TextNode) {
                    TextNode textNode = (TextNode) node;
                    String text = textNode.text();
                    String[] contents = PARAGRAPH_SEPARATOR_PATTERN.split(text);
                    Matcher matcher = PARAGRAPH_SEPARATOR_PATTERN.matcher(text);
                    for (String content : contents) {
                        if (matcher.find()) {
                            content += matcher.group();
                        }
                        html.append(content);
                        textLength += content.length();
                        if (textLength >= PAGE_CONTENT_LENGTH) {
                            pageContents.add(html.toString());
                            textLength = 0;
                            html.setLength(0);
                        }
                    }
                }
            }
            String pageContent = html.toString();
            if (StringUtils.isNotEmpty(pageContent)) {
                pageContents.add(pageContent);
            }
        }
        return pageContents.toArray(new String[pageContents.size()]);
    }
}

From source file:org.nuxeo.ecm.webengine.model.impl.AbstractWebContext.java

@Override
public String getURL() {
    StringBuffer sb = request.getRequestURL();
    if (sb.charAt(sb.length() - 1) == '/') {
        sb.setLength(sb.length() - 1);
    }/*from w ww  .  j a  va  2  s.co m*/
    return sb.toString();
}

From source file:org.danann.cernunnos.runtime.XmlGrammar.java

public Phrase newPhrase(Node n) {

    // Assertions...
    if (n == null) {
        String msg = "Argument 'n [Node]' cannot be null.";
        throw new IllegalArgumentException(msg);
    }/*from   www.  j  a  v a  2 s  . c om*/

    List<String> chunks = new LinkedList<String>();
    String chunkMe = n.getText();
    while (chunkMe.length() != 0) {
        if (chunkMe.startsWith(Phrase.OPEN_PHRASE_DELIMITER)) {
            chunks.add(Phrase.OPEN_PHRASE_DELIMITER);
            chunkMe = chunkMe.substring(2);
        } else {
            chunks.add(chunkMe.substring(0, 1));
            chunkMe = chunkMe.substring(1);
        }
    }

    List<Phrase> children = new LinkedList<Phrase>();
    StringBuffer buffer = new StringBuffer();
    int openCount = 0;
    for (String chunk : chunks) {
        switch (openCount) {
        case 0:
            if (chunk.equals(Phrase.OPEN_PHRASE_DELIMITER)) {
                if (buffer.length() > 0) {
                    children.add(new LiteralPhrase(buffer.toString()));
                    buffer.setLength(0);
                }
                ++openCount;
            } else {
                buffer.append(chunk);
            }
            break;
        default:
            if (chunk.equals(Phrase.OPEN_PHRASE_DELIMITER)) {
                ++openCount;
                buffer.append(chunk);
            } else if (chunk.equals(Phrase.CLOSE_PHRASE_DELIMITER)) {
                --openCount;
                if (openCount == 0) {

                    // Time to create a dynamic component...
                    String expression = buffer.toString();
                    String name = null; // Name of the phrase to use...
                    String nested = null; // Content passed to the phrase

                    // Determine if a Phrase impl was specified or if we should use the default...
                    int openParenIndex = expression.indexOf("(");
                    if (openParenIndex != -1 && expression.endsWith(")")) {
                        // A phrase impl was specified -- use it!
                        try {
                            name = expression.substring(0, openParenIndex);
                            nested = expression.substring(expression.indexOf("(") + 1, expression.length() - 1);
                        } catch (Throwable t) {
                            String msg = "The specified expression is not well formed:  " + expression;
                            throw new RuntimeException(msg, t);
                        }
                    } else {
                        // Use the default phrase impl...
                        name = Grammar.DEFAULT_PHRASE_IMPL.getName();
                        nested = expression;
                    }

                    Entry y = getEntry(name, Entry.Type.PHRASE);
                    Phrase p = null;
                    try {

                        // Create & bootstrap the phrase...
                        EntityConfig config = prepareEntryConfig(y, fac.createText(nested), n.getUniquePath());
                        Phrase enclosed = (Phrase) y.getFormula().getImplementationClass().newInstance();
                        enclosed.init(config);
                        p = new RuntimePhraseDecorator(enclosed, config);

                    } catch (Throwable t) {
                        String msg = "Unable to create the specified phrase:  " + name;
                        throw new RuntimeException(msg, t);
                    }

                    children.add(p);
                    buffer.setLength(0);
                } else {
                    buffer.append(chunk);
                }
            } else {
                buffer.append(chunk);
            }
            break;
        }
    }
    if (buffer.length() > 0) {
        // Add anything that's left...
        children.add(new LiteralPhrase(buffer.toString()));
    }

    return new ConcatenatingPhrase(children);

}

From source file:com.stimulus.archiva.domain.Email.java

public String toString() {
    StringBuffer outStr = new StringBuffer(); //= emailId.toString();

    if (getEmailId() != null) {
        outStr.append(getEmailId().toString());
        outStr.append(",");
    }/*  ww w . ja  v  a2s.  co  m*/
    for (Iterator it = getFields().values().iterator(); it.hasNext();) {
        EmailFieldValue efv = (EmailFieldValue) it.next();
        outStr.append(efv);
        outStr.append(",");
    }
    outStr.setLength(outStr.length() - 1);
    return outStr.toString();
}

From source file:com.tremolosecurity.unison.openshiftv3.OpenShiftTarget.java

public String callWS(String token, HttpCon con, String uri) throws IOException, ClientProtocolException {
    StringBuffer b = new StringBuffer();

    b.append(this.url).append(uri);
    HttpGet get = new HttpGet(b.toString());
    b.setLength(0);
    b.append("Bearer ").append(token);
    get.addHeader(new BasicHeader("Authorization", "Bearer " + token));
    HttpResponse resp = con.getHttp().execute(get);

    String json = EntityUtils.toString(resp.getEntity());
    return json;/*from  w  ww  . j a  va2s .  c om*/
}