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:HTMLHelper.java

public static String unescapeString(String value) {
    StringBuffer unescapedString = new StringBuffer();
    StringBuffer charBuf = null;

    for (int pos = 0; pos < value.length(); pos++) {
        char c = value.charAt(pos);

        if (c == '&') { // Process reference...
            c = value.charAt(++pos);/*from ww w  . java 2s. c  o  m*/
            boolean numeric = false;
            if (c == '#') {
                numeric = true;
                c = value.charAt(++pos);
            }

            if (charBuf == null) {
                charBuf = new StringBuffer(32);
            } else {
                charBuf.setLength(0);
            }

            while (c != ';' && pos < value.length() - 1) {
                charBuf.append(c);
                c = value.charAt(++pos);
            }

            if (numeric) {
                try {
                    c = (char) Integer.parseInt(charBuf.toString(), 16);
                } catch (NumberFormatException nfe) {
                    // If we can't process it, just write out the text...
                    unescapedString.append("&#").append(charBuf.toString()).append(';');
                }
            } else {
                Character unescapedVer = (Character) escapeMap.get(charBuf.toString());
                if (unescapedVer != null) {
                    unescapedString.append(unescapedVer);
                } else {
                    unescapedString.append("&").append(charBuf.toString()).append(';');
                }
            }

        } else {
            unescapedString.append(c);
        }

    }

    return unescapedString.toString();
}

From source file:org.lwes.util.NumberCodec.java

/**
 * Write a number in unsigned hexadecimal form, padding with zeroes,
 * with a fixed result size.  Extra opening "f"'s are removed.
 *
 * @param num      the number to convert
 * @param numBytes the number of bytes to write (each is two hex digits)
 * @param buf      the StringBuffer into which to write
 *//*from ww  w.  j ava2  s  .co m*/
private static void writeHexString(long num, int numBytes, StringBuffer buf) {
    final int startLen = buf.length();
    int numNibbles = numBytes << 1;
    int pos = startLen + numNibbles;
    buf.setLength(pos);
    while (numNibbles != 0) {
        --pos;
        final byte masked = (byte) (num & 0xf);
        buf.setCharAt(pos, hexCharMap[masked]);
        num >>>= 4;
        --numNibbles;
    }
}

From source file:org.eclipse.wb.internal.swt.model.property.editor.image.plugin.WorkspacePluginInfo.java

private static Map<String, String> parseBundleManifest(IFile manifestFile) throws Exception {
    Map<String, String> headers = Maps.newHashMap();
    BufferedReader reader;//w  ww  .  j  a  va  2s  .c  o  m
    try {
        reader = new BufferedReader(new InputStreamReader(manifestFile.getContents(true), "UTF8"));
    } catch (UnsupportedEncodingException e) {
        reader = new BufferedReader(new InputStreamReader(manifestFile.getContents(true)));
    }
    try {
        String header = null;
        StringBuffer value = new StringBuffer(256);
        boolean firstLine = true;
        while (true) {
            String line = reader.readLine();
            if (line == null || line.length() == 0) {
                if (!firstLine) {
                    headers.put(header, value.toString().trim());
                }
                break;
            }
            if (line.charAt(0) == ' ') {
                if (firstLine) {
                    throw new Exception();
                }
                value.append(line.substring(1));
                continue;
            }
            if (!firstLine) {
                headers.put(header, value.toString().trim());
                value.setLength(0);
            }
            int colon = line.indexOf(':');
            if (colon == -1) {
                throw new Exception();
            }
            header = line.substring(0, colon).trim();
            value.append(line.substring(colon + 1));
            firstLine = false;
        }
    } finally {
        IOUtils.closeQuietly(reader);
    }
    return headers;
}

From source file:org.apache.fop.complexscripts.bidi.UnicodeBidiAlgorithm.java

