List of usage examples for java.io FileNotFoundException getMessage
public String getMessage()
From source file:com.mycompany.mavenproject4.NewMain.java
/** * @param args the command line arguments *///w w w .j a v a 2s. co m public static void main(String[] args) { System.out.println("Enter your choice do you want to work with 1.postgre 2.Redis 3.Mongodb"); InputStreamReader IORdatabase = new InputStreamReader(System.in); BufferedReader BIOdatabase = new BufferedReader(IORdatabase); String databasechoice = null; try { databasechoice = BIOdatabase.readLine(); } catch (Exception E7) { System.out.println(E7.getMessage()); } // loading data from the CSV file CsvReader Employees = null; try { Employees = new CsvReader("CSVFile\\Employees.csv"); } catch (FileNotFoundException EB) { System.out.println(EB.getMessage()); } int ColumnCount = 3; int RowCount = 100; int iloop = 0; try { Employees = new CsvReader("CSVFile\\Employees.csv"); } catch (FileNotFoundException E) { System.out.println(E.getMessage()); } String[][] Dataarray = new String[RowCount][ColumnCount]; try { while (Employees.readRecord()) { String v; String[] x; v = Employees.getRawRecord(); x = v.split(","); for (int j = 0; j < ColumnCount; j++) { String value = null; int z = j; value = x[z]; try { Dataarray[iloop][j] = value; } catch (Exception E) { System.out.println(E.getMessage()); } // System.out.println(Dataarray[iloop][j]); } iloop = iloop + 1; } } catch (IOException Em) { System.out.println(Em.getMessage()); } Employees.close(); // connection to Database switch (databasechoice) { // postgre code goes here case "1": Connection Conn = null; Statement Stmt = null; URI dbUri = null; String choice = null; InputStreamReader objin = new InputStreamReader(System.in); BufferedReader objbuf = new BufferedReader(objin); try { Class.forName("org.postgresql.Driver"); } catch (Exception E1) { System.out.println(E1.getMessage()); } String username = "ldoiarosfrzrua"; String password = "HBkE_pJpK5mMIg3p2q1_odmEFX"; String dbUrl = "jdbc:postgresql://ec2-54-83-53-120.compute-1.amazonaws.com:5432/d6693oljh5cco4?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory"; // now update data in the postgress Database // for(int i=0;i<RowCount;i++) // { // try // { // Conn= DriverManager.getConnection(dbUrl, username, password); // Stmt = Conn.createStatement(); // String Connection_String = "insert into EmployeeDistinct (name,jobtitle,department) values (' "+ Dataarray[i][0]+" ',' "+ Dataarray[i][1]+" ',' "+ Dataarray[i][2]+" ')"; // Stmt.executeUpdate(Connection_String); // // } // catch(SQLException E4) // { // System.out.println(E4.getMessage()); // } // } // Quering with the Database System.out.println("1. Display Data "); System.out.println("2. Select data based on primary key"); System.out.println("3. Select data based on Other attributes e.g Name"); System.out.println("Enter your Choice "); try { choice = objbuf.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } switch (choice) { case "1": try { Conn = DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = " Select * from EmployeeDistinct;"; ResultSet objRS = Stmt.executeQuery(Connection_String); while (objRS.next()) { System.out.println("Employee ID: " + objRS.getInt("EmployeeID")); System.out.println("Employee Name: " + objRS.getString("Name")); System.out.println("Employee City: " + objRS.getString("Jobtitle")); System.out.println("Employee City: " + objRS.getString("Department")); } } catch (Exception E2) { System.out.println(E2.getMessage()); } break; case "2": System.out.println("Enter the Primary Key"); InputStreamReader objkey = new InputStreamReader(System.in); BufferedReader objbufkey = new BufferedReader(objkey); int key = 0; try { key = Integer.parseInt(objbufkey.readLine()); } catch (IOException E) { System.out.println(E.getMessage()); } try { Conn = DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = " Select * from EmployeeDistinct where EmployeeID=" + key + ";"; ResultSet objRS = Stmt.executeQuery(Connection_String); while (objRS.next()) { System.out.println("Employee Name: " + objRS.getString("Name")); System.out.println("Employee City: " + objRS.getString("Jobtitle")); System.out.println("Employee City: " + objRS.getString("Department")); } } catch (Exception E2) { System.out.println(E2.getMessage()); } break; case "3": String Name = null; System.out.println("Enter Name to find the record"); InputStreamReader objname = new InputStreamReader(System.in); BufferedReader objbufname = new BufferedReader(objname); try { Name = (objbufname.readLine()).toString(); } catch (IOException E) { System.out.println(E.getMessage()); } try { Conn = DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = " Select * from EmployeeDistinct where Name=" + "'" + Name + "'" + ";"; ResultSet objRS = Stmt.executeQuery(Connection_String); while (objRS.next()) { System.out.println("Employee ID: " + objRS.getInt("EmployeeID")); System.out.println("Employee City: " + objRS.getString("Jobtitle")); System.out.println("Employee City: " + objRS.getString("Department")); } } catch (Exception E2) { System.out.println(E2.getMessage()); } break; } try { Conn.close(); } catch (SQLException E6) { System.out.println(E6.getMessage()); } break; // Redis code goes here case "2": int Length = 0; String ID = null; Length = 100; // Connection to Redis Jedis jedis = new Jedis("pub-redis-18017.us-east-1-4.6.ec2.redislabs.com", 18017); jedis.auth("7EFOisRwMu8zvhin"); System.out.println("Connected to Redis"); // Storing values in the database // System.out.println("Storing values in the Database might take a minute "); // for(int i=0;i<Length;i++) // { // Store data in redis // int j=i+1; // jedis.hset("Employe:" + j , "Name", Dataarray[i][0]); // jedis.hset("Employe:" + j , "Jobtitle ", Dataarray[i][1]); // jedis.hset("Employe:" + j , "Department", Dataarray[i][2]); // } System.out.println("Search by 1.primary key,2.Name 3.display first 20"); InputStreamReader objkey = new InputStreamReader(System.in); BufferedReader objbufkey = new BufferedReader(objkey); String interimChoice1 = null; try { interimChoice1 = objbufkey.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } switch (interimChoice1) { case "1": System.out.print("Get details using the primary Key"); InputStreamReader IORKey = new InputStreamReader(System.in); BufferedReader BIORKey = new BufferedReader(IORKey); String ID1 = null; try { ID1 = BIORKey.readLine(); } catch (IOException E3) { System.out.println(E3.getMessage()); } Map<String, String> properties = jedis.hgetAll("Employe:" + Integer.parseInt(ID1)); for (Map.Entry<String, String> entry : properties.entrySet()) { System.out.println("Name:" + jedis.hget("Employee:" + Integer.parseInt(ID1), "Name")); System.out.println("Jobtitle:" + jedis.hget("Employee:" + Integer.parseInt(ID1), "Jobtitle")); System.out .println("Department:" + jedis.hget("Employee:" + Integer.parseInt(ID1), "Department")); } break; case "2": System.out.print("Get details using Department"); InputStreamReader IORName1 = new InputStreamReader(System.in); BufferedReader BIORName1 = new BufferedReader(IORName1); String ID2 = null; try { ID2 = BIORName1.readLine(); } catch (IOException E3) { System.out.println(E3.getMessage()); } for (int i = 0; i < 100; i++) { Map<String, String> properties3 = jedis.hgetAll("Employe:" + i); for (Map.Entry<String, String> entry : properties3.entrySet()) { String value = entry.getValue(); if (entry.getValue().equals(ID2)) { System.out.println("Name:" + jedis.hget("Employee:" + i, "Name")); System.out.println("Jobtitle:" + jedis.hget("Employee:" + i, "Jobtitle")); System.out.println("Department:" + jedis.hget("Employee:" + i, "Department")); } } } //for (Map.Entry<String, String> entry : properties1.entrySet()) //{ //System.out.println(entry.getKey() + "---" + entry.getValue()); // } break; case "3": for (int i = 1; i < 21; i++) { Map<String, String> properties3 = jedis.hgetAll("Employe:" + i); for (Map.Entry<String, String> entry : properties3.entrySet()) { // System.out.println(jedis.hget("Employee:" + i,"Name")); System.out.println("Name:" + jedis.hget("Employee:" + i, "Name")); System.out.println("Jobtitle:" + jedis.hget("Employee:" + i, "Jobtitle")); System.out.println("Department:" + jedis.hget("Employee:" + i, "Department")); } } break; } break; // mongo db code goes here case "3": MongoClient mongo = new MongoClient( new MongoClientURI("mongodb://root2:12345@ds055564.mongolab.com:55564/heroku_766dnj8c")); DB db; db = mongo.getDB("heroku_766dnj8c"); // storing values in the database // for(int i=0;i<100;i++) // { // BasicDBObject document = new BasicDBObject(); // document.put("_id", i+1); // document.put("Name", Dataarray[i][0]); // document.put("Jobtitle", Dataarray[i][1]); // document.put("Department", Dataarray[i][2]); // db.getCollection("EmployeeRaw").insert(document); // } System.out.println("Search by 1.primary key,2.Name 3.display first 20"); InputStreamReader objkey6 = new InputStreamReader(System.in); BufferedReader objbufkey6 = new BufferedReader(objkey6); String interimChoice = null; try { interimChoice = objbufkey6.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } switch (interimChoice) { case "1": System.out.println("Enter the Primary Key"); InputStreamReader IORPkey = new InputStreamReader(System.in); BufferedReader BIORPkey = new BufferedReader(IORPkey); int Pkey = 0; try { Pkey = Integer.parseInt(BIORPkey.readLine()); } catch (IOException E) { System.out.println(E.getMessage()); } BasicDBObject inQuery = new BasicDBObject(); inQuery.put("_id", Pkey); DBCursor cursor = db.getCollection("EmployeeRaw").find(inQuery); while (cursor.hasNext()) { // System.out.println(cursor.next()); System.out.println(cursor.next()); } break; case "2": System.out.println("Enter the Name to Search"); InputStreamReader objName = new InputStreamReader(System.in); BufferedReader objbufName = new BufferedReader(objName); String Name = null; try { Name = objbufName.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } BasicDBObject inQuery1 = new BasicDBObject(); inQuery1.put("Name", Name); DBCursor cursor1 = db.getCollection("EmployeeRaw").find(inQuery1); while (cursor1.hasNext()) { // System.out.println(cursor.next()); System.out.println(cursor1.next()); } break; case "3": for (int i = 1; i < 21; i++) { BasicDBObject inQuerya = new BasicDBObject(); inQuerya.put("_id", i); DBCursor cursora = db.getCollection("EmployeeRaw").find(inQuerya); while (cursora.hasNext()) { // System.out.println(cursor.next()); System.out.println(cursora.next()); } } break; } break; } }
From source file:com.mycompany.mavenproject4.web.java
/** * @param args the command line arguments *///from ww w.j a v a 2 s . c o m public static void main(String[] args) { System.out.println("Enter your choice do you want to work with \n 1.PostGreSQL \n 2.Redis \n 3.Mongodb"); InputStreamReader IORdatabase = new InputStreamReader(System.in); BufferedReader BIOdatabase = new BufferedReader(IORdatabase); String Str1 = null; try { Str1 = BIOdatabase.readLine(); } catch (Exception E7) { System.out.println(E7.getMessage()); } // loading data from the CSV file CsvReader data = null; try { data = new CsvReader("\\data\\Consumer_Complaints.csv"); } catch (FileNotFoundException EB) { System.out.println(EB.getMessage()); } int noofcolumn = 5; int noofrows = 100; int loops = 0; try { data = new CsvReader("\\data\\Consumer_Complaints.csv"); } catch (FileNotFoundException E) { System.out.println(E.getMessage()); } String[][] Dataarray = new String[noofrows][noofcolumn]; try { while (data.readRecord()) { String v; String[] x; v = data.getRawRecord(); x = v.split(","); for (int j = 0; j < noofcolumn; j++) { String value = null; int z = j; value = x[z]; try { Dataarray[loops][j] = value; } catch (Exception E) { System.out.println(E.getMessage()); } // System.out.println(Dataarray[iloop][j]); } loops = loops + 1; } } catch (IOException Em) { System.out.println(Em.getMessage()); } data.close(); // connection to Database switch (Str1) { // postgre code goes here case "1": Connection Conn = null; Statement Stmt = null; URI dbUri = null; String choice = null; InputStreamReader objin = new InputStreamReader(System.in); BufferedReader objbuf = new BufferedReader(objin); try { Class.forName("org.postgresql.Driver"); } catch (Exception E1) { System.out.println(E1.getMessage()); } String username = "ahkyjdavhedkzg"; String password = "2f7c3_MBJbIy1uJsFyn7zebkhY"; String dbUrl = "jdbc:postgresql://ec2-54-83-199-54.compute-1.amazonaws.com:5432/d2l6hq915lp9vi?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory"; // now update data in the postgress Database /* for(int i=0;i<RowCount;i++) { try { Conn= DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = "insert into Webdata (Id,Product,state,Submitted,Complaintid) values (' "+ Dataarray[i][0]+" ',' "+ Dataarray[i][1]+" ',' "+ Dataarray[i][2]+" ',' "+ Dataarray[i][3]+" ',' "+ Dataarray[i][4]+" ')"; Stmt.executeUpdate(Connection_String); Conn.close(); } catch(SQLException E4) { System.out.println(E4.getMessage()); } } */ // Quering with the Database System.out.println("1. Display Data "); System.out.println("2. Select data based on primary key"); System.out.println("3. Select data based on Other attributes e.g Name"); System.out.println("Enter your Choice "); try { choice = objbuf.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } switch (choice) { case "1": try { Conn = DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = " Select * from Webdata;"; ResultSet objRS = Stmt.executeQuery(Connection_String); while (objRS.next()) { System.out.println(" ID: " + objRS.getInt("ID")); System.out.println("Product Name: " + objRS.getString("Product")); System.out.println("Which state: " + objRS.getString("State")); System.out.println("Sumbitted through: " + objRS.getString("Submitted")); System.out.println("Complain Number: " + objRS.getString("Complaintid")); Conn.close(); } } catch (Exception E2) { System.out.println(E2.getMessage()); } break; case "2": System.out.println("Enter Id(Primary Key) :"); InputStreamReader objkey = new InputStreamReader(System.in); BufferedReader objbufkey = new BufferedReader(objkey); int key = 0; try { key = Integer.parseInt(objbufkey.readLine()); } catch (IOException E) { System.out.println(E.getMessage()); } try { Conn = DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = " Select * from Webdata where Id=" + key + ";"; ResultSet objRS = Stmt.executeQuery(Connection_String); while (objRS.next()) { //System.out.println(" ID: " + objRS.getInt("ID")); System.out.println("Product Name: " + objRS.getString("Product")); System.out.println("Which state: " + objRS.getString("State")); System.out.println("Sumbitted through: " + objRS.getString("Submitted")); System.out.println("Complain Number: " + objRS.getString("Complaintid")); Conn.close(); } } catch (Exception E2) { System.out.println(E2.getMessage()); } break; case "3": //String Name=null; System.out.println("Enter Complaintid to find the record"); // Scanner input = new Scanner(System.in); // int Number = 0; try { InputStreamReader objname = new InputStreamReader(System.in); BufferedReader objbufname = new BufferedReader(objname); Number = Integer.parseInt(objbufname.readLine()); } catch (Exception E10) { System.out.println(E10.getMessage()); } //System.out.println(Name); try { Conn = DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = " Select * from Webdata where complaintid=" + Number + ";"; //2 System.out.println(Connection_String); ResultSet objRS = Stmt.executeQuery(Connection_String); while (objRS.next()) { int id = objRS.getInt("id"); System.out.println(" ID: " + id); System.out.println("Product Name: " + objRS.getString("Product")); String state = objRS.getString("state"); System.out.println("Which state: " + state); String Submitted = objRS.getString("submitted"); System.out.println("Sumbitted through: " + Submitted); String Complaintid = objRS.getString("complaintid"); System.out.println("Complain Number: " + Complaintid); } Conn.close(); } catch (Exception E2) { System.out.println(E2.getMessage()); } break; } try { Conn.close(); } catch (SQLException E6) { System.out.println(E6.getMessage()); } break; // Redis code goes here case "2": int Length = 0; String ID = null; Length = 100; // Connection to Redis Jedis jedis = new Jedis("pub-redis-13274.us-east-1-2.1.ec2.garantiadata.com", 13274); jedis.auth("rfJ8OLjlv9NjRfry"); System.out.println("Connected to Redis Database"); // Storing values in the database /* for(int i=0;i<Length;i++) { //Store data in redis int j=i+1; jedis.hset("Record:" + j , "Product", Dataarray[i][1]); jedis.hset("Record:" + j , "State ", Dataarray[i][2]); jedis.hset("Record:" + j , "Submitted", Dataarray[i][3]); jedis.hset("Record:" + j , "Complaintid", Dataarray[i][4]); } */ System.out.println( "Search by \n 11.Get records through primary key \n 22.Get Records through Complaintid \n 33.Display "); InputStreamReader objkey = new InputStreamReader(System.in); BufferedReader objbufkey = new BufferedReader(objkey); String str2 = null; try { str2 = objbufkey.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } switch (str2) { case "11": System.out.print("Enter Primary Key : "); InputStreamReader IORKey = new InputStreamReader(System.in); BufferedReader BIORKey = new BufferedReader(IORKey); String ID1 = null; try { ID1 = BIORKey.readLine(); } catch (IOException E3) { System.out.println(E3.getMessage()); } Map<String, String> properties = jedis.hgetAll("Record:" + Integer.parseInt(ID1)); for (Map.Entry<String, String> entry : properties.entrySet()) { System.out.println("Product:" + jedis.hget("Record:" + Integer.parseInt(ID1), "Product")); System.out.println("State:" + jedis.hget("Record:" + Integer.parseInt(ID1), "State")); System.out.println("Submitted:" + jedis.hget("Record:" + Integer.parseInt(ID1), "Submitted")); System.out .println("Complaintid:" + jedis.hget("Record:" + Integer.parseInt(ID1), "Complaintid")); } break; case "22": System.out.print(" Enter Complaintid : "); InputStreamReader IORName1 = new InputStreamReader(System.in); BufferedReader BIORName1 = new BufferedReader(IORName1); String ID2 = null; try { ID2 = BIORName1.readLine(); } catch (IOException E3) { System.out.println(E3.getMessage()); } for (int i = 0; i < 100; i++) { Map<String, String> properties3 = jedis.hgetAll("Record:" + i); for (Map.Entry<String, String> entry : properties3.entrySet()) { String value = entry.getValue(); if (entry.getValue().equals(ID2)) { System.out .println("Product:" + jedis.hget("Record:" + Integer.parseInt(ID2), "Product")); System.out.println("State:" + jedis.hget("Record:" + Integer.parseInt(ID2), "State")); System.out.println( "Submitted:" + jedis.hget("Record:" + Integer.parseInt(ID2), "Submitted")); System.out.println( "Complaintid:" + jedis.hget("Record:" + Integer.parseInt(ID2), "Complaintid")); } } } break; case "33": for (int i = 1; i < 21; i++) { Map<String, String> properties3 = jedis.hgetAll("Record:" + i); for (Map.Entry<String, String> entry : properties3.entrySet()) { System.out.println("Product:" + jedis.hget("Record:" + i, "Product")); System.out.println("State:" + jedis.hget("Record:" + i, "State")); System.out.println("Submitted:" + jedis.hget("Record:" + i, "Submitted")); System.out.println("Complaintid:" + jedis.hget("Record:" + i, "Complaintid")); } } break; } break; // mongo db case "3": MongoClient mongo = new MongoClient(new MongoClientURI( "mongodb://naikhpratik:naikhpratik@ds053964.mongolab.com:53964/heroku_6t7n587f")); DB db; db = mongo.getDB("heroku_6t7n587f"); // storing values in the database /*for(int i=0;i<100;i++) { BasicDBObject document = new BasicDBObject(); document.put("Id", i+1); document.put("Product", Dataarray[i][1]); document.put("State", Dataarray[i][2]); document.put("Submitted", Dataarray[i][3]); document.put("Complaintid", Dataarray[i][4]); db.getCollection("Naiknaik").insert(document); }*/ System.out.println("Search by \n 1.Enter Primary key \n 2.Enter Complaintid \n 3.Display"); InputStreamReader objkey6 = new InputStreamReader(System.in); BufferedReader objbufkey6 = new BufferedReader(objkey6); String str3 = null; try { str3 = objbufkey6.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } switch (str3) { case "1": System.out.println("Enter the Primary Key"); InputStreamReader IORPkey = new InputStreamReader(System.in); BufferedReader BIORPkey = new BufferedReader(IORPkey); int Pkey = 0; try { Pkey = Integer.parseInt(BIORPkey.readLine()); } catch (IOException E) { System.out.println(E.getMessage()); } BasicDBObject inQuery = new BasicDBObject(); inQuery.put("Id", Pkey); DBCursor cursor = db.getCollection("Naiknaik").find(inQuery); while (cursor.hasNext()) { // System.out.println(cursor.next()); System.out.println(cursor.next()); } break; case "2": System.out.println("Enter the Product to Search"); InputStreamReader objName = new InputStreamReader(System.in); BufferedReader objbufName = new BufferedReader(objName); String Name = null; try { Name = objbufName.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } BasicDBObject inQuery1 = new BasicDBObject(); inQuery1.put("Product", Name); DBCursor cursor1 = db.getCollection("Naiknaik").find(inQuery1); while (cursor1.hasNext()) { // System.out.println(cursor.next()); System.out.println(cursor1.next()); } break; case "3": for (int i = 1; i < 21; i++) { BasicDBObject inQuerya = new BasicDBObject(); inQuerya.put("_id", i); DBCursor cursora = db.getCollection("Naiknaik").find(inQuerya); while (cursora.hasNext()) { // System.out.println(cursor.next()); System.out.println(cursora.next()); } } break; } break; } }
From source file:tuit.java
@SuppressWarnings("ConstantConditions") public static void main(String[] args) { System.out.println(licence);//from w w w . ja v a 2s .co m //Declare variables File inputFile; File outputFile; File tmpDir; File blastnExecutable; File properties; File blastOutputFile = null; // TUITPropertiesLoader tuitPropertiesLoader; TUITProperties tuitProperties; // String[] parameters = null; // Connection connection = null; MySQL_Connector mySQL_connector; // Map<Ranks, TUITCutoffSet> cutoffMap; // BLASTIdentifier blastIdentifier = null; // RamDb ramDb = null; CommandLineParser parser = new GnuParser(); Options options = new Options(); options.addOption(tuit.IN, "input<file>", true, "Input file (currently fasta-formatted only)"); options.addOption(tuit.OUT, "output<file>", true, "Output file (in " + tuit.TUIT_EXT + " format)"); options.addOption(tuit.P, "prop<file>", true, "Properties file (XML formatted)"); options.addOption(tuit.V, "verbose", false, "Enable verbose output"); options.addOption(tuit.B, "blast_output<file>", true, "Perform on a pre-BLASTed output"); options.addOption(tuit.DEPLOY, "deploy", false, "Deploy the taxonomic databases"); options.addOption(tuit.UPDATE, "update", false, "Update the taxonomic databases"); options.addOption(tuit.USE_DB, "usedb", false, "Use RDBMS instead of RAM-based taxonomy"); Option option = new Option(tuit.REDUCE, "reduce", true, "Pack identical (100% similar sequences) records in the given sample file"); option.setArgs(Option.UNLIMITED_VALUES); options.addOption(option); option = new Option(tuit.COMBINE, "combine", true, "Combine a set of given reduction files into an HMP Tree-compatible taxonomy"); option.setArgs(Option.UNLIMITED_VALUES); options.addOption(option); options.addOption(tuit.NORMALIZE, "normalize", false, "If used in combination with -combine ensures that the values are normalized by the root value"); HelpFormatter formatter = new HelpFormatter(); try { //Get TUIT directory final File tuitDir = new File( new File(tuit.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()) .getParent()); final File ramDbFile = new File(tuitDir, tuit.RAM_DB); //Setup logger Log.getInstance().setLogName("tuit.log"); //Read command line final CommandLine commandLine = parser.parse(options, args, true); //Check if the REDUCE option is on if (commandLine.hasOption(tuit.REDUCE)) { final String[] fileList = commandLine.getOptionValues(tuit.REDUCE); for (String s : fileList) { final Path path = Paths.get(s); Log.getInstance().log(Level.INFO, "Processing " + path.toString() + "..."); final NucleotideFastaSequenceReductor nucleotideFastaSequenceReductor = NucleotideFastaSequenceReductor .fromPath(path); ReductorFileOperator.save(nucleotideFastaSequenceReductor, path.resolveSibling(path.getFileName().toString() + ".rdc")); } Log.getInstance().log(Level.FINE, "Task done, exiting..."); return; } //Check if COMBINE is on if (commandLine.hasOption(tuit.COMBINE)) { final boolean normalize = commandLine.hasOption(tuit.NORMALIZE); final String[] fileList = commandLine.getOptionValues(tuit.COMBINE); //TODO: implement a test for format here final List<TreeFormatter.TreeFormatterFormat.HMPTreesOutput> hmpTreesOutputs = new ArrayList<>(); final TreeFormatter treeFormatter = TreeFormatter .newInstance(new TreeFormatter.TuitLineTreeFormatterFormat()); for (String s : fileList) { final Path path = Paths.get(s); Log.getInstance().log(Level.INFO, "Merging " + path.toString() + "..."); treeFormatter.loadFromPath(path); final TreeFormatter.TreeFormatterFormat.HMPTreesOutput output = TreeFormatter.TreeFormatterFormat.HMPTreesOutput .newInstance(treeFormatter.toHMPTree(normalize), s.substring(0, s.indexOf("."))); hmpTreesOutputs.add(output); treeFormatter.erase(); } final Path destination; if (commandLine.hasOption(OUT)) { destination = Paths.get(commandLine.getOptionValue(tuit.OUT)); } else { destination = Paths.get("merge.tcf"); } CombinatorFileOperator.save(hmpTreesOutputs, treeFormatter, destination); Log.getInstance().log(Level.FINE, "Task done, exiting..."); return; } if (!commandLine.hasOption(tuit.P)) { throw new ParseException("No properties file option found, exiting."); } else { properties = new File(commandLine.getOptionValue(tuit.P)); } //Load properties tuitPropertiesLoader = TUITPropertiesLoader.newInstanceFromFile(properties); tuitProperties = tuitPropertiesLoader.getTuitProperties(); //Create tmp directory and blastn executable tmpDir = new File(tuitProperties.getTMPDir().getPath()); blastnExecutable = new File(tuitProperties.getBLASTNPath().getPath()); //Check for deploy if (commandLine.hasOption(tuit.DEPLOY)) { if (commandLine.hasOption(tuit.USE_DB)) { NCBITablesDeployer.fastDeployNCBIDatabasesFromNCBI(connection, tmpDir); } else { NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile); } Log.getInstance().log(Level.FINE, "Task done, exiting..."); return; } //Check for update if (commandLine.hasOption(tuit.UPDATE)) { if (commandLine.hasOption(tuit.USE_DB)) { NCBITablesDeployer.updateDatabasesFromNCBI(connection, tmpDir); } else { //No need to specify a different way to update the database other than just deploy in case of the RAM database NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile); } Log.getInstance().log(Level.FINE, "Task done, exiting..."); return; } //Connect to the database if (commandLine.hasOption(tuit.USE_DB)) { mySQL_connector = MySQL_Connector.newDefaultInstance( "jdbc:mysql://" + tuitProperties.getDBConnection().getUrl().trim() + "/", tuitProperties.getDBConnection().getLogin().trim(), tuitProperties.getDBConnection().getPassword().trim()); mySQL_connector.connectToDatabase(); connection = mySQL_connector.getConnection(); } else { //Probe for ram database if (ramDbFile.exists() && ramDbFile.canRead()) { Log.getInstance().log(Level.INFO, "Loading RAM taxonomic map..."); try { ramDb = RamDb.loadSelfFromFile(ramDbFile); } catch (IOException ie) { if (ie instanceof java.io.InvalidClassException) throw new IOException("The RAM-based taxonomic database needs to be updated."); } } else { Log.getInstance().log(Level.SEVERE, "The RAM database either has not been deployed, or is not accessible." + "Please use the --deploy option and check permissions on the TUIT directory. " + "If you were looking to use the RDBMS as a taxonomic reference, plese use the -usedb option."); return; } } if (commandLine.hasOption(tuit.B)) { blastOutputFile = new File(commandLine.getOptionValue(tuit.B)); if (!blastOutputFile.exists() || !blastOutputFile.canRead()) { throw new Exception("BLAST output file either does not exist, or is not readable."); } else if (blastOutputFile.isDirectory()) { throw new Exception("BLAST output file points to a directory."); } } //Check vital parameters if (!commandLine.hasOption(tuit.IN)) { throw new ParseException("No input file option found, exiting."); } else { inputFile = new File(commandLine.getOptionValue(tuit.IN)); Log.getInstance().setLogName(inputFile.getName().split("\\.")[0] + ".tuit.log"); } //Correct the output file option if needed if (!commandLine.hasOption(tuit.OUT)) { outputFile = new File((inputFile.getPath()).split("\\.")[0] + tuit.TUIT_EXT); } else { outputFile = new File(commandLine.getOptionValue(tuit.OUT)); } //Adjust the output level if (commandLine.hasOption(tuit.V)) { Log.getInstance().setLevel(Level.FINE); Log.getInstance().log(Level.INFO, "Using verbose output for the log"); } else { Log.getInstance().setLevel(Level.INFO); } //Try all files if (inputFile != null) { if (!inputFile.exists() || !inputFile.canRead()) { throw new Exception("Input file either does not exist, or is not readable."); } else if (inputFile.isDirectory()) { throw new Exception("Input file points to a directory."); } } if (!properties.exists() || !properties.canRead()) { throw new Exception("Properties file either does not exist, or is not readable."); } else if (properties.isDirectory()) { throw new Exception("Properties file points to a directory."); } //Create blast parameters final StringBuilder stringBuilder = new StringBuilder(); for (Database database : tuitProperties.getBLASTNParameters().getDatabase()) { stringBuilder.append(database.getUse()); stringBuilder.append(" ");//Gonna insert an extra space for the last database } String remote; String entrez_query; if (tuitProperties.getBLASTNParameters().getRemote().getDelegate().equals("yes")) { remote = "-remote"; entrez_query = "-entrez_query"; parameters = new String[] { "-db", stringBuilder.toString(), remote, entrez_query, tuitProperties.getBLASTNParameters().getEntrezQuery().getValue(), "-evalue", tuitProperties.getBLASTNParameters().getExpect().getValue() }; } else { if (!commandLine.hasOption(tuit.B)) { if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase() .startsWith("NOT") || tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase() .startsWith("ALL")) { parameters = new String[] { "-db", stringBuilder.toString(), "-evalue", tuitProperties.getBLASTNParameters().getExpect().getValue(), "-negative_gilist", TUITFileOperatorHelper.restrictToEntrez(tmpDir, tuitProperties.getBLASTNParameters().getEntrezQuery().getValue() .toUpperCase().replace("NOT", "OR")) .getAbsolutePath(), "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() }; } else if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase() .equals("")) { parameters = new String[] { "-db", stringBuilder.toString(), "-evalue", tuitProperties.getBLASTNParameters().getExpect().getValue(), "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() }; } else { parameters = new String[] { "-db", stringBuilder.toString(), "-evalue", tuitProperties.getBLASTNParameters().getExpect().getValue(), /*"-gilist", TUITFileOperatorHelper.restrictToEntrez( tmpDir, tuitProperties.getBLASTNParameters().getEntrezQuery().getValue()).getAbsolutePath(),*/ //TODO remove comment!!!!! "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() }; } } } //Prepare a cutoff Map if (tuitProperties.getSpecificationParameters() != null && tuitProperties.getSpecificationParameters().size() > 0) { cutoffMap = new HashMap<Ranks, TUITCutoffSet>(tuitProperties.getSpecificationParameters().size()); for (SpecificationParameters specificationParameters : tuitProperties .getSpecificationParameters()) { cutoffMap.put(Ranks.valueOf(specificationParameters.getCutoffSet().getRank()), TUITCutoffSet.newDefaultInstance( Double.parseDouble( specificationParameters.getCutoffSet().getPIdentCutoff().getValue()), Double.parseDouble(specificationParameters.getCutoffSet() .getQueryCoverageCutoff().getValue()), Double.parseDouble( specificationParameters.getCutoffSet().getAlpha().getValue()))); } } else { cutoffMap = new HashMap<Ranks, TUITCutoffSet>(); } final TUITFileOperatorHelper.OutputFormat format; if (tuitProperties.getBLASTNParameters().getOutputFormat().getFormat().equals("rdp")) { format = TUITFileOperatorHelper.OutputFormat.RDP_FIXRANK; } else { format = TUITFileOperatorHelper.OutputFormat.TUIT; } try (TUITFileOperator<NucleotideFasta> nucleotideFastaTUITFileOperator = NucleotideFastaTUITFileOperator .newInstance(format, cutoffMap);) { nucleotideFastaTUITFileOperator.setInputFile(inputFile); nucleotideFastaTUITFileOperator.setOutputFile(outputFile); final String cleanupString = tuitProperties.getBLASTNParameters().getKeepBLASTOuts().getKeep(); final boolean cleanup; if (cleanupString.equals("no")) { Log.getInstance().log(Level.INFO, "Temporary BLAST files will be deleted."); cleanup = true; } else { Log.getInstance().log(Level.INFO, "Temporary BLAST files will be kept."); cleanup = false; } //Create blast identifier ExecutorService executorService = Executors.newSingleThreadExecutor(); if (commandLine.hasOption(tuit.USE_DB)) { if (blastOutputFile == null) { blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromFileOperator(tmpDir, blastnExecutable, parameters, nucleotideFastaTUITFileOperator, connection, cutoffMap, Integer.parseInt( tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()), cleanup); } else { try { blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromBLASTOutput( nucleotideFastaTUITFileOperator, connection, cutoffMap, blastOutputFile, Integer.parseInt( tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()), cleanup); } catch (JAXBException e) { Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName() + ", please check input. The file must be XML formatted."); } catch (Exception e) { e.printStackTrace(); } } } else { if (blastOutputFile == null) { blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromFileOperator(tmpDir, blastnExecutable, parameters, nucleotideFastaTUITFileOperator, cutoffMap, Integer.parseInt( tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()), cleanup, ramDb); } else { try { blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromBLASTOutput( nucleotideFastaTUITFileOperator, cutoffMap, blastOutputFile, Integer.parseInt( tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()), cleanup, ramDb); } catch (JAXBException e) { Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName() + ", please check input. The file must be XML formatted."); } catch (Exception e) { e.printStackTrace(); } } } Future<?> runnableFuture = executorService.submit(blastIdentifier); runnableFuture.get(); executorService.shutdown(); } } catch (ParseException pe) { Log.getInstance().log(Level.SEVERE, (pe.getMessage())); formatter.printHelp("tuit", options); } catch (SAXException saxe) { Log.getInstance().log(Level.SEVERE, saxe.getMessage()); } catch (FileNotFoundException fnfe) { Log.getInstance().log(Level.SEVERE, fnfe.getMessage()); } catch (TUITPropertyBadFormatException tpbfe) { Log.getInstance().log(Level.SEVERE, tpbfe.getMessage()); } catch (ClassCastException cce) { Log.getInstance().log(Level.SEVERE, cce.getMessage()); } catch (JAXBException jaxbee) { Log.getInstance().log(Level.SEVERE, "The properties file is not well formatted. Please ensure that the XML is consistent with the io.properties.dtd schema."); } catch (ClassNotFoundException cnfe) { //Probably won't happen unless the library deleted from the .jar Log.getInstance().log(Level.SEVERE, cnfe.getMessage()); //cnfe.printStackTrace(); } catch (SQLException sqle) { Log.getInstance().log(Level.SEVERE, "A database communication error occurred with the following message:\n" + sqle.getMessage()); //sqle.printStackTrace(); if (sqle.getMessage().contains("Access denied for user")) { Log.getInstance().log(Level.SEVERE, "Please use standard database login: " + NCBITablesDeployer.login + " and password: " + NCBITablesDeployer.password); } } catch (Exception e) { Log.getInstance().log(Level.SEVERE, e.getMessage()); e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException sqle) { Log.getInstance().log(Level.SEVERE, "Problem closing the database connection: " + sqle); } } Log.getInstance().log(Level.FINE, "Task done, exiting..."); } }
From source file:edu.upenn.ircs.lignos.morsel.MorphLearner.java
/** * Call the learner on the specified arguments. Exit using standard error codes * (sysexits.h) if an error is encountered. * @param args command line arguments//from w ww . j ava 2s . c o m */ public static void main(String[] args) { // create the command line parser CommandLineParser parser = new PosixParser(); // Set up command line arguments Options options = new Options(); options.addOption(new Option("h", "help", false, "dislay this help and exit")); Option encodingOption = new Option("e", "encoding", true, "input and output file encoding. Defaults to ISO8859_1."); encodingOption.setArgName("encoding"); options.addOption(encodingOption); options.addOption(new Option("b", "base-inf", false, "output the examples of base inference. This does not change whether base inference" + " is used; it simply outputs the examples that used it.")); options.addOption(new Option("s", "conflation-sets", false, "output the learner's conflation sets")); options.addOption(new Option("c", "compounds", false, "output the learner's analsyis before final compounding is used")); HelpFormatter formatter = new HelpFormatter(); String usage = "MorphLearner [options] wordlist outfile logfile paramfile"; CommandLine line = null; String[] otherArgs = null; try { // Parse the command line arguments line = parser.parse(options, args); otherArgs = line.getArgs(); // Handle help if (line.hasOption("help")) { formatter.printHelp(usage, options); System.exit(0); } if (otherArgs.length != 4) { throw new ParseException("Incorrect number of required arguments specified"); } } catch (ParseException exp) { System.out.println(exp.getMessage()); formatter.printHelp(usage, options); System.exit(64); } // Get options String encoding = line.getOptionValue("encoding", "ISO8859_1"); boolean outputBaseInf = line.hasOption("base-inf"); boolean outputConflation = line.hasOption("conflation-sets"); boolean outputCompounds = line.hasOption("compounds"); // Setup timing long start; float elapsedSeconds; start = System.currentTimeMillis(); // Initialize the learner MorphLearner learner = null; try { learner = new MorphLearner(otherArgs[0], otherArgs[1], otherArgs[2], otherArgs[3], encoding, outputBaseInf, outputConflation, outputCompounds); } catch (FileNotFoundException e) { System.err.println(e.getMessage()); System.exit(66); } catch (UnsupportedEncodingException e) { System.err.println("Unsupported file encoding: " + encoding); System.exit(74); } // Output time stats elapsedSeconds = (System.currentTimeMillis() - start) / 1000F; System.out.println("Init time: " + elapsedSeconds + "s\n"); // Time learning start = System.currentTimeMillis(); learner.learn(); learner.cleanUp(); // Output time stats elapsedSeconds = (System.currentTimeMillis() - start) / 1000F; System.out.println("\nLearning time: " + elapsedSeconds + "s"); }
From source file:com.minoritycode.Application.java
public static void main(String[] args) { System.out.println("Trello Backup Application"); File configFile = new File(workingDir + "\\config.properties"); InputStream input = null;//from w w w . j av a 2 s . co m try { input = new FileInputStream(configFile); config.load(input); input.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // String workingDir = System.getProperty("user.dir"); manualOperation = Boolean.parseBoolean(config.getProperty("manualOperation")); logger.startErrorLogger(); setBackupDir(); try { report.put("backupDate", backupDate); } catch (JSONException e) { e.printStackTrace(); logger.logLine(e.getMessage()); } lock = new ReentrantLock(); lockErrorRep = new ReentrantLock(); lockErrorLog = new ReentrantLock(); Application.key = config.getProperty("trellokey"); Application.token = config.getProperty("trellotoken"); boolean useProxy = Boolean.parseBoolean(config.getProperty("useProxy")); boolean proxySet = true; if (useProxy) { proxySet = setProxy(); } // GUI swingContainerDemo = new GUI(); // swingContainerDemo.showJPanelDemo(); if (proxySet) { Credentials credentials = new Credentials(); if (Application.key.isEmpty()) { Application.key = credentials.getKey(); } else { Application.key = config.getProperty("trellokey"); } if (token.isEmpty()) { Application.token = credentials.getToken(); } else { Application.token = config.getProperty("trellotoken"); } BoardDownloader downloader = new BoardDownloader(); downloader.downloadMyBoard(url); boards = downloader.downloadOrgBoard(url); if (boards != null) { try { report.put("boardNum", boards.size()); } catch (JSONException e) { e.printStackTrace(); logger.logLine(e.getMessage()); } Integer numberOfThreads = Integer.parseInt(config.getProperty("numberOfThreads")); if (numberOfThreads == null) { logger.logLine("error number of threads not set in config file"); if (manualOperation) { String message = "How many threads do you want to use (10) is average"; numberOfThreads = Integer.parseInt(Credentials.getInput(message)); Credentials.saveProperty("numberOfThreads", numberOfThreads.toString()); } else { if (Boolean.parseBoolean(config.getProperty("useMailer"))) { Mailer mailer = new Mailer(); mailer.SendMail(); } System.exit(-1); } } ArrayList<Thread> threadList = new ArrayList<Thread>(); for (int i = 0; i < numberOfThreads; i++) { Thread thread = new Thread(new Application(), "BoardDownloadThread"); threadList.add(thread); thread.start(); } } else { //create empty report try { report.put("boardsNotDownloaded", "99999"); report.put("boardNum", 0); report.put("boardNumSuccessful", 0); } catch (JSONException e) { e.printStackTrace(); logger.logLine(e.getMessage()); } if (Boolean.parseBoolean(config.getProperty("useMailer"))) { Mailer mailer = new Mailer(); mailer.SendMail(); } logger.logger(report); } } else { //create empty report try { report.put("boardsNotDownloaded", "99999"); report.put("boardNum", 0); report.put("boardNumSuccessful", 0); } catch (JSONException e) { e.printStackTrace(); logger.logLine(e.getMessage()); } if (Boolean.parseBoolean(config.getProperty("useMailer"))) { Mailer mailer = new Mailer(); mailer.SendMail(); } } }
From source file:net.mybox.mybox.ClientStatus.java
/** * Handle the command line args and instantiate the Client * @param args// ww w .jav a 2 s .co m */ public static void main(String args[]) { Options options = new Options(); options.addOption("c", "config", true, "configuration directory (default=~/.mybox)"); options.addOption("a", "apphome", true, "application home directory"); options.addOption("h", "help", false, "show help screen"); options.addOption("V", "version", false, "print the Mybox version"); CommandLineParser line = new GnuParser(); CommandLine cmd = null; String configDir = defaultConfigDir; try { cmd = line.parse(options, args); } catch (Exception exp) { System.err.println(exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(Client.class.getName(), options); return; } if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(Client.class.getName(), options); return; } if (cmd.hasOption("V")) { Client.printMessage("version " + Common.appVersion); return; } if (cmd.hasOption("a")) { String appHomeDir = cmd.getOptionValue("a"); try { Common.updatePaths(appHomeDir); } catch (FileNotFoundException e) { printErrorExit(e.getMessage()); } updatePaths(); } if (cmd.hasOption("c")) { configDir = cmd.getOptionValue("c"); } setConfigDir(configDir); File fileCheck = new File(configFile); if (!fileCheck.isFile()) System.err.println("Config file does not exist: " + configFile); Client client = new Client(); client.Config(configFile); client.start(); }
From source file:fi.hoski.remote.ui.Admin.java
/** * @param args the command line arguments *//*from ww w. j av a 2 s . c o m*/ public static void main(String[] args) { try { Properties properties = new Properties(); if (args.length != 0) { try (InputStream pFile = new FileInputStream(args[0])) { properties.load(pFile); } catch (FileNotFoundException ex) { } } ServerProperties sp = new ServerProperties(properties); DataObjectDialog<ServerProperties> dod = new DataObjectDialog<>(null, sp.getModel().hide( ServerProperties.Tables, ServerProperties.SupportsZonerSMS, ServerProperties.SuperUser), sp); if (dod.edit()) { String[] server = sp.getServer().split(","); RemoteAppEngine.init(server[0], sp.getUsername(), sp.getPassword()); DataStoreProxy dsp = new DataStoreProxy(properties); dsp.start(); Admin r = new Admin(sp); } else { System.exit(0); } } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, ex.getMessage()); } }
From source file:com.muni.fi.pa165.survive.rest.client.SurviveRESTClient.java
public static void main(String[] args) { File file = new File("err.txt"); FileOutputStream fos = null;// ww w. j a va 2 s . c o m try { fos = new FileOutputStream(file); } catch (FileNotFoundException ex) { Logger.getLogger(SurviveRESTClient.class.getName()).log(Level.SEVERE, null, ex); } PrintStream ps = new PrintStream(fos); System.setErr(ps); CommandLineParser parser = new PosixParser(); Options options = OptionsProvider.getInstance().getOptions(); try { CommandLine line = parser.parse(options, args); List<String> validate = CommandLineValidator.validate(line); if (!validate.isEmpty()) { System.out.println("The following errors occured when parsing the command:"); for (String string : validate) { System.out.println(string); } System.out.println(""); printHelp(options); System.exit(1); } if (line.hasOption("h")) { printHelp(options); System.exit(0); } CustomRestService crudService; String operation = line.getOptionValue("o"); // weapon mode if (line.hasOption("w")) { crudService = new WeaponServiceImpl(); switch (operation) { case "C": { WeaponDto dto = DtoBuilder.getWeaponDto(line); Object byId = crudService.create(dto); printEntity(crudService.getResponse(), "Creating a weapon", byId); break; } case "R": { Long id = Long.parseLong(line.getOptionValue("i")); Object byId = crudService.getById(id); printEntity(crudService.getResponse(), "Reading a weapon with id " + id, byId); break; } case "U": { WeaponDto dto = DtoBuilder.getWeaponDto(line); Object byId = crudService.update(dto); printEntity(crudService.getResponse(), "Updating a weapon with id " + line.getOptionValue("i"), byId); break; } case "D": { Long id = Long.parseLong(line.getOptionValue("i")); Response delete = crudService.delete(id); printEntity(crudService.getResponse(), "Deleting a weapon with id " + line.getOptionValue("i"), crudService.getResponse().getStatusInfo()); break; } case "A": List<AbstractDto> all = crudService.getAll(); printEntities(crudService.getResponse(), "Reading all weapons", all); break; } } else if (line.hasOption("a")) { crudService = new AreaServiceImpl(); switch (operation) { case "C": { AreaDto dto = DtoBuilder.getAreaDto(line); Object byId = crudService.create(dto); printEntity(crudService.getResponse(), "Creating an area", byId); break; } case "R": { Long id = Long.parseLong(line.getOptionValue("i")); Object byId = crudService.getById(id); printEntity(crudService.getResponse(), "Reading an area with id " + id, byId); break; } case "U": { AreaDto dto = DtoBuilder.getAreaDto(line); Object byId = crudService.update(dto); printEntity(crudService.getResponse(), "Updating an area with id " + line.getOptionValue("i"), byId); break; } case "D": { Long id = Long.parseLong(line.getOptionValue("i")); Object byId = crudService.delete(id); printEntity(crudService.getResponse(), "Deleting an area with id " + line.getOptionValue("i"), crudService.getResponse().getStatusInfo()); break; } case "A": List<AbstractDto> all = crudService.getAll(); printEntities(crudService.getResponse(), "Reading all areas", all); break; } } else { printHelp(options); } } catch (ParseException ex) { System.out.println(ex.getMessage()); printHelp(options); System.exit(1); } catch (NumberFormatException ex) { System.out.println(ex.getMessage()); printHelp(options); System.exit(2); } catch (MessageBodyProviderNotFoundException ex) { System.out.println("Couldn't connect to the server! Please make sure that the server side is running."); System.exit(3); } catch (ProcessingException ex) { System.out.println("Couldn't connect to the server! Please make sure that the server side is running."); System.exit(4); } catch (Exception ex) { System.out.println( "There was an error when connecting to the server. Please make sure that the server side is running."); } }
From source file:ca.uqac.info.trace.execution.BabelTrace.java
/** * Main program loop// w ww.jav a 2 s . c o m * @param args */ public static void main(String[] args) { String trace_type = "", tool_name = ""; String trace_in_filename = "", formula_in_filename = ""; String out_formula = "", out_trace = "", out_signature = "", output_dir = ""; File formula_in, trace_in; trace_in = null; Operator op = null; EventTrace trace = null; boolean run_tool = false, show_command = false; // Parse command line arguments Options options = setupOptions(); CommandLine c_line = setupCommandLine(args, options); assert c_line != null; if (c_line.hasOption("version")) { System.out.println("\nBabelTrace build " + BUILD_STRING); System.out.println("(C) 2012-2013 Sylvain Hall et al., Universit du Qubec Chicoutimi"); System.out.println("This program comes with ABSOLUTELY NO WARRANTY."); System.out.println("This is a free software, and you are welcome to redistribute it"); System.out.println("under certain conditions. See the file COPYING for details.\n"); System.exit(ERR_OK); } if (c_line.hasOption("h")) { showUsage(options); System.exit(ERR_OK); } if (c_line.hasOption("t")) trace_in_filename = c_line.getOptionValue("t"); else { showUsage(options); System.exit(ERR_ARGUMENTS); } if (c_line.hasOption("f")) formula_in_filename = c_line.getOptionValue("f"); else { showUsage(options); System.exit(ERR_ARGUMENTS); } if (c_line.hasOption("i")) trace_type = c_line.getOptionValue("i"); else { showUsage(options); System.exit(ERR_ARGUMENTS); } if (c_line.hasOption("c")) tool_name = c_line.getOptionValue("c"); else { showUsage(options); System.exit(ERR_ARGUMENTS); } if (c_line.hasOption("o")) output_dir = c_line.getOptionValue("o"); else { showUsage(options); System.exit(ERR_ARGUMENTS); } if (c_line.hasOption("b")) { run_tool = false; show_command = true; } if (c_line.hasOption("r")) { run_tool = true; show_command = false; } // Read input formula formula_in = new File(formula_in_filename); if (!formula_in.exists()) { System.err.println("Error reading " + formula_in_filename); System.exit(ERR_IO); } try { out_formula = ca.uqac.info.util.FileReadWrite.readFile(formula_in_filename); } catch (java.io.FileNotFoundException e) { System.err.println("File not found: " + formula_in_filename); System.exit(ERR_IO); } catch (java.io.IOException e) { System.err.println("IO Exception: " + formula_in_filename); e.printStackTrace(); System.exit(ERR_IO); } // Get trace file trace_in = new File(trace_in_filename); // Get execution Execution ex = getExecution(tool_name); // Get filenames for each part String base_filename = FileReadWrite.baseName(trace_in) + "." + FileReadWrite.baseName(formula_in); String trace_filename = output_dir + "/" + base_filename + "." + ex.getTraceExtension(); String formula_filename = output_dir + "/" + base_filename + "." + ex.getFormulaExtension(); String signature_filename = output_dir + "/" + base_filename + "." + ex.getSignatureExtension(); // Setup execution environment ex.setProperty(formula_filename); ex.setSignature(signature_filename); ex.setTrace(trace_filename); // Show command lines and leave if (show_command) { String[] cl = ex.getCommandLines(); for (String c : cl) { System.out.println(c); } System.exit(ERR_OK); } // Initialize the translator Translator tt = getTraceTranslator(tool_name); if (tt == null) { System.err.println("Error: unrecognized conversion format \"" + tool_name + "\""); System.exit(ERR_NO_SUCH_TOOL); } tt.setTrace(trace); // Parse the trace TraceReader t_read = getTraceReader(trace_type); try { trace = t_read.parseEventTrace(new FileInputStream(trace_in)); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(ERR_IO); } // Get the formula as an operator try { op = Operator.parseFromString(out_formula); } catch (ParseException e) { System.err.println("Error parsing the input formula"); System.exit(ERR_PARSE); } assert op != null; // Does the formula require flat messages and formulas? if (tt.requiresFlat()) { // Convert the first-order formula to a propositional one FlatTranslator pt = new FlatTranslator(); pt.setFormula(op); pt.setTrace(trace); // Flatten the trace String tr_trans = pt.translateTrace(); TraceReader xtr = new XmlTraceReader(); trace = xtr.parseEventTrace(new ByteArrayInputStream(tr_trans.getBytes())); // Flatten the formula String op_trans = pt.translateFormula(); try { op = Operator.parseFromString(op_trans); } catch (ParseException e) { System.err.println("Error parsing the formula once translated to propositional"); System.exit(ERR_PARSE); } } // Is the formula first-order while the tool requires propositional? if (tt.requiresPropositional() && FirstOrderDetector.isFirstOrder(op)) { // Convert the first-order formula to a propositional one PropositionalTranslator pt = new PropositionalTranslator(); pt.setFormula(op); pt.setTrace(trace); String op_trans = pt.translateFormula(); try { op = Operator.parseFromString(op_trans); } catch (ParseException e) { System.err.println("Error parsing the formula once translated to propositional"); System.exit(ERR_PARSE); } // We also convert equalities between constants produced by the translator // into Booleans ConstantConverter cc = new ConstantConverter(); op.accept(cc); op = cc.getFormula(); // And then propagate those constants UnitPropagator up = new UnitPropagator(); op.accept(up); op = up.getFormula(); } // Convert tt.setTrace(trace); tt.setFormula(op); tt.translateAll(); out_trace = tt.getTraceFile(); out_formula = tt.getFormulaFile(); out_signature = tt.getSignatureFile(); // Save conversions to files try { if (!out_trace.isEmpty()) { ca.uqac.info.util.FileReadWrite.writeToFile(trace_filename, out_trace); } if (!out_formula.isEmpty()) { ca.uqac.info.util.FileReadWrite.writeToFile(formula_filename, out_formula); } if (!out_signature.isEmpty()) { ca.uqac.info.util.FileReadWrite.writeToFile(signature_filename, out_signature); } } catch (java.io.IOException e) { System.err.println("Error writing to file"); System.err.println(e.getMessage()); System.exit(ERR_IO); } // Now that all conversions have been made, run the tool if (run_tool) { try { ex.run(); } catch (Execution.CommandLineException e) { System.err.println("Error running command"); System.exit(ERR_TOOL_EXECUTION); } // Print results ReturnVerdict ex_retval = ex.getReturnVerdict(); float ex_time = (float) ex.getTime() / (float) 1000000000; // We show seconds, not s float ex_memory = (float) ex.getMemory() / (float) 1024; // We show megabytes, not bytes System.out.printf("%s,%.2f,%.2f\n", ex_retval, ex_time, ex_memory); // If an error occurred, dump it if (ex_retval == ReturnVerdict.ERROR) { System.err.println("Error while executing " + tool_name); System.err.println("Command line(s):"); for (String cl : ex.getCommandLines()) { System.err.println(cl); } System.err.println("Below is the string returned by the tool\n"); System.err.println(ex.getErrorString()); System.exit(ERR_TOOL_EXECUTION); } } // Quit System.exit(ERR_OK); }
From source file:Main.java
public static String getCrop(Activity activity, String name) { Bitmap bmp = getCrop(activity);//w w w . j a va 2 s . c om File file = new File(activity.getFilesDir(), name); FileOutputStream fileOutput = null; try { fileOutput = new FileOutputStream(file); } catch (FileNotFoundException e) { Log.e("golfpad", e.getMessage()); } bmp.compress(CompressFormat.JPEG, 50, fileOutput); return file.getAbsolutePath(); }