Example usage for java.lang StringBuffer append

List of usage examples for java.lang StringBuffer append

Introduction

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

Prototype

@Override
    public synchronized StringBuffer append(double d) 

Source Link

Usage

From source file:com.annuletconsulting.homecommand.server.HomeCommand.java

/**
 * This class will accept commands from a node in each room. For it to react to events on the server
 * computer, it must be also running as a node.  However the server can cause all nodes to react
 * to an event happening on any node, such as an email or text arriving.  A call on a node device
 * could pause all music devices, for example.
 * //from  w  w w  .  j a  v  a  2  s  .  co  m
 * @param args
 */
public static void main(String[] args) {
    try {
        socket = Integer.parseInt(HomeComandProperties.getInstance().getServerPort());
        nonJavaUserModulesPath = HomeComandProperties.getInstance().getNonJavaUserDir();
    } catch (Exception exception) {
        System.out.println("Error loading from properties file.");
        exception.printStackTrace();
    }
    try {
        sharedKey = HomeComandProperties.getInstance().getSharedKey();
        if (sharedKey == null)
            System.out.println("shared_key is null, commands without valid signatures will be processed.");
    } catch (Exception exception) {
        System.out.println("shared_key not found in properties file.");
        exception.printStackTrace();
    }
    try {
        if (args.length > 0) {
            String arg0 = args[0];
            if (arg0.equals("help") || arg0.equals("?") || arg0.equals("usage") || arg0.equals("-help")
                    || arg0.equals("-?")) {
                System.out.println(
                        "The defaults can be changed by editing the HomeCommand.properties file, or you can override them temporarily using command line options.");
                System.out.println("\nHome Command Server command line overrride usage:");
                System.out.println(
                        "hcserver [server_port] [java_user_module_directory] [non_java_user_module_directory]"); //TODO make hcserver.sh
                System.out.println("\nDefaults:");
                System.out.println("server_port: " + socket);
                System.out.println("java_user_module_directory: " + userModulesPath);
                System.out.println("non_java_user_module_directory: " + nonJavaUserModulesPath);
                System.out.println("\n2013 | Annulet, LLC");
            }
            socket = Integer.parseInt(arg0);
        }
        if (args.length > 1)
            userModulesPath = args[1];
        if (args.length > 2)
            nonJavaUserModulesPath = args[2];

        System.out.println("Config loaded, initializing modules.");
        modules.add(new HueLightModule());
        System.out.println("HueLightModule initialized.");
        modules.add(new QuestionModule());
        System.out.println("QuestionModule initialized.");
        modules.add(new MathModule());
        System.out.println("MathModule initialized.");
        modules.add(new MusicModule());
        System.out.println("MusicModule initialized.");
        modules.add(new NonCopyrightInfringingGenericSpaceExplorationTVShowModule());
        System.out.println("NonCopyrightInfringingGenericSpaceExplorationTVShowModule initialized.");
        modules.add(new HelpModule());
        System.out.println("HelpModule initialized.");
        modules.add(new SetUpModule());
        System.out.println("SetUpModule initialized.");
        modules.addAll(NonJavaUserModuleLoader.loadModulesAt(nonJavaUserModulesPath));
        System.out.println("NonJavaUserModuleLoader initialized.");
        ServerSocket serverSocket = new ServerSocket(socket);
        System.out.println("Listening...");
        while (!end) {
            Socket socket = serverSocket.accept();
            InputStreamReader isr = new InputStreamReader(socket.getInputStream());
            PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
            int character;
            StringBuffer inputStrBuffer = new StringBuffer();
            while ((character = isr.read()) != 13) {
                inputStrBuffer.append((char) character);
            }
            System.out.println(inputStrBuffer.toString());
            String[] cmd; // = inputStrBuffer.toString().split(" ");
            String result = "YOUR REQUEST WAS NOT VALID JSON";
            if (inputStrBuffer.substring(0, 1).equals("{")) {
                nodeType = extractElement(inputStrBuffer.toString(), "node_type");
                if (sharedKey != null) {
                    if (validateSignature(extractElement(inputStrBuffer.toString(), "time_stamp"),
                            extractElement(inputStrBuffer.toString(), "signature"))) {
                        if ("Y".equalsIgnoreCase(extractElement(inputStrBuffer.toString(), "cmd_encoded")))
                            cmd = decryptCommand(extractElement(inputStrBuffer.toString(), "command"));
                        else
                            cmd = extractElement(inputStrBuffer.toString(), "command").split(" ");
                        result = getResult(cmd);
                    } else
                        result = "YOUR SIGNATURE DID NOT MATCH, CHECK SHARED KEY";
                } else {
                    cmd = extractElement(inputStrBuffer.toString(), "command").split(" ");
                    result = getResult(cmd);
                }
            }
            System.out.println(result);
            output.print(result);
            output.print((char) 13);
            output.close();
            isr.close();
            socket.close();
        }
        serverSocket.close();
        System.out.println("Shutting down.");
    } catch (Exception exception) {
        exception.printStackTrace();
    }
}

