Example usage for java.lang StringBuffer toString

List of usage examples for java.lang StringBuffer toString

Introduction

In this page you can find the example usage for java.lang StringBuffer toString.

Prototype

@Override
    @HotSpotIntrinsicCandidate
    public synchronized String toString() 

Source Link

Usage

From source file:esg.security.yadis.XrdsDoc.java

/**
 * TODO: move this test harness to unit tests
 * @param args//from  ww  w .  j  av  a 2 s.  c  o m
 * @throws IOException 
 * @throws SAXException 
 * @throws ParserConfigurationException 
 * @throws XPathExpressionException 
 * @throws XrdsParseException 
 */
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException,
        XPathExpressionException, XrdsParseException {

    String yadisDocFilePath = "/home/pjkersha/workspace/EsgYadisParser/data/yadis.xml";
    XrdsDoc yadisParser = new XrdsDoc();
    StringBuffer contents = new StringBuffer();

    FileReader fileReader = new FileReader(yadisDocFilePath);
    BufferedReader in = new BufferedReader(fileReader);
    try {
        String text = null;

        while ((text = in.readLine()) != null) {
            contents.append(text);
            contents.append(System.getProperty("line.separator"));
        }
        in.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String yadisDocContent = contents.toString();
    yadisParser.parse(yadisDocContent);
}

From source file:com.frostvoid.trekwar.server.TrekwarServer.java

public static void main(String[] args) {
    // load language
    try {/*  w  w  w. j a v a2s .co m*/
        lang = new Language(Language.ENGLISH);
    } catch (IOException ioe) {
        System.err.println("FATAL ERROR: Unable to load language file!");
        System.exit(1);
    }

    System.out.println(lang.get("trekwar_server") + " " + VERSION);
    System.out.println("==============================================".substring(0,
            lang.get("trekwar_server").length() + 1 + VERSION.length()));

    // Handle parameters
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("file").withLongOpt("galaxy").hasArg()
            .withDescription("the galaxy file to load").create("g")); //"g", "galaxy", true, "the galaxy file to load");
    options.addOption(OptionBuilder.withArgName("port number").withLongOpt("port").hasArg()
            .withDescription("the port number to bind to (default 8472)").create("p"));
    options.addOption(OptionBuilder.withArgName("number").withLongOpt("save-interval").hasArg()
            .withDescription("how often (in turns) to save the galaxy to disk (default: 5)").create("s"));
    options.addOption(OptionBuilder.withArgName("log level").withLongOpt("log").hasArg()
            .withDescription("sets the log level: ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF")
            .create("l"));
    options.addOption("h", "help", false, "prints this help message");

    CommandLineParser cliParser = new BasicParser();

    try {
        CommandLine cmd = cliParser.parse(options, args);
        String portStr = cmd.getOptionValue("p");
        String galaxyFileStr = cmd.getOptionValue("g");
        String saveIntervalStr = cmd.getOptionValue("s");
        String logLevelStr = cmd.getOptionValue("l");

        if (cmd.hasOption("h")) {
            HelpFormatter help = new HelpFormatter();
            help.printHelp("TrekwarServer", options);
            System.exit(0);
        }

        if (cmd.hasOption("g") && galaxyFileStr != null) {
            galaxyFileName = galaxyFileStr;
        } else {
            throw new ParseException("galaxy file not specified");
        }

        if (cmd.hasOption("p") && portStr != null) {
            port = Integer.parseInt(portStr);
            if (port < 1 || port > 65535) {
                throw new NumberFormatException(lang.get("port_number_out_of_range"));
            }
        } else {
            port = 8472;
        }

        if (cmd.hasOption("s") && saveIntervalStr != null) {
            saveInterval = Integer.parseInt(saveIntervalStr);
            if (saveInterval < 1 || saveInterval > 100) {
                throw new NumberFormatException("Save Interval out of range (1-100)");
            }
        } else {
            saveInterval = 5;
        }

        if (cmd.hasOption("l") && logLevelStr != null) {
            if (logLevelStr.equalsIgnoreCase("finest")) {
                LOG.setLevel(Level.FINEST);
            } else if (logLevelStr.equalsIgnoreCase("finer")) {
                LOG.setLevel(Level.FINER);
            } else if (logLevelStr.equalsIgnoreCase("fine")) {
                LOG.setLevel(Level.FINE);
            } else if (logLevelStr.equalsIgnoreCase("config")) {
                LOG.setLevel(Level.CONFIG);
            } else if (logLevelStr.equalsIgnoreCase("info")) {
                LOG.setLevel(Level.INFO);
            } else if (logLevelStr.equalsIgnoreCase("warning")) {
                LOG.setLevel(Level.WARNING);
            } else if (logLevelStr.equalsIgnoreCase("severe")) {
                LOG.setLevel(Level.SEVERE);
            } else if (logLevelStr.equalsIgnoreCase("off")) {
                LOG.setLevel(Level.OFF);
            } else if (logLevelStr.equalsIgnoreCase("all")) {
                LOG.setLevel(Level.ALL);
            } else {
                System.err.println("ERROR: invalid log level: " + logLevelStr);
                System.err.println("Run again with -h flag to see valid log level values");
                System.exit(1);
            }
        } else {
            LOG.setLevel(Level.INFO);
        }
        // INIT LOGGING
        try {
            LOG.setUseParentHandlers(false);
            initLogging();
        } catch (IOException ex) {
            System.err.println("Unable to initialize logging to file");
            System.err.println(ex);
            System.exit(1);
        }

    } catch (Exception ex) {
        System.err.println("ERROR: " + ex.getMessage());
        System.err.println("use -h for help");
        System.exit(1);
    }

    LOG.log(Level.INFO, "Trekwar2 server " + VERSION + " starting up");

    // LOAD GALAXY
    File galaxyFile = new File(galaxyFileName);
    if (galaxyFile.exists()) {
        try {
            long timer = System.currentTimeMillis();
            LOG.log(Level.INFO, "Loading galaxy file {0}", galaxyFileName);
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(galaxyFile));
            galaxy = (Galaxy) ois.readObject();
            timer = System.currentTimeMillis() - timer;
            LOG.log(Level.INFO, "Galaxy file loaded in {0} ms", timer);
            ois.close();
        } catch (IOException ioe) {
            LOG.log(Level.SEVERE, "IO error while trying to load galaxy file", ioe);
        } catch (ClassNotFoundException cnfe) {
            LOG.log(Level.SEVERE, "Unable to find class while loading galaxy", cnfe);
        }
    } else {
        System.err.println("Error: file " + galaxyFileName + " not found");
        System.exit(1);
    }

    // if turn == 0 (start of game), execute first turn to update fog of war.
    if (galaxy.getCurrentTurn() == 0) {
        TurnExecutor.executeTurn(galaxy);
    }

    LOG.log(Level.INFO, "Current turn  : {0}", galaxy.getCurrentTurn());
    LOG.log(Level.INFO, "Turn speed    : {0} seconds", galaxy.getTurnSpeed() / 1000);
    LOG.log(Level.INFO, "Save Interval : {0}", saveInterval);
    LOG.log(Level.INFO, "Users / max   : {0} / {1}",
            new Object[] { galaxy.getUserCount(), galaxy.getMaxUsers() });

    // START SERVER
    try {
        server = new ServerSocket(port);
        LOG.log(Level.INFO, "Server listening on port {0}", port);
    } catch (BindException be) {
        LOG.log(Level.SEVERE, "Error: Unable to bind to port {0}", port);
        System.err.println(be);
        System.exit(1);
    } catch (IOException ioe) {
        LOG.log(Level.SEVERE, "Error: IO error while binding to port {0}", port);
        System.err.println(ioe);
        System.exit(1);
    }

    galaxy.startup();

    Thread timerThread = new Thread(new Runnable() {

        @Override
        @SuppressWarnings("SleepWhileInLoop")
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                    // && galaxy.getLoggedInUsers().size() > 0 will make server pause when nobody is logged in (TESTING)
                    if (System.currentTimeMillis() > galaxy.nextTurnDate) {
                        StringBuffer loggedInUsers = new StringBuffer();
                        for (User u : galaxy.getLoggedInUsers()) {
                            loggedInUsers.append(u.getUsername()).append(", ");
                        }

                        long time = TurnExecutor.executeTurn(galaxy);
                        LOG.log(Level.INFO, "Turn {0} executed in {1} ms",
                                new Object[] { galaxy.getCurrentTurn(), time });
                        LOG.log(Level.INFO, "Logged in users: " + loggedInUsers.toString());
                        LOG.log(Level.INFO,
                                "====================================================================================");

                        if (galaxy.getCurrentTurn() % saveInterval == 0) {
                            saveGalaxy();
                        }

                        galaxy.lastTurnDate = System.currentTimeMillis();
                        galaxy.nextTurnDate = galaxy.lastTurnDate + galaxy.turnSpeed;
                    }

                } catch (InterruptedException e) {
                    LOG.log(Level.SEVERE, "Error in main server loop, interrupted", e);
                }
            }
        }
    });
    timerThread.start();

    // ACCEPT CONNECTIONS AND DELEGATE TO CLIENT SESSIONS
    while (true) {
        Socket clientConnection;
        try {
            clientConnection = server.accept();
            ClientSession c = new ClientSession(clientConnection, galaxy);
            Thread t = new Thread(c);
            t.start();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, "IO Exception while trying to handle incoming client connection", ex);
        }
    }
}

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;/*www. j  a v  a  2s.c om*/
    // 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:CSV_ReportingConsolidator.java

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

    // Construct an array containing the list of files in the input folder
    String inputPath = "input/"; // Set the directory containing the CSV files
    String outputPath = "output/"; // Set the output directory for the consolidated report
    String outputFile = "Consolidated_CSV_Report.csv";
    File folder = new File(inputPath); // Load the selected path
    File[] listOfFiles = folder.listFiles(); // Retrieve the list of files from the directory

    // Serialize the reference headers to write the output CSV header
    CSVReader referenceReader = new CSVReader(new FileReader("reference/example_fields.csv"));
    String[] referenceHeaders = referenceReader.readNext();
    CSVWriter writer = new CSVWriter(new FileWriter(outputPath + outputFile), ',',
            CSVWriter.NO_QUOTE_CHARACTER);

    System.out.println("-- CSV parser initiated, found " + listOfFiles.length + " input files.\n");

    for (int i = 0; i < listOfFiles.length; i++) {
        if (listOfFiles[i].isFile()) {
            String filename = listOfFiles[i].getName(); // Retrieve the file name

            if (!filename.endsWith("csv")) { // Check if the file has a CSV extension
                System.out.println("EE | Fatal error: The input path contains non-csv files: " + filename
                        + ".\n Please remove them and try again.");
                writer.close();/*www . ja v  a 2  s  .co  m*/
                System.exit(1); // Exit if non-CSV files are found
            }

            String filePath = String.valueOf(inputPath + filename); // Combine the path with the filename
            File file = new File(filePath);
            CSVReader csvFile = new CSVReader(new FileReader(filePath));
            String[] nextLine; // CSV line data container
            int rowIterator = 0; // Used to loop between rows
            int colIterator = 0; // Used to loop between columns
            int rowCount = 0; // Used to count the total number of rows
            int pageCount = 0;
            int f = 0;

            String[] pageName = new String[100]; // Holder for Page names
            double[] individualPRT = new double[100]; // Holder for Page Response Times
            String PTrun = ""; // Name of Performance Test Run
            String startTime = ""; // Test start time

            double PRT = 0; // Average Page Response Time
            double PRd = 0; // Page Response Time Standard Deviation
            double ERT = 0; // Average Element Response Time
            double ERd = 0; // Element Response Time Standard Deviation
            double MRT = 0; // Maximum Page Response Time
            double mRT = 0; // Minimum Page Response Time
            int elapsedTime = 0; // Test Elapsed Time
            int completedUsers = 0; // Number of Completed Users
            int TPA = 0; // Total Page Attempts
            int TPH = 0; // Total Page Hits
            int TEA = 0; // Total Element Attempts
            int TEH = 0; // Total Element Hits

            // Fetch the total row count:
            FileReader fr = new FileReader(file);
            LineNumberReader ln = new LineNumberReader(fr);
            while (ln.readLine() != null) {
                rowCount++;
            }
            ln.close(); // Close the file reader

            // Fetch test identification data:
            nextLine = csvFile.readNext();
            PTrun = nextLine[1]; // Name of Performance Test Run
            nextLine = csvFile.readNext();
            startTime = nextLine[1]; // Performance Test Start Time

            // Skip 9 uninteresting rows:
            while (rowIterator < 9) {
                nextLine = csvFile.readNext();
                rowIterator++;
            }

            // Check if there are VP fails (adds another column)
            if (nextLine[9].equals("Total Page VPs Error For Run")) {
                f = 2;
            } else if (nextLine[8].equals("Total Page VPs Failed For Run")
                    || nextLine[8].equals("Total Page VPs Error For Run")) {
                f = 1;
            } else {
                f = 0;
            }

            // Read the page titles:
            while (colIterator != -1) {
                pageName[colIterator] = nextLine[colIterator + 18 + f];
                if ((pageName[colIterator].equals(pageName[0])) && colIterator > 0) {
                    pageCount = colIterator;
                    pageName[colIterator] = null;
                    colIterator = -1; // Detects when the page titles start to repeat
                } else {
                    colIterator++;
                }
            }

            // Retrieve non-continuous performance data, auto-detect gaps, auto-convert in seconds where needed
            nextLine = csvFile.readNext();
            nextLine = csvFile.readNext();
            while (rowIterator < rowCount - 3) {
                if (nextLine.length > 1) {
                    if (nextLine[0].length() != 0) {
                        elapsedTime = Integer.parseInt(nextLine[0]) / 1000;
                    }
                }
                if (nextLine.length > 5) {
                    if (nextLine[5].length() != 0) {
                        completedUsers = Integer.parseInt(nextLine[5]);
                    }
                }
                if (nextLine.length > 8 + f) {
                    if (nextLine[8 + f].length() != 0) {
                        TPA = (int) Double.parseDouble(nextLine[8 + f]);
                    }
                }
                if (nextLine.length > 9 + f) {
                    if (nextLine[9 + f].length() != 0) {
                        TPH = (int) Double.parseDouble(nextLine[9 + f]);
                    }
                }
                if (nextLine.length > 14 + f) {
                    if (nextLine[14 + f].length() != 0) {
                        TEA = (int) Double.parseDouble(nextLine[14 + f]);
                    }
                }
                if (nextLine.length > 15 + f) {
                    if (nextLine[15 + f].length() != 0) {
                        TEH = (int) Double.parseDouble(nextLine[15 + f]);
                    }
                }
                if (nextLine.length > 10 + f) {
                    if (nextLine[10 + f].length() != 0) {
                        PRT = Double.parseDouble(nextLine[10 + f]) / 1000;
                    }
                }
                if (nextLine.length > 11 + f) {
                    if (nextLine[11 + f].length() != 0) {
                        PRd = Double.parseDouble(nextLine[11 + f]) / 1000;
                    }
                }
                if (nextLine.length > 16 + f) {
                    if (nextLine[16 + f].length() != 0) {
                        ERT = Double.parseDouble(nextLine[16 + f]) / 1000;
                    }
                }
                if (nextLine.length > 17 + f) {
                    if (nextLine[17 + f].length() != 0) {
                        ERd = Double.parseDouble(nextLine[17 + f]) / 1000;
                    }
                }
                if (nextLine.length > 12 + f) {
                    if (nextLine[12 + f].length() != 0) {
                        MRT = Double.parseDouble(nextLine[12 + f]) / 1000;
                    }
                }
                if (nextLine.length > 13 + f) {
                    if (nextLine[13 + f].length() != 0) {
                        mRT = Double.parseDouble(nextLine[13 + f]) / 1000;
                    }
                }

                nextLine = csvFile.readNext();
                rowIterator++;
            }

            // Convert the elapsed time from seconds to HH:MM:SS format
            int hours = elapsedTime / 3600, remainder = elapsedTime % 3600, minutes = remainder / 60,
                    seconds = remainder % 60;
            String eTime = (hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes + ":"
                    + (seconds < 10 ? "0" : "") + seconds;

            csvFile.close(); // File recycled to reset the line parser
            CSVReader csvFile2 = new CSVReader(new FileReader(filePath));

            // Reset iterators to allow re-usage:
            rowIterator = 0;
            colIterator = 0;

            // Skip first 13 rows:
            while (rowIterator < 13) {
                nextLine = csvFile2.readNext();
                rowIterator++;
            }

            // Dynamically retrieve individual page response times in seconds, correlate with page names:
            while (rowIterator < rowCount) {
                while (colIterator < pageCount) {
                    if (nextLine.length > 18 + f) {
                        if (nextLine[colIterator + 18 + f].length() != 0) {
                            individualPRT[colIterator] = Double.parseDouble(nextLine[colIterator + 18 + f])
                                    / 1000;
                        }
                    }
                    colIterator++;
                }
                nextLine = csvFile2.readNext();
                rowIterator++;
                colIterator = 0;
            }

            csvFile2.close(); // Final file closing

            // Reset iterators to allow re-usage:
            rowIterator = 0;
            colIterator = 0;

            // Display statistics in console, enable only for debugging purposes:
            /*
            System.out.println(" Elapsed Time: " + elapsedTime
                   + "\n Completed Users: " + completedUsers
                   + "\n Total Page Attempts: " + TPA
                   + "\n Total Page Hits: " + TPH
                   + "\n Average Response Time For All Pages For Run: " + PRT
                   + "\n Response Time Standard Deviation For All Pages For Run: " + PRd
                   + "\n Maximum Response Time For All Pages For Run: " + MRT
                   + "\n Minimum Response Time For All Pages For Run: " + mRT
                   + "\n Total Page Element Attempts: " + TEA
                   + "\n Total Page Element Hits: " + TEH
                   + "\n Average Response Time For All Page Elements For Run: " + ERT
                   + "\n Response Time Standard Deviation For All Page Elements For Run: " + ERd
                   + "\n");
                    
            // Display individual page response times in console:
            while (colIterator < 9)   {
               System.out.println("Page " + Page[colIterator] + " - Response Time: " + PagePRT[colIterator]);
               colIterator++;
            }
            */

            // Serialize individual Page Response Times into CSV values
            StringBuffer individualPRTList = new StringBuffer();
            if (individualPRT.length > 0) {
                individualPRTList.append(String.valueOf(individualPRT[0]));
                for (int k = 1; k < pageCount; k++) {
                    individualPRTList.append(",");
                    individualPRTList.append(String.valueOf(individualPRT[k]));
                }
            }

            // Serialize all retrieved performance parameters:
            String[] entries = { PTrun, startTime, String.valueOf(completedUsers), eTime, String.valueOf(TPA),
                    String.valueOf(TPH), String.valueOf(PRT), String.valueOf(PRd), String.valueOf(MRT),
                    String.valueOf(mRT), String.valueOf(TEA), String.valueOf(TEH), String.valueOf(ERT),
                    String.valueOf(ERd), "", individualPRTList.toString(), };

            // Define header and write it to the first CSV row
            Object[] headerConcatenator = ArrayUtils.addAll(referenceHeaders, pageName);
            String[] header = new String[referenceHeaders.length + pageCount];
            header = Arrays.copyOf(headerConcatenator, header.length, String[].class);

            if (i == 0) {
                writer.writeNext(header); // Write CSV header
            }
            writer.writeNext(entries); // Write performance parameters in CSV format
            System.out.println("== Processed: " + filename + " ===========================");
        }
    }
    writer.close(); // Close the CSV writer
    System.out.println("\n-- Done processing " + listOfFiles.length + " files."
            + "\n-- The consolidated report has been saved to " + outputPath + outputFile);
}

