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:org.latticesoft.util.resource.DatabaseUtil.java

/** 
 * Analyse the SQL string into the components
 * @return a String[] of the components 
 *//*from   www . j av  a2s.  c om*/
private static String[] analyseSelectSQL(String sql) {
    String[] s = null;
    if (sql == null)
        return s;
    sql = sql.trim();
    String ss = sql.toLowerCase();
    if (!ss.startsWith("select"))
        return s;
    int index = ss.indexOf("from");
    if (index < 0)
        return s;
    String cols = sql.substring("select".length(), index).trim();

    if (cols.equals("*")) {
        s = null;
    } else {
        s = StringUtil.tokenizeIntoStringArray(cols, ",");
        // regroup
        int open = 0;
        int close = 0;
        ArrayList result = new ArrayList();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length; i++) {
            sb.append(s[i]).append(",");
            open += StringUtil.countOf(s[i], "(");
            close += StringUtil.countOf(s[i], ")");
            if (open == close) {
                sb.deleteCharAt(sb.length() - 1);
                result.add(sb.toString());
                sb.setLength(0);
                open = 0;
                close = 0;
            }
        }
        s = new String[result.size()];
        s = (String[]) result.toArray(s);

        for (int i = 0; i < s.length; i++) {
            if (s[i] != null) {
                index = s[i].toLowerCase().indexOf(" as ");
                if (index > -1) {
                    s[i] = s[i].substring(index + 4, s[i].length()).trim();
                }
                index = s[i].toLowerCase().indexOf(" ");
                if (index > -1) {
                    s[i] = s[i].substring(index + 1, s[i].length()).trim();
                }
            }
        }
    }
    return s;
}

From source file:URIUtil.java

static String removeDotSegments(String path) {

    StringBuffer output = new StringBuffer();

    while (path.length() > 0) {
        if (path.startsWith("/./")) {
            path = '/' + path.substring(3);
        } else if (path.equals("/.")) {
            path = "/";
        } else if (path.startsWith("/../")) {
            path = '/' + path.substring(4);
            int lastSlash = output.toString().lastIndexOf('/');
            if (lastSlash != -1)
                output.setLength(lastSlash);
        } else if (path.equals("/..")) {
            path = "/";
            int lastSlash = output.toString().lastIndexOf('/');
            if (lastSlash != -1)
                output.setLength(lastSlash);
        }/*from   ww  w  .  ja  va  2s  .  co  m*/
        // These next three cases are unreachable in the context of XOM.
        // They may be needed in a more general public URIUtil.
        // ???? need to consider whether these are still unreachable now that
        // Builder.canonicalizeURL is calling this method.
        /* else if (path.equals(".") || path.equals("..")) {
        path = "";
        }
        else if (path.startsWith("../")) {
        path = path.substring(3);
        }
        else if (path.startsWith("./")) {
        path = path.substring(2);
        } */
        else {
            int nextSlash = path.indexOf('/');
            if (nextSlash == 0)
                nextSlash = path.indexOf('/', 1);
            if (nextSlash == -1) {
                output.append(path);
                path = "";
            } else {
                output.append(path.substring(0, nextSlash));
                path = path.substring(nextSlash);
            }
        }
    }

    return output.toString();

}

From source file:org.jboss.test.bpel.ws.consumption.partner.resource.ResourceDictionaryFactory.java

protected String getBaseName(String sourceLanguage) {
    StringBuffer baseName = new StringBuffer(getClass().getName());
    baseName.setLength(baseName.lastIndexOf(".") + 1);
    baseName.append(sourceLanguage);/*from  ww w  .j a v a2s  . c  om*/
    return baseName.toString();
}

From source file:cn.teamlab.wg.framework.util.csv.CsvWriter.java

/**
 * Bean?CSV?//from   ww w. ja  v  a2  s  .com
 * Bean@CsvPropAnno(index = ?)
 * @param objList
 * @return
 * @throws NoSuchMethodException 
 * @throws InvocationTargetException 
 * @throws IllegalAccessException 
 */
