Example usage for java.io FileWriter FileWriter

List of usage examples for java.io FileWriter FileWriter

Introduction

In this page you can find the example usage for java.io FileWriter FileWriter.

Prototype

public FileWriter(FileDescriptor fd) 

Source Link

Document

Constructs a FileWriter given a file descriptor, using the platform's java.nio.charset.Charset#defaultCharset() default charset .

Usage

From source file:contractEditor.contractHOST2.java

public static void main(String[] args) {

    JSONObject obj = new JSONObject();
    obj.put("name", "HOST2");
    obj.put("context", "VM-deployment");

    //obj.put("Context", new Integer);

    HashMap serviceDescription = new HashMap();
    serviceDescription.put("location", "UK");
    serviceDescription.put("certificate", "false");
    serviceDescription.put("volume", "200_GB");
    serviceDescription.put("price", "5_euro");

    obj.put("serviceDescription", serviceDescription);

    HashMap gauranteeTerm = new HashMap();
    gauranteeTerm.put("availability", "more_99_percentage");
    obj.put("gauranteeTerm", gauranteeTerm);

    //Constraint1

    HashMap host_rule1 = new HashMap();
    HashMap VM_rule1 = new HashMap();
    host_rule1.put("ID", "HOST2");
    VM_rule1.put("data", "private");

    ArrayList rule1 = new ArrayList();
    rule1.add("prohibition");
    rule1.add(host_rule1);/*  w w w . ja v  a2  s  .  co m*/
    rule1.add(VM_rule1);

    ArrayList policyInConstraint1 = new ArrayList();
    policyInConstraint1.add(rule1);

    ArrayList creationConstraint1 = new ArrayList();
    creationConstraint1.add("other");
    creationConstraint1.add("true");
    creationConstraint1.add("true");
    creationConstraint1.add(policyInConstraint1);

    ArrayList totalConstraint = new ArrayList();
    totalConstraint.add(creationConstraint1);

    obj.put("creationConstraint", totalConstraint);

    try {

        FileWriter file = new FileWriter("confSP" + File.separator + "Host2.json");
        file.write(obj.toJSONString());
        file.flush();
        file.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.print(obj);

    /*
            
    JSONParser parser = new JSONParser();
            
    try {
            
    Object obj2 = parser.parse(new FileReader("confSP\\confHost1.json"));
            
    JSONObject jsonObject = (JSONObject) obj2;
            
        HashMap serviceDescription2=(HashMap) jsonObject.get("serviceDescription");
                 
        method.printHashMap(serviceDescription2);
                
                
        HashMap gauranteeTerm2=(HashMap) jsonObject.get("gauranteeTerm");
                 
        method.printHashMap(gauranteeTerm2);
                
                
                
        ArrayList creationConstraint=(ArrayList) jsonObject.get("creationConstraint");
                
        method.printArrayList(creationConstraint);
            
            
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (ParseException e) {
    e.printStackTrace();
    }
            
            
            
            
            
    */

}

From source file:contractEditor.contractHOST1.java

public static void main(String[] args) {

    JSONObject obj = new JSONObject();
    obj.put("name", "HOST1");
    obj.put("context", "VM-deployment");

    //obj.put("Context", new Integer);

    HashMap serviceDescription = new HashMap();
    serviceDescription.put("location", "France");
    serviceDescription.put("certificate", "true");
    serviceDescription.put("volume", "100_GB");
    serviceDescription.put("price", "6_euro");

    obj.put("serviceDescription", serviceDescription);

    HashMap gauranteeTerm = new HashMap();
    gauranteeTerm.put("availability", "more_98_percentage");
    obj.put("gauranteeTerm", gauranteeTerm);

    //Constraint1

    HashMap host_rule1 = new HashMap();
    HashMap VM_rule1 = new HashMap();
    host_rule1.put("ID", "HOST1");
    VM_rule1.put("purpose", "test");

    ArrayList rule1 = new ArrayList();
    rule1.add("prohibition");
    rule1.add(host_rule1);/*w  w  w  . ja  va2s. c  o m*/
    rule1.add(VM_rule1);

    ArrayList policyInConstraint1 = new ArrayList();
    policyInConstraint1.add(rule1);

    ArrayList creationConstraint1 = new ArrayList();
    creationConstraint1.add("other");
    creationConstraint1.add("true");
    creationConstraint1.add("true");
    creationConstraint1.add(policyInConstraint1);

    ArrayList totalConstraint = new ArrayList();
    totalConstraint.add(creationConstraint1);

    obj.put("creationConstraint", totalConstraint);

    try {

        FileWriter file = new FileWriter("confSP" + File.separator + "Host1.json");
        file.write(obj.toJSONString());
        file.flush();
        file.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.print(obj);

    /*
            
    JSONParser parser = new JSONParser();
            
    try {
            
    Object obj2 = parser.parse(new FileReader("confSP\\confHost1.json"));
            
    JSONObject jsonObject = (JSONObject) obj2;
            
        HashMap serviceDescription2=(HashMap) jsonObject.get("serviceDescription");
                 
        method.printHashMap(serviceDescription2);
                
                
        HashMap gauranteeTerm2=(HashMap) jsonObject.get("gauranteeTerm");
                 
        method.printHashMap(gauranteeTerm2);
                
                
                
        ArrayList creationConstraint=(ArrayList) jsonObject.get("creationConstraint");
                
        method.printArrayList(creationConstraint);
            
            
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (ParseException e) {
    e.printStackTrace();
    }
            
            
            
            
            
    */

}

From source file:contractEditor.contractHOST3.java

public static void main(String[] args) {

    JSONObject obj = new JSONObject();
    obj.put("name", "HOST3");
    obj.put("context", "VM-deployment");

    //obj.put("Context", new Integer);

    HashMap serviceDescription = new HashMap();
    serviceDescription.put("location", "China");
    serviceDescription.put("certificate", "false");
    serviceDescription.put("volume", "70_GB");
    serviceDescription.put("price", "4_euro");

    obj.put("serviceDescription", serviceDescription);

    HashMap gauranteeTerm = new HashMap();
    gauranteeTerm.put("availability", "more_97_percentage");
    obj.put("gauranteeTerm", gauranteeTerm);

    //Constraint1

    HashMap host_rule1 = new HashMap();
    HashMap VM_rule1 = new HashMap();
    host_rule1.put("ID", "HOST3");
    VM_rule1.put("application", "internal");

    ArrayList rule1 = new ArrayList();
    rule1.add("prohibition");
    rule1.add(host_rule1);//w ww .ja v a  2 s.c  om
    rule1.add(VM_rule1);

    ArrayList policyInConstraint1 = new ArrayList();
    policyInConstraint1.add(rule1);

    ArrayList creationConstraint1 = new ArrayList();
    creationConstraint1.add("other");
    creationConstraint1.add("true");
    creationConstraint1.add("true");
    creationConstraint1.add(policyInConstraint1);

    ArrayList totalConstraint = new ArrayList();
    totalConstraint.add(creationConstraint1);

    obj.put("creationConstraint", totalConstraint);

    try {

        FileWriter file = new FileWriter("confSP" + File.separator + "Host3.json");
        file.write(obj.toJSONString());
        file.flush();
        file.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.print(obj);

    /*
            
    JSONParser parser = new JSONParser();
            
    try {
            
    Object obj2 = parser.parse(new FileReader("confSP\\confHost1.json"));
            
    JSONObject jsonObject = (JSONObject) obj2;
            
        HashMap serviceDescription2=(HashMap) jsonObject.get("serviceDescription");
                 
        method.printHashMap(serviceDescription2);
                
                
        HashMap gauranteeTerm2=(HashMap) jsonObject.get("gauranteeTerm");
                 
        method.printHashMap(gauranteeTerm2);
                
                
                
        ArrayList creationConstraint=(ArrayList) jsonObject.get("creationConstraint");
                
        method.printArrayList(creationConstraint);
            
            
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (ParseException e) {
    e.printStackTrace();
    }
            
            
            
            
            
    */

}

From source file:com.aestel.chemistry.openEye.fp.DistMatrix.java

public static void main(String... args) throws IOException {
    long start = System.currentTimeMillis();

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("i", true, "input file [.tsv from FingerPrinter]");
    opt.setRequired(true);//w ww.j  a va 2s . c  o m
    options.addOption(opt);

    opt = new Option("o", true, "outpur file [.tsv ");
    opt.setRequired(true);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (args.length != 0)
        exitWithHelp(options);

    String file = cmd.getOptionValue("i");
    BufferedReader in = new BufferedReader(new FileReader(file));

    file = cmd.getOptionValue("o");
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));

    ArrayList<Fingerprint> fps = new ArrayList<Fingerprint>();
    ArrayList<String> ids = new ArrayList<String>();
    String line;
    while ((line = in.readLine()) != null) {
        String[] parts = line.split("\t");
        if (parts.length == 3) {
            ids.add(parts[0]);
            fps.add(new ByteFingerprint(parts[2]));
        }
    }
    in.close();

    out.print("ID");
    for (int i = 0; i < ids.size(); i++) {
        out.print('\t');
        out.print(ids.get(i));
    }
    out.println();

    for (int i = 0; i < ids.size(); i++) {
        out.print(ids.get(i));
        Fingerprint fp1 = fps.get(i);

        for (int j = 0; j <= i; j++) {
            out.printf("\t%.4g", fp1.tanimoto(fps.get(j)));
        }
        out.println();
    }
    out.close();

    System.err.printf("Done %d fingerprints in %.2gsec\n", fps.size(),
            (System.currentTimeMillis() - start) / 1000D);
}

From source file:OldExtractor.java

/**
 * @param args the command line arguments
 *///  w  w w  .j a  v  a2  s.  co  m
public static void main(String[] args) {
    // TODO code application logic here
    String bingUrl = "https://api.datamarket.azure.com/Bing/Search/Web?$top=10&$format=Atom&Query=%27gates%27";
    //Provide your account key here.
    String accountKey = "ghTYY7wD6LpyxUO9VRR7e1f98WFhHWYERMcw87aQTqQ";
    //  String accountKey = "xqbCjT87/MQz25JWdRzgMHdPkGYnOz77IYmP5FUIgC8";

    byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
    String accountKeyEnc = new String(accountKeyBytes);

    try {
        URL url = new URL(bingUrl);
        URLConnection urlConnection = url.openConnection();

        urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
        InputStream inputStream = (InputStream) urlConnection.getContent();
        byte[] contentRaw = new byte[urlConnection.getContentLength()];
        inputStream.read(contentRaw);
        String content = new String(contentRaw);
        //System.out.println(content);
        try {
            File file = new File("Results.xml");
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(content);
            //fileWriter.write("a test");
            fileWriter.flush();
            fileWriter.close();

        } catch (IOException e) {
            System.out.println(e);
        }

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {
            //System.out.println("here");
            //Using factory get an instance of document builder
            DocumentBuilder db = dbf.newDocumentBuilder();

            //parse using builder to get DOM representation of the XML file
            Document dom = db.parse("Results.xml");
            Element docEle = (Element) dom.getDocumentElement();

            //get a nodelist of elements

            NodeList nl = docEle.getElementsByTagName("d:Url");
            if (nl != null && nl.getLength() > 0) {
                for (int i = 0; i < nl.getLength(); i++) {

                    //get the employee element
                    Element el = (Element) nl.item(i);
                    // System.out.println("here");
                    System.out.println(el.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }
            NodeList n2 = docEle.getElementsByTagName("d:Title");
            if (n2 != null && n2.getLength() > 0) {
                for (int i = 0; i < n2.getLength(); i++) {

                    //get the employee element
                    Element e2 = (Element) n2.item(i);
                    // System.out.println("here");
                    System.out.println(e2.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }

            NodeList n3 = docEle.getElementsByTagName("d:Description");
            if (n3 != null && n3.getLength() > 0) {
                for (int i = 0; i < n3.getLength(); i++) {

                    //get the employee element
                    Element e3 = (Element) n3.item(i);
                    // System.out.println("here");
                    System.out.println(e3.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }

        } catch (SAXException se) {
            se.printStackTrace();
        } catch (ParserConfigurationException pe) {
            pe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    } catch (IOException e) {
        System.out.println(e);
    }

    //The content string is the xml/json output from Bing.

}

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 w ww  .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 + 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();/* w  ww  .  j  av a  2s.  com*/
                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.twentyn.chemicalClassifier.Runner.java

public static void main(String[] args) throws Exception {
    BufferedReader reader = new BufferedReader(new FileReader(args[0]));
    BufferedWriter writer = new BufferedWriter(new FileWriter(args[1]));

    try {// w ww . j  a v  a 2 s.  co m
        Oscar oscar = new Oscar();

        String line = null;
        /* NOTE: this is exactly the wrong way to write a TSV reader.  Caveat emptor.
         * See http://tburette.github.io/blog/2014/05/25/so-you-want-to-write-your-own-CSV-code/
         * and then use org.apache.commons.csv.CSVParser instead.
         */
        while ((line = reader.readLine()) != null) {
            // TSV means split on tabs!  Nothing else will do.
            List<String> fields = Arrays.asList(line.split("\t"));
            // Choke if our invariants aren't satisfied.  We expect ever line to have a name and an InChI.
            if (fields.size() != 2) {
                throw new RuntimeException(
                        String.format("Found malformed line (all lines must have two fields: %s", line));
            }
            String name = fields.get(1);
            List<ResolvedNamedEntity> entities = oscar.findAndResolveNamedEntities(name);

            System.out.println("**********");
            System.out.println("Name: " + name);
            List<String> outputFields = new ArrayList<>(fields.size() + 1);
            outputFields.addAll(fields);
            if (entities.size() == 0) {
                System.out.println("No match");
                outputFields.add("noMatch");
            } else if (entities.size() == 1) {
                ResolvedNamedEntity entity = entities.get(0);
                NamedEntity ne = entity.getNamedEntity();
                if (ne.getStart() != 0 || ne.getEnd() != name.length()) {
                    System.out.println("Partial match");
                    printEntity(entity);
                    outputFields.add("partialMatch");
                } else {
                    System.out.println("Exact match");
                    printEntity(entity);
                    outputFields.add("exactMatch");
                    List<ChemicalStructure> structures = entity.getChemicalStructures(FormatType.STD_INCHI);
                    for (ChemicalStructure s : structures) {
                        outputFields.add(s.getValue());
                    }
                }
            } else { // Multiple matches found!
                System.out.println("Multiple matches");
                for (ResolvedNamedEntity e : entities) {
                    printEntity(e);
                }
                outputFields.add("multipleMatches");
            }

            writer.write(String.join("\t", outputFields));
            writer.newLine();
        }
    } finally {
        writer.flush();
        writer.close();
    }
}

From source file:test1.ApacheHttpRestClient2.java

public final static void main(String[] args) {

    HttpClient httpClient = new DefaultHttpClient();
    try {/*from w  w  w .  j  ava2 s.co  m*/
        // this ona api call returns results in a JSON format
        HttpGet httpGetRequest = new HttpGet("https://api.ona.io/api/v1/users");

        // Execute HTTP request
        HttpResponse httpResponse = httpClient.execute(httpGetRequest);

        System.out.println("------------------HTTP RESPONSE----------------------");
        System.out.println(httpResponse.getStatusLine());
        System.out.println("------------------HTTP RESPONSE----------------------");

        // Get hold of the response entity
        HttpEntity entity = httpResponse.getEntity();

        // If the response does not enclose an entity, there is no need
        // to bother about connection release
        byte[] buffer = new byte[1024];
        if (entity != null) {
            InputStream inputStream = entity.getContent();
            try {
                int bytesRead = 0;
                BufferedInputStream bis = new BufferedInputStream(inputStream);
                while ((bytesRead = bis.read(buffer)) != -1) {
                    String chunk = new String(buffer, 0, bytesRead);
                    FileWriter file = new FileWriter("C:\\Users\\fred\\Desktop\\webicons\\output.txt");
                    //file.write(chunk.toJSONString());
                    file.write(chunk.toCharArray());
                    file.flush();
                    file.close();

                    System.out.print(chunk);
                    System.out.println(chunk);
                }
            } catch (IOException ioException) {
                // In case of an IOException the connection will be released
                // back to the connection manager automatically
                ioException.printStackTrace();
            } catch (RuntimeException runtimeException) {
                // In case of an unexpected exception you may want to abort
                // the HTTP request in order to shut down the underlying
                // connection immediately.
                httpGetRequest.abort();
                runtimeException.printStackTrace();
            }
            //          try {
            //              FileWriter file = new FileWriter("C:\\Users\\fred\\Desktop\\webicons\\output.json");
            //                file.write(bis.toJSONString());
            //                file.flush();
            //                file.close();
            //
            //                System.out.print(bis);
            //          } catch (Exception e) {
            //          }

            finally {
                // Closing the input stream will trigger connection release
                try {
                    inputStream.close();
                } catch (Exception ignore) {
                }
            }
        }
    } catch (ClientProtocolException e) {
        // thrown by httpClient.execute(httpGetRequest)
        e.printStackTrace();
    } catch (IOException e) {
        // thrown by entity.getContent();
        e.printStackTrace();
    } 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.ibm.watson.catalyst.corpus.tfidf.SearchTemplate.java

public static void main(String[] args) {

    System.out.println("Loading Corpus.");
    TermCorpusBuilder cb = new TermCorpusBuilder();
    cb.setDocumentCombiner(0, 0);//from  ww  w .  ja va 2s  .com
    cb.setJson(new File("health-corpus.json"));
    TermCorpus c = cb.build();

    List<TermDocument> termDocuments = c.getDocuments();
    List<TemplateMatch> matches = new ArrayList<TemplateMatch>();

    Pattern p3 = Template.getTemplatePattern(new File("verbs-list.words"), "\\b(\\w+ )", "( \\w+)\\b");

    int index = 0;
    for (TermDocument termDocument : termDocuments) {
        DocumentMatcher dm = new DocumentMatcher(termDocument);

        matches.addAll(dm.getParagraphMatches(p3, "", ""));

        double progress = ((double) ++index / (double) termDocuments.size());
        System.out.print("Progress " + progress + "\r");
    }
    System.out.println();

    WordFrequencyHashtable f = new WordFrequencyHashtable();

    for (TemplateMatch match : matches) {
        f.put(match.getMatch(), 1);
    }

    JsonNode jn = f.toJsonNode(5);

    try (BufferedWriter bw = new BufferedWriter(new FileWriter("health-trigrams.json"))) {
        bw.write(jn.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}