From source file:CSV_ReportingConsolidator.java

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

    // Construct an array containing the list of files in the input folder
    String inputPath = "input/"; // Set the directory containing the CSV files
    String outputPath = "output/"; // Set the output directory for the consolidated report
    String outputFile = "Consolidated_CSV_Report.csv";
    File folder = new File(inputPath); // Load the selected path
    File[] listOfFiles = folder.listFiles(); // Retrieve the list of files from the directory

    // Serialize the reference headers to write the output CSV header
    CSVReader referenceReader = new CSVReader(new FileReader("reference/example_fields.csv"));
    String[] referenceHeaders = referenceReader.readNext();
    CSVWriter writer = new CSVWriter(new FileWriter(outputPath + outputFile), ',',
            CSVWriter.NO_QUOTE_CHARACTER);

    System.out.println("-- CSV parser initiated, found " + listOfFiles.length + " input files.\n");

    for (int i = 0; i < listOfFiles.length; i++) {
        if (listOfFiles[i].isFile()) {
            String filename = listOfFiles[i].getName(); // Retrieve the file name

            if (!filename.endsWith("csv")) { // Check if the file has a CSV extension
                System.out.println("EE | Fatal error: The input path contains non-csv files: " + filename
                        + ".\n Please remove them and try again.");
                writer.close();/*from   ww w  .j av  a 2 s.  c  o  m*/
                System.exit(1); // Exit if non-CSV files are found
            }

            String filePath = String.valueOf(inputPath + filename); // Combine the path with the filename
            File file = new File(filePath);
            CSVReader csvFile = new CSVReader(new FileReader(filePath));
            String[] nextLine; // CSV line data container
            int rowIterator = 0; // Used to loop between rows
            int colIterator = 0; // Used to loop between columns
            int rowCount = 0; // Used to count the total number of rows
            int pageCount = 0;
            int f = 0;

            String[] pageName = new String[100]; // Holder for Page names
            double[] individualPRT = new double[100]; // Holder for Page Response Times
            String PTrun = ""; // Name of Performance Test Run
            String startTime = ""; // Test start time

            double PRT = 0; // Average Page Response Time
            double PRd = 0; // Page Response Time Standard Deviation
            double ERT = 0; // Average Element Response Time
            double ERd = 0; // Element Response Time Standard Deviation
            double MRT = 0; // Maximum Page Response Time
            double mRT = 0; // Minimum Page Response Time
            int elapsedTime = 0; // Test Elapsed Time
            int completedUsers = 0; // Number of Completed Users
            int TPA = 0; // Total Page Attempts
            int TPH = 0; // Total Page Hits
            int TEA = 0; // Total Element Attempts
            int TEH = 0; // Total Element Hits

            // Fetch the total row count:
            FileReader fr = new FileReader(file);
            LineNumberReader ln = new LineNumberReader(fr);
            while (ln.readLine() != null) {
                rowCount++;
            }
            ln.close(); // Close the file reader

            // Fetch test identification data:
            nextLine = csvFile.readNext();
            PTrun = nextLine[1]; // Name of Performance Test Run
            nextLine = csvFile.readNext();
            startTime = nextLine[1]; // Performance Test Start Time

            // Skip 9 uninteresting rows:
            while (rowIterator < 9) {
                nextLine = csvFile.readNext();
                rowIterator++;
            }

            // Check if there are VP fails (adds another column)
            if (nextLine[9].equals("Total Page VPs Error For Run")) {
                f = 2;
            } else if (nextLine[8].equals("Total Page VPs Failed For Run")
                    || nextLine[8].equals("Total Page VPs Error For Run")) {
                f = 1;
            } else {
                f = 0;
            }

            // Read the page titles:
            while (colIterator != -1) {
                pageName[colIterator] = nextLine[colIterator + 16 + f];
                if ((pageName[colIterator].equals(pageName[0])) && colIterator > 0) {
                    pageCount = colIterator;
                    pageName[colIterator] = null;
                    colIterator = -1; // Detects when the page titles start to repeat
                } else {
                    colIterator++;
                }
            }

            // Retrieve non-continuous performance data, auto-detect gaps, auto-convert in seconds where needed
            nextLine = csvFile.readNext();
            nextLine = csvFile.readNext();
            while (rowIterator < rowCount - 3) {
                if (nextLine.length > 1) {
                    if (nextLine[0].length() != 0) {
                        elapsedTime = Integer.parseInt(nextLine[0]) / 1000;
                    }
                }
                if (nextLine.length > 4) {
                    if (nextLine[4].length() != 0) {
                        completedUsers = Integer.parseInt(nextLine[4]);
                    }
                }
                if (nextLine.length > 6 + f) {
                    if (nextLine[6 + f].length() != 0) {
                        TPA = (int) Double.parseDouble(nextLine[6 + f]);
                    }
                }
                if (nextLine.length > 7 + f) {
                    if (nextLine[7 + f].length() != 0) {
                        TPH = (int) Double.parseDouble(nextLine[7 + f]);
                    }
                }
                if (nextLine.length > 12 + f) {
                    if (nextLine[12 + f].length() != 0) {
                        TEA = (int) Double.parseDouble(nextLine[12 + f]);
                    }
                }
                if (nextLine.length > 13 + f) {
                    if (nextLine[13 + f].length() != 0) {
                        TEH = (int) Double.parseDouble(nextLine[13 + f]);
                    }
                }
                if (nextLine.length > 8 + f) {
                    if (nextLine[8 + f].length() != 0) {
                        PRT = Double.parseDouble(nextLine[8 + f]) / 1000;
                    }
                }
                if (nextLine.length > 9 + f) {
                    if (nextLine[9 + f].length() != 0) {
                        PRd = Double.parseDouble(nextLine[9 + f]) / 1000;
                    }
                }
                if (nextLine.length > 14 + f) {
                    if (nextLine[14 + f].length() != 0) {
                        ERT = Double.parseDouble(nextLine[14 + f]) / 1000;
                    }
                }
                if (nextLine.length > 15 + f) {
                    if (nextLine[15 + f].length() != 0) {
                        ERd = Double.parseDouble(nextLine[15 + f]) / 1000;
                    }
                }
                if (nextLine.length > 10 + f) {
                    if (nextLine[10 + f].length() != 0) {
                        MRT = Double.parseDouble(nextLine[10 + f]) / 1000;
                    }
                }
                if (nextLine.length > 11 + f) {
                    if (nextLine[11 + f].length() != 0) {
                        mRT = Double.parseDouble(nextLine[11 + f]) / 1000;
                    }
                }

                nextLine = csvFile.readNext();
                rowIterator++;
            }

            // Convert the elapsed time from seconds to HH:MM:SS format
            int hours = elapsedTime / 3600, remainder = elapsedTime % 3600, minutes = remainder / 60,
                    seconds = remainder % 60;
            String eTime = (hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes + ":"
                    + (seconds < 10 ? "0" : "") + seconds;

            csvFile.close(); // File recycled to reset the line parser
            CSVReader csvFile2 = new CSVReader(new FileReader(filePath));

            // Reset iterators to allow re-usage:
            rowIterator = 0;
            colIterator = 0;

            // Skip first 13 rows:
            while (rowIterator < 13) {
                nextLine = csvFile2.readNext();
                rowIterator++;
            }

            // Dynamically retrieve individual page response times in seconds, correlate with page names:
            while (rowIterator < rowCount) {
                while (colIterator < pageCount) {
                    if (nextLine.length > 16 + f) {
                        if (nextLine[colIterator + 16 + f].length() != 0) {
                            individualPRT[colIterator] = Double.parseDouble(nextLine[colIterator + 16 + f])
                                    / 1000;
                        }
                    }
                    colIterator++;
                }
                nextLine = csvFile2.readNext();
                rowIterator++;
                colIterator = 0;
            }

            csvFile2.close(); // Final file closing

            // Reset iterators to allow re-usage:
            rowIterator = 0;
            colIterator = 0;

            // Display statistics in console, enable only for debugging purposes:
            /*
            System.out.println(" Elapsed Time: " + elapsedTime
                   + "\n Completed Users: " + completedUsers
                   + "\n Total Page Attempts: " + TPA
                   + "\n Total Page Hits: " + TPH
                   + "\n Average Response Time For All Pages For Run: " + PRT
                   + "\n Response Time Standard Deviation For All Pages For Run: " + PRd
                   + "\n Maximum Response Time For All Pages For Run: " + MRT
                   + "\n Minimum Response Time For All Pages For Run: " + mRT
                   + "\n Total Page Element Attempts: " + TEA
                   + "\n Total Page Element Hits: " + TEH
                   + "\n Average Response Time For All Page Elements For Run: " + ERT
                   + "\n Response Time Standard Deviation For All Page Elements For Run: " + ERd
                   + "\n");
                    
            // Display individual page response times in console:
            while (colIterator < 9)   {
               System.out.println("Page " + Page[colIterator] + " - Response Time: " + PagePRT[colIterator]);
               colIterator++;
            }
            */

            // Serialize individual Page Response Times into CSV values
            StringBuffer individualPRTList = new StringBuffer();
            if (individualPRT.length > 0) {
                individualPRTList.append(String.valueOf(individualPRT[0]));
                for (int k = 1; k < pageCount; k++) {
                    individualPRTList.append(",");
                    individualPRTList.append(String.valueOf(individualPRT[k]));
                }
            }

            // Serialize all retrieved performance parameters:
            String[] entries = { PTrun, startTime, String.valueOf(completedUsers), eTime, String.valueOf(TPA),
                    String.valueOf(TPH), String.valueOf(PRT), String.valueOf(PRd), String.valueOf(MRT),
                    String.valueOf(mRT), String.valueOf(TEA), String.valueOf(TEH), String.valueOf(ERT),
                    String.valueOf(ERd), "", individualPRTList.toString(), };

            // Define header and write it to the first CSV row
            Object[] headerConcatenator = ArrayUtils.addAll(referenceHeaders, pageName);
            String[] header = new String[referenceHeaders.length + pageCount];
            header = Arrays.copyOf(headerConcatenator, header.length, String[].class);

            if (i == 0) {
                writer.writeNext(header); // Write CSV header
            }
            writer.writeNext(entries); // Write performance parameters in CSV format
            System.out.println("== Processed: " + filename + " ===========================");
        }
    }
    writer.close(); // Close the CSV writer
    System.out.println("\n-- Done processing " + listOfFiles.length + " files."
            + "\n-- The consolidated report has been saved to " + outputPath + outputFile);
}

