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:net.lightbody.bmp.proxy.jetty.http.ajp.AJP13Packet.java

public String toString(int max) {
    StringBuffer b = new StringBuffer();
    StringBuffer a = new StringBuffer();

    b.append(_bytes);//  w w w  .  ja  va2  s . c  o  m
    b.append('/');
    b.append(_buf.length);
    b.append('[');
    b.append(_pos);
    b.append("]: ");

    switch (_buf[__HDR_SIZE]) {
    case __FORWARD_REQUEST:
        b.append("FORWARD_REQUEST{:");
        break;
    case __SHUTDOWN:
        b.append("SHUTDOWN        :");
        break;
    case __SEND_BODY_CHUNK:
        b.append("SEND_BODY_CHUNK :");
        break;
    case __SEND_HEADERS:
        b.append("SEND_HEADERS  ( :");
        break;
    case __END_RESPONSE:
        b.append("END_RESPONSE  )}:");
        break;
    case __GET_BODY_CHUNK:
        b.append("GET_BODY_CHUNK  :");
        break;
    }

    if (max == 0)
        return b.toString();

    b.append("\n");

    for (int i = 0; i < _bytes; i++) {
        int d = _buf[i] & 0xFF;
        if (d < 16)
            b.append('0');
        b.append(Integer.toString(d, 16));

        char c = (char) d;

        if (Character.isLetterOrDigit(c))
            a.append(c);
        else
            a.append('.');

        if (i % 32 == 31 || i == (_bytes - 1)) {
            b.append(" : ");
            b.append(a.toString());
            a.setLength(0);
            b.append("\n");
            if (max > 0 && (i + 1) >= max)
                break;
        } else
            b.append(",");
    }

    return b.toString();
}

From source file:com.cloud.bridge.service.controller.s3.S3ObjectAction.java