public static String bean2Csv(List<?> objList) throws Exception {
    if (objList == null || objList.size() == 0) {
        return "";
    }
    TreeMap<Integer, CsvFieldBean> map = new TreeMap<Integer, CsvFieldBean>();
    Object bean0 = objList.get(0);
    Class<?> clazz = bean0.getClass();

    PropertyDescriptor[] arr = org.springframework.beans.BeanUtils.getPropertyDescriptors(clazz);
    for (PropertyDescriptor p : arr) {
        String fieldName = p.getName();
        Field field = FieldUtils.getDeclaredField(clazz, fieldName, true);
        if (field == null) {
            continue;
        }

        boolean isAnno = field.isAnnotationPresent(CsvFieldAnno.class);
        if (isAnno) {
            CsvFieldAnno anno = field.getAnnotation(CsvFieldAnno.class);
            int idx = anno.index();
            map.put(idx, new CsvFieldBean(idx, anno.title(), fieldName));
        }
    }

    // CSVBuffer
    StringBuffer buff = new StringBuffer();

    // ???
    boolean withTitle = clazz.isAnnotationPresent(CsvTitleAnno.class);
    // ??csv
    if (withTitle) {
        StringBuffer titleBuff = new StringBuffer();
        for (int key : map.keySet()) {
            CsvFieldBean fieldBean = map.get(key);
            titleBuff.append(Letters.QUOTE).append(fieldBean.getTitle()).append(Letters.QUOTE);
            titleBuff.append(Letters.COMMA);
        }
        buff.append(StringUtils.chop(titleBuff.toString()));
        buff.append(Letters.LF);
        titleBuff.setLength(0);
    }

    for (Object o : objList) {
        StringBuffer tmpBuff = new StringBuffer();

        for (int key : map.keySet()) {
            CsvFieldBean fieldBean = map.get(key);

            Object val = BeanUtils.getProperty(o, fieldBean.getFieldName());
            if (val != null) {
                tmpBuff.append(Letters.QUOTE).append(val).append(Letters.QUOTE);
            } else {
                tmpBuff.append(StringUtils.EMPTY);
            }
            tmpBuff.append(Letters.COMMA);
        }

        buff.append(StringUtils.chop(tmpBuff.toString()));
        buff.append(Letters.LF);
        tmpBuff.setLength(0);
    }

    return buff.toString();
}

From source file:gov.llnl.lc.smt.command.port.SmtPort.java

protected static String getProblemLines(String type, IB_Port[] pArray) {
    StringBuffer buff = new StringBuffer();

    // show the ports with problems
    if ((pArray != null) && (pArray.length > 0)) {
        // collect all these ports into bins, organized by port guids
        BinList<IB_Port> pbL = new BinList<IB_Port>();
        for (IB_Port p : pArray) {
            pbL.add(p, p.guid.toColonString());
        }/*from www .  j  a  v  a2 s.  c  o m*/

        // there should be at least one bin
        int n = pbL.size();
        for (int j = 0; j < n; j++) {
            ArrayList<IB_Port> pL = pbL.getBin(j);
            IB_Port p0 = pL.get(0);
            String pDesc = ("guid=" + p0.guid + " desc=" + p0.Description);
            StringBuffer sbuff = new StringBuffer();
            for (IB_Port p : pL)
                sbuff.append(p.portNumber + ", ");

            // strip off the trailing 
            sbuff.setLength((sbuff.length() - 2));
            String pNum = sbuff.toString();

            buff.append(getAbbreviatedType(type) + "--" + pDesc + SmtConstants.NEW_LINE);
            buff.append("port(s)=" + pNum + SmtConstants.NEW_LINE);
        }
    }
    return buff.toString();
}

From source file:com.digitalgeneralists.assurance.notification.NotificationProvider.java

public void fireEvent(IAssuranceEvent event) {
    StringBuffer message = new StringBuffer(128);
    logger.info(message.append("Firing event: ").append(event));
    message.setLength(0);
    message = null;//from  w  w  w . ja  v a  2  s . c o m
    Collection<IEventObserver> eventObservers = eventObserverList.get(event.getClass());
    if (eventObservers != null) {
        for (IEventObserver observer : eventObservers) {
            observer.notify(event);
        }
    }

    eventObservers = null;
}

From source file:org.apache.xmlgraphics.fonts.Glyphs.java