From source file:com.hsbc.frc.SevenHero.ClientProxyAuthentication.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//w w w .  j  av  a2  s.c  om
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080),
                new UsernamePasswordCredentials("43668069", "wf^O^2013"));

        HttpHost targetHost = new HttpHost("pt.3g.qq.com");
        HttpHost proxy = new HttpHost("133.13.162.149", 8080);

        BasicClientCookie netscapeCookie = null;

        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        // httpclient.getCookieStore().addCookie(netscapeCookie);
        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        HttpGet httpget = new HttpGet("/");
        httpget.addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");

        System.out.println("executing request: " + httpget.getRequestLine());
        System.out.println("via proxy: " + proxy);
        System.out.println("to target: " + targetHost);

        HttpResponse response = httpclient.execute(targetHost, httpget);

        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        InputStream is = entity.getContent();
        StringBuffer sb = new StringBuffer(200);
        byte data[] = new byte[65536];
        int n = 1;
        do {
            n = is.read(data);
            if (n > 0) {
                sb.append(new String(data));
            }
        } while (n > 0);

        // System.out.println(sb);
        EntityUtils.consume(entity);

        System.out.println("----------------------------------------");
        Header[] headerlist = response.getAllHeaders();
        for (int i = 0; i < headerlist.length; i++) {
            Header header = headerlist[i];
            if (header.getName().equals("Set-Cookie")) {
                String setCookie = header.getValue();
                String cookies[] = setCookie.split(";");
                for (int j = 0; j < cookies.length; j++) {
                    String cookie[] = cookies[j].split("=");
                    CookieManager.cookie.put(cookie[0], cookie[1]);
                }
            }
            System.out.println(header.getName() + ":" + header.getValue());
        }
        String sid = getSid(sb.toString(), "&");
        System.out.println("sid: " + sid);

        httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080),
                new UsernamePasswordCredentials("43668069", "wf^O^2013"));
        String url = Constant.openUrl + "&" + sid;
        targetHost = new HttpHost(url);

        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        httpget = new HttpGet("/");
        httpget.addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        Iterator it = CookieManager.cookie.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            netscapeCookie = new BasicClientCookie((String) (key), (String) (value));
            netscapeCookie.setVersion(0);
            netscapeCookie.setDomain(".qq.com");
            netscapeCookie.setPath("/");
            // httpclient.getCookieStore().addCookie(netscapeCookie);
        }

        response = httpclient.execute(targetHost, httpget);

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.metadave.kash.KashConsole.java