private static void dump(String header, int[] chars, int[] classes, int defaultLevel, int[] levels) {
    log.debug(header);//from  ww w.  j a  va 2s.  com
    log.debug("BD: default level(" + defaultLevel + ")");
    StringBuffer sb = new StringBuffer();
    if (chars != null) {
        for (int i = 0, n = chars.length; i < n; i++) {
            int ch = chars[i];
            sb.setLength(0);
            if ((ch > 0x20) && (ch < 0x7F)) {
                sb.append((char) ch);
            } else {
                sb.append(CharUtilities.charToNCRef(ch));
            }
            for (int k = sb.length(); k < 12; k++) {
                sb.append(' ');
            }
            sb.append(": " + padRight(getClassName(classes[i]), 4) + " " + levels[i]);
            log.debug(sb);
        }
    } else {
        for (int i = 0, n = classes.length; i < n; i++) {
            sb.setLength(0);
            for (int k = sb.length(); k < 12; k++) {
                sb.append(' ');
            }
            sb.append(": " + padRight(getClassName(classes[i]), 4) + " " + levels[i]);
            log.debug(sb);
        }
    }
}

From source file:Util.java

public static String dateToIsoDateTime(String date) {
    StringBuffer sb = new StringBuffer(date);

    if (date.length() >= 8) {
        //20070101 -> 2007-01-01
        //insert hyphens between year, month, and day
        sb.insert(4, '-');
        sb.insert(7, '-');

        //2007-01-01T173012 -> 2007-01-01T17:30:12
        if (date.length() >= 15) {
            //insert colons between hours, minutes, and seconds
            sb.insert(13, ':');
            sb.insert(16, ':');

            //2007-01-01T17:30:12 -> 2007-01-01T17:30:12.000
            //append milliseconds
            if (sb.toString().length() > 19)
                sb.insert(20, ".000");
            else//from w  ww.  ja  v a  2 s.c o m
                sb.append(".000");

            //2007-01-01T17:30:12.000 -> 2007-01-01T17:30:12.000Z
            //append UTC indicator if exists
            if (date.length() > 15 && date.charAt(15) == 'Z')
                sb.append('Z');
        }

        if (sb.length() > 19)
            sb.setLength(19);
    }

    return sb.toString();
}

From source file:org.castafiore.utils.StringUtil.java

/** Process one file */
public static void process(String fileName, InputStream inStream) {
    try {//from  ww  w  . j  av  a  2s . c o m
        int i;
        char ch;

        // This line alone cuts the runtime by about 66% on large files.
        BufferedInputStream is = new BufferedInputStream(inStream);

        StringBuffer sb = new StringBuffer();

        // Read a byte, cast it to char, check if part of printable string.
        while ((i = is.read()) != -1) {
            ch = (char) i;
            if (isStringChar(ch) || (sb.length() > 0 && ch == ' '))
                // If so, build up string.
                sb.append(ch);
            else {
                // if not, see if anything to output.
                if (sb.length() == 0)
                    continue;
                if (sb.length() >= 4) {
                    report(fileName, sb);
                }
                sb.setLength(0);
            }
        }
        is.close();
    } catch (IOException e) {
        //System.out.println("IOException: " + e);
    }
}

From source file:com.ikanow.aleph2.harvest.logstash.utils.LogstashConfigUtils.java

