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.bstek.dorado.view.config.attachment.JavaScriptParser.java

private JavaScriptContent parse(StringBuffer source, JavaScriptContext context) throws IOException {
    StringBuffer reserveWord = new StringBuffer(8), modifiedSource = null;
    int autoNameSeed = 0, copyStart = 0;
    Boolean isController = context.getIsController();
    CodeReader reader = new CodeReader(source);
    try {/*from  w ww.ja v  a 2s .  c o  m*/
        while (true) {
            char c = reader.read();
            if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9'
                    || VALID_NAME_CHARS.indexOf(c) >= 0) {
                reserveWord.append(c);
            } else if (c == RETURN) {
                // do nothing
            } else if (c == ANONYMOUS_FUNCTION_PREFIX) {
                reserveWord.setLength(0);
                reserveWord.append(c);
            } else {
                int len = reserveWord.length();
                if (len > 0) {
                    if (len == FUNCTION_LEN && reserveWord.toString().equals(FUNCTION)) {
                        reader.moveCursor(-1);
                        String functionName = extractFunctionName(reader);
                        if (StringUtils.isNotEmpty(functionName)) {
                            if (context.isHasAnnotation()) {
                                FunctionInfo functionInfo = new FunctionInfo(functionName);
                                functionInfo.setBindingInfo(context.getCurrentBindingInfo());
                                functionInfo
                                        .setShouldRegisterToGlobal(context.getCurrentShouldRegisterToGlobal());
                                functionInfo.setShouldRegisterToView(context.getCurrentShouldRegisterToView());
                                context.addFunctionInfo(functionInfo);
                            }
                        }
                    } else if (len == ANONYMOUS_FUNCTION_LEN
                            && reserveWord.toString().equals(ANONYMOUS_FUNCTION)) {
                        reader.moveCursor(-1);
                        int copyEnd = reader.getCurrentPos() - ANONYMOUS_FUNCTION_LEN;
                        String functionName = extractFunctionName(reader);
                        if (StringUtils.isEmpty(functionName) && context.isHasAnnotation()) {
                            BindingInfo currentBindingInfo = context.getCurrentBindingInfo();
                            if (currentBindingInfo != null) {
                                functionName = AUTO_FUNCTION_NAME_PREFIX + (++autoNameSeed);

                                if (modifiedSource == null) {
                                    modifiedSource = new StringBuffer(source.length());
                                }

                                modifiedSource.append(source.substring(copyStart, copyEnd)).append(FUNCTION)
                                        .append(SPACE).append(functionName);
                                copyStart = reader.getCurrentPos() - 1;

                                FunctionInfo functionInfo = new FunctionInfo(functionName);
                                functionInfo.setBindingInfo(context.getCurrentBindingInfo());
                                context.addFunctionInfo(functionInfo);
                            }
                        }
                    }

                    if (context.isHasAnnotation()) {
                        context.reset();
                    }
                    reserveWord.setLength(0);
                } else {
                    if (c == BACKSLASH) {
                        c = reader.read();
                        if (c == BACKSLASH || c == STAR) {
                            parseComment(reader, (c == BACKSLASH), context);
                            isController = context.getIsController();
                            if (isController != null && !isController) {
                                break;
                            }
                            continue;
                        }
                    }

                    if (isController == null && c != SPACE && c != TAB && c != RETURN) {
                        context.setIsController(false);
                        break;
                    }

                    if (c == QUOTE1 || c == QUOTE2) {
                        skipString(reader, c);
                    } else if (c == BLOCK_START) {
                        skipBlock(reader, BLOCK_END);
                    } else if (c == BRACKET_START) {
                        skipBlock(reader, BRACKET_END);
                    }
                }
            }
        }
    } catch (EOFException e) {
        // do nothing
    }

    if (modifiedSource != null) {
        modifiedSource.append(source.substring(copyStart));
        source = modifiedSource;
    }

    JavaScriptContent javaScriptContent = new JavaScriptContent();
    javaScriptContent.setContent(source.toString());
    javaScriptContent.setIsController(context.getIsController());
    javaScriptContent.setFunctionInfos(context.getFunctionInfos());
    return javaScriptContent;
}

From source file:BasicEditor3.java