public void executePostObject(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String bucket = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
    String contentType = request.getHeader("Content-Type");
    int boundaryIndex = contentType.indexOf("boundary=");
    String boundary = "--" + (contentType.substring(boundaryIndex + 9));
    String lastBoundary = boundary + "--";

    InputStreamReader isr = new InputStreamReader(request.getInputStream());
    BufferedReader br = new BufferedReader(isr);

    StringBuffer temp = new StringBuffer();
    String oneLine = null;//from   www  .  j a v a  2 s .c o  m
    String name = null;
    String value = null;
    String metaName = null; // -> after stripped off the x-amz-meta-
    boolean isMetaTag = false;
    int countMeta = 0;
    int state = 0;

    // [A] First parse all the parts out of the POST request and message body
    // -> bucket name is still encoded in a Host header
    S3AuthParams params = new S3AuthParams();
    List<S3MetaDataEntry> metaSet = new ArrayList<S3MetaDataEntry>();
    S3PutObjectInlineRequest engineRequest = new S3PutObjectInlineRequest();
    engineRequest.setBucketName(bucket);

    // -> the last body part contains the content that is used to write the S3 object, all
    //    other body parts are header values
    while (null != (oneLine = br.readLine())) {
        if (oneLine.startsWith(lastBoundary)) {
            // -> this is the data of the object to put
            if (0 < temp.length()) {
                value = temp.toString();
                temp.setLength(0);

                engineRequest.setContentLength(value.length());
                engineRequest.setDataAsString(value);
            }
            break;
        } else if (oneLine.startsWith(boundary)) {
            // -> this is the header data
            if (0 < temp.length()) {
                value = temp.toString().trim();
                temp.setLength(0);
                //System.out.println( "param: " + name + " = " + value );

                if (name.equalsIgnoreCase("key")) {
                    engineRequest.setKey(value);
                } else if (name.equalsIgnoreCase("x-amz-acl")) {
                    engineRequest.setCannedAccess(value);
                } else if (isMetaTag) {
                    S3MetaDataEntry oneMeta = new S3MetaDataEntry();
                    oneMeta.setName(metaName);
                    oneMeta.setValue(value);
                    metaSet.add(oneMeta);
                    countMeta++;
                    metaName = null;
                }

                // -> build up the headers so we can do authentication on this POST
                HeaderParam oneHeader = new HeaderParam();
                oneHeader.setName(name);
                oneHeader.setValue(value);
                params.addHeader(oneHeader);
            }
            state = 1;
        } else if (1 == state && 0 == oneLine.length()) {
            // -> data of a body part starts here 
            state = 2;
        } else if (1 == state) {
            // -> the name of the 'name-value' pair is encoded in the Content-Disposition header
            if (oneLine.startsWith("Content-Disposition: form-data;")) {
                isMetaTag = false;
                int nameOffset = oneLine.indexOf("name=");
                if (-1 != nameOffset) {
                    name = oneLine.substring(nameOffset + 5);
                    if (name.startsWith("\""))
                        name = name.substring(1);
                    if (name.endsWith("\""))
                        name = name.substring(0, name.length() - 1);
                    name = name.trim();

                    if (name.startsWith("x-amz-meta-")) {
                        metaName = name.substring(11);
                        isMetaTag = true;
                    }
                }
            }
        } else if (2 == state) {
            // -> the body parts data may take up multiple lines
            //System.out.println( oneLine.length() + " body data: " + oneLine );
            temp.append(oneLine);
        }
        //         else System.out.println( oneLine.length() + " preamble: " + oneLine );
    }

    // [B] Authenticate the POST request after we have all the headers
    try {
        S3RestServlet.authenticateRequest(request, params);
    } catch (Exception e) {
        throw new IOException(e.toString());
    }

    // [C] Perform the request
    if (0 < countMeta)
        engineRequest.setMetaEntries(metaSet.toArray(new S3MetaDataEntry[0]));
    S3PutObjectInlineResponse engineResponse = ServiceProvider.getInstance().getS3Engine()
            .handleRequest(engineRequest);
    response.setHeader("ETag", engineResponse.getETag());
    String version = engineResponse.getVersion();
    if (null != version)
        response.addHeader("x-amz-version-id", version);
}

From source file:com.pureinfo.srm.outlay.action.OutlayAssginCheckAction.java

/**
 * get message content/*  www .j  ava  2 s  .co m*/
 * 
 * @param _project
 * @param _sFailed
 * @return
 * @throws PureException 
 */
private String messageContentForCheckEdit(Project _project, OutlayAssgin _oa, String _sFailed,
        boolean _bApprove) throws PureException {
    StringBuffer buffer = new StringBuffer();
    Date date = new Date();
    SRMUser prjAdmin = _project.getAdministrator();
    SRMUser _loginuser = (SRMUser) ArkHelper.getLoginUser();
    String authorName = "";
    String checkName = "";
    if (prjAdmin != null) {
        authorName = prjAdmin.getTrueName();
    }
    if (_loginuser != null) {
        checkName = _loginuser.getTrueName();
    }
    String dateStr = DateUtil.formatDate(date, "yyyy-MM-dd HH:mm");
    String dateYMD = DateUtil.formatDate(date, "yyyy-MM-dd");
    try {
        buffer.append(authorName + ",:\n");
        if (_bApprove) {
            buffer.append("");
            buffer.append("");
            buffer.append(_project.getProjectName());
            buffer.append("");
            buffer.append(dateStr + " ");
            buffer.append(_sFailed);
        } else {
            buffer.append("");
            buffer.append(_project.getProjectName());
            buffer.append("\n");
            buffer.append(":");
            buffer.append(_oa.getCheckSuggestion());
        }
        buffer.append("\n");
        buffer.append(checkName);
        buffer.append("\n\r");
        buffer.append("\n");
        buffer.append(dateYMD);

        return buffer.toString();
    } finally {
        if (buffer != null) {
            buffer.setLength(0);
        }
    }
}