public static String validateLogstashInput(LogstashHarvesterConfigBean globals, String sourceKey, String config,
        StringBuffer errorMessage, boolean isAdmin) {

    _allowedInputs.addAll(Arrays.asList(globals.non_admin_inputs().toLowerCase().split("\\s*,\\s*")));
    _allowedFilters.addAll(Arrays.asList(globals.non_admin_filters().toLowerCase().split("\\s*,\\s*")));
    _allowedOutputs.addAll(Arrays.asList(globals.non_admin_outputs().toLowerCase().split("\\s*,\\s*")));

    // Configuration validation, phase 1

    errorMessage.append("Validation error:");
    ObjectNode jsonifiedConfig = parseLogstashConfig(config, errorMessage);
    if (null == jsonifiedConfig) {
        return null;
    }/*from  w  ww. j  a  v a 2 s  .  c om*/
    errorMessage.setLength(0);

    // Configuration validation, phase 2 - very basic checks on the structure of the object

    Object input = jsonifiedConfig.get("input");
    if ((null == input) || !(input instanceof ObjectNode)) { // Does input exist?
        errorMessage.append(
                "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (0)");
        return null;
    } //TESTED (3_1d)
    else { // Check there's only one input type and (unless admin) it's one of the allowed types
        ObjectNode inputDbo = (ObjectNode) input;
        if (1 != inputDbo.size()) {
            errorMessage.append(
                    "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (1)");
            return null;
        } //TESTED
        if (!isAdmin) {
            for (String key : (Iterable<String>) () -> inputDbo.fieldNames()) {
                if (!_allowedInputs.contains(key.toLowerCase())) {
                    errorMessage.append("Security error, non-admin not allowed input type " + key
                            + ", allowed options: " + _allowedInputs.toString());
                    return null;
                } //TESTED
            }
        } //TESTED (3_1abc)
    }
    Object filter = jsonifiedConfig.get("filter");
    if ((null == filter) || !(filter instanceof ObjectNode)) { // Does filter exist?
        errorMessage.append(
                "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (2)");
        return null;
    } //TESTED (3_2d)
    else { // Check there's only one input type and (unless admin) it's one of the allowed types
        if (!isAdmin) {
            ObjectNode filterDbo = (ObjectNode) filter;
            for (String key : (Iterable<String>) () -> filterDbo.fieldNames()) {
                if (!_allowedFilters.contains(key.toLowerCase())) {
                    errorMessage.append("Security error, non-admin not allowed filter type " + key
                            + ", allowed options: " + _allowedFilters.toString());
                    return null;
                } //TESTED
            }
        } //TESTED (3_2abc)
    }

    //TODO: same for output

    // Configuration validation, phase 3

    Matcher m = null;
    m = _validationRegexInputReplace.matcher(config);
    if (!m.find()) {
        errorMessage.append(
                "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (3)");
        return null;
    } //TESTED (see above)
    else { // If admin check on allowed types
        String inputType = m.group(2).toLowerCase();

        // If it's a file-based plugin then replace sincedb_path (check that it's not used during the JSON-ification):
        if (inputType.equalsIgnoreCase("file")) {
            config = _validationRegexInputReplace.matcher(config)
                    .replaceFirst("$1\n      sincedb_path => \"_XXX_DOTSINCEDB_XXX_\"\n");
        } else if (inputType.equalsIgnoreCase("s3")) {
            config = _validationRegexInputReplace.matcher(config).replaceFirst(
                    "$1\n      sincedb_path => \"_XXX_DOTSINCEDB_XXX_\"\n      temporary_directory => \"_XXX_LSTEMPDIR_XXX_\"");
        }

    } //TESTED

    m = _validationRegexNoSourceKey.matcher(config);
    // (this won't help malicious changes to source key, but will let people know they're not supposed to)
    if (m.find()) {
        errorMessage.append(
                "Not allowed to reference sourceKey - this is automatically appended by the logstash harvester");
        return null;
    } //TESTED      

    // OK now need to append the sourceKey at each stage of the pipeline to really really ensure that nobody sets sourceKey to be different 

    m = _validationRegexAppendFields.matcher(config);
    StringBuffer newConfig = new StringBuffer();
    if (m.find()) {
        m.appendReplacement(newConfig, "add_field => [  \"[@metadata][sourceKey]\", \"" + sourceKey + "\"] \n\n"
                + m.group() + " \n if [@metadata][sourceKey] == \"" + sourceKey + "\" { \n\n ");
    } else {
        errorMessage.append(
                "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (4)");
        return null;
    }
    m.appendTail(newConfig);
    config = newConfig.toString();
    config = config.replaceAll("}[^}]*$", ""); // (remove the last })
    config += "\n\n mutate { update => [ \"[@metadata][sourceKey]\", \"" + sourceKey + "\"] } \n}\n}\n"; // double check the sourceKey hasn't been overwritten and close the if from above
    //TESTED (syntactically correct and does overwrite sourceKey everywhere - success_2_2)

    return config;
}

From source file:JavascriptUtil.java

/**
 * <p>Unescapes any JavaScript literals found in the <code>String</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>
 * @param str the <code>String</code> to unescape, may be null
 * @return A new unescaped <code>String</code>, <code>null</code> if null string input
 *///from w  w w.  ja  va  2 s.com
