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

public static void main(String args[]) {
    StringBuffer sb = new StringBuffer("java2s.com");
    System.out.println("buffer before = " + sb);

    sb.setLength(2);
    System.out.println("buffer after = " + sb);
}

From source file:setCharAtDemo.java

public static void main(String args[]) {
    StringBuffer sb = new StringBuffer("Hello");
    System.out.println("buffer before = " + sb);
    System.out.println("charAt(1) before = " + sb.charAt(1));
    sb.setCharAt(1, 'i');
    sb.setLength(2);
    System.out.println("buffer after = " + sb);
    System.out.println("charAt(1) after = " + sb.charAt(1));
}

From source file:MainClass.java

public static void main(String[] arg) {
    StringBuffer newString = new StringBuffer("abcde1234567890");

    System.out.println(newString.capacity());
    System.out.println(newString.length());
    System.out.println(newString);

    newString.setLength(8);

    System.out.println(newString.capacity());
    System.out.println(newString.length());
    System.out.println(newString);

}

From source file:MainClass.java

public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("abc");

    System.out.println("sb = " + sb);
    System.out.println("Length = " + sb.length());
    System.out.println("Capacity = " + sb.capacity());

    sb.setLength(2);

    System.out.println("sb = " + sb);
    System.out.println("Length = " + sb.length());
    System.out.println("Capacity = " + sb.capacity());

    sb.setLength(4);//w w w.j av  a 2s .  c  o m

    System.out.println("sb = " + sb);
    System.out.println("Length = " + sb.length());
    System.out.println("Capacity = " + sb.capacity());
}

From source file:com.digitalgeneralists.assurance.Application.java

public static void main(String[] args) {
    Logger logger = Logger.getLogger(Application.class);

    logger.info("App is starting.");

    Properties applicationProperties = new Properties();
    String applicationInfoFileName = "/version.txt";
    InputStream inputStream = Application.class.getResourceAsStream(applicationInfoFileName);
    applicationInfoFileName = null;/*from   w  w w.  j  a  va 2 s.  c o m*/

    try {
        if (inputStream != null) {
            applicationProperties.load(inputStream);

            Application.applicationShortName = applicationProperties.getProperty("name");
            Application.applicationName = applicationProperties.getProperty("applicationName");
            Application.applicationVersion = applicationProperties.getProperty("version");
            Application.applicationBuildNumber = applicationProperties.getProperty("buildNumber");

            applicationProperties = null;
        }
    } catch (IOException e) {
        logger.warn("Could not load application version information.", e);
    } finally {
        try {
            inputStream.close();
        } catch (IOException e) {
            logger.error("Couldn't close the application version input stream.");
        }
        inputStream = null;
    }

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        private Logger logger = Logger.getLogger(Application.class);

        public void run() {
            logger.info("Starting the Swing run thread.");

            try {
                Application.installDb();
            } catch (IOException e) {
                logger.fatal("Unable to install the application database.", e);
                System.exit(1);
            } catch (SQLException e) {
                logger.fatal("Unable to install the application database.", e);
                System.exit(1);
            }

            IApplicationUI window = null;
            ClassPathXmlApplicationContext springContext = null;
            try {
                springContext = new ClassPathXmlApplicationContext("/META-INF/spring/app-context.xml");
                StringBuffer message = new StringBuffer(256);
                logger.info(message.append("Spring Context: ").append(springContext));
                message.setLength(0);
                window = (IApplicationUI) springContext.getBean("ApplicationUI");
            } finally {
                if (springContext != null) {
                    springContext.close();
                }
                springContext = null;
            }

            if (window != null) {
                logger.info("Launching the window.");
                window.display();
            } else {
                logger.fatal("The main application window object is null.");
            }

            logger = null;
        }
    });
}

From source file:net.java.sen.tools.MkCompoundTable.java

/**
 * Build compound word table.//  ww  w. jav a2  s .c o m
 */