void printText(String text) {
    PrintDialog dialog = new PrintDialog(shell);
    PrinterData printerData = dialog.open();
    if (printerData == null)
        return;/*from   www  .j  a v  a 2 s.c  o m*/
    Printer printer = new Printer(printerData);
    if (!printer.startJob("text"))
        return;

    GC gc = new GC(printer);

    margins = PrintMargin.getPrintMargin(printer, 1.0);
    x = margins.left;
    y = margins.top;

    StringBuffer buffer = new StringBuffer();

    Font font = new Font(printer, "Arial", 12, SWT.NORMAL);
    gc.setFont(font);
    lineHeight = gc.getFontMetrics().getHeight();

    printer.startPage();
    // prints page number at the bottom margin. 
    String page = "- " + pageNumber + " -";
    gc.drawString(page, (margins.right - margins.left - gc.textExtent(page).x) / 2 + margins.left,
            margins.bottom + gc.textExtent(page).y);

    for (int index = 0; index < text.length();) {
        char c = text.charAt(index);

        switch (c) {
        case '\r':
            if (index < text.length() - 1 && text.charAt(index + 1) == '\n') {
                printNewLine(printer, gc, buffer.toString());
                buffer.setLength(0);
                index += 2;
            }
            break;

        case '\t':
        case ' ':
            if (gc.textExtent(buffer.toString() + ' ').x > margins.right - margins.left) {
                printNewLine(printer, gc, buffer.toString());
                buffer.setLength(0);
            }
            buffer.append(c);

            if (index < text.length() - 1 && (!Character.isWhitespace(text.charAt(index + 1)))) { // Looks up one word to see whether the line should wraps here.
                String word = readWord(text, index + 1);
                if (gc.textExtent(buffer.toString() + word).x > margins.right - margins.left) {
                    printNewLine(printer, gc, buffer.toString());
                    buffer.setLength(0);
                }
            }
            index += 1;
            break;

        default:
            buffer.append(c);
            index += 1;
        }
    }

    if (buffer.length() > 0)
        printNewLine(printer, gc, buffer.toString());

    if (y + lineHeight <= margins.bottom)
        printer.endPage();
    printer.endJob();

    gc.dispose();
    font.dispose();
    printer.dispose();
}

From source file:ca.hedlund.jiss.blocks.preprocessor.ListBlocksPreprocessor.java

@Override
public boolean preprocessCommand(JissModel jissModel, String orig, StringBuffer cmd) {
    if (!orig.startsWith("::block list"))
        return false;

    final ScriptEngine se = jissModel.getScriptEngine();
    final ScriptEngineFactory seFactory = se.getFactory();

    final boolean incnl = !seFactory.getOutputStatement("").startsWith("println");

    final List<String> blockInfoCmds = new ArrayList<String>();
    blockInfoCmds.add(seFactory.getOutputStatement("Available blocks:" + (incnl ? "\\n" : "")));

    final Matcher matcher = LIST_BLOCKS_PATTERN.matcher(orig);
    if (matcher.matches()) {
        final String blockNameRegex = matcher.group(1);
        final BlockManager bm = new BlockManager();

        for (String blockName : bm.getBlocks()) {
            boolean printBlock = true;
            if (blockNameRegex != null) {
                printBlock = blockName.matches(blockNameRegex);
            }/*  w w  w. j a v  a 2  s .com*/
            if (printBlock) {
                blockInfoCmds.add(seFactory.getOutputStatement(blockName) + (incnl ? "\\n" : ""));
            }
        }
    }

    final String program = seFactory.getProgram(blockInfoCmds.toArray(new String[0]));
    cmd.setLength(0);
    cmd.append(StringEscapeUtils.unescapeJava(program));

    return false;
}

From source file:org.hashtrees.test.HashTreesImplTest.java

