Example usage for java.io FileWriter close

List of usage examples for java.io FileWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:CopyCharacters.java

public static void main(String[] args) throws IOException {
    FileReader inputStream = null;
    FileWriter outputStream = null;

    try {//  w w w.  j  a va  2 s . c o  m
        inputStream = new FileReader("xanadu.txt");
        outputStream = new FileWriter("characteroutput.txt");

        int c;
        while ((c = inputStream.read()) != -1) {
            outputStream.write(c);
        }
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

From source file:com.jaeksoft.searchlib.util.StringUtils.java

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

    List<String> lines = FileUtils.readLines(new File(args[0]));
    FileWriter fw = new FileWriter(new File(args[1]));
    PrintWriter pw = new PrintWriter(fw);
    for (String line : lines)
        pw.println(StringEscapeUtils.unescapeHtml(line));
    pw.close();/*  w  w  w. ja  v a  2  s  .c  om*/
    fw.close();
}

From source file:contractEditor.contractClients.java

public static void main(String[] args) {

    JSONObject obj = new JSONObject();
    obj.put("name", "clientTemplate");
    obj.put("context", "VM-deployment");
    //obj.put("Context", new Integer);

    HashMap serviceRequirement = new HashMap();

    HashMap serviceDescription = new HashMap();
    serviceRequirement.put("VM1_volume", "18_GB");
    serviceDescription.put("VM1_purpose", "dev");
    serviceDescription.put("VM1_data", "private");
    serviceDescription.put("VM1_application", "internal");

    serviceRequirement.put("VM2_volume", "20_GB");
    serviceDescription.put("VM2_purpose", "prod");
    serviceDescription.put("VM2_data", "public");
    serviceDescription.put("VM2_application", "business");

    serviceRequirement.put("VM3_volume", "30_GB");
    serviceDescription.put("VM3_purpose", "test");
    serviceDescription.put("VM3_data", "public");
    serviceDescription.put("VM3_application", "business");

    serviceRequirement.put("VM4_volume", "20_GB");
    serviceDescription.put("VM4_purpose", "prod");
    serviceDescription.put("VM4_data", "public");
    serviceDescription.put("VM4_application", "business");

    obj.put("serviceRequirement", serviceRequirement);
    obj.put("serviceDescription", serviceDescription);

    HashMap gauranteeTerm = new HashMap();
    gauranteeTerm.put("VM1_availability", "more_97_percentage");
    gauranteeTerm.put("VM2_availability", "more_99_percentage");
    gauranteeTerm.put("VM3_availability", "more_95_percentage");
    gauranteeTerm.put("VM4_availability", "more_99_percentage");
    obj.put("gauranteeTerm", gauranteeTerm);

    //Constraint1

    HashMap host_rule1 = new HashMap();
    HashMap VM_rule1 = new HashMap();
    host_rule1.put("certificate", "true");
    VM_rule1.put("purpose", "dev");

    ArrayList rule1 = new ArrayList();
    rule1.add("permission");
    rule1.add(host_rule1);/*ww w  .  jav a2  s.  c om*/
    rule1.add(VM_rule1);

    HashMap host_rule1_2 = new HashMap();
    HashMap VM_rule1_2 = new HashMap();
    host_rule1_2.put("certificate", "true");
    VM_rule1_2.put("purpose", "prod");

    ArrayList rule1_2 = new ArrayList();
    rule1_2.add("permission");
    rule1_2.add(host_rule1_2);
    rule1_2.add(VM_rule1_2);

    HashMap host_rule1_3 = new HashMap();
    HashMap VM_rule1_3 = new HashMap();
    host_rule1_3.put("certificate", "true");
    VM_rule1_3.put("purpose", "test");

    ArrayList rule1_3 = new ArrayList();
    rule1_3.add("permission");
    rule1_3.add(host_rule1_3);
    rule1_3.add(VM_rule1_3);

    HashMap host_rule2 = new HashMap();
    HashMap VM_rule2 = new HashMap();
    host_rule2.put("location", "France");
    VM_rule2.put("ID", "VM2");

    ArrayList rule2 = new ArrayList();
    rule2.add("permission");
    rule2.add(host_rule2);
    rule2.add(VM_rule2);

    HashMap host_rule2_1 = new HashMap();
    HashMap VM_rule2_1 = new HashMap();
    host_rule2_1.put("location", "UK");
    VM_rule2_1.put("ID", "VM2");

    ArrayList rule2_1 = new ArrayList();
    rule2_1.add("permission");
    rule2_1.add(host_rule2_1);
    rule2_1.add(VM_rule2_1);

    HashMap host_rule3 = new HashMap();
    HashMap VM_rule3 = new HashMap();
    host_rule3.put("location", "France");
    VM_rule3.put("application", "business");

    ArrayList rule3 = new ArrayList();
    rule3.add("permission");
    rule3.add(host_rule3);
    rule3.add(VM_rule3);

    HashMap host_rule3_1 = new HashMap();
    HashMap VM_rule3_1 = new HashMap();
    host_rule3_1.put("location", "UK");
    VM_rule3_1.put("application", "business");

    ArrayList rule3_1 = new ArrayList();
    rule3_1.add("permission");
    rule3_1.add(host_rule3_1);
    rule3_1.add(VM_rule3_1);

    HashMap VMSeperation_rule_1_1 = new HashMap();
    HashMap VMSeperation_rule_1_2 = new HashMap();

    VMSeperation_rule_1_1.put("ID", "VM1");
    VMSeperation_rule_1_2.put("ID", "VM3");

    ArrayList rule4 = new ArrayList();
    rule4.add("separation");
    rule4.add(VMSeperation_rule_1_1);
    rule4.add(VMSeperation_rule_1_2);

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

    policyInConstraint1.add(rule2);
    policyInConstraint1.add(rule2_1);

    policyInConstraint1.add(rule3);
    policyInConstraint1.add(rule3_1);

    policyInConstraint1.add(rule4);

    ArrayList creationConstraint1 = new ArrayList();
    creationConstraint1.add("RP4");
    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("confClient" + File.separator + "test3.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("test2.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:evaluation.evaluation1VMPolicyGeneration.java

public static void main(String[] args) {

    int VMNumber = 5;
    int attributeNumber = 20;

    JSONObject obj = new JSONObject();
    obj.put("name", "clientTemplate");
    obj.put("context", "VM-deployment");
    //obj.put("Context", new Integer);

    HashMap serviceRequirement = new HashMap();

    HashMap serviceDescription = new HashMap();
    serviceRequirement.put("VM1_volume", "1_GB");
    serviceDescription.put("VM1_purpose", "dev");
    serviceDescription.put("VM1_data", "private");
    serviceDescription.put("VM1_application", "internal");

    for (int j = 5; j < attributeNumber; j++) {
        serviceDescription.put("VM1_other" + j, "other");
    }/*from   w ww.  ja v a  2  s  . c  om*/

    serviceRequirement.put("VM2_volume", "2_GB");
    serviceDescription.put("VM2_purpose", "prod");
    serviceDescription.put("VM2_data", "public");
    serviceDescription.put("VM2_application", "business");

    for (int j = 5; j < attributeNumber; j++) {
        serviceDescription.put("VM2_other" + j, "other");
    }

    serviceRequirement.put("VM3_volume", "1_GB");
    serviceDescription.put("VM3_purpose", "test");
    serviceDescription.put("VM3_data", "public");
    serviceDescription.put("VM3_application", "business");

    for (int j = 5; j < attributeNumber; j++) {
        serviceDescription.put("VM3_other" + j, "other");
    }

    serviceRequirement.put("VM4_volume", "12_GB");
    serviceDescription.put("VM4_purpose", "prod");
    serviceDescription.put("VM4_data", "public");
    serviceDescription.put("VM4_application", "business");

    for (int j = 5; j < attributeNumber; j++) {
        serviceDescription.put("VM4_other" + j, "other");
    }

    for (int i = 5; i < VMNumber; i++) {
        serviceRequirement.put("VM" + i + "_volume", "20_GB");
        serviceDescription.put("VM" + i + "_purpose", "prod");
        serviceDescription.put("VM" + i + "_data", "public");
        serviceDescription.put("VM" + i + "_application", "business");
        for (int j = 5; j < attributeNumber; j++) {
            serviceDescription.put("VM" + i + "_other" + j, "other");
        }

    }

    obj.put("serviceRequirement", serviceRequirement);
    obj.put("serviceDescription", serviceDescription);

    HashMap gauranteeTerm = new HashMap();
    gauranteeTerm.put("VM1_availability", "more_97_percentage");
    gauranteeTerm.put("VM2_availability", "more_99_percentage");
    gauranteeTerm.put("VM3_availability", "more_95_percentage");
    gauranteeTerm.put("VM4_availability", "more_99_percentage");
    obj.put("gauranteeTerm", gauranteeTerm);

    //Constraint1

    HashMap host_rule1 = new HashMap();
    HashMap VM_rule1 = new HashMap();
    host_rule1.put("certificate", "true");
    VM_rule1.put("purpose", "dev");

    ArrayList rule1 = new ArrayList();
    rule1.add("permission");
    rule1.add(host_rule1);
    rule1.add(VM_rule1);

    HashMap host_rule1_2 = new HashMap();
    HashMap VM_rule1_2 = new HashMap();
    host_rule1_2.put("certificate", "true");
    VM_rule1_2.put("purpose", "prod");

    ArrayList rule1_2 = new ArrayList();
    rule1_2.add("permission");
    rule1_2.add(host_rule1_2);
    rule1_2.add(VM_rule1_2);

    HashMap host_rule1_3 = new HashMap();
    HashMap VM_rule1_3 = new HashMap();
    host_rule1_3.put("certificate", "true");
    VM_rule1_3.put("purpose", "test");

    ArrayList rule1_3 = new ArrayList();
    rule1_3.add("permission");
    rule1_3.add(host_rule1_3);
    rule1_3.add(VM_rule1_3);

    HashMap host_rule2 = new HashMap();
    HashMap VM_rule2 = new HashMap();
    host_rule2.put("location", "France");
    VM_rule2.put("ID", "VM2");

    ArrayList rule2 = new ArrayList();
    rule2.add("permission");
    rule2.add(host_rule2);
    rule2.add(VM_rule2);

    HashMap host_rule2_1 = new HashMap();
    HashMap VM_rule2_1 = new HashMap();
    host_rule2_1.put("location", "UK");
    VM_rule2_1.put("ID", "VM2");

    ArrayList rule2_1 = new ArrayList();
    rule2_1.add("permission");
    rule2_1.add(host_rule2_1);
    rule2_1.add(VM_rule2_1);

    HashMap host_rule3 = new HashMap();
    HashMap VM_rule3 = new HashMap();
    host_rule3.put("location", "France");
    VM_rule3.put("application", "business");

    ArrayList rule3 = new ArrayList();
    rule3.add("permission");
    rule3.add(host_rule3);
    rule3.add(VM_rule3);

    HashMap host_rule3_1 = new HashMap();
    HashMap VM_rule3_1 = new HashMap();
    host_rule3_1.put("location", "UK");
    VM_rule3_1.put("application", "business");

    ArrayList rule3_1 = new ArrayList();
    rule3_1.add("permission");
    rule3_1.add(host_rule3_1);
    rule3_1.add(VM_rule3_1);

    HashMap VMSeperation_rule_1_1 = new HashMap();
    HashMap VMSeperation_rule_1_2 = new HashMap();

    VMSeperation_rule_1_1.put("ID", "VM1");
    VMSeperation_rule_1_2.put("ID", "VM3");

    ArrayList rule4 = new ArrayList();
    rule4.add("separation");
    rule4.add(VMSeperation_rule_1_1);
    rule4.add(VMSeperation_rule_1_2);

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

    policyInConstraint1.add(rule2);
    policyInConstraint1.add(rule2_1);

    policyInConstraint1.add(rule3);
    policyInConstraint1.add(rule3_1);

    policyInConstraint1.add(rule4);

    ArrayList creationConstraint1 = new ArrayList();
    creationConstraint1.add("RP4");
    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("confClient" + File.separator + "test3.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("test2.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:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getHSQLConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("create table survey (id int,name varchar);");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
    st.executeUpdate("insert into survey (id,name ) values (2,'anotherValue')");

    WebRowSet webRS;/*from ww w . java 2  s  . c o  m*/
    ResultSet rs = null;
    Statement stmt = null;
    stmt = conn.createStatement();
    webRS = null;
    String sqlQuery = "SELECT * FROM survey WHERE id='1'";
    webRS = new WebRowSetImpl();
    webRS.setCommand(sqlQuery);
    webRS.execute(conn);

    FileWriter fw = null;

    File file = new File("1.xml");
    fw = new FileWriter(file);
    System.out.println("Writing db data to file " + file.getAbsolutePath());
    webRS.writeXml(fw);

    // convert xml to a String object
    StringWriter sw = new StringWriter();
    webRS.writeXml(sw);
    System.out.println("==============");
    System.out.println(sw.toString());
    System.out.println("==============");
    fw.flush();
    fw.close();
    rs.close();
    stmt.close();
    conn.close();
}

From source file:net.sf.tweety.cli.plugins.CliMain.java

public static void main(String[] args) {

    // check, if first call parameter is for the helptext
    if (args.length == 0) {
        System.out.println("Welcome to the Tweety command line interface.");
        System.out.println("Obtain help with command --help");
        System.exit(0);/*from   w w  w .ja  v a  2s .  c  om*/
    } else if ((args.length == 1 && args[0].equals("--help"))) {
        printHelpText();
        System.exit(0);
    } else if (args.length == 1 && !args[0].contains("--help")) {
        System.out.println("No valid input, call with --help for helptext");
        System.exit(0);
    }

    // create new plugin manager
    PluginManager pm = PluginManagerFactory.createPluginManager();
    // create plugin manager util
    PluginManagerUtil pmu = new PluginManagerUtil(pm);

    // System.out.println(pmu.getPlugins());

    // collected parameter
    ArrayList<ArrayList<String>> collectedparams = new ArrayList<ArrayList<String>>();

    // list of available plugins
    Map<String, String> availablePlugins = new HashMap<String, String>();

    // try to configure CLI
    try {
        availablePlugins = configCLI();
    } catch (ConfigurationException e) {
        System.out.println("Something went wrong with your Configuration: ");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        System.out.println("No such configuration file: ");
        e.printStackTrace();
    }

    // handle all input parameter
    for (int i = 0; i < args.length; i++) {
        // The called plugin
        if (args[i].equals(ARG__CALLED_PLUGIN) || args[i].equals(ARG__CALLED_PLUGIN_SHORT)) {
            String calledPlugin = "";
            while ((i + 1) < args.length && !args[i + 1].startsWith("-")) {
                calledPlugin += args[++i];
            }
            plugin = calledPlugin;
        }

        // the input files
        else if (args[i].equals(ARG__INPUT_FILES) || args[i].equals(ARG__INPUT_FILES_SHORT)) {
            ArrayList<String> inFiles = new ArrayList<String>();
            while ((i + 1) < args.length && !args[i + 1].startsWith("-")) {
                inFiles.add(args[++i]);
            }

            String[] files = new String[inFiles.size()];
            inFiles.toArray(files);

            File[] inf = new File[inFiles.size()];

            for (int k = 0; k < inf.length; k++) {
                inf[k] = new File(files[k]).getAbsoluteFile();
            }

            inputFiles = inf;
        }

        // output file
        else if (args[i].equals(ARG__OUTPUT_FILE) || args[i].equals(ARG__OUTPUT_FILE_SHORT)) {
            // outputFile not used!
            outputFile = args[++i];
        }

        // collecting given command parameters
        else if (args[i].startsWith("-")) {
            ArrayList<String> temp = new ArrayList<String>();
            temp.add(args[i]);
            while ((i + 1) < args.length && !args[i + 1].startsWith("-")) {
                temp.add(args[++i]);

            }
            collectedparams.add(temp);
        } // else if (args[i].equals(ARG__DEBUG_FLAG)
          // ||args[i].equals(ARG__DEBUG_FLAG_SHORT)){
          // debug = true;
          // }
    }

    // check whether the called plugin is present
    boolean pluginPresent = false;
    for (TweetyPlugin tp : pmu.getPlugins(TweetyPlugin.class)) {
        if (tp.getCommand().equalsIgnoreCase(plugin)) {
            pluginPresent = true;
            System.out.println("Called plugin present");
        }
    }
    // TODO: move loading into own method
    // trying to load plugin if not present
    // old method for loading plugins
    if (!pluginPresent) {
        System.out.print("Trying to find plugin...");
        if (availablePlugins.containsKey(plugin)) {
            pm.addPluginsFrom(new File(availablePlugins.get(plugin)).toURI());
            System.out.print("success.\n");
        } else {
            System.out.print("no such plugin available.\n");
        }
    }

    // Test: print all plugins
    // System.out.println("Plugin loaded due to call parameter: " +
    // pm.getPlugin(TweetyPlugin.class, new
    // OptionCapabilities("Tweety Plugin", plugin) ));
    // System.out.println("Print all plugins: " + pmu.getPlugins());
    // System.out.println("Given plugin call parameter: " + plugin);

    // each plugin MUST implement the capabilites "Tweety Plugin" and the
    // variable "call parameter" to select called plugin from plugin pool
    TweetyPlugin tp = pm.getPlugin(TweetyPlugin.class, new OptionCapabilities("Tweety Plugin", plugin));

    // for (TweetyPlugin tp : pmu.getPlugins(TweetyPlugin.class)) {
    if (tp.getCommand().equalsIgnoreCase(plugin)) {
        System.out.println("Valid plugin found.");
        // each input parameter is checked against the called plugin
        // whether it is valid
        ArrayList<CommandParameter> ip = new ArrayList<CommandParameter>();

        System.out.print("Trying to instantiate parameters...");
        try {
            ip.addAll(instantiateParameters(tp, collectedparams));
            System.out.print("done.\n");
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        PluginOutput out = new PluginOutput();

        System.out.println("Execute Plugin...");
        out = tp.execute(inputFiles, ip.toArray(new CommandParameter[ip.size()]));

        if (outputFile != null) {

            try {
                FileWriter fw = new FileWriter(outputFile);
                fw.write(out.getOutput());
                fw.close();
                System.out.println("Output written to file: " + outputFile);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else {
            System.out.println("No output file given, writing to console...");
            System.out.println("Output: \n" + out.getOutput());
        }
    } else {
        System.out.println("Faulty parameters. Please check input.");

    }

}

From source file:com.thesmartweb.vivliocrawlermaven.VivlioCrawlerMavenMain.java

/**
 * @param args the command line arguments
 */// ww  w . j av  a  2  s .  co  m
public static void main(String[] args) {
    // TODO code application logic here
    try {

        OaiPmhServer server = new OaiPmhServer("http://vivliothmmy.ee.auth.gr/cgi/oai2");
        RecordsList listRecords = server.listRecords("oai_dc");//we capture all the records in oai dc format
        List<VivlioCrawlerMavenMain> listtotal = new ArrayList<VivlioCrawlerMavenMain>();
        //we capture all the names of the professors and former professor of ECE of AUTH from a txt file
        //change the directory to yours
        List<String> profs = Files.readAllLines(Paths.get(
                "/home/themis/NetBeansProjects/VivlioCrawlerMaven/src/main/java/com/thesmartweb/vivliocrawlermaven/profs.txt"));

        boolean more = true;//it is a flag used if we encounter more entries than the initial capture
        JSONArray array = new JSONArray();//it is going to be our final total json array
        JSONObject jsonObject = new JSONObject();//it is going to be our final total json object
        while (more) {
            for (Record rec : listRecords.asList()) {
                VivlioCrawlerMavenMain vc = new VivlioCrawlerMavenMain();
                Element metadata = rec.getMetadata();
                if (metadata != null) {
                    //System.out.println(rec.getMetadataAsString());
                    List<Element> elements = metadata.elements();
                    //System.out.println(metadata.getStringValue());
                    for (Element element : elements) {
                        String name = element.getName();
                        //we get the title, remove \r, \n and beginning and trailing whitespace
                        if (name.equalsIgnoreCase("title")) {
                            vc.title = element.getStringValue();
                            vc.title = vc.title.trim();
                            vc.title = vc.title.replaceAll("(\\r|\\n)", "");
                            if (!(vc.title.endsWith("."))) {
                                vc.title = vc.title + ".";//we also add dot in the end for the titles to be uniformed
                            }
                        }
                        if (name.equalsIgnoreCase("creator")) {
                            vc.creators.add(element.getStringValue());//we capture the students' names
                        }
                        if (name.equalsIgnoreCase("subject")) {
                            vc.subjects.add(element.getStringValue());//we capture the subjects
                        }
                        if (name.equalsIgnoreCase("description")) {
                            vc.description = element.getStringValue();//we capture the abstract
                        }
                        if (name.equalsIgnoreCase("date")) {
                            vc.datestring = element.getStringValue();
                        }
                        if (name.equalsIgnoreCase("identifier")) {
                            if (element.getStringValue().contains("http://")) {
                                vc.thesisFiles.add(element.getStringValue());//we capture the url of the thesis whole file
                                if (vc.thesisURL == null) {
                                    vc.thesisURL = element.getStringValue().substring(0, 32);
                                }
                            }
                            //if the identifier contains the title then it must be the citation 
                            //out of the citation we need to extract the supevisor's name
                            if (element.getStringValue().contains(vc.title.substring(0, 10))) {
                                vc.citation = element.getStringValue();
                                vc.supervisor = element.getStringValue();
                                Iterator profsIterator = profs.iterator();
                                vc.supervisor = vc.supervisor.replace(vc.title, "");//we remove the title out of the citation
                                //if we have two students we remove the first occurence of "" which stands for "and"
                                if (vc.creators.size() == 2) {
                                    vc.supervisor = vc.supervisor.replaceFirst("", "");
                                }
                                //we remove the students' names
                                Iterator creatorsIterator = vc.creators.iterator();
                                while (creatorsIterator.hasNext()) {
                                    vc.supervisor = vc.supervisor.replace(creatorsIterator.next().toString(),
                                            "");
                                }
                                boolean profFlag = false;//flag used that declares that we found the professor that was supervisor
                                while (profsIterator.hasNext() && !profFlag) {
                                    String prof = profsIterator.next().toString();
                                    //we split the professor's name to surname and name
                                    //because some entries have first the surname and others first the name
                                    String[] profSplitted = prof.split("\\s+");
                                    String supervisorCleared = vc.supervisor;
                                    supervisorCleared = supervisorCleared.replaceAll("\\s+", "");//we clear the white space
                                    supervisorCleared = supervisorCleared.replaceAll("(\\r|\\n)", "");//we remove the \r\n
                                    //now we check if the citation includes any name of the professors from the txt
                                    if (supervisorCleared.contains(profSplitted[0])
                                            && supervisorCleared.contains(profSplitted[1])) {
                                        vc.supervisor = prof;
                                        profFlag = true;
                                    }
                                }
                                //if we don't find the name of the supervisor, we have to perform string manipulation to extract it
                                if (!profFlag) {
                                    vc.supervisor = vc.supervisor.trim();
                                    //we remove the word "" which stands for "Thessaloniki" and "" which stands for Greece
                                    if (vc.supervisor.contains("")) {
                                        vc.supervisor = vc.supervisor.replaceFirst("",
                                                "");
                                    }
                                    if (vc.supervisor.contains("")) {
                                        vc.supervisor = vc.supervisor.replaceFirst("",
                                                "");
                                    }
                                    if (vc.supervisor.contains("")) {
                                        vc.supervisor = vc.supervisor.replaceFirst("", "");
                                    }
                                    if (vc.supervisor.contains("")) {
                                        vc.supervisor = vc.supervisor.replaceFirst("", "");
                                    }
                                    //we remove the year and then we should be left only with the supervisor's name
                                    vc.supervisor = vc.supervisor.replace("(", "");
                                    vc.supervisor = vc.supervisor.trim();
                                    vc.supervisor = vc.supervisor.replace(")", "");
                                    vc.supervisor = vc.supervisor.trim();
                                    vc.supervisor = vc.supervisor.replace(",", "");
                                    vc.supervisor = vc.supervisor.trim();
                                    vc.supervisor = vc.supervisor.replace(".", "");
                                    vc.supervisor = vc.supervisor.trim();
                                    vc.supervisor = vc.supervisor.replace(vc.datestring.substring(0, 4), "");
                                    vc.supervisor = vc.supervisor.trim();
                                }
                                //we put everything in a json object
                                JSONObject obj = new JSONObject();
                                obj.put("title", vc.title);
                                obj.put("description", vc.description);
                                JSONArray creatorsArray = new JSONArray();
                                creatorsArray.add(vc.creators);
                                obj.put("creators", creatorsArray);
                                JSONArray subjectsArray = new JSONArray();
                                List<String> subjectsList = new ArrayList<String>(vc.subjects);
                                subjectsArray.add(subjectsList);
                                obj.put("subjects", subjectsArray);
                                obj.put("datestring", vc.datestring);
                                JSONArray thesisFilesArray = new JSONArray();
                                thesisFilesArray.add(vc.thesisFiles);
                                obj.put("thesisFiles", thesisFilesArray);
                                obj.put("thesisURL", vc.thesisURL);
                                obj.put("supervisor", vc.supervisor);
                                obj.put("citation", vc.citation);
                                //if you are using JSON.simple do this
                                array.add(obj);
                            }
                        }
                    }
                    listtotal.add(vc);//a list containing all the objects
                    //it is not used for now, but created for potential extension of the work
                }
            }
            //the following if clause searches for new records
            if (listRecords.getResumptionToken() != null) {
                listRecords = server.listRecords(listRecords.getResumptionToken());
            } else {
                more = false;
            }
        }
        //we print which records did not have a supervisor
        for (VivlioCrawlerMavenMain vctest : listtotal) {

            if (vctest.supervisor == null) {
                System.out.println(vctest.title);
                System.out.println(vctest.citation);
            }
        }
        //we create a pretty json with GSON and we write it into a file
        jsonObject.put("VivliothmmyOldArray", array);
        JsonParser parser = new JsonParser();
        JsonObject json = parser.parse(jsonObject.toJSONString()).getAsJsonObject();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String prettyJson = gson.toJson(json);
        try {

            FileWriter file = new FileWriter(
                    "/home/themis/NetBeansProjects/VivlioCrawlerMaven/src/main/java/com/thesmartweb/vivliocrawlermaven/VivliothmmyOldRecords.json");
            file.write(prettyJson);
            file.flush();
            file.close();

        } catch (IOException e) {
            System.out.println("Exception: " + e);
        }

        //System.out.print(prettyJson);

        //int j=0;

    } catch (OAIException | IOException e) {
        System.out.println("Exception: " + e);
    }
}

From source file:com.mycompany.myelasticsearch.MainClass.java

/**
 * @param args the command line arguments
 *//*  ww w.  j a v  a 2  s.co  m*/
public static void main(String[] args) {

    // TODO code application logic here
    Tika tika = new Tika();
    String fileEntry = "C:\\Contract\\Contract1.pdf";
    String filetype = tika.detect(fileEntry);
    System.out.println("FileType " + filetype);
    BodyContentHandler handler = new BodyContentHandler(-1);
    String text = "";
    Metadata metadata = new Metadata();

    FileInputStream inputstream = null;

    try {
        inputstream = new FileInputStream(fileEntry);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    }
    ParseContext pcontext = new ParseContext();

    //parsing the document using PDF parser
    PDFParser pdfparser = new PDFParser();
    try {
        pdfparser.parse(inputstream, handler, metadata, pcontext);
    } catch (IOException ex) {

        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TikaException ex) {
        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    }
    String docText = "";
    String outputArray[];
    String out[];
    //getting the content of the document
    docText = handler.toString().replaceAll("(/[^\\da-zA-Z.]/)", "");

    // PhraseDetection.getPhrases(docText);
    try {
        Node node = nodeBuilder().node();
        Client client = node.client();
        DocumentReader.parseString(docText, client);
        //"Borrowing should be replaced by the user input key"
        Elastic.getDefinedTerm(client, "definedterms", "term", "1", "Borrowing");
        node.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    }
    Stanford.getSentence(docText);

    int definedTermsEnd = docText.indexOf("SCHEDULES");
    String toc = docText.substring(0, definedTermsEnd);
    String c = docText.substring(definedTermsEnd);

    System.out.println("Table of content" + toc);
    System.out.println("--------------------------------");
    System.out.println("content" + c);

    out = toc.split("Article|article|ARTICLE");
    int count = 0;
    String outputArrayString = "";
    int s = 0;
    StringBuffer tocOutput = new StringBuffer();

    for (String o : out) {
        if (count != 0) {
            s = Integer.parseInt(String.valueOf(o.charAt(1)));
            if (s == count) {
                tocOutput.append(o);
                tocOutput.append("JigarAnkitNeeraj");
                System.out.println(s);
            }
        }
        outputArrayString += "Count" + count + o;
        count++;
        System.out.println();
    }
    System.out.println("---------------------------------------------------Content---------");
    count = 1;
    StringBuffer contentOutput = new StringBuffer();

    String splitContent[] = c.split("ARTICLE|Article");
    Node node = nodeBuilder().node();
    Client client = node.client();
    for (String o : splitContent) {
        o = o.replaceAll("[^a-zA-Z0-9.,\\/#!$%\\^&\\*;:{}=\\-_`~()?\\s]+", "");
        o = o.replaceAll("\n", " ");
        char input = o.charAt(1);
        if (input >= '0' && input <= '9') {
            s = Integer.parseInt(String.valueOf(o.charAt(1)));
            if (s == count) {
                //System.out.println(s);
                JSONObject articleJSONObject = new JSONObject();
                contentOutput.append(" \n MyArticlesSeparated \n ");
                articleJSONObject.put("Article" + count, o.toString());
                try {
                    try {
                        JSONObject articleJSONObject1 = new JSONObject();
                        articleJSONObject1.put("hi", "j");
                        client.prepareIndex("contract", "article", String.valueOf(count))
                                .setSource(articleJSONObject.toString()).execute().actionGet();
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    //"Borrowing should be replaced by the user input key"

                } catch (Exception ex) {
                    Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
                }
                System.out.println(s);
                count++;
            }
            //outputArrayString += "Count" + count + o;

            contentOutput.append(o);
        }
    }
    Elastic.getDocument(client, "contract", "article", "1");
    Elastic.searchDocument(client, "contract", "article", "Lenders");
    Elastic.searchDocument(client, "contract", "article", "Negative Covenants");

    Elastic.searchDocument(client, "contract", "article", "Change in Law");
    String tableOfContent[];
    tableOfContent = tocOutput.toString().split("JigarAnkitNeeraj");

    String splitContectsAccordingToArticles[];
    splitContectsAccordingToArticles = contentOutput.toString().split("MyArticlesSeparated");
    int numberOfArticle = splitContectsAccordingToArticles.length;

    int countArticle = 1;
    Double toBeTruncated = new Double("" + countArticle + ".00");

    String section = "Section";
    toBeTruncated += 0.01;

    System.out.println(toBeTruncated);
    String sectionEnd;
    StringBuffer sectionOutput = new StringBuffer();
    int skipFirstArtcile = 0;
    JSONObject obj = new JSONObject();

    for (String article : splitContectsAccordingToArticles) {
        if (skipFirstArtcile != 0) {
            DecimalFormat f = new DecimalFormat("##.00");
            String sectionStart = section + " " + f.format(toBeTruncated);
            int start = article.indexOf(sectionStart);
            toBeTruncated += 0.01;

            System.out.println();
            sectionEnd = section + " " + f.format(toBeTruncated);

            int end = article.indexOf(sectionEnd);
            while (end != -1) {
                sectionStart = section + " " + f.format(toBeTruncated - 0.01);
                sectionOutput.append(" \n Key:" + sectionStart);
                if (start < end) {
                    sectionOutput.append("\n Value:" + article.substring(start, end));
                    obj.put(sectionStart, article.substring(start, end).replaceAll("\\r\\n|\\r|\\n", " "));
                    try {
                        try {
                            JSONObject articleJSONObject1 = new JSONObject();
                            articleJSONObject1.put("hi", "j");
                            client.prepareIndex("contract", "section", String.valueOf(count))
                                    .setSource(obj.toString()).execute().actionGet();
                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                        }
                        //"Borrowing should be replaced by the user input key"

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

                }

                start = end;
                toBeTruncated += 0.01;
                sectionEnd = section + " " + f.format(toBeTruncated);
                System.out.println("SectionEnd " + sectionEnd);
                try {
                    end = article.indexOf(sectionEnd);
                } catch (Exception e) {
                    System.out.print(e.getMessage());
                }

                System.out.println("End section index " + end);
            }
            end = article.length() - 1;
            sectionOutput.append(" \n Key:" + sectionStart);
            try {
                sectionOutput.append(" \n Value:" + article.substring(start, end));
                obj.put(sectionStart, article.substring(start, end).replaceAll("\\r\\n|\\r|\\n", " "));
            } catch (Exception e) {
                //What if Article has No Sections
                String numberOnly = article.replaceAll("[^0-9]", "").substring(0, 1);
                String sectionArticle = "ARTICLE " + numberOnly;
                sectionOutput.append(" \n Value:" + article);
                obj.put(sectionArticle, article);

                System.out.println(e.getMessage());
            }

            DecimalFormat ff = new DecimalFormat("##");
            toBeTruncated = Double.valueOf(ff.format(toBeTruncated)) + 1.01;
        }
        skipFirstArtcile++;
    }

    for (String article : splitContectsAccordingToArticles) {
        if (skipFirstArtcile != 0) {
            DecimalFormat f = new DecimalFormat("##.00");
            String sectionStart = section + " " + f.format(toBeTruncated);
            int start = article.indexOf(sectionStart);
            toBeTruncated += 0.01;
            System.out.println();
            sectionEnd = section + " " + f.format(toBeTruncated);

            int end = article.indexOf(sectionEnd);
            while (end != -1) {
                sectionStart = section + " " + f.format(toBeTruncated - 0.01);
                sectionOutput.append(" \n Key:" + sectionStart);
                if (start < end) {
                    sectionOutput.append("\n Value:" + article.substring(start, end));
                    System.out.println(sectionOutput);
                    String patternStr = "\\n\\n+[(]";
                    String paragraphSubstringArray[] = article.substring(start, end).split(patternStr);

                    JSONObject paragraphObject = new JSONObject();
                    int counter = 0;
                    for (String paragraphSubstring : paragraphSubstringArray) {
                        counter++;
                        paragraphObject.put("Paragraph " + counter, paragraphSubstring);

                    }
                    obj.put(sectionStart, paragraphObject);

                }

                start = end;
                toBeTruncated += 0.01;
                sectionEnd = section + " " + f.format(toBeTruncated);
                System.out.println("SectionEnd " + sectionEnd);
                try {
                    end = article.indexOf(sectionEnd);
                } catch (Exception e) {
                    System.out.print(e.getMessage());
                }

                System.out.println("End section index " + end);
            }
            end = article.length() - 1;
            sectionOutput.append(" \n Key:" + sectionStart);
            try {
                sectionOutput.append(" \n Value:" + article.substring(start, end));
                obj.put(sectionStart, article.substring(start, end));
                PhraseDetection.getPhrases(docText);
            } catch (Exception e) {
                //What if Article has No Sections
                String sectionArticle = "ARTICLE";
                System.out.println(e.getMessage());
            }
            DecimalFormat ff = new DecimalFormat("##");
            toBeTruncated = Double.valueOf(ff.format(toBeTruncated)) + 1.01;
        }
        skipFirstArtcile++;
    }

    Elastic.getDocument(client, "contract", "section", "1");
    Elastic.searchDocument(client, "contract", "section", "Lenders");
    Elastic.searchDocument(client, "contract", "section", "Negative Covenants");
    try {
        FileWriter file = new FileWriter("TableOfIndex.txt");
        file.write(tocOutput.toString());
        file.flush();
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        FileWriter file = new FileWriter("Contract3_JSONFile.txt");
        file.write(obj.toString());
        file.flush();
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        FileWriter file = new FileWriter("Contract1_KeyValueSections.txt");
        file.write(sectionOutput.toString());
        file.flush();
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:etomica.virial.MCMoveClusterRingRegrowOrientation.java

public static void main(String[] args) {
    ISpace space = Space3D.getInstance();
    ClusterWeight cluster = new ClusterWeight() {

        @Override/*from  w  ww .  jav a2 s .  c om*/
        public double value(BoxCluster box) {
            // TODO Auto-generated method stub
            return 1;
        }

        @Override
        public void setTemperature(double temperature) {
            // TODO Auto-generated method stub

        }

        @Override
        public int pointCount() {
            // TODO Auto-generated method stub
            return 1;
        }

        @Override
        public ClusterAbstract makeCopy() {
            // TODO Auto-generated method stub
            return null;
        }
    };
    BoxCluster box = new BoxCluster(cluster, space);
    Simulation sim = new Simulation(space);
    sim.addBox(box);
    IAtomTypeOriented atype = new AtomTypeOrientedSphere(Hydrogen.INSTANCE, space);
    SpeciesSpheresHetero species = new SpeciesSpheresHetero(space, new IAtomTypeOriented[] { atype });
    sim.addSpecies(species);
    File file1 = new File("acceptance.dat");
    if (file1.exists()) {
        file1.delete();
    }
    for (int p = 2; p <= 512; p *= 2) {
        box.setNMolecules(species, 0);
        species.setChildCount(new int[] { p });
        box.setNMolecules(species, 1);
        IntegratorMC integrator = new IntegratorMC(sim, null);
        integrator.setBox(box);
        MCMoveClusterRingRegrowOrientation move = new MCMoveClusterRingRegrowOrientation(sim.getRandom(), space,
                p);

        for (int iTemp = 40; iTemp <= 40; iTemp += 2) {
            move.foo = 0;
            move.setStiffness(Kelvin.UNIT.toSim(iTemp), species.getAtomType(0).getMass());
            integrator.getMoveManager().addMCMove(move);
            integrator.reset();
            int total = 100;
            for (int i = 0; i < total; i++) {
                integrator.doStep();
            }
            try {
                FileWriter Temp = new FileWriter("acceptance.dat", true);
                Temp.write(
                        iTemp + " " + p + " " + move.getStiffness() + " " + ((double) move.foo) / total + "\n");
                Temp.close();
            } catch (IOException ex1) {
                throw new RuntimeException(ex1);
            }
            System.out.println(
                    "p = " + p + " ,Temp = " + iTemp + " ,acceptance ratio = " + ((double) move.foo) / total);
        }

    }
}

From source file:ValidateLicenseHeaders.java

/**
 * ValidateLicenseHeaders jboss-src-root
 * /*from  w w w.  jav a  2s  .c om*/
 * @param args
 */
public static void main(String[] args) throws Exception {
    if (args.length == 0 || args[0].startsWith("-h")) {
        log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root");
        System.exit(1);
    }
    int rootArg = 0;
    if (args.length == 2) {
        if (args[0].startsWith("-add"))
            addDefaultHeader = true;
        else {
            log.severe("Uknown argument: " + args[0]);
            log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root");
            System.exit(1);

        }
        rootArg = 1;
    }

    File jbossSrcRoot = new File(args[rootArg]);
    if (jbossSrcRoot.exists() == false) {
        log.info("Src root does not exist, check " + jbossSrcRoot.getAbsolutePath());
        System.exit(1);
    }

    URL u = Thread.currentThread().getContextClassLoader()
            .getResource("META-INF/services/javax.xml.parsers.DocumentBuilderFactory");
    System.err.println(u);

    // Load the valid copyright statements for the licenses
    File licenseInfo = new File(jbossSrcRoot, "varia/src/etc/license-info.xml");
    if (licenseInfo.exists() == false) {
        log.severe("Failed to find the varia/src/etc/license-info.xml under the src root");
        System.exit(1);
    }
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = factory.newDocumentBuilder();
    Document doc = db.parse(licenseInfo);
    NodeList licenses = doc.getElementsByTagName("license");
    for (int i = 0; i < licenses.getLength(); i++) {
        Element license = (Element) licenses.item(i);
        String key = license.getAttribute("id");
        ArrayList headers = new ArrayList();
        licenseHeaders.put(key, headers);
        NodeList copyrights = license.getElementsByTagName("terms-header");
        for (int j = 0; j < copyrights.getLength(); j++) {
            Element copyright = (Element) copyrights.item(j);
            copyright.normalize();
            String id = copyright.getAttribute("id");
            // The id will be blank if there is no id attribute
            if (id.length() == 0)
                continue;
            String text = getElementContent(copyright);
            if (text == null)
                continue;
            // Replace all duplicate whitespace and '*' with a single space
            text = text.replaceAll("[\\s*]+", " ");
            if (text.length() == 1)
                continue;

            text = text.toLowerCase().trim();
            // Replace any copyright date0-date1,date2 with copyright ...
            text = text.replaceAll(COPYRIGHT_REGEX, "...");
            LicenseHeader lh = new LicenseHeader(id, text);
            headers.add(lh);
        }
    }
    log.fine(licenseHeaders.toString());

    File[] files = jbossSrcRoot.listFiles(dotJavaFilter);
    log.info("Root files count: " + files.length);
    processSourceFiles(files, 0);

    log.info("Processed " + totalCount);
    log.info("Updated jboss headers: " + jbossCount);
    // Files with no headers details
    log.info("Files with no headers: " + noheaders.size());
    FileWriter fw = new FileWriter("NoHeaders.txt");
    for (Iterator iter = noheaders.iterator(); iter.hasNext();) {
        File f = (File) iter.next();
        fw.write(f.getAbsolutePath());
        fw.write('\n');
    }
    fw.close();

    // Files with unknown headers details
    log.info("Files with invalid headers: " + invalidheaders.size());
    fw = new FileWriter("InvalidHeaders.txt");
    for (Iterator iter = invalidheaders.iterator(); iter.hasNext();) {
        File f = (File) iter.next();
        fw.write(f.getAbsolutePath());
        fw.write('\n');
    }
    fw.close();

    // License usage summary
    log.info("Creating HeadersSummary.txt");
    fw = new FileWriter("HeadersSummary.txt");
    for (Iterator iter = licenseHeaders.entrySet().iterator(); iter.hasNext();) {
        Map.Entry entry = (Map.Entry) iter.next();
        String key = (String) entry.getKey();
        fw.write("+++ License type=" + key);
        fw.write('\n');
        List list = (List) entry.getValue();
        Iterator jiter = list.iterator();
        while (jiter.hasNext()) {
            LicenseHeader lh = (LicenseHeader) jiter.next();
            fw.write('\t');
            fw.write(lh.id);
            fw.write(", count=");
            fw.write("" + lh.count);
            fw.write('\n');
        }
    }
    fw.close();
}