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.jbpm.bpel.tools.WsdlServiceTool.java

private static String generateName(String base, Set existingNames) {
    StringBuffer nameBuffer = new StringBuffer(base);
    int baseLength = base.length();
    for (int i = 2; i < Integer.MAX_VALUE; i++) {
        // append a natural number to the base text
        String altName = nameBuffer.append(i).toString();

        // check there is no collision with existing names
        if (!existingNames.contains(altName))
            return altName;

        // remove appended number
        nameBuffer.setLength(baseLength);
    }// w w  w .  j  a v a 2s  .  c o  m
    throw new Error("could not generate name from base: " + base);
}

From source file:org.geoserver.security.DataAccessRule.java

/**
 * Returns the list of roles as a comma separated string for this rule
 * @return// w w  w  .j a  v  a 2  s .  c o  m
 */
public String getValue() {
    if (roles.isEmpty()) {
        return DataAccessRule.ANY;
    } else {
        StringBuffer sb = new StringBuffer();
        for (String role : roles) {
            sb.append(role);
            sb.append(",");
        }
        sb.setLength(sb.length() - 1);
        return sb.toString();
    }
}

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

public static void generatePairsFromTwoDifferentFilesWithNoClass(String inputFilePath1, String inputFilePath2,
        String outputFilePath) {//from w  ww .  ja v a 2 s  .co m

    List<String> phenotypeList1 = new ArrayList<String>();
    List<String> phenotypeList2 = new ArrayList<String>();
    try {

        //Reader paramReader = new InputStreamReader(getClass().getResourceAsStream("/com/test/services/LoadRunner/FireCollection/fire.txt"));  
        //System.out.println(PairsFileIO.class.getClassLoader().getResource(inputFilePath1).getPath());
        //System.out.println(PairsFileIO.class.getClassLoader().getResource(inputFilePath2).getPath());

        //phenotypeList1 = FileUtils.readLines(new File (PairsFileIO.class.getClassLoader().getResource(inputFilePath1).getPath()));
        //phenotypeList2 = FileUtils.readLines(new File (PairsFileIO.class.getClassLoader().getResource(inputFilePath2).getPath()));

        phenotypeList1 = FileUtils.readLines(new File(inputFilePath1));
        phenotypeList2 = FileUtils.readLines(new File(inputFilePath2));

    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    String[] phenotype1, phenotype2;
    StringBuffer outputBuffer = new StringBuffer();

    BufferedWriter bw = null;
    try {
        bw = new BufferedWriter(new FileWriter(outputFilePath));

        for (int i = 0; i < phenotypeList1.size(); i++) {
            phenotype1 = phenotypeList1.get(i).split("\t");
            for (int j = 0; j < phenotypeList2.size(); j++) {
                phenotype2 = phenotypeList2.get(j).split("\t");

                //System.out.println("The value is:"+  phenotype1[3] + " : " + phenotype2[3]);

                outputBuffer.append(String.format("%s\t%s\t%d\n", phenotype1[3], phenotype2[3], 0));
                bw.append(outputBuffer.toString());
                outputBuffer.setLength(0);
            }
        }
    } catch (IOException io) {
        try {
            if (bw != null) {
                bw.close();
                bw = null;
            }
            io.printStackTrace();
        } catch (IOException e) {
            System.out.println("Problem occured while closing output stream  " + bw);
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (bw != null) {
                bw.close();
                bw = null;
            }
        } catch (IOException e) {
            System.out.println("Problem occured while closing output stream  " + bw);
            e.printStackTrace();
        }
    }
}

From source file:org.ojbc.intermediaries.sn.notification.EmailNotification.java

private String createCommaSeparatedStringFromSet(Set<String> addresses) {
    if (addresses.isEmpty()) {
        return null;
    }//from w  w  w.  ja va  2s .  c  om
    StringBuffer ret = new StringBuffer();
    for (String address : addresses) {
        ret.append(address).append(",");
    }
    if (ret.length() != 0) {
        ret.setLength(ret.length() - 1);
    }
    return ret.toString();
}

From source file:opennlp.tools.textsimilarity.TextProcessor.java

public static ArrayList<String> fastTokenize(String txt, boolean retainPunc) {
    ArrayList<String> tokens = new ArrayList<String>();
    if (StringUtils.isEmpty(txt)) {
        return tokens;
    }/*from w w w .  j a va  2s  . c o m*/

    StringBuffer tok = new StringBuffer();
    char[] chars = txt.toCharArray();

    for (int i = 0; i < chars.length; i++) {
        char c = chars[i];
        if (Character.isLetterOrDigit(c) || isSafePunc(chars, i)) {
            tok.append(c);
        } else if (Character.isWhitespace(c)) {
            if (tok.length() > 0) {
                tokens.add(tok.toString());
                tok.setLength(0);
            }
        } else {
            if (tok.length() > 0) {
                tokens.add(tok.toString());
                tok.setLength(0);
            }
            if (retainPunc) {
                tokens.add("<punc>");
            }
        }
    }

    if (tok.length() > 0) {
        tokens.add(tok.toString());
        tok.setLength(0);
    }
    return tokens;
}

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

/**
 * /* w w  w. j a  v a 2s . c o m*/
 * @param strUrl
 * @param strPostRequest
 * @return
 */
public static String getPageContent(String strUrl, String strPostRequest) {
    //
    StringBuffer buffer = new StringBuffer();
    System.setProperty("sun.net.client.defaultConnectTimeout", "5000");
    System.setProperty("sun.net.client.defaultReadTimeout", "5000");
    try {
        URL newUrl = new URL(strUrl);
        HttpURLConnection hConnect = (HttpURLConnection) newUrl.openConnection();
        //POST
        if (strPostRequest.length() > 0) {
            hConnect.setDoOutput(true);
            OutputStreamWriter out = new OutputStreamWriter(hConnect.getOutputStream());
            out.write(strPostRequest);
            out.flush();
            out.close();
        }
        //
        BufferedReader rd = new BufferedReader(new InputStreamReader(hConnect.getInputStream()));
        int ch;
        for (int length = 0; (ch = rd.read()) > -1; length++)
            buffer.append((char) ch);
        rd.close();
        hConnect.disconnect();
        return buffer.toString().trim();
    } catch (Exception e) {
        // return ":";
        return null;
    } finally {
        buffer.setLength(0);
    }
}

From source file:net.itransformers.topologyviewer.fulfilmentfactory.impl.TelnetCLIInterface.java

public String readUntil(String regexp) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    logger.info("looking for : " + regexp);
    int chInt;//w w  w  .  j a  v  a  2s .com
    StringBuffer sb = new StringBuffer();
    while ((chInt = reader.read()) != -1) {
        char ch = (char) chInt;
        if (ch == '\n') {
            logger.info(sb.toString());
            sb.setLength(0);
            continue;
        }
        sb.append(ch);
        String st = sb.toString();
        if (st.matches(regexp)) {
            logger.info("### Found match: " + sb);
            return st;
        }
        if (!reader.ready()) {
            logger.info("Buffer is not ready. Read characters until now: " + sb.toString());
        }
    }
    return null;
}