From source file:com.leixl.easyframework.action.httpclient.TestHttpPost.java

public static void main(String[] args) {

    Map<String, Object> paramMap = new HashMap<String, Object>();
    paramMap.put("uid", 1);
    paramMap.put("desc",
            "?????");
    paramMap.put("payStatus", 1);

    //HttpConnUtils.postHttpContent(URL, paramMap);

    //HttpClient/* w w w  .j av a  2s . co m*/
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(URL);
    // ??
    NameValuePair[] data = { new NameValuePair("uid", "1"),
            new NameValuePair("desc",
                    "?????"),
            new NameValuePair("payStatus", "1") };
    // ?postMethod
    postMethod.setRequestBody(data);
    // postMethod
    int statusCode;
    try {
        statusCode = httpClient.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_OK) {
            StringBuffer contentBuffer = new StringBuffer();
            InputStream in = postMethod.getResponseBodyAsStream();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in, postMethod.getResponseCharSet()));
            String inputLine = null;
            while ((inputLine = reader.readLine()) != null) {
                contentBuffer.append(inputLine);
                System.out.println("input line:" + inputLine);
                contentBuffer.append("/n");
            }
            in.close();

        } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
            // ???
            Header locationHeader = postMethod.getResponseHeader("location");
            String location = null;
            if (locationHeader != null) {
                location = locationHeader.getValue();
                System.out.println("The page was redirected to:" + location);
            } else {
                System.err.println("Location field value is null.");
            }
        }
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

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

/**
 * TODO: move this test harness to unit tests
 * @param args/*from   w ww  . j  a  v a  2  s.  co  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:DataIODemo.java

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

    // write the data out
    DataOutputStream out = new DataOutputStream(new FileOutputStream("invoice1.txt"));

    double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
    int[] units = { 12, 8, 13, 29, 50 };
    String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" };

    for (int i = 0; i < prices.length; i++) {
        out.writeDouble(prices[i]);// w w w  . ja  v a  2s  . com
        out.writeChar('\t');
        out.writeInt(units[i]);
        out.writeChar('\t');
        out.writeChars(descs[i]);
        out.writeChar('\n');
    }
    out.close();

    // read it in again
    DataInputStream in = new DataInputStream(new FileInputStream("invoice1.txt"));

    double price;
    int unit;
    StringBuffer desc;
    double total = 0.0;

    try {
        while (true) {
            price = in.readDouble();
            in.readChar(); // throws out the tab
            unit = in.readInt();
            in.readChar(); // throws out the tab
            char chr;
            desc = new StringBuffer(20);
            char lineSep = System.getProperty("line.separator").charAt(0);
            while ((chr = in.readChar()) != lineSep)
                desc.append(chr);
            System.out.println("You've ordered " + unit + " units of " + desc + " at $" + price);
            total = total + unit * price;
        }
    } catch (EOFException e) {
    }
    System.out.println("For a TOTAL of: $" + total);
    in.close();
}

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

/**
 * Build compound word table.//from w w  w . ja  v  a  2s.  c  om
 */
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:comparetopics.CompareTopics.java

/**
 * @param args the command line arguments
 *///ww  w  . jav  a  2  s  .co  m
public static void main(String[] args) {
    try {
        File file1 = new File(
                "/Users/apple/Desktop/graduation-project/topic-modeling/output/jhotdraw-extracted-code/keys.txt");
        File file2 = new File(
                "/Users/apple/Desktop/graduation-project/topic-modeling/output/jhotdraw-extracted-code/keys.txt");

        CompareTopics compareTopics = new CompareTopics();
        String[] words1 = compareTopics.getWords(file1);
        String[] words2 = compareTopics.getWords(file2);
        StringBuffer words = new StringBuffer();

        File outputFile = new File("/Users/apple/Desktop/test.txt");
        if (outputFile.createNewFile()) {
            System.out.println("Create successful: " + outputFile.getName());
        }
        boolean hasSame = false;

        for (String w1 : words1) {
            if (!NumberUtils.isNumber(w1)) {
                for (String w2 : words2) {
                    if (w1.equals(w2)) {
                        words.append(w1);
                        //                            words.append("\r\n");
                        words.append(" ");
                        hasSame = true;
                        break;
                    }
                }
            }
        }
        if (!hasSame) {
            System.out.println("No same word.");
        } else {
            compareTopics.printToFile(words.toString(), outputFile);
        }

    } catch (IOException ex) {
        Logger.getLogger(CompareTopics.class.getName()).log(Level.SEVERE, null, ex);
    }

}

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();/*  w  w  w .  ja  va 2s.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  www  .  j a  v  a2s. 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:MainClass.java

public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.java2s.com");
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    HTMLEditorKit htmlKit = new HTMLEditorKit();
    HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
    HTMLEditorKit.Parser parser = new ParserDelegator();
    HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
    parser.parse(br, callback, true);/*from w  w w  . j  ava 2  s.c o  m*/

    ElementIterator iterator = new ElementIterator(htmlDoc);
    Element element;
    while ((element = iterator.next()) != null) {
        AttributeSet attributes = element.getAttributes();
        Object name = attributes.getAttribute(StyleConstants.NameAttribute);
        if ((name instanceof HTML.Tag) && (name == HTML.Tag.H1)) {
            StringBuffer text = new StringBuffer();
            int count = element.getElementCount();
            for (int i = 0; i < count; i++) {
                Element child = element.getElement(i);
                AttributeSet childAttributes = child.getAttributes();
                if (childAttributes.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) {
                    int startOffset = child.getStartOffset();
                    int endOffset = child.getEndOffset();
                    int length = endOffset - startOffset;
                    text.append(htmlDoc.getText(startOffset, length));
                }
            }
            System.out.println(name + ": " + text.toString());
        }
    }
}