@Test
public void testUpdateSegmentHashesTest() throws IOException {

    int rootNodeId = 0;
    int nodeId = 2;
    int segId = 1;
    int noOfSegments = 2;
    HashTreesStore[] stores = generateInMemoryAndPersistentStores();

    try {// w  w w  . ja v a 2 s  .  co m
        for (HashTreesStore store : stores) {
            HTreeComponents components = createHashTree(noOfSegments, false, TREE_ID_PROVIDER, SEG_ID_PROVIDER,
                    store);
            HashTrees testTree = components.hTree;

            ByteBuffer expectedKey = generateRandomKeyWithPrefix(segId);
            ByteBuffer expectedValue = ByteBuffer.wrap(randomBytes());
            StringBuffer sb = new StringBuffer();
            ByteBuffer expectedDigest = ByteBuffer.wrap(ByteUtils.sha1(expectedValue.array()));
            sb.append(HashTreesImpl.getHexString(expectedKey, expectedDigest) + "\n");
            byte[] expectedLeafNodeDigest = ByteUtils.sha1(sb.toString().getBytes());

            testTree.hPut(expectedKey, expectedValue);
            testTree.rebuildHashTree(SimpleTreeIdProvider.TREE_ID, false);
            SegmentHash segHash = testTree.getSegmentHash(SimpleTreeIdProvider.TREE_ID, nodeId);
            Assert.assertNotNull(segHash);
            Assert.assertTrue(Arrays.equals(expectedLeafNodeDigest, segHash.getHash()));

            sb.setLength(0);
            sb.append(Hex.encodeHexString(expectedLeafNodeDigest) + "\n");
            byte[] expectedRootNodeDigest = ByteUtils.sha1(sb.toString().getBytes());
            SegmentHash actualRootNodeDigest = testTree.getSegmentHash(SimpleTreeIdProvider.TREE_ID,
                    rootNodeId);
            Assert.assertNotNull(actualRootNodeDigest);
            Assert.assertTrue(Arrays.equals(expectedRootNodeDigest, actualRootNodeDigest.getHash()));
        }
    } finally {
        HashTreesImplTestUtils.closeStores(stores);
    }
}

From source file:com.silverpeas.ical.StringUtils.java

private static long resolveUnit(StringBuffer buffer) {
    long unit = 1;
    int i = -1;/*from  ww w .  ja va2  s .com*/
    for (;;) {
        i = buffer.indexOf("msec", 0);
        if (i != -1) {
            break;
        }
        i = buffer.indexOf("mill", 0);
        if (i != -1) {
            break;
        }
        i = buffer.indexOf("sec", 0);
        if (i != -1) {
            unit = 1000L;
            break;
        }
        i = buffer.indexOf("min", 0);
        if (i != -1) {
            unit = 1000L * 60;
            break;
        }
        i = buffer.indexOf("hour", 0);
        if (i != -1) {
            unit = 1000L * 60 * 60;
            break;
        }
        i = buffer.indexOf("day", 0);
        if (i != -1) {
            unit = 1000L * 60 * 60 * 24;
            break;
        }
        i = buffer.indexOf("week", 0);
        if (i != -1) {
            unit = 1000L * 60 * 60 * 24 * 7;
            break;
        }
        i = buffer.indexOf("month", 0);
        if (i != -1) {
            unit = 1000L * 60 * 60 * 24 * 30;
            break;
        }
        i = buffer.indexOf("year", 0);
        if (i != -1) {
            unit = 1000L * 60 * 60 * 24 * 365;
            break;
        }
        i = buffer.indexOf("kbyte", 0);
        if (i != -1) {
            unit = 1024L;
            break;
        }
        i = buffer.indexOf("mbyte", 0);
        if (i != -1) {
            unit = 1024L * 1024;
            break;
        }
        i = buffer.indexOf("gbyte", 0);
        if (i != -1) {
            unit = 1024L * 1024 * 1024;
            break;
        }
        i = buffer.indexOf("tbyte", 0);
        if (i != -1) {
            unit = 1024L * 1024 * 1024 * 1024;
            break;
        }
        i = buffer.indexOf("byte", 0);
        break;
    }
    if (i != -1) {
        buffer.setLength(i);
    }
    return unit;
}

From source file:com.sec.ose.osi.localdb.identification.IdentificationDBManager.java