From source file:nz.co.jsrsolutions.ds3.command.UpdateExchangeQuotesCommand.java

public boolean execute(Context context) throws Exception {

    logger.info("Executing: updateexchangequotes");

    final String exchange = (String) context.get(CommandContext.EXCHANGE_KEY);

    if (exchange == null) {
        throw new CommandException("Must supply --exchange [exchangecode]");
    }//from  w  w w.  j  a v a2s . co m

    long nQuotesWritten = 0;

    final int availableMonths = _eodDataProvider.getExchangeMonths(exchange);

    final String[] symbols = _eodDataSink.readExchangeSymbols(exchange);

    if (symbols == null) {
        logger.info("No symbols associated with this exchange...");
        return false;
    }

    final Collection<Future<Long>> futures = new LinkedList<Future<Long>>();

    for (String symbol : symbols) {

        final Calendar firstAvailableDateTime = Calendar.getInstance();

        if (availableMonths > 0) {
            firstAvailableDateTime.add(Calendar.MONTH, -1 * availableMonths);
            firstAvailableDateTime.add(Calendar.DATE, 1);
        }

        final Calendar today = Calendar.getInstance();

        final Range<Calendar> sinkRange = _eodDataSink.readExchangeSymbolDateRange(exchange, symbol);

        final ArrayList<Range<Calendar>> requestRangesList = new ArrayList<Range<Calendar>>(2);

        if (sinkRange != null) {

            if (firstAvailableDateTime.compareTo(sinkRange.getLower()) < 0) {

                // In this implementation we can't ask for this!

                /*      
                       final Calendar upper = (Calendar) sinkRange.getLower().clone();
                       upper.add(Calendar.DATE, -1);
                       final Calendar lower = (firstAvailableDateTime.compareTo(upper) < 0) ? firstAvailableDateTime : upper;
                               
                       requestRangesList.add(new Range<Calendar>(firstAvailableDateTime,
                           upper));
                                  
                       // TODO: implement prepend in Hd5 Sink
                */
            }

            if (today.compareTo(sinkRange.getUpper()) > 0) {

                final Calendar lower = (Calendar) sinkRange.getUpper().clone();
                lower.add(Calendar.DATE, 1);
                // TODO: fix this by observing timezones
                final Calendar upper = (Calendar) today.clone();
                // cheat for now with upper bound on today (anywhere in the world!)
                upper.add(Calendar.DATE, 1);

                requestRangesList.add(new Range<Calendar>(lower, upper));

            }

        } else {
            requestRangesList.add(new Range<Calendar>(firstAvailableDateTime, today));
        }

        for (Range<Calendar> requestRange : requestRangesList) {

            if (logger.isInfoEnabled()) {

                StringBuffer logMessageBuffer = new StringBuffer();
                logMessageBuffer.setLength(0);
                logMessageBuffer.append(" Attempting to retrieve quotes on [ ");
                logMessageBuffer.append(exchange);
                logMessageBuffer.append(" ] for [ ");
                logMessageBuffer.append(symbol);
                logMessageBuffer.append(" ] between [ ");
                logMessageBuffer.append(requestRange.getLower().getTime().toString());
                logMessageBuffer.append(" ] and [ ");
                logMessageBuffer.append(requestRange.getUpper().getTime().toString());
                logMessageBuffer.append(" ] ");
                logger.info(logMessageBuffer.toString());

            }

            try {

                futures.add(_executorService.submit(new ReadWriteQuotesTask(_eodDataProvider, _eodDataSink,
                        exchange, symbol, requestRange.getLower(), requestRange.getUpper())));

            } catch (Exception e) {
                logger.error("Task submission failed", e);
            }

        }

    }

    for (Future<Long> future : futures) {
        try {
            nQuotesWritten += future.get();
        } catch (ExecutionException e) {
            logger.error("Execution exception: ", e);
        } catch (InterruptedException e) {
            logger.error("Interrupted exception: ", e);
        }
    }

    if (_emailService != null) {
        final StringBuffer subjectBuffer = new StringBuffer();
        subjectBuffer.append("Updated quotes on ");
        subjectBuffer.append(exchange);

        final StringBuffer messageBuffer = new StringBuffer();
        messageBuffer.append("Wrote ");
        messageBuffer.append(nQuotesWritten);
        messageBuffer.append(" quotes over ");
        messageBuffer.append(symbols.length);
        messageBuffer.append(" symbols ");

        _emailService.send(subjectBuffer.toString(), messageBuffer.toString());
    }

    return false;

}