From source file:jp.ksksue.app.terminal.AndroidUSBSerialMonitorLite.java

/**
 * <p>Unescapes any Java literals found in the <code>String</code> to a
 * <code>Writer</code>.</p>
 *
 * <p>For example, it will turn a sequence of <code>'\'</code> and
 * <code>'n'</code> into a newline character, unless the <code>'\'</code>
 * is preceded by another <code>'\'</code>.</p>
 * /* w w w  .ja v a2  s .  co m*/
 * <p>A <code>null</code> string input has no effect.</p>
 * 
 * @param out  the <code>String</code> used to output unescaped characters
 * @param str  the <code>String</code> to unescape, may be null
 * @throws IllegalArgumentException if the Writer is <code>null</code>
 * @throws IOException if error occurs on underlying Writer
 */
private String unescapeJava(String str) throws IOException {
    if (str == null) {
        return "";
    }
    int sz = str.length();
    StringBuffer unicode = new StringBuffer(4);

    StringBuilder strout = new StringBuilder();
    boolean hadSlash = false;
    boolean inUnicode = false;
    for (int i = 0; i < sz; i++) {
        char ch = str.charAt(i);
        if (inUnicode) {
            // if in unicode, then we're reading unicode
            // values in somehow
            unicode.append(ch);
            if (unicode.length() == 4) {
                // unicode now contains the four hex digits
                // which represents our unicode character
                try {
                    int value = Integer.parseInt(unicode.toString(), 16);
                    strout.append((char) value);
                    unicode.setLength(0);
                    inUnicode = false;
                    hadSlash = false;
                } catch (NumberFormatException nfe) {
                    // throw new NestableRuntimeException("Unable to parse unicode value: " + unicode, nfe);
                    throw new IOException("Unable to parse unicode value: " + unicode, nfe);
                }
            }
            continue;
        }
        if (hadSlash) {
            // handle an escaped value
            hadSlash = false;
            switch (ch) {
            case '\\':
                strout.append('\\');
                break;
            case '\'':
                strout.append('\'');
                break;
            case '\"':
                strout.append('"');
                break;
            case 'r':
                strout.append('\r');
                break;
            case 'f':
                strout.append('\f');
                break;
            case 't':
                strout.append('\t');
                break;
            case 'n':
                strout.append('\n');
                break;
            case 'b':
                strout.append('\b');
                break;
            case 'u': {
                // uh-oh, we're in unicode country....
                inUnicode = true;
                break;
            }
            default:
                strout.append(ch);
                break;
            }
            continue;
        } else if (ch == '\\') {
            hadSlash = true;
            continue;
        }
        strout.append(ch);
    }
    if (hadSlash) {
        // then we're in the weird case of a \ at the end of the
        // string, let's output it anyway.
        strout.append('\\');
    }
    return new String(strout.toString());
}

From source file:org.ednovo.gooru.domain.service.resource.ResourceImportServiceImpl.java