synchronized public static void updateStringSearchForMultiFileFolderView(String pProjectName,
        ArrayList<String> pPaths, MultipleFileSummary pMultipleFileSummary) {

    String table = "stringsearch_" + getProjectTablePostfix(pProjectName);
    StringBuffer sqlString = new StringBuffer();
    HashMap<String, StringMatchInfoForFolder> stringMatchMap = new HashMap<String, StringMatchInfoForFolder>();
    for (String path : pPaths) {
        sqlString.setLength(0);
        sqlString.append(/*w  ww. j  ava2 s .com*/
                "select path, stringsearch, component, version, license, status, matchedLine, comment, count(CASE status WHEN '");
        sqlString.append(AbstractMatchInfo.STATUS_PENDING);
        sqlString.append("' THEN ");
        sqlString.append(AbstractMatchInfo.STATUS_IDENTIFIED);
        sqlString.append(" END) as pending, count(CASE status WHEN '");
        sqlString.append(AbstractMatchInfo.STATUS_IDENTIFIED);
        sqlString.append("' THEN ");
        sqlString.append(AbstractMatchInfo.STATUS_IDENTIFIED);
        sqlString.append(" END) as identified from ");
        sqlString.append(table);
        sqlString.append(" where path='");
        sqlString.append(path);
        sqlString.append("' GROUP BY stringsearch,component,version");

        log.debug("updateStringSearchInfoForMultipleFileFolderView : " + sqlString.toString());
        ResultSet rs = null;
        try {
            rs = selectSQL(sqlString.toString());
            while (rs.next()) {
                StringMatchInfoForFolder stringMatchFolder = new StringMatchInfoForFolder(
                        rs.getString(TableStringMatch.PATH), rs.getString(TableStringMatch.STRINGSEARCH),
                        rs.getString(TableStringMatch.COMPONENT), rs.getString(TableStringMatch.VERSION),
                        rs.getString(TableStringMatch.LICENSE), rs.getInt(TableStringMatch.PENDING_HITS),
                        rs.getInt(TableStringMatch.IDENTIFIED_HITS));

                String key = stringMatchFolder.getStringSearchName() + "_"
                        + stringMatchFolder.getComponentName() + "_" + stringMatchFolder.getVersionName();

                if (stringMatchMap.containsKey(key)) {
                    StringMatchInfoForFolder stringMatchFolderBase = stringMatchMap.get(key);
                    stringMatchFolderBase.increaseFileCount();
                    stringMatchFolderBase.plusPendingHits(stringMatchFolder.getPendingHits());
                    stringMatchFolderBase.plusIdentifiedHits(stringMatchFolder.getIdentifiedHits());
                } else {
                    stringMatchMap.put(key, stringMatchFolder);
                }
            }
            //         if(rs!=null) rs.close();
        } catch (Exception e) {
            log.debug(e);
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    log.debug(e);
                }
            }
        }
    }

    Iterator<Map.Entry<String, StringMatchInfoForFolder>> iter = stringMatchMap.entrySet().iterator();
    if (iter == null) {
        return;
    }

    while (iter.hasNext()) {
        String key = iter.next().getKey();
        StringMatchInfoForFolder stringMatchFolder = stringMatchMap.get(key);
        pMultipleFileSummary.addStringMatchInforForMultipleFileSummary(stringMatchFolder.getStringSearchName(),
                stringMatchFolder.getComponentName(), stringMatchFolder.getVersionName(),
                stringMatchFolder.getLicenseName(), stringMatchFolder.getFileCount(),
                stringMatchFolder.getPendingHits(), stringMatchFolder.getIdentifiedHits());
    }
}

From source file:com.sforce.LiveDataServiceImpl_SF.java

private String setBindParameters(QueryRunner queryRunner, String queryName, Object... valueObjs) {
    String name = "com/sforce/queries/sforce-queries.xml";
    InputStream is = this.getClass().getClassLoader().getResourceAsStream(name);

    HbmQueryParser p;//from  w  w w. j a  v  a 2  s  . c  om
    try {
        String s = IOUtils.toString(is);
        p = new HbmQueryParser(s);
        p.initAll();
    } catch (Exception ex) {
        throw new WMRuntimeException(ex);
    }

    QueryInfo qi = p.getQueries().get(queryName);

    Input[] inputs = qi.getInputs();

    List<String> names = null;
    List<String> types = null;
    List<Boolean> isList = null;
    StringBuffer sb = null;
    if (inputs != null && inputs.length > 0 && valueObjs != null && valueObjs.length > 0) {
        names = new ArrayList<String>(inputs.length);
        types = new ArrayList<String>(inputs.length);
        isList = new ArrayList<Boolean>(inputs.length);
        sb = new StringBuffer();

        for (int i = 0; i < inputs.length; i++) {
            names.add(inputs[i].getParamName());
            types.add(inputs[i].getParamType());
            isList.add(inputs[i].getList());
            if (inputs[i].getList()) {
                List<Object> vals = (List<Object>) valueObjs[i];
                sb = sb.append("[");
                for (Object val : vals) {
                    sb.append(val.toString());
                    sb.append(", ");
                }
                sb.setLength(sb.length() - 2);
                sb.append("], ");
            } else {
                sb.append(valueObjs[i].toString());
                sb.append(", ");
            }
        }
        sb.setLength(sb.length() - 2);
        queryRunner.addBindParameters(names, types, sb.toString(), isList);
    }

    return qi.getQuery();
}

From source file:org.apache.ode.bpel.elang.xpath20.compiler.XPath20ExpressionCompilerImpl.java

/**
 * Returns the list of variable references in the given XPath expression
 * that may not have been resolved properly, which is the case especially
 * if the expression contains a function, which short circuited the evaluation.
 *
 * @param xpathStr//  w  w w.  j  a v  a 2 s. co  m
 * @return list of variable expressions that may not have been resolved properly
 */