From source file:bluevia.examples.MODemo.java

/**
 * @param args/*w  ww .  j a  va2s.  c o m*/
 */
public static void main(String[] args) throws IOException {

    BufferedReader iReader = null;
    String apiDataFile = "API-AccessToken.ini";

    String consumer_key;
    String consumer_secret;
    String registrationId;

    OAuthConsumer apiConsumer = null;
    HttpURLConnection request = null;
    URL moAPIurl = null;

    Logger logger = Logger.getLogger("moSMSDemo.class");
    int i = 0;
    int rc = 0;

    Thread mThread = Thread.currentThread();

    try {
        System.setProperty("debug", "1");

        iReader = new BufferedReader(new FileReader(apiDataFile));

        // Private data: consumer info + access token info + phone info
        consumer_key = iReader.readLine();
        consumer_secret = iReader.readLine();
        registrationId = iReader.readLine();

        // Set up the oAuthConsumer
        while (true) {
            try {

                logger.log(Level.INFO, String.format("#%d: %s\n", ++i, "Requesting messages..."));

                apiConsumer = new DefaultOAuthConsumer(consumer_key, consumer_secret);

                apiConsumer.setMessageSigner(new HmacSha1MessageSigner());

                moAPIurl = new URL("https://api.bluevia.com/services/REST/SMS/inbound/" + registrationId
                        + "/messages?version=v1&alt=json");

                request = (HttpURLConnection) moAPIurl.openConnection();
                request.setRequestMethod("GET");

                apiConsumer.sign(request);

                StringBuffer doc = new StringBuffer();
                BufferedReader br = null;

                rc = request.getResponseCode();
                if (rc == HttpURLConnection.HTTP_OK) {
                    br = new BufferedReader(new InputStreamReader(request.getInputStream()));

                    String line = br.readLine();
                    while (line != null) {
                        doc.append(line);
                        line = br.readLine();
                    }

                    System.out.printf("Output message: %s\n", doc.toString());
                    try {
                        JSONObject apiResponse1 = new JSONObject(doc.toString());
                        String aux = apiResponse1.getString("receivedSMS");
                        if (aux != null) {
                            String szMessage;
                            String szOrigin;
                            String szDate;

                            JSONObject smsPool = apiResponse1.getJSONObject("receivedSMS");
                            JSONArray smsInfo = smsPool.optJSONArray("receivedSMS");
                            if (smsInfo != null) {
                                for (i = 0; i < smsInfo.length(); i++) {
                                    szMessage = smsInfo.getJSONObject(i).getString("message");
                                    szOrigin = smsInfo.getJSONObject(i).getJSONObject("originAddress")
                                            .getString("phoneNumber");
                                    szDate = smsInfo.getJSONObject(i).getString("dateTime");
                                    System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate,
                                            szOrigin, szMessage);
                                }
                            } else {
                                JSONObject sms = smsPool.getJSONObject("receivedSMS");
                                szMessage = sms.getString("message");
                                szOrigin = sms.getJSONObject("originAddress").getString("phoneNumber");
                                szDate = sms.getString("dateTime");
                                System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate, szOrigin,
                                        szMessage);
                            }
                        }
                    } catch (JSONException e) {
                        System.err.println("JSON error: " + e.getMessage());
                    }

                } else if (rc == HttpURLConnection.HTTP_NO_CONTENT)
                    System.out.printf("No content\n");
                else
                    System.err.printf("Error: %d:%s\n", rc, request.getResponseMessage());

                request.disconnect();

            } catch (Exception e) {
                System.err.println("Exception: " + e.getMessage());
            }
            mThread.sleep(15000);
        }
    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
    }
}