public static void main(String[] args) throws IOException {
    CommandLine commandLine = processArgs(args);
    ConsoleReader reader = new ConsoleReader();
    reader.setBellEnabled(false);//w  ww.j  a  va  2s .  c  o  m
    reader.setExpandEvents(false); // TODO: look into this
    // TODO: Pasting in text with tabs prints out a ton of completions
    //reader.addCompleter(new jline.console.completer.StringsCompleter(keywords));

    String line;
    PrintWriter out = new PrintWriter(System.out);

    KashRuntimeContext ctx = new KashRuntimeContext();
    if (!commandLine.hasOption("nosignals")) {
        ConsoleSignalHander.install("INT", ctx);
    }

    boolean nextLinePrompt = false;

    ANSIBuffer buf = new ANSIBuffer();
    buf.setAnsiEnabled(!commandLine.hasOption("nocolor"));
    buf.blue("Welcome to Kash\n");
    buf.blue("(c) 2015 Dave Parfitt\n");
    System.out.println(buf.toString());

    if (!commandLine.hasOption("noconfig")) {
        String config = null;
        try {
            config = readConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (config != null && !config.trim().isEmpty()) {
            processInput(config, ctx);
            processOutput(ctx, out, !commandLine.hasOption("nocolor"));
        }
    }

    //        if (commandLine.hasOption("infile")) {
    //            String filename = commandLine.getOptionValue("infile");
    //            readInputFile(filename, ctx);
    //            ctx.getActionListener().term();
    //            System.exit(0);
    //        }

    StringBuffer lines = new StringBuffer();
    ANSIBuffer ansiprompt = new ANSIBuffer();
    ansiprompt.setAnsiEnabled(true);
    ansiprompt.green("> ");
    String prompt = ansiprompt.toString(!commandLine.hasOption("nocolor"));
    boolean inHereDoc = false;

    while ((line = reader.readLine(nextLinePrompt ? "" : prompt)) != null) {
        out.flush();
        String chunks[] = line.split(" ");
        String consoleCommandCheck = chunks[0].toLowerCase().trim();
        if (consoleOnlyCommands.containsKey(consoleCommandCheck)) {
            consoleOnlyCommands.get(consoleCommandCheck).run(line, reader);
            continue;
        }

        if (line.contains("~%~") && !line.contains("\\~%~")) {
            inHereDoc = !inHereDoc;
        }

        if (!line.trim().endsWith(";")) {
            nextLinePrompt = true;
            lines.append(line);
            lines.append("\n");
        } else if (line.trim().endsWith(";") && !inHereDoc) {
            lines.append(line);
            String input = lines.toString();
            nextLinePrompt = false;
            processInput(input, ctx);
            processOutput(ctx, out, !commandLine.hasOption("nocolor"));
            lines = new StringBuffer();
        } else if (inHereDoc) {
            lines.append(line);
            lines.append("\n");
        }

    }
}

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        System.out.println("Use: ContentFetcher mainurl contenturl destdir"); //$NON-NLS-1$
        System.out.println(//from w w w.jav a  2  s. c om
                "Example: ContentFetcher http://site.com http://site.com/dir[0-2]/image_A[001-040].jpg c:/temp"); //$NON-NLS-1$
        System.out.println(
                "Result: accessing http://site.com for cookie, reading http://site.com/dir1/image_A004.jpg writing c:/temp/dir_1_image_A004.jpg"); //$NON-NLS-1$
    } else {
        String url = args[1];
        String destdir = args[2];

        List parts = new ArrayList();
        int dir_from = 0;
        int dir_to = 0;
        int dir_fill = 0;
        int from = 0;
        int to = 0;
        int fill = 0;

        StringTokenizer tk = new StringTokenizer(url, "[]", true); //$NON-NLS-1$
        boolean hasDir = (tk.countTokens() > 5);
        boolean inDir = hasDir;
        System.out.println("hasDir " + hasDir); //$NON-NLS-1$
        boolean inTag = false;
        while (tk.hasMoreTokens()) {
            String token = tk.nextToken();
            if (token.equals("[")) //$NON-NLS-1$
            {
                inTag = true;
                continue;
            }
            if (token.equals("]")) //$NON-NLS-1$
            {
                inTag = false;
                if (inDir)
                    inDir = false;
                continue;
            }
            if (inTag) {
                int idx = token.indexOf('-');
                String s_from = token.substring(0, idx);
                int a_from = new Integer(s_from).intValue();
                int a_fill = s_from.length();
                int a_to = new Integer(token.substring(idx + 1)).intValue();
                if (inDir) {
                    dir_from = a_from;
                    dir_to = a_to;
                    dir_fill = a_fill;
                } else {
                    from = a_from;
                    to = a_to;
                    fill = a_fill;
                }
            } else {
                parts.add(token);
            }
        }

        DefaultHttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpGet main = new HttpGet(args[0]);
        HttpResponse res = client.execute(main);
        ;
        int main_rs = res.getStatusLine().getStatusCode();
        if (main_rs != 200) {
            System.out.println("main page retrieval failed " + main_rs); //$NON-NLS-1$
            return;
        }

        for (int d = dir_from; d <= dir_to; d++) {
            String dir_number = "" + d; //$NON-NLS-1$
            if (dir_fill > 1) {
                dir_number = "000000" + d; //$NON-NLS-1$
                int dir_digits = (int) (Math.log(fill) / Math.log(10));
                System.out.println("dir_digits " + dir_digits); //$NON-NLS-1$
                dir_number = dir_number.substring(dir_number.length() - (dir_fill - dir_digits),
                        dir_number.length());
            }
            for (int i = from; i <= to; i++) {
                try {
                    String number = "" + i; //$NON-NLS-1$
                    if (fill > 1) {
                        number = "000000" + i; //$NON-NLS-1$
                        int digits = (int) (Math.log(fill) / Math.log(10));
                        System.out.println("digits " + digits); //$NON-NLS-1$
                        number = number.substring(number.length() - (fill - digits), number.length());
                    }
                    int part = 0;
                    StringBuffer surl = new StringBuffer((String) parts.get(part++));
                    if (hasDir) {
                        surl.append(dir_number);
                        surl.append(parts.get(part++));
                    }
                    surl.append(number);
                    surl.append(parts.get(part++));
                    System.out.println("reading url " + surl); //$NON-NLS-1$

                    int indx = surl.toString().lastIndexOf('/');
                    StringBuffer sfile = new StringBuffer(destdir);
                    sfile.append("\\"); //$NON-NLS-1$
                    if (hasDir) {
                        sfile.append("dir_"); //$NON-NLS-1$
                        sfile.append(dir_number);
                        sfile.append("_"); //$NON-NLS-1$
                    }
                    sfile.append(surl.toString().substring(indx + 1));
                    File file = new File(sfile.toString());
                    if (file.exists()) {
                        file = new File("" + System.currentTimeMillis() + sfile.toString());
                    }
                    System.out.println("write file " + file.getAbsolutePath()); //$NON-NLS-1$

                    //                  URL iurl = createURLFromString(surl.toString());
                    HttpGet get = new HttpGet(surl.toString());

                    HttpResponse response = client.execute(get);
                    int result = response.getStatusLine().getStatusCode();
                    System.out.println("page http result " + result); //$NON-NLS-1$
                    if (result == 200) {
                        InputStream is = response.getEntity().getContent();
                        FileOutputStream fos = new FileOutputStream(file);
                        Utils.streamCopy(is, fos);
                        fos.close();
                    }
                } catch (Exception e) {
                    System.err.println(e);
                }
            }
        }
    }
}

