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.apache.nutch.protocol.http.HttpResponse.java

private void parseHeaders(PushbackInputStream in, StringBuffer line, StringBuffer httpHeaders)
        throws IOException, HttpException {

    while (readLine(in, line, true) != 0) {

        if (httpHeaders != null)
            httpHeaders.append(line).append("\n");

        // handle HTTP responses with missing blank line after headers
        int pos;//from ww w .j  a  v a2 s  .c  om
        if (((pos = line.indexOf("<!DOCTYPE")) != -1) || ((pos = line.indexOf("<HTML")) != -1)
                || ((pos = line.indexOf("<html")) != -1)) {

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

        processHeaderLine(line);
    }
}

From source file:org.latticesoft.util.common.FileUtil.java

/** 
 * Copy a file//from w w  w.j  a v  a 2s.c o m
 * @param fSrc source file
 * @param fTgt target file / destination
 */
public static void copyFile(File fSrc, File fTgt) {
    InputStream is = null;
    OutputStream os = null;
    try {
        if (fSrc.isFile()) {
            if (fSrc.exists()) {
                copyFileBytes(fSrc, fTgt);
                if (log.isDebugEnabled()) {
                    log.debug(fSrc + " copied.");
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(fSrc + " does not exist.");
                }
            }
        } else if (fSrc.isDirectory()) {
            if (!fTgt.exists()) {
                fTgt.mkdir();
            }
            if (fTgt.exists()) {
                File[] f = fSrc.listFiles();
                if (f != null) {
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < f.length; i++) {
                        if (f[i] != null && f[i].exists()) {
                            if (f[i].isFile()) {
                                sb.setLength(0);
                                sb.append(FileUtil.getUnixPath(fTgt.getPath()));
                                sb.append("/");
                                sb.append(f[i].getName());
                                File f1 = new File(sb.toString());
                                copyFileBytes(f[i], f1);
                            } else if (f[i].isDirectory()) {
                                sb.setLength(0);
                                sb.append(FileUtil.getUnixPath(fTgt.getPath()));
                                sb.append("/");
                                sb.append(fSrc.getName());
                                copyFile(f[i].getPath(), sb.toString());
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Error", e);
        }
    } finally {
        try {
            is.close();
        } catch (Exception e) {
        }
        try {
            os.close();
        } catch (Exception e) {
        }
    }
}

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

private String doPerform(String _sName, int _nValue, String[] _arrayMaps) {
    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   w w  w . ja  va2  s  .  c  o m
        String sBoxValue = map[0];
        boolean checked = false;
        String sBoxShow = map.length > 1 ? map[1] : " ";
        sb.append("<INPUT type=\"checkbox\" name=\"").append(_sName).append("\" ").append("value=\"")
                .append(sBoxValue).append('\"');
        if (sBoxValue != null && sBoxValue.matches("[0-9]+")) {
            logger.debug("====" + sBoxValue + ":" + _nValue);
            if ((Integer.parseInt(sBoxValue) & _nValue) != 0) {
                sb.append(" checked");
            }
        }
        if (checked) {
            sb.append(" checked");
        }
        sb.append('>').append(sBoxShow);
    }
    String sResult = new String(sb);
    sb.setLength(0);
    return sResult;
}

From source file:org.etudes.jforum.EtudesJForumBaseServlet.java

/**
 * reads the .sql file and runs the sql statements
 * @param conn connection/* ww  w.  ja  va2  s  .co m*/
 * @param resource .sql file
 * @return true if 
 */
public boolean ddl(Connection conn, String resource) throws Exception {

    InputStream in = null;
    try {
        //get the resource
        in = new FileInputStream(new File(resource));
        if (in == null) {
            if (logger.isWarnEnabled())
                logger.warn(this.getClass().getName() + ".ddl() : missing resource: " + resource);
            return false;
        }

        BufferedReader r = new BufferedReader(new InputStreamReader(in));
        try {
            // read the first line, skipping any '--' comment lines
            boolean firstLine = true;
            StringBuffer buf = new StringBuffer();
            for (String line = r.readLine(); line != null; line = r.readLine()) {
                line = line.trim();
                if (line.startsWith("--"))
                    continue;
                if (line.length() == 0)
                    continue;

                // add the line to the buffer
                buf.append(' ');
                buf.append(line);

                // process if the line ends with a ';'
                boolean process = line.endsWith(";");

                if (!process)
                    continue;

                // remove trailing ';'
                buf.setLength(buf.length() - 1);

                // run the first sql statement as the test - if it fails, 
                // we can assume tables are existing in the database
                if (firstLine) {
                    firstLine = false;
                    if (!dbWrite(conn, buf.toString())) {
                        if (logger.isDebugEnabled())
                            logger.debug(this.getClass().getName()
                                    + ":ddl() JForum Table's are already existing in the database");
                        return false;
                    }
                }
                // run other lines, until done - any one can fail (we will
                // report it)
                else {
                    dbWrite(conn, buf.toString());
                }

                // clear the buffer for next
                buf.setLength(0);
            }
        } catch (IOException ioe) {
            if (logger.isWarnEnabled())
                logger.warn(this.getClass().getName() + ".ddl() : resource: " + resource + " : " + ioe);
            throw ioe;
        } finally {
            try {
                r.close();
            } catch (IOException ioe) {
                if (logger.isWarnEnabled())
                    logger.warn(this.getClass().getName() + ".ddl() : resource: " + resource + " : " + ioe);
                throw ioe;
            }
        }
    } catch (FileNotFoundException e) {
        if (logger.isWarnEnabled())
            logger.warn(e);
        throw e;
    } finally {
        try {
            in.close();
        } catch (IOException ioe) {
            if (logger.isWarnEnabled())
                logger.warn(this.getClass().getName() + ".ddl() : resource: " + resource + " : " + ioe);
            throw ioe;
        }
    }
    return true;
}

From source file:edu.isi.pfindr.learn.util.PairsFileIO.java

public void readDistinctElementsFromPairsAddClass(String pairsFilepath) {
    //readDistinctElementsIntoList
    List<Object> distinctElements = readDistinctElementsIntoList(pairsFilepath);
    System.out.println("Size of distinctElements" + distinctElements.size());
    for (int i = 0; i < distinctElements.size(); i++) {
        System.out.println("distinctElements " + i + " " + distinctElements.get(i));
    }/*from  w  ww . j  av a 2s  .c o  m*/

    //get class for those distinct elements from original cohort file
    String originalFile = "data/cohort1/bio_nlp/cohort1_s.txt";
    BufferedReader br = null;
    String thisLine;
    String[] lineArray;
    LinkedMap originalMap = new LinkedMap();
    BufferedWriter distinctPriorityPairsWriter = null;

    try {
        br = new BufferedReader(new FileReader(originalFile));
        while ((thisLine = br.readLine()) != null) {
            thisLine = thisLine.trim();
            if (thisLine.equals(""))
                continue;

            lineArray = thisLine.split("\t");
            originalMap.put(lineArray[3], lineArray[1]);
        }

        //write distinct elements with class to an output file
        StringBuffer outfileBuffer = new StringBuffer();
        for (int i = 0; i < distinctElements.size(); i++)
            outfileBuffer.append(distinctElements.get(i)).append("\t")
                    .append(originalMap.get(distinctElements.get(i)) + "\n");

        distinctPriorityPairsWriter = new BufferedWriter(
                new FileWriter(pairsFilepath.split("\\.")[0] + "_distinct_with_class.txt"));

        distinctPriorityPairsWriter.append(outfileBuffer.toString());
        outfileBuffer.setLength(0);
        distinctPriorityPairsWriter.flush();

    } catch (IOException io) {
        try {
            if (br != null)
                br.close();
            io.printStackTrace();
        } catch (IOException e) {
            System.out.println("Problem occured while closing output stream " + br);
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.apache.torque.task.TorqueSQLExec.java

/**
 * print any results in the statement.//from w w w.java 2 s  .c o m
 *
 * @param out
 * @throws SQLException
 */
protected void printResults(PrintStream out) throws java.sql.SQLException {
    ResultSet rs = null;
    do {
        rs = statement.getResultSet();
        if (rs != null) {
            log("Processing new result set.", Project.MSG_VERBOSE);
            ResultSetMetaData md = rs.getMetaData();
            int columnCount = md.getColumnCount();
            StringBuffer line = new StringBuffer();
            if (showheaders) {
                for (int col = 1; col < columnCount; col++) {
                    line.append(md.getColumnName(col));
                    line.append(",");
                }
                line.append(md.getColumnName(columnCount));
                out.println(line);
                line.setLength(0);
            }
            while (rs.next()) {
                boolean first = true;
                for (int col = 1; col <= columnCount; col++) {
                    String columnValue = rs.getString(col);
                    if (columnValue != null) {
                        columnValue = columnValue.trim();
                    }

                    if (first) {
                        first = false;
                    } else {
                        line.append(",");
                    }
                    line.append(columnValue);
                }
                out.println(line);
                line.setLength(0);
            }
        }
    } while (statement.getMoreResults());
    out.println();
}

From source file:com.pureinfo.srm.product.action.ProductListAction.java

public String getTailedButtons() throws PureException {
    SRMUser user = (SRMUser) loginUser;/*from w  w w .ja  v a2s.  c om*/
    String sProductForm = request.getParameter("dp_productForm");

    if (request.getParameter("paperForm") != null) {
        Product product = new Product();
        product.setProductForm(ProductConstants.SPRODUCT_FORM_PAPER);
        product.setCollege(user.getCollegeId());
        if (Auth2Helper.getManager().hasRight(loginUser, product, ArkActionTypes.AUDIT, false)) {
            StringBuffer sbuff = new StringBuffer();
            try {
                sbuff.append("<BUTTON class=\"img_button\" onClick=\"if(count()<1)alert('');");
                sbuff.append("else{if(confirm('')){");
                sbuff.append("this.disabled=true;mainForm.action='../product/productBackWaitCheck.do");
                sbuff.append("';mainForm.target='_blank';mainForm.submit();}}\">");
                sbuff.append(
                        "<img align=\"absMiddle\" src=\"../images/return.gif\"></button>&nbsp;&nbsp;");
                return sbuff.toString();
            } finally {
                sbuff.setLength(0);
            }
        }
    }

    if (user.isAdmin1() || user.isProductAdmin()) {
        if (ProductConstants.SPRODUCT_FORM_HONOR.equals(sProductForm)
                || ProductConstants.SPRODUCT_FORM_APPRAISE.equals(sProductForm)) {
            StringBuffer sbuff = new StringBuffer();
            try {
                if (ProductConstants.SPRODUCT_FORM_HONOR.equals(sProductForm)) {
                    sbuff.append(
                            "<BUTTON class=\"img_button\" onClick=\"if(count()<1)alert('');");
                    sbuff.append("else{doCompile();this.disabled=true;}\">");
                    sbuff.append(
                            "<img align=\"absMiddle\" src=\"../images/word.gif\"></button>&nbsp;&nbsp;");
                    sbuff.append("<script>");
                    sbuff.append("   function doCompile() {");
                    sbuff.append("       var aa = document.getElementsByName('id');");
                    sbuff.append("var ids = '';");
                    sbuff.append("for(var i=0;i<aa.length;i++){");
                    sbuff.append("if(aa[i].checked){");
                    sbuff.append("ids += aa[i].value + ',';");
                    sbuff.append("}");
                    sbuff.append("}");
                    sbuff.append("document.HeadForm.ids.value = ids;");
                    sbuff.append("document.HeadForm.action = '../product/honor-compile-type-select.jsp';");
                    // sbuff.append("document.HeadForm.target='_blank';");
                    sbuff.append("document.HeadForm.submit();");
                    sbuff.append("}");
                    sbuff.append("</script>");
                }
                sbuff.append("<BUTTON class=\"img_button\" onClick=\"if(count()<1)alert('');");
                sbuff.append("else{if(confirm('')){");
                sbuff.append("this.disabled=true;mainForm.action='../product/ProductBatchEditDatumAndCer.do?");
                sbuff.append("actionType=cer&dp_productForm=").append(sProductForm);
                sbuff.append("';mainForm.submit();}}\">");
                sbuff.append(
                        "<img align=\"absMiddle\" src=\"../images/edit.gif\"></button>&nbsp;&nbsp;");
                sbuff.append("<BUTTON class=\"img_button\" onClick=\"if(count()<1)alert('');");
                sbuff.append("else{if(confirm('')){");
                sbuff.append("this.disabled=true;mainForm.action='../product/ProductBatchEditDatumAndCer.do?");
                sbuff.append("actionType=datum&dp_productForm=");
                sbuff.append(sProductForm).append("';mainForm.submit();}}\">");
                sbuff.append(
                        "<img align=\"absMiddle\" src=\"../images/edit.gif\"></button>&nbsp;&nbsp;");
                return sbuff.toString();
            } finally {
                sbuff.setLength(0);
            }
        }
    }

    return null;
}

From source file:com.qpark.maven.plugin.persistenceconfig.SpringPersistenceConfigMojo.java

/**
 * @see org.apache.maven.plugin.Mojo#execute()
 *//*from w w  w.  ja  v a2s . c om*/
@Override
public void execute() throws MojoExecutionException {
    StaticLoggerBinder.getSingleton().setLog(this.getLog());
    this.getLog().debug("+execute");
    this.eipVersion = this.getEipVersion();
    if (this.persistenceUnitName == null || this.persistenceUnitName.trim().length() == 0) {
        throw new MojoExecutionException(
                "No persistence unit name entered. Please use property persistenceUnitName to define.");
    }
    if (this.datasourceJndiName == null || this.datasourceJndiName.trim().length() == 0) {
        throw new MojoExecutionException(
                "No JNDI datasource name entered. Please use property datasourceJndiName to define.");
    }
    if (this.springJpaVendorAdapter == null || this.springJpaVendorAdapter.trim().length() == 0) {
        throw new MojoExecutionException(
                "No spring JPA vendor adapter supplied. Please use property springJpaVendorAdapter which defaults to org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter.");
    }
    if (this.project.getExecutionProject() != null) {
        this.eipVersion = this.project.getExecutionProject().getVersion();
    }

    File f;
    StringBuffer sb = new StringBuffer(1024);

    // sb.append(this.getSpringPersistenceConfigXml());
    // File f = Util.getFile(this.outputDirectory,
    // new StringBuffer().append(this.basePackageName)
    // .append("-persistence-spring-config.xml").toString());
    // this.getLog().info(new StringBuffer().append("Write ")
    // .append(f.getAbsolutePath()));
    // try {
    // Util.writeToFile(f, sb.toString());
    // } catch (Exception e) {
    // this.getLog().error(e.getMessage());
    // e.printStackTrace();
    // }

    sb.setLength(0);
    sb.append(this.getSpringPersistenceJavaConfig());
    f = Util.getFile(this.outputDirectory,
            new StringBuffer().append(this.basePackageName).append(".persistenceconfig").toString(),
            "PersistenceConfig.java");
    this.getLog().info(new StringBuffer().append("Write ").append(f.getAbsolutePath()));
    try {
        Util.writeToFile(f, sb.toString());
    } catch (Exception e) {
        this.getLog().error(e.getMessage());
        e.printStackTrace();
    }

    sb.setLength(0);
    sb.append(this.getSpringDataSourceJavaConfig());
    f = Util.getFile(this.outputDirectory,
            new StringBuffer().append(this.basePackageName).append(".persistenceconfig").toString(),
            "JndiDataSourceConfig.java");
    this.getLog().info(new StringBuffer().append("Write ").append(f.getAbsolutePath()));
    try {
        Util.writeToFile(f, sb.toString());
    } catch (Exception e) {
        this.getLog().error(e.getMessage());
        e.printStackTrace();
    }
    this.getLog().debug("-execute");
}

From source file:com.fuseim.webapp.ProxyServlet.java

/**
 * For a redirect response from the target server, this translates {@code theUrl} to redirect to
 * and translates it to one the original client can use.
 *///w w w . ja  va 2s .com
protected String rewriteUrlFromResponse(HttpServletRequest servletRequest, String theUrl) {
    //TODO document example paths
    final String targetUri = getTargetUri(servletRequest);
    if (theUrl.startsWith(targetUri)) {
        /*-
         * The URL points back to the back-end server.
         * Instead of returning it verbatim we replace the target path with our
         * source path in a way that should instruct the original client to
         * request the URL pointed through this Proxy.
         * We do this by taking the current request and rewriting the path part
         * using this servlet's absolute path and the path from the returned URL
         * after the base target URL.
         */
        StringBuffer curUrl = servletRequest.getRequestURL(); //no query
        int pos;
        // Skip the protocol part
        if ((pos = curUrl.indexOf("://")) >= 0) {
            // Skip the authority part
            // + 3 to skip the separator between protocol and authority
            if ((pos = curUrl.indexOf("/", pos + 3)) >= 0) {
                // Trim everything after the authority part.
                curUrl.setLength(pos);
            }
        }
        // Context path starts with a / if it is not blank
        curUrl.append(servletRequest.getContextPath());
        // Servlet path starts with a / if it is not blank
        curUrl.append(servletRequest.getServletPath());
        curUrl.append(theUrl, targetUri.length(), theUrl.length());
        theUrl = curUrl.toString();
    }
    return theUrl;
}

From source file:com.gdevelop.gwt.syncrpc.SyncClientSerializationStreamReader.java

private void buildStringTable() {
    String raw = results.get(--index);
    Log.d("PROBLEMA", "BuildStringTable: " + index);
    byte b1;/*from  w  w  w.ja  v a2  s  . c o  m*/
    byte b2;
    byte b3;
    byte b4;

    boolean startNewString = true;
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < raw.length(); i++) {
        char ch = raw.charAt(i);
        if (startNewString) {
            assert ch == '\"';
            startNewString = false;
            continue;
        }
        if (ch == '\"') { // end-of-string
            this.stringTable.add(buffer.toString());

            buffer.setLength(0);
            startNewString = true;

            if (i != raw.length() - 1) {
                assert raw.charAt(i + 1) == ',';
                i++;
            }
            continue;
        }
        if (ch == JS_ESCAPE_CHAR) {
            i++;
            ch = raw.charAt(i);
            switch (ch) {
            case '0': // \0
                buffer.append('\u0000');
                break;
            case 'b': // \b
                buffer.append('\b');
                break;
            case 't': // \t
                buffer.append('\t');
                break;
            case 'n': // \n
                buffer.append('\n');
                break;
            case 'f': // \f
                buffer.append('\f');
                break;
            case 'r': // \r
                buffer.append('\r');
                break;
            case '\"': // \"
                buffer.append('\"');
                break;
            case '\\': // \\
                buffer.append('\\');
                break;
            case 'x': // \\xNN
                b1 = hex2byte(raw.charAt(++i));
                b2 = hex2byte(raw.charAt(++i));
                ch = (char) (b1 * 16 + b2);
                buffer.append(ch);
                break;
            case 'u': // \\uNNNN
                b1 = hex2byte(raw.charAt(++i));
                b2 = hex2byte(raw.charAt(++i));
                b3 = hex2byte(raw.charAt(++i));
                b4 = hex2byte(raw.charAt(++i));
                ch = (char) (b1 * 16 * 16 * 16 + b2 * 16 * 16 + b3 * 16 + b4);
                buffer.append(ch);
                break;
            default:
                // TODO:
                System.out.println("???");
            }
        } else {
            buffer.append(ch);
        }
    }
}