private List<String> extractVariableExprs(String xpathStr) {
    ArrayList<String> variableExprs = new ArrayList<String>();
    int firstVariable = xpathStr.indexOf("$"), lastVariable = xpathStr.lastIndexOf("$"),
            firstFunction = xpathStr.indexOf("(");
    StringBuffer variableExpr = new StringBuffer();
    if ((firstVariable > 0 && // the xpath references a variable
            firstFunction > 0) || // the xpath contains a function
            (firstVariable < lastVariable)) { // the xpath references multiple variables
        // most likely, the variable reference has not been resolved, so make that happen
        boolean quoted = false, doubleQuoted = false, variable = false;
        Name11Checker nameChecker = Name11Checker.getInstance();
        for (int index = 0; index < xpathStr.length(); index++) {
            char ch = xpathStr.charAt(index);
            if (ch == '\'') {
                quoted = !quoted;
            }
            if (ch == '\"') {
                doubleQuoted = !doubleQuoted;
            }
            if (quoted || doubleQuoted) {
                continue;
            }
            if (ch == '$') {
                variable = true;
                variableExpr.setLength(0);
                variableExpr.append(ch);
            } else {
                if (variable) {
                    variableExpr.append(ch);
                    // in the name is qualified, don't check if its a qname when we're at the ":" character
                    if (ch == ':') {
                        continue;
                    }
                    if (index == xpathStr.length() || !nameChecker.isQName(variableExpr.substring(1))) {
                        variable = false;
                        variableExpr.setLength(variableExpr.length() - 1);
                        variableExprs.add(variableExpr.toString());
                        variableExpr.setLength(0);
                    }
                }
            }
        }
        if (variableExpr.length() > 0) {
            variableExprs.add(variableExpr.toString());
        }
    }
    return variableExprs;
}

From source file:org.kuali.rice.kew.rule.xmlrouting.StandardGenericXMLRuleAttribute.java

private NodeList getFields(XPath xpath, Element root, String[] types) throws XPathExpressionException {
    final String OR = " or ";
    StringBuffer findField = new StringBuffer("//routingConfig/" + FIELD_DEF_E);
    if (types != null && types.length > 0) {
        findField.append("[");
        for (String type : types) {
            findField.append("@workflowType='" + type + "'" + OR);
            // missing workflowType is equivalent ("defaults") to ALL
            if ("ALL".equals(type)) {
                findField.append("not(@workflowType)" + OR);
            }//w w w  .j  av a2s  .  c  o m
        }
        if (types.length > 0) {
            // remove trailing " or "
            findField.setLength(findField.length() - OR.length());
        }
        findField.append("]");
    }

    try {
        return (NodeList) xpath.evaluate(findField.toString(), root, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        LOG.error("Error evaluating expression: '" + findField + "'");
        throw e;
    }
}

From source file:org.codelibs.fess.helper.ViewHelper.java

protected String replaceHighlightQueries(final String cache, final String[] queries) {
    final StringBuffer buf = new StringBuffer(cache.length() + 100);
    final StringBuffer segBuf = new StringBuffer(1000);
    final Pattern p = Pattern.compile("<[^>]+>");
    final Matcher m = p.matcher(cache);
    final String[] regexQueries = new String[queries.length];
    final String[] hlQueries = new String[queries.length];
    for (int i = 0; i < queries.length; i++) {
        regexQueries[i] = Pattern.quote(queries[i]);
        hlQueries[i] = highlightTagPre + queries[i] + highlightTagPost;
    }//from  w w  w .  j  a  v a  2s  .  c o  m
    while (m.find()) {
        segBuf.setLength(0);
        m.appendReplacement(segBuf, StringUtil.EMPTY);
        String segment = segBuf.toString();
        for (int i = 0; i < queries.length; i++) {
            segment = Pattern.compile(regexQueries[i], Pattern.CASE_INSENSITIVE).matcher(segment)
                    .replaceAll(hlQueries[i]);
        }
        buf.append(segment);
        buf.append(m.group(0));
    }
    segBuf.setLength(0);
    m.appendTail(segBuf);
    String segment = segBuf.toString();
    for (int i = 0; i < queries.length; i++) {
        segment = Pattern.compile(regexQueries[i], Pattern.CASE_INSENSITIVE).matcher(segment)
                .replaceAll(hlQueries[i]);
    }
    buf.append(segment);
    return buf.toString();
}