From source file:com.metadave.eql.EQLConsole.java

public static void main(String[] args) throws IOException {
    CommandLine commandLine = processArgs(args);
    ConsoleReader reader = new ConsoleReader();
    reader.setBellEnabled(false);/*  w w  w .j av a 2  s.  c  om*/
    reader.setExpandEvents(false); // TODO: look into this
    // TODO: Pasting in text with tabs prints out a ton of completions
    //reader.addCompleter(new jline.console.completer.StringsCompleter(keywords));

    String line;
    PrintWriter out = new PrintWriter(System.out);

    RuntimeContext ctx = new RuntimeContext();
    if (!commandLine.hasOption("nosignals")) {
        ConsoleSignalHander.install("INT", ctx);
    }

    boolean nextLinePrompt = false;

    ANSIBuffer buf = new ANSIBuffer();
    buf.setAnsiEnabled(!commandLine.hasOption("nocolor"));
    buf.blue("Welcome to EQL\n");
    buf.blue("(c) 2015 Dave Parfitt\n");
    System.out.println(buf.toString());

    if (!commandLine.hasOption("noconfig")) {
        String config = null;
        try {
            config = readConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (config != null && !config.trim().isEmpty()) {
            processInput(config, ctx);
            processOutput(ctx, out, !commandLine.hasOption("nocolor"));
        }
    }

    //        if (commandLine.hasOption("infile")) {
    //            String filename = commandLine.getOptionValue("infile");
    //            readInputFile(filename, ctx);
    //            ctx.getActionListener().term();
    //            System.exit(0);
    //        }

    StringBuffer lines = new StringBuffer();
    ANSIBuffer ansiprompt = new ANSIBuffer();
    ansiprompt.setAnsiEnabled(true);
    ansiprompt.green("> ");
    String prompt = ansiprompt.toString(!commandLine.hasOption("nocolor"));
    boolean inHereDoc = false;

    while ((line = reader.readLine(nextLinePrompt ? "" : prompt)) != null) {
        out.flush();
        String chunks[] = line.split(" ");
        String consoleCommandCheck = chunks[0].toLowerCase().trim();
        if (consoleOnlyCommands.containsKey(consoleCommandCheck)) {
            consoleOnlyCommands.get(consoleCommandCheck).run(line, reader);
            continue;
        }

        if (line.contains("~%~") && !line.contains("\\~%~")) {
            inHereDoc = !inHereDoc;
        }

        if (!line.trim().endsWith(";")) {
            nextLinePrompt = true;
            lines.append(line);
            lines.append("\n");
        } else if (line.trim().endsWith(";") && !inHereDoc) {
            lines.append(line);
            String input = lines.toString();
            nextLinePrompt = false;
            processInput(input, ctx);
            processOutput(ctx, out, !commandLine.hasOption("nocolor"));
            lines = new StringBuffer();
        } else if (inHereDoc) {
            lines.append(line);
            lines.append("\n");
        }

    }
}

From source file:com.basho.contact.ContactConsole.java

public static void main(String[] args) throws IOException {
    CommandLine commandLine = processArgs(args);
    ConsoleReader reader = new ConsoleReader();
    reader.setBellEnabled(false);//from  w w w.  j  av a2  s.  co  m
    reader.setExpandEvents(false); // TODO: look into this
    // TODO: Pasting in text with tabs prints out a ton of completions
    //reader.addCompleter(new jline.console.completer.StringsCompleter(keywords));

    String line;
    PrintWriter out = new PrintWriter(System.out);
    DefaultConnectionProvider connections = new DefaultConnectionProvider();
    RuntimeContext ctx = new RuntimeContext(connections, System.out, System.err);
    if (!commandLine.hasOption("nosignals")) {
        ConsoleSignalHander.install("INT", ctx);
    }
    ContactWalker walker = new ContactWalker(ctx);
    ContactAdminWalker adminWalker = new ContactAdminWalker(ctx);
    List<ContactBaseListener> walkers = new ArrayList<ContactBaseListener>();
    walkers.add(walker);
    walkers.add(adminWalker);

    boolean nextLinePrompt = false;

    ANSIBuffer buf = new ANSIBuffer();
    buf.setAnsiEnabled(!commandLine.hasOption("nocolor"));
    buf.blue("Welcome to Riak Contact\n");
    buf.blue("(c) 2013 Dave Parfitt\n");
    System.out.println(buf.toString());

    if (!commandLine.hasOption("noconfig")) {
        String config = null;
        try {
            config = readConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (config != null && !config.trim().isEmpty()) {
            processInput(config, walkers, ctx);
            processOutput(ctx, out, !commandLine.hasOption("nocolor"));
        }
    }

    if (commandLine.hasOption("infile")) {
        String filename = commandLine.getOptionValue("infile");
        readInputFile(filename, walkers, ctx);
        ctx.getActionListener().term();
        System.exit(0);
    }

    StringBuffer lines = new StringBuffer();
    ANSIBuffer ansiprompt = new ANSIBuffer();
    ansiprompt.setAnsiEnabled(true);
    ansiprompt.green("> ");
    String prompt = ansiprompt.toString(!commandLine.hasOption("nocolor"));
    boolean inHereDoc = false;

    while ((line = reader.readLine(nextLinePrompt ? "" : prompt)) != null) {
        out.flush();
        String chunks[] = line.split(" ");
        String consoleCommandCheck = chunks[0].toLowerCase().trim();
        if (consoleOnlyCommands.containsKey(consoleCommandCheck)) {
            consoleOnlyCommands.get(consoleCommandCheck).run(line, reader);
            continue;
        }

        if (line.contains("~%~") && !line.contains("\\~%~")) {
            inHereDoc = !inHereDoc;
        }

        if (!line.trim().endsWith(";")) {
            nextLinePrompt = true;
            lines.append(line);
            lines.append("\n");
        } else if (line.trim().endsWith(";") && !inHereDoc) {
            lines.append(line);
            String input = lines.toString();
            nextLinePrompt = false;
            processInput(input, walkers, ctx);
            processOutput(ctx, out, !commandLine.hasOption("nocolor"));
            lines = new StringBuffer();
        } else if (inHereDoc) {
            lines.append(line);
            lines.append("\n");
        }

    }
    ctx.getActionListener().term();
}