@Override
@Transactional(readOnly = false, propagation = Propagation.NOT_SUPPORTED, noRollbackFor = Exception.class)
public void createOrUpdateResource(String filename, User user) {
    final String mediaFileName = UserGroupSupport.getUserOrganizationNfsInternalPath()
            + Constants.UPLOADED_MEDIA_FOLDER + '/' + filename;
    List<String> keys = null;
    StringBuffer json = new StringBuffer();
    CSVReader csvReader = null;// www .  ja v  a 2s  .com
    File file = null;
    try {
        file = new File(mediaFileName);
        csvReader = new CSVReader(new FileReader(file));
        String[] row = null;
        while ((row = csvReader.readNext()) != null) {
            if (keys == null) {
                keys = getJsonKeys(row);
            } else {
                String data = formInputJson(row, json, keys).toString();
                JSONObject jsonObj = requestData(generateJSONInput(data, UNDER_SCORE));
                String gooruOid = getValue(GOORU_OID, requestData(getValue(RESOURCE, jsonObj)));
                if (!(StringUtils.isBlank(gooruOid))) {
                    this.getResourceService().updateResource(gooruOid,
                            this.buildResourceFromInputParameters(getValue(RESOURCE, jsonObj)),
                            getValue(RESOURCE_TAGS, jsonObj) == null ? null
                                    : buildResourceTags(getValue(RESOURCE_TAGS, jsonObj)),
                            user);
                } else {
                    this.getResourceService().createResource(
                            this.getResourceService()
                                    .buildResourceFromInputParameters(getValue(RESOURCE, jsonObj), user),
                            (getValue(RESOURCE_TAGS, jsonObj) != null)
                                    ? buildResourceTags(getValue(RESOURCE_TAGS, jsonObj))
                                    : null,
                            user, true);
                }
                json.setLength(0);
            }
        }
    } catch (FileNotFoundException e) {
        throw new NotFoundException(generateErrorMessage(GL0056, FILE), GL0056);
    } catch (Exception e) {
        LOGGER.error(_ERROR, e);
    } finally {
        try {
            if (file.exists()) {
                csvReader.close();
                file.delete();
            }
        } catch (Exception e) {
            LOGGER.error(_ERROR, e);
        }
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.search.solr.documentBuilding.IndividualToSolrDocument.java

protected void addAllText(Individual ind, SolrInputDocument doc, StringBuffer classPublicNames,
        StringBuffer objectNames) {
    String t = null;//w  w  w  . jav a2s .  com
    //ALLTEXT, all of the 'full text'
    StringBuffer allTextValue = new StringBuffer();

    //collecting data property statements
    List<DataPropertyStatement> dataPropertyStatements = ind.getDataPropertyStatements();
    if (dataPropertyStatements != null) {
        Iterator<DataPropertyStatement> dataPropertyStmtIter = dataPropertyStatements.iterator();
        while (dataPropertyStmtIter.hasNext()) {
            DataPropertyStatement dataPropertyStmt = dataPropertyStmtIter.next();
            if (dataPropertyStmt.getDatapropURI().equals(label)) { // we don't want label to be added to alltext
                continue;
            } else if (dataPropertyStmt.getDatapropURI()
                    .equals("http://vivoweb.org/ontology/core#preferredTitle")) {
                //add the preferredTitle field
                String preferredTitle = null;
                doc.addField(term.PREFERRED_TITLE,
                        ((preferredTitle = dataPropertyStmt.getData()) == null) ? "" : preferredTitle);
                log.debug("Preferred Title: " + dataPropertyStmt.getData());
            }
            allTextValue.append(" ");
            allTextValue.append(((t = dataPropertyStmt.getData()) == null) ? "" : t);
        }
    }

    allTextValue.append(objectNames.toString());

    allTextValue.append(' ');
    allTextValue.append(classPublicNames);

    try {
        String stripped = Jsoup.parse(allTextValue.toString()).text();
        allTextValue.setLength(0);
        allTextValue.append(stripped);
    } catch (Exception e) {
        log.debug("Could not strip HTML during search indexing. " + e);
    }

    String alltext = allTextValue.toString();

    doc.addField(term.ALLTEXT, alltext);
    doc.addField(term.ALLTEXTUNSTEMMED, alltext);
    doc.addField(term.ALLTEXT_PHONETIC, alltext);
}

From source file:org.apache.hadoop.mapreduce.jobhistory.HistoryViewer.java

private void printAnalysis(JobHistoryParser.TaskAttemptInfo[] tasks,
        Comparator<JobHistoryParser.TaskAttemptInfo> cmp, String taskType, long avg, int showTasks) {
    Arrays.sort(tasks, cmp);/*from   www .j av  a2  s .c om*/
    JobHistoryParser.TaskAttemptInfo min = tasks[tasks.length - 1];
    StringBuffer details = new StringBuffer();
    details.append("\nTime taken by best performing ");
    details.append(taskType).append(" task ");
    details.append(min.getAttemptId().getTaskID().toString()).append(": ");
    if ("map".equals(taskType)) {
        details.append(StringUtils.formatTimeDiff(min.getFinishTime(), min.getStartTime()));
    } else if ("shuffle".equals(taskType)) {
        details.append(StringUtils.formatTimeDiff(min.getShuffleFinishTime(), min.getStartTime()));
    } else {
        details.append(StringUtils.formatTimeDiff(min.getFinishTime(), min.getShuffleFinishTime()));
    }
    details.append("\nAverage time taken by ");
    details.append(taskType).append(" tasks: ");
    details.append(StringUtils.formatTimeDiff(avg, 0));
    details.append("\nWorse performing ");
    details.append(taskType).append(" tasks: ");
    details.append("\nTaskId\t\tTimetaken");
    System.out.println(details.toString());
    for (int i = 0; i < showTasks && i < tasks.length; i++) {
        details.setLength(0);
        details.append(tasks[i].getAttemptId().getTaskID()).append(" ");
        if ("map".equals(taskType)) {
            details.append(StringUtils.formatTimeDiff(tasks[i].getFinishTime(), tasks[i].getStartTime()));
        } else if ("shuffle".equals(taskType)) {
            details.append(
                    StringUtils.formatTimeDiff(tasks[i].getShuffleFinishTime(), tasks[i].getStartTime()));
        } else {
            details.append(
                    StringUtils.formatTimeDiff(tasks[i].getFinishTime(), tasks[i].getShuffleFinishTime()));
        }
        System.out.println(details.toString());
    }
}

From source file:com.zenkey.net.prowser.Request.java

/**************************************************************************
 * Uses this <code>Request</code> object's current collection of
 * parameters to build a query string for the request's URI.
 * <p>//from   www. j  a  v  a2  s .c o  m
 * This method should be called internally by any method of the
 * <code>Request</code> class that adds, changes or removes a parameter.
 * However, this method should <b>only</b> be called for a request that
 * uses the HTTP <code>GET</code> method because the <code>POST</code>
 * method does not use query strings within URIs.
 */
private void updateQueryString() {

    String newQueryString = null;

    // If request parameters exist, process them
    Map<String, String[]> parameterMap;
    if ((parameterMap = getParameterMap()) != null) {

        // Build a query string from the parameters
        StringBuffer newQueryStringBuffer = new StringBuffer(EMPTY_STRING);
        for (String name : parameterMap.keySet()) {
            String[] values = getParameterValues(name);
            for (String value : values) {
                newQueryStringBuffer.append(name + "=" + value + "&");
            }
        }

        // Remove the trailing "&" from the new query string
        if (newQueryStringBuffer.length() > 0)
            newQueryStringBuffer.setLength(newQueryStringBuffer.length() - 1);

        // Convert the StringBuffer to a String
        newQueryString = newQueryStringBuffer.toString();
    }

    // Rebuild the URI with the new query string
    try {
        String encodedUri = (uri.getScheme() == null ? EMPTY_STRING : uri.getScheme())
                + (uri.getRawAuthority() == null ? EMPTY_STRING : "://" + uri.getRawAuthority())
                + (uri.getRawPath() == null ? EMPTY_STRING : uri.getRawPath())
                + (newQueryString == null ? EMPTY_STRING : "?" + newQueryString)
                + (uri.getRawFragment() == null ? EMPTY_STRING : "#" + uri.getRawFragment());
        uri = new URI(encodedUri);
    }

    // This catch block should never be reached because this method is only
    // called after a valid URI established
    catch (URISyntaxException e) {
        throw new IllegalStateException("URI syntax exception occurred during update of request query "
                + "string (" + e.getMessage() + ")");
    }
}

From source file:org.htmlcleaner.XWikiDOMSerializer.java

/**
 * Perform CDATA transformations if the user has specified to use CDATA inside scripts and style elements.
 *
 * @param document the W3C Document to use for creating new DOM elements
 * @param element the W3C element to which we'll add the text content to
 * @param bufferedContent the buffered text content on which we need to perform the CDATA transformations
 * @param item the current HTML Cleaner node being processed
 *///from   www  . java 2 s  . c om
private void flushContent(Document document, Element element, StringBuffer bufferedContent, Object item) {
    if (bufferedContent.length() > 0 && !(item instanceof ContentNode)) {
        // Flush the buffered content
        boolean specialCase = this.props.isUseCdataForScriptAndStyle() && isScriptOrStyle(element);
        String content = bufferedContent.toString();

        if (this.escapeXml && !specialCase) {
            content = Utils.escapeXml(content, this.props, true);
        } else if (specialCase) {
            content = processCDATABlocks(content);
        }

        // Generate a javascript comment in front on the CDATA block so that it works in IE and when
        // serving XHTML under a mimetype of HTML.
        if (specialCase) {
            if (SCRIPT_TAG_NAME.equalsIgnoreCase(element.getNodeName())) {
                // JS
                element.appendChild(document.createTextNode(JS_COMMENT));
                element.appendChild(document.createCDATASection(NEW_LINE + content + NEW_LINE + JS_COMMENT));
            } else {
                // CSS
                element.appendChild(document.createTextNode(CSS_COMMENT_START));
                element.appendChild(document.createCDATASection(
                        CSS_COMMENT_END + StringUtils.chomp(content) + NEW_LINE + CSS_COMMENT_START));
                element.appendChild(document.createTextNode(CSS_COMMENT_END));
            }
        } else {
            element.appendChild(document.createTextNode(content));
        }

        bufferedContent.setLength(0);
    }
}

From source file:com.vladium.emma.report.html.ReportGenerator.java

private void addClassRow(final ClassItem item, final int clsIndex, final HTMLTable table, final int[] columns,
        final String itemHREF, final boolean isAnchor) {
    if ($assert.ENABLED) {
        $assert.ASSERT(item != null, "null input: item");
        $assert.ASSERT(table != null, "null input: table");
        $assert.ASSERT(columns != null, "null input: columns");
    }/*  ww w  .  j av a  2 s.  c om*/

    final HTMLTable.IRow blank = table.newRow();

    final HTMLTable.IRow row = table.newRow();
    row.setClass(CSS_CLASS_ITEM_SPECIAL);

    final StringBuffer buf = new StringBuffer(11);

    for (int c = 0; c < columns.length; ++c) {
        final int attrID = columns[c];
        final IItemAttribute attr = item.getAttribute(attrID, m_settings.getUnitsType());

        if (attr != null) {
            buf.setLength(0);
            attr.format(item, buf);

            final HTMLTable.ICell blankcell = blank.newCell();
            blankcell.setClass(clsIndex == 0 ? CSS_BLANK : CSS_BOTTOM);
            blankcell.setText(" ", true);

            final HTMLTable.ICell cell = row.newCell();

            boolean fail = false;
            if (attrID == IItemAttribute.ATTRIBUTE_NAME_ID) {
                if (itemHREF != null) {
                    final String fullItemHREF = isAnchor ? "#".concat(itemHREF) : itemHREF;

                    cell.add(new Text("class ", true));
                    cell.add(new HyperRef(fullItemHREF, buf.toString(), true));
                } else {
                    cell.setText("class " + buf.toString(), true);
                }
            } else {
                fail = (m_metrics[attrID] > 0) && !attr.passes(item, m_metrics[attrID]);

                cell.setText(buf.toString(), true);
            }

            cell.setClass(dataCellStyle(c, fail));
        } else {
            final HTMLTable.ICell cell = row.newCell();
            cell.setText(" ", true);
            cell.setClass(dataCellStyle(c, false));
        }
    }
}