From source file:net.sourceforge.pmd.renderers.HTMLRenderer.java

private void glomProcessingErrors(Writer writer, List<Report.ProcessingError> errors) throws IOException {

    if (errors.isEmpty()) {
        return;//from   w w w .  j  av a  2  s.  c o  m
    }

    writer.write("<hr/>");
    writer.write("<center><h3>Processing errors</h3></center>");
    writer.write("<table align=\"center\" cellspacing=\"0\" cellpadding=\"3\"><tr>" + PMD.EOL
            + "<th>File</th><th>Problem</th></tr>" + PMD.EOL);

    StringBuffer buf = new StringBuffer(500);
    boolean colorize = true;
    for (Report.ProcessingError pe : errors) {
        buf.setLength(0);
        buf.append("<tr");
        if (colorize) {
            buf.append(" bgcolor=\"lightgrey\"");
        }
        colorize = !colorize;
        buf.append("> " + PMD.EOL);
        buf.append("<td>" + pe.getFile() + "</td>" + PMD.EOL);
        buf.append("<td><pre>" + pe.getDetail() + "</pre></td>" + PMD.EOL);
        buf.append("</tr>" + PMD.EOL);
        writer.write(buf.toString());
    }
    writer.write("</table>");
}

From source file:com.bstek.dorado.data.method.MethodAutoMatchingUtils.java

private static String getExceptionMessage(String resourceKey, Method[] methods, Type[] requiredTypes,
        Type[] exactTypes, Type[] optionalTypes, Type returnType) {
    MethodInfo methodInfo = getMethodInfo(methods);

    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < requiredTypes.length; i++) {
        if (i > 0) {
            sb.append(",");
        }/*from  ww  w  .  ja  v  a2 s.  c om*/
        Type argType = requiredTypes[i];
        if (argType != null) {
            sb.append(getClassName(argType));
        } else {
            sb.append("*");
        }
    }
    String required = sb.toString();

    sb.setLength(0);
    for (int i = 0; i < exactTypes.length; i++) {
        if (i > 0) {
            sb.append(",");
        }
        Type argType = exactTypes[i];
        if (argType != null) {
            sb.append(getClassName(argType));
        } else {
            sb.append("*");
        }
    }
    String exact = sb.toString();

    sb.setLength(0);
    for (int i = 0; i < optionalTypes.length; i++) {
        if (i > 0) {
            sb.append(",");
        }
        Type argType = optionalTypes[i];
        if (argType != null) {
            sb.append(getClassName(argType));
        } else {
            sb.append("*");
        }
    }
    String optional = sb.toString();

    return resourceManager.getString(resourceKey, methodInfo.getClassName(), methodInfo.getMethodName(),
            required, exact, optional, ((returnType != null) ? returnType.toString() : "*"));
}