public static void main(String args[]) {
    ResourceBundle rb = ResourceBundle.getBundle("dictionary");
    int pos_start = Integer.parseInt(rb.getString("pos_start"));
    int pos_size = Integer.parseInt(rb.getString("pos_size"));

    try {
        log.info("reading compound word information ... ");
        HashMap compoundTable = new HashMap();

        log.info("load dic: " + rb.getString("compound_word_file"));
        BufferedReader dicStream = new BufferedReader(new InputStreamReader(
                new FileInputStream(rb.getString("compound_word_file")), rb.getString("dic.charset")));

        String t;
        int line = 0;

        StringBuffer pos_b = new StringBuffer();
        while ((t = dicStream.readLine()) != null) {
            CSVParser parser = new CSVParser(t);
            String csv[] = parser.nextTokens();
            if (csv.length < (pos_size + pos_start)) {
                throw new RuntimeException("format error:" + line);
            }

            pos_b.setLength(0);
            for (int i = pos_start; i < (pos_start + pos_size - 1); i++) {
                pos_b.append(csv[i]);
                pos_b.append(',');
            }

            pos_b.append(csv[pos_start + pos_size - 1]);
            pos_b.append(',');

            for (int i = pos_start + pos_size; i < (csv.length - 2); i++) {
                pos_b.append(csv[i]);
                pos_b.append(',');
            }
            pos_b.append(csv[csv.length - 2]);
            compoundTable.put(pos_b.toString(), csv[csv.length - 1]);
        }
        dicStream.close();
        log.info("done.");
        log.info("writing compound word table ... ");
        ObjectOutputStream os = new ObjectOutputStream(
                new FileOutputStream(rb.getString("compound_word_table")));
        os.writeObject(compoundTable);
        os.close();
        log.info("done.");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLEventReader xmlr = xif.createXMLEventReader((new FileInputStream(new File("./file.xml"))));

    boolean inline = false;
    StringBuffer sb = new StringBuffer();
    while (xmlr.hasNext()) {
        XMLEvent event = xmlr.nextEvent();

        if (event.isStartElement()) {
            StartElement element = (StartElement) event;
            if ("data".equals(element.getName().toString().trim())) {
                inline = true;/*from  w  w  w.  ja  va 2 s  .c om*/
            }
        }

        if (inline) {
            sb.append(xmlr.peek());
        }

        if (event.isEndElement()) {
            EndElement element = (EndElement) event;
            if ("data".equals(element.getName().toString().trim())) {
                inline = false;
                System.out.println(sb.toString());
                sb.setLength(0);
            }
        }
    }
}

From source file:com.ikanow.infinit.e.application.utils.LogstashConfigUtils.java

public static void main(String[] args) throws IOException {

    System.out.println(Arrays.toString(args));
    Globals.setIdentity(com.ikanow.infinit.e.data_model.Globals.Identity.IDENTITY_API);
    Globals.overrideConfigLocation(args[0]);

    // 1) Errored sources - things that break the formatting
    StringBuffer errors = new StringBuffer();
    String testName;//  w w w  .  j a v a 2  s.c o m
    // 1.1) {} mismatch 1
    //a
    errors.setLength(0);
    testName = "error_1_1a";
    if (null != parseLogstashConfig(getTestFile(testName), errors)) {
        System.out.println("**** FAIL " + testName);
    } else if (!errors.toString().startsWith("{} Mismatch (})")) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }
    //b
    errors.setLength(0);
    testName = "error_1_1b";
    if (null != parseLogstashConfig(getTestFile(testName), errors)) {
        System.out.println("**** FAIL " + testName);
    } else if (!errors.toString().startsWith("{} Mismatch (})")) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }
    //c
    errors.setLength(0);
    testName = "error_1_1c";
    if (null != parseLogstashConfig(getTestFile(testName), errors)) {
        System.out.println("**** FAIL " + testName);
    } else if (!errors.toString().startsWith("{} Mismatch (})")) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }

    // 1.2) {} mismatch 2

    //a
    errors.setLength(0);
    testName = "error_1_2a";
    if (null != parseLogstashConfig(getTestFile(testName), errors)) {
        System.out.println("**** FAIL " + testName);
    } else if (!errors.toString().startsWith("{} Mismatch ({)")) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }

    // 1.3) multiple input/filter blocks
    // 1.3a) input
    errors.setLength(0);
    testName = "error_1_3a";
    if (null != parseLogstashConfig(getTestFile(testName), errors)) {
        System.out.println("**** FAIL " + testName);
    } else if (!errors.toString().equals("Multiple input or filter blocks: input")) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }
    // 1.3b) filter
    errors.setLength(0);
    testName = "error_1_3b";
    if (null != parseLogstashConfig(getTestFile(testName), errors)) {
        System.out.println("**** FAIL " + testName);
    } else if (!errors.toString().equals("Multiple input or filter blocks: filter")) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }

    // 1.4) unrecognized blocks
    // a output - special case
    errors.setLength(0);
    testName = "error_1_4a";
    if (null != parseLogstashConfig(getTestFile(testName), errors)) {
        System.out.println("**** FAIL " + testName);
    } else if (!errors.toString()
            .equals("Not allowed output blocks - these are appended automatically by the logstash harvester")) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }
    // b
    errors.setLength(0);
    testName = "error_1_4b";
    if (null != parseLogstashConfig(getTestFile(testName), errors)) {
        System.out.println("**** FAIL " + testName);
    } else if (!errors.toString().equals("Unrecognized processing block: something_random")) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }

    // 1.5) fields/sub-elements that are not permitted
    // a ... sincedb_path
    errors.setLength(0);
    testName = "error_1_5a";
    if (null != parseLogstashConfig(getTestFile(testName), errors)) {
        System.out.println("**** FAIL " + testName);
    } else if (!errors.toString().equals("Not allowed sincedb_path in input.* block")) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }
    // b ... filter as sub-path of input
    errors.setLength(0);
    testName = "error_1_5b";
    if (null != parseLogstashConfig(getTestFile(testName), errors)) {
        System.out.println("**** FAIL " + testName);
    } else if (!errors.toString().equals("Not allowed sub-elements of input called 'filter' (1)")) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }
    // c ... filter as sub-path of sub-element of input
    errors.setLength(0);
    testName = "error_1_5c";
    if (null != parseLogstashConfig(getTestFile(testName), errors)) {
        System.out.println("**** FAIL " + testName);
    } else if (!errors.toString().equals("Not allowed sub-elements of input called 'filter' (2)")) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }

    // 2) Valid formatted source
    BasicDBObject retVal;
    String output;
    String inputName; // (for re-using config files across text)
    //2.1)
    errors.setLength(0);
    testName = "success_2_1";
    if (null == (retVal = parseLogstashConfig(getTestFile(testName), errors))) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    } else if (!retVal.toString().equals(
            "{ \"input\" : { \"file\" : [ { \"path\" : { } , \"start_position\" : { } , \"type\" : { } , \"codec.multiline\" : { }}]} , \"filter\" : { \"csv\" : [ { \"columns\" : { }}] , \"drop\" : [ { }] , \"mutate\" : [ { \"convert\" : { }} , { \"add_fields\" : { }} , { \"rename\" : { }}] , \"date\" : [ { \"timezone\" : { } , \"match\" : { }}] , \"geoip\" : [ { \"source\" : { } , \"fields\" : { }}]}}")) {
        System.out.println("**** FAIL " + testName + ": " + retVal.toString());
    }
    //System.out.println("(val="+retVal+")");

    // 2.2
    errors.setLength(0);
    testName = "success_2_2";
    if (null == (retVal = parseLogstashConfig(getTestFile(testName), errors))) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }
    if (null == MongoDbUtil.getProperty(retVal, "filter.geoip.fields")) {
        System.out.println("**** FAIL " + testName + ": " + retVal);
    }
    //System.out.println(retVal);

    //2.3)   - check that the sincedb is added correctly, plus the sourceKey manipulation
    // (USE success_2_1 for this)
    errors.setLength(0);
    testName = "inputs_2_3";
    inputName = "success_2_3";
    if (null == (output = validateLogstashInput(testName, getTestFile(inputName), errors, true))) {
        System.out.println("**** FAIL " + testName + ": errored: " + errors);
    } else {
        String outputToTest = output.replaceAll("[\n\r]", "\\\\n").replaceAll("\\s+", " ");
        String testAgainst = "input {\n\n file {\n sincedb_path => \"_XXX_DOTSINCEDB_XXX_\"\n\n\n path => \"/root/odin-poc-data/proxy_logs/may_known_cnc.csv\"\n\n start_position => beginning\n\n type => \"proxy_logs\"\n\n codec => multiline {\n\n pattern => \"^%{YEAR}-%{MONTHNUM}-%{MONTHDAY}%{DATA:summary}\"\n\n negate => true\n\n what => \"previous\"\n\n } \n\n add_field => [ \"sourceKey\", \"inputs_2_3\"] \n\n}\n\n}\n\n\n\nfilter { \n if [sourceKey] == \"inputs_2_3\" { \n\n \n\n if [type] == \"proxy_logs\" {\n\n csv {\n\n columns => [\"Device_Name\",\"SimpleDate\",\"Event_#Date\",\"Source_IP\",\"Source_Port\",\"Destination_IP\",\"Destination_Port\",\"Protocol\",\"Vendor_Alert\",\"MSS_Action\",\"Logging_Device_IP\",\"Application\",\"Bytes_Received\",\"Bytes_Sent\",\"Dest._Country\",\"Message\",\"Message_Type\",\"MSS_Log_Source_IP\",\"MSS_Log_Source_Type\",\"MSS_Log_Source_UUID\",\"network_protocol_id\",\"OS_Type\",\"PIX_Main-Code\",\"PIX_Sub-Code\",\"Port\",\"Product_ID\",\"Product\",\"Rule\",\"Rule_Identifier\",\"Sensor_Name\",\"Class\",\"Translate_Destination_IP\",\"Translate_Destination_Port\",\"Translate_Source_IP\"]\n\n }\n\n if [Device_Name] == \"Device Name\" {\n\n drop {}\n\n }\n\n mutate {\n\n convert => [ \"Bytes_Received\", \"integer\" ]\n\n convert => [ \"Bytes_Sent\", \"integer\" ]\n\n }\n\n date {\n\n timezone => \"Europe/London\"\n\n match => [ \"Event_Date\" , \"yyyy-MM-dd'T'HH:mm:ss\" ]\n\n }\n\n geoip {\n\n source => \"Destination_IP\"\n\n fields => [\"timezone\",\"location\",\"latitude\",\"longitude\"]\n\n }\n\n }\n\n\n\n mutate { update => [ \"sourceKey\", \"inputs_2_3\"] } \n}\n}\n";
        testAgainst = testAgainst.replaceAll("[\n\r]", "\\\\n").replaceAll("\\s+", " ");
        if (!outputToTest.equals(testAgainst)) {
            System.out.println("**** FAIL " + testName + ": " + output);
        }
    }

    // 3) Valid formatted source, access to restricted types

    // 3.1) input 
    // a) restricted - admin
    // (USE success_2_1 for this)
    errors.setLength(0);
    testName = "inputs_3_1a";
    inputName = "success_2_1";
    if (null != (output = validateLogstashInput(testName, getTestFile(inputName), errors, false))) {
        System.out.println("**** FAIL " + testName + ": Should have errored: " + output);
    } else if (!errors.toString()
            .startsWith("Security error, non-admin not allowed input type file, allowed options: ")) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }

    // b) restricted - non admin
    // (USE success_2_1 for this)
    errors.setLength(0);
    testName = "inputs_3_1b";
    inputName = "success_2_1";
    if (null == (output = validateLogstashInput(testName, getTestFile(inputName), errors, true))) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }

    // c) unrestricted - non admin
    errors.setLength(0);
    testName = "inputs_3_1c";
    inputName = "inputs_3_1c";
    if (null == (output = validateLogstashInput(testName, getTestFile(inputName), errors, true))) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }
    //System.out.println("(val="+output+")");

    // d) no input at all
    errors.setLength(0);
    testName = "inputs_3_1d";
    inputName = "inputs_3_1d";
    if (null != (output = validateLogstashInput(testName, getTestFile(inputName), errors, false))) {
        System.out.println("**** FAIL " + testName + ": Should have errored: " + output);
    } else if (!errors.toString().startsWith(
            "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them.")) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }

    // 3.2) filter
    // a) restricted - admin
    errors.setLength(0);
    testName = "filters_3_2a";
    inputName = "filters_3_2a";
    if (null != (output = validateLogstashInput(testName, getTestFile(inputName), errors, false))) {
        System.out.println("**** FAIL " + testName + ": Should have errored: " + output);
    } else if (!errors.toString()
            .startsWith("Security error, non-admin not allowed filter type elasticsearch, allowed options: ")) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }
    //System.out.println("(err="+errors.toString()+")");

    // b) restricted - non admin
    // (USE filters_3_2a for this)
    errors.setLength(0);
    testName = "filters_3_2a";
    inputName = "filters_3_2a";
    if (null == (output = validateLogstashInput(testName, getTestFile(inputName), errors, true))) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }
    //System.out.println("(val="+output+")");

    // c) unrestricted - non admin
    // (implicitly tested via 3.1bc)

    // d) no filter at all
    errors.setLength(0);
    testName = "filters_3_2d";
    inputName = "filters_3_2d";
    if (null != (output = validateLogstashInput(testName, getTestFile(inputName), errors, false))) {
        System.out.println("**** FAIL " + testName + ": Should have errored: " + output);
    } else if (!errors.toString().startsWith(
            "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them.")) {
        System.out.println("**** FAIL " + testName + ": " + errors.toString());
    }

}