private static String[] loadGlyphList(String filename, Map charNameToUnicodeMap) {
    List lines = new java.util.ArrayList();
    InputStream in = Glyphs.class.getResourceAsStream(filename);
    if (in == null) {
        throw new Error("Cannot load " + filename + ". The Glyphs class cannot properly be initialized!");
    }/*w w  w . ja va 2 s .co  m*/
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "US-ASCII"));
        String line;
        while ((line = reader.readLine()) != null) {
            if (!line.startsWith("#")) {
                lines.add(line);
            }
        }
    } catch (UnsupportedEncodingException uee) {
        throw new Error("Incompatible JVM! US-ASCII encoding is not supported."
                + " The Glyphs class cannot properly be initialized!");
    } catch (IOException ioe) {
        throw new Error(
                "I/O error while loading " + filename + ". The Glyphs class cannot properly be initialized!");
    } finally {
        IOUtils.closeQuietly(in);
    }
    String[] arr = new String[lines.size() * 2];
    int pos = 0;
    StringBuffer buf = new StringBuffer();
    for (int i = 0, c = lines.size(); i < c; i++) {
        String line = (String) lines.get(i);
        int semicolon = line.indexOf(';');
        if (semicolon <= 0) {
            continue;
        }
        String charName = line.substring(0, semicolon);
        String rawUnicode = line.substring(semicolon + 1);
        buf.setLength(0);

        StringTokenizer tokenizer = new StringTokenizer(rawUnicode, " ", false);
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            assert token.length() == 4;
            buf.append(hexToChar(token));
        }

        String unicode = buf.toString();
        arr[pos] = unicode;
        pos++;
        arr[pos] = charName;
        pos++;
        assert !charNameToUnicodeMap.containsKey(charName);
        charNameToUnicodeMap.put(charName, unicode);
    }
    return arr;
}

From source file:ca.hedlund.jiss.preprocessor.InfoPreprocessor.java

@Override
public boolean preprocessCommand(JissModel jissModel, String orig, StringBuffer cmd) {
    final String c = cmd.toString();
    if (c.equals(INFO_CMD)) {
        // clear string
        cmd.setLength(0);

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

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

        final String infoCmd = seFactory.getOutputStatement(INFO_TXT + (incnl ? "\\n" : ""));
        final String langCmd = seFactory.getOutputStatement("Language:" + seFactory.getLanguageName() + " "
                + seFactory.getLanguageVersion() + (incnl ? "\\n" : ""));
        final String engineCmd = seFactory.getOutputStatement("Engine:" + seFactory.getEngineName() + " "
                + seFactory.getEngineVersion() + (incnl ? "\\n" : ""));
        final String program = seFactory.getProgram(infoCmd, langCmd, engineCmd);
        cmd.append(StringEscapeUtils.unescapeJava(program));
    }//from www. j a v a2  s  .  c  o m
    // we want the scripting engine to handle the replaced command
    return false;
}

From source file:com.android.internal.util.weather.HttpRetriever.java

public Document getDocumentFromURL(String strURL) throws IOException {
    if (strURL == null) {
        Log.e(TAG, "Invalid input URL");
        return null;
    }/*from   w w w  . j  av a2 s .com*/

    // Connect to server, get data and close
    requestConnectServer(strURL);
    String strDocContent = getDataFromConnection();
    requestDisconnect();

    if (strDocContent == null) {
        Log.e(TAG, "Cannot get XML content");
        return null;
    }

    int strContentSize = strDocContent.length();
    StringBuffer strBuff = new StringBuffer();
    strBuff.setLength(strContentSize + 1);
    strBuff.append(strDocContent);
    ByteArrayInputStream is = new ByteArrayInputStream(strDocContent.getBytes());

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db;
    Document docData = null;

    try {
        db = dbf.newDocumentBuilder();
        docData = db.parse(is);
    } catch (Exception e) {
        Log.e(TAG, "Parser data error");
        return null;
    }
    return docData;
}

From source file:ca.hedlund.jiss.preprocessor.LangPreprocessor.java

@Override
public boolean preprocessCommand(JissModel jissModel, String orig, StringBuffer cmd) {
    final String c = cmd.toString();
    if (c.equals("::langs")) {
        cmd.setLength(0);
        printLangs(jissModel, cmd);/*from   w ww.ja  v  a2s .  c om*/
    } else if (c.equals("::lang")) {
        cmd.setLength(0);
        printCurrentLang(jissModel, cmd);
    } else if (c.startsWith("::lang")) {
        cmd.setLength(0);

        final String parts[] = c.split("\\p{Space}");
        if (parts.length == 2) {
            final String lang = parts[1];

            final ScriptEngineManager manager = new ScriptEngineManager(JissModel.class.getClassLoader());
            ScriptEngine newEngine = null;
            for (ScriptEngineFactory factory : manager.getEngineFactories()) {
                if (factory.getLanguageName().equals(lang) || factory.getExtensions().contains(lang)
                        || factory.getMimeTypes().contains(lang)) {
                    newEngine = factory.getScriptEngine();
                    break;
                }
            }

            if (newEngine != null) {
                jissModel.setScriptEngine(newEngine);
                printCurrentLang(jissModel, cmd);
            }
        }
    }
    return false;
}