public static String unescapeJavaScript(String str) {
    if (str == null) {
        return null;
    }

    StringBuffer writer = new StringBuffer(str.length());
    int sz = str.length();
    StringBuffer unicode = new StringBuffer(4);
    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);
                    writer.append((char) value);
                    unicode.setLength(0);
                    inUnicode = false;
                    hadSlash = false;
                } catch (NumberFormatException nfe) {
                    throw new IllegalArgumentException(
                            "Unable to parse unicode value: " + unicode + " cause: " + nfe);
                }
            }
            continue;
        }

        if (hadSlash) {
            // handle an escaped value
            hadSlash = false;
            switch (ch) {
            case '\\':
                writer.append('\\');
                break;
            case '\'':
                writer.append('\'');
                break;
            case '\"':
                writer.append('"');
                break;
            case 'r':
                writer.append('\r');
                break;
            case 'f':
                writer.append('\f');
                break;
            case 't':
                writer.append('\t');
                break;
            case 'n':
                writer.append('\n');
                break;
            case 'b':
                writer.append('\b');
                break;
            case 'u':
                // uh-oh, we're in unicode country....
                inUnicode = true;
                break;
            default:
                writer.append(ch);
                break;
            }
            continue;
        } else if (ch == '\\') {
            hadSlash = true;
            continue;
        }
        writer.append(ch);
    }

    if (hadSlash) {
        // then we're in the weird case of a \ at the end of the
        // string, let's output it anyway.
        writer.append('\\');
    }

    return writer.toString();
}

From source file:HexDump.java

/**
 * Dump an array of bytes to an OutputStream.
 *
 * @param data  the byte array to be dumped
 * @param offset  its offset, whatever that might mean
 * @param stream  the OutputStream to which the data is to be
 *               written/* ww  w  .  j  av  a2  s .c  o m*/
 * @param index initial index into the byte array
 *
 * @throws IOException is thrown if anything goes wrong writing
 *         the data to stream
 * @throws ArrayIndexOutOfBoundsException if the index is
 *         outside the data array's bounds
 * @throws IllegalArgumentException if the output stream is null
 */

public static void dump(byte[] data, long offset, OutputStream stream, int index)
        throws IOException, ArrayIndexOutOfBoundsException, IllegalArgumentException {

    if ((index < 0) || (index >= data.length)) {
        throw new ArrayIndexOutOfBoundsException(
                "illegal index: " + index + " into array of length " + data.length);
    }
    if (stream == null) {
        throw new IllegalArgumentException("cannot write to nullstream");
    }
    long display_offset = offset + index;
    StringBuffer buffer = new StringBuffer(74);

    for (int j = index; j < data.length; j += 16) {
        int chars_read = data.length - j;

        if (chars_read > 16) {
            chars_read = 16;
        }
        dump(buffer, display_offset).append(' ');
        for (int k = 0; k < 16; k++) {
            if (k < chars_read) {
                dump(buffer, data[k + j]);
            } else {
                buffer.append("  ");
            }
            buffer.append(' ');
        }
        for (int k = 0; k < chars_read; k++) {
            if ((data[k + j] >= ' ') && (data[k + j] < 127)) {
                buffer.append((char) data[k + j]);
            } else {
                buffer.append('.');
            }
        }
        buffer.append(EOL);
        stream.write(buffer.toString().getBytes());
        stream.flush();
        buffer.setLength(0);
        display_offset += chars_read;
    }
}

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

public static void generatePairsFromStringAndFileContentWithNoClass(String userInput, String inputFilePath,
        String outputFilePath) {//from   w w  w  .java  2  s .  c  o  m

    List<String> phenotypeList = new ArrayList<String>();

    try {
        phenotypeList = FileUtils.readLines(new File(inputFilePath));
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    String[] phenotype2;
    StringBuffer outputBuffer = new StringBuffer();

    BufferedWriter bw = null;
    try {
        bw = new BufferedWriter(new FileWriter(outputFilePath));
        for (int j = 0; j < phenotypeList.size(); j++) {
            phenotype2 = phenotypeList.get(j).split("\t");

            outputBuffer.append(String.format("%s\t%s\t%d\n", userInput, 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();
        }
    }
}