From source file:Main.java

private static void addChildren(Writer writer, ResultSet rs) throws SQLException, IOException {
    ResultSetMetaData metaData = rs.getMetaData();
    int nbColumns = metaData.getColumnCount();
    StringBuffer buffer = new StringBuffer();
    while (rs.next()) {
        buffer.setLength(0);
        buffer.append("<" + metaData.getTableName(1) + ">");
        for (int i = 1; i <= nbColumns; i++) {
            buffer.append("<" + metaData.getColumnName(i) + ">");
            buffer.append(rs.getString(i));
            buffer.append("</" + metaData.getColumnName(i) + ">");
        }//from  ww w .ja v a  2 s.c  o  m
        buffer.append("</" + metaData.getTableName(1) + ">");
        writer.write(buffer.toString());
    }
}

From source file:Main.java

private static SecretKeySpec createKey(String key) {
    byte[] data = null;
    if (key == null) {
        key = "";
    }/*from   w ww . j a  va  2  s . co  m*/
    StringBuffer sb = new StringBuffer(16);
    sb.append(key);
    while (sb.length() < 16) {
        sb.append("0");
    }
    if (sb.length() > 16) {
        sb.setLength(16);
    }
    try {
        data = sb.toString().getBytes("UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new SecretKeySpec(data, "AES");
}