List of usage examples for java.lang ClassNotFoundException getMessage
public String getMessage()
From source file:net.jradius.server.Main.java
public static void main(String[] args) { if (args.length != 1) { showUsage();//w w w . j a v a2 s .co m System.exit(1); } /** * CADBiS daemon run * ---> */ if (JRadiusConfigurator.getInstance().getProperty("cadbis_daemon").equals("enabled")) CADBiS.getInstance().start(); /** * <--- eof CADBiS */ String configFilePath = args[0]; try { File file = new File(configFilePath); Configuration.initialize(file); JRadiusServer server = new JRadiusServer(); server.start(); } catch (FileNotFoundException e) { System.err.println("Error: The configuration file '" + configFilePath + "' does not exist."); } catch (ConfigurationException e1) { System.err.println("Error: The configuration file could not be read," + " because the file contains an error: " + e1.getMessage()); showStackTrace(e1); } catch (SecurityException e2) { System.err.println("Error: The configuration file could not be read," + " because a security error occurred: " + e2.getMessage()); showStackTrace(e2); } catch (IllegalArgumentException e3) { System.err.println("Error: The configuration file could not be read," + " because an illegal argument error occurred: " + e3.getMessage()); showStackTrace(e3); } catch (ClassNotFoundException e4) { System.err.println("Error: The configuration file could not be read," + " because a class specified in the configuration file could not be found: " + e4.getMessage()); showStackTrace(e4); } catch (NoSuchMethodException e5) { System.err.println("Error: The configuration file could not be read," + " because a method does not exist in a class specified in the configuration file: " + e5.getMessage()); showStackTrace(e5); } catch (InstantiationException e6) { System.err.println("Error: The configuration file could not be read," + " because an object specified in the configuration file could not be instantiated: " + e6.getMessage()); showStackTrace(e6); } catch (IllegalAccessException e7) { System.err.println("Error: The configuration file could not be read," + " because an illegal access error occurred: " + e7.getMessage()); showStackTrace(e7); } catch (InvocationTargetException e8) { System.err.println("Error: The configuration file could not be read," + " because an invocation target exception was thrown: " + e8.getMessage()); showStackTrace(e8); } catch (Exception e) { e.printStackTrace(); } return; }
From source file:Logging.java
public static void main(String args[]) throws Exception { FileOutputStream errors = new FileOutputStream("StdErr.txt", true); PrintStream stderr = new PrintStream(errors); PrintWriter errLog = new PrintWriter(errors, true); System.setErr(stderr);/*from w w w.j a va 2 s . c om*/ String query = "SELECT Name,Description,Qty,Cost,Sell_Price FROM Stock"; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:Inventory"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String name = rs.getString("Name"); String desc = rs.getString("Description"); int qty = rs.getInt("Qty"); float cost = rs.getFloat("Cost"); } } catch (ClassNotFoundException e) { e.printStackTrace(errLog); } catch (SQLException e) { System.err.println((new GregorianCalendar()).getTime()); System.err.println("Thread: " + Thread.currentThread()); System.err.println("ErrorCode: " + e.getErrorCode()); System.err.println("SQLState: " + e.getSQLState()); System.err.println("Message: " + e.getMessage()); System.err.println("NextException: " + e.getNextException()); e.printStackTrace(errLog); System.err.println(); } stderr.close(); }
From source file:it.imtech.configuration.StartWizard.java
public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override//from w ww. j av a2 s . c o m public void run() { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager .getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { logger.error(ex.getMessage()); } catch (InstantiationException ex) { logger.error(ex.getMessage()); } catch (IllegalAccessException ex) { logger.error(ex.getMessage()); } catch (javax.swing.UnsupportedLookAndFeelException ex) { logger.error(ex.getMessage()); } StartWizard.getInstance(); } }); }
From source file:CreateNewType.java
public static void main(String[] args) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;/* w ww . ja v a 2 s . co m*/ Statement stmt; try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(); String typeToCreate = null; String prompt = "Enter 's' to create a structured type " + "or 'd' to create a distinct type\n" + "and hit Return: "; do { typeToCreate = getInput(prompt) + " "; typeToCreate = typeToCreate.toLowerCase().substring(0, 1); } while (!(typeToCreate.equals("s") || typeToCreate.equals("d"))); Vector dataTypes = getDataTypes(con, typeToCreate); String typeName; String attributeName; String sqlType; prompt = "Enter the new type name and hit Return: "; typeName = getInput(prompt); String createTypeString = "create type " + typeName; if (typeToCreate.equals("d")) createTypeString += " as "; else createTypeString += " ("; String commaAndSpace = ", "; boolean firstTime = true; while (true) { System.out.println(""); prompt = "Enter an attribute name " + "(or nothing when finished) \nand hit Return: "; attributeName = getInput(prompt); if (firstTime) { if (attributeName.length() == 0) { System.out.print("Need at least one attribute;"); System.out.println(" please try again"); continue; } else { createTypeString += attributeName + " "; firstTime = false; } } else if (attributeName.length() == 0) { break; } else { createTypeString += commaAndSpace + attributeName + " "; } String localTypeName = null; String paramString = ""; while (true) { System.out.println(""); System.out.println("LIST OF TYPES YOU MAY USE: "); boolean firstPrinted = true; int length = 0; for (int i = 0; i < dataTypes.size(); i++) { DataType dataType = (DataType) dataTypes.get(i); if (!dataType.needsToBeSet()) { if (!firstPrinted) System.out.print(commaAndSpace); else firstPrinted = false; System.out.print(dataType.getSQLType()); length += dataType.getSQLType().length(); if (length > 50) { System.out.println(""); length = 0; firstPrinted = true; } } } System.out.println(""); int index; prompt = "Enter an attribute type " + "from the list and hit Return: "; sqlType = getInput(prompt); for (index = 0; index < dataTypes.size(); index++) { DataType dataType = (DataType) dataTypes.get(index); if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) { break; } } localTypeName = null; paramString = ""; if (index < dataTypes.size()) { // there was a match String params; DataType dataType = (DataType) dataTypes.get(index); params = dataType.getParams(); localTypeName = dataType.getLocalType(); if (params != null) { prompt = "Enter " + params + ": "; paramString = "(" + getInput(prompt) + ")"; } break; } else { // use the name as given prompt = "Are you sure? " + "Enter 'y' or 'n' and hit Return: "; String check = getInput(prompt) + " "; check = check.toLowerCase().substring(0, 1); if (check.equals("n")) continue; else { localTypeName = sqlType; break; } } } createTypeString += localTypeName + paramString; if (typeToCreate.equals("d")) break; } if (typeToCreate.equals("s")) createTypeString += ")"; System.out.println(""); System.out.print("Your CREATE TYPE statement as "); System.out.println("sent to your DBMS: "); System.out.println(createTypeString); System.out.println(""); stmt.executeUpdate(createTypeString); stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }
From source file:Main.java
public static void main(String[] args) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;/*w ww. j a v a 2 s .co m*/ Statement stmt; try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(); Vector dataTypes = getDataTypes(con); String tableName; String columnName; String sqlType; String prompt = "Enter the new table name and hit Return: "; tableName = getInput(prompt); String createTableString = "create table " + tableName + " ("; String commaAndSpace = ", "; boolean firstTime = true; while (true) { System.out.println(""); prompt = "Enter a column name " + "(or nothing when finished) \nand hit Return: "; columnName = getInput(prompt); if (firstTime) { if (columnName.length() == 0) { System.out.print("Need at least one column;"); System.out.println(" please try again"); continue; } else { createTableString += columnName + " "; firstTime = false; } } else if (columnName.length() == 0) { break; } else { createTableString += commaAndSpace + columnName + " "; } String localTypeName = null; String paramString = ""; while (true) { System.out.println(""); System.out.println("LIST OF TYPES YOU MAY USE: "); boolean firstPrinted = true; int length = 0; for (int i = 0; i < dataTypes.size(); i++) { DataType dataType = (DataType) dataTypes.get(i); if (!dataType.needsToBeSet()) { if (!firstPrinted) System.out.print(commaAndSpace); else firstPrinted = false; System.out.print(dataType.getSQLType()); length += dataType.getSQLType().length(); if (length > 50) { System.out.println(""); length = 0; firstPrinted = true; } } } System.out.println(""); int index; prompt = "Enter a column type " + "from the list and hit Return: "; sqlType = getInput(prompt); for (index = 0; index < dataTypes.size(); index++) { DataType dataType = (DataType) dataTypes.get(index); if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) { break; } } localTypeName = null; paramString = ""; if (index < dataTypes.size()) { // there was a match String params; DataType dataType = (DataType) dataTypes.get(index); params = dataType.getParams(); localTypeName = dataType.getLocalType(); if (params != null) { prompt = "Enter " + params + ": "; paramString = "(" + getInput(prompt) + ")"; } break; } else { // use the name as given prompt = "Are you sure? " + "Enter 'y' or 'n' and hit Return: "; String check = getInput(prompt) + " "; check = check.toLowerCase().substring(0, 1); if (check.equals("n")) continue; else { localTypeName = sqlType; break; } } } createTableString += localTypeName + paramString; } createTableString += ")"; System.out.println(""); System.out.print("Your CREATE TABLE statement as "); System.out.println("sent to your DBMS: "); System.out.println(createTableString); System.out.println(""); stmt.executeUpdate(createTableString); stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }
From source file:TestClassForNameApp.java
public static void main(String args[]) { try {/*from w w w . j a va2 s.co m*/ Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { System.out.println("Oops! Can't find class oracle.jdbc.driver.OracleDriver"); System.exit(1); } Connection conn = null; Statement stmt = null; ResultSet rset = null; try { conn = DriverManager.getConnection("jdbc:oracle:thin:@dssw2k01:1521:orcl", "scott", "tiger"); stmt = conn.createStatement(); rset = stmt.executeQuery("select 'Hello '||USER||'!' result from dual"); while (rset.next()) System.out.println(rset.getString(1)); rset.close(); rset = null; stmt.close(); stmt = null; conn.close(); conn = null; } catch (SQLException e) { System.out.println("Darn! A SQL error: " + e.getMessage()); } finally { if (rset != null) try { rset.close(); } catch (SQLException ignore) { } if (stmt != null) try { stmt.close(); } catch (SQLException ignore) { } if (conn != null) try { conn.close(); } catch (SQLException ignore) { } } }
From source file:net.sf.joost.Main.java
/** * Entry point/*from ww w . j ava2 s .co m*/ * @param args array of strings containing the parameter for Joost and * at least two URLs addressing xml-source and stx-sheet */ public static void main(String[] args) { // input filename String xmlFile = null; // the currently last processor (as XMLFilter) Processor processor = null; // output filename (optional) String outFile = null; // custom message emitter class name (optional) String meClassname = null; // log4j properties filename (optional) String log4jProperties = null; // log4j message level (this is an object of the class Level) Level log4jLevel = null; // set to true if a command line parameter was wrong boolean wrongParameter = false; // set to true if -help was specified on the command line boolean printHelp = false; // set to true if -pdf was specified on the command line boolean doFOP = false; // set to true if -nodecl was specified on the command line boolean nodecl = false; // set to true if -noext was specified on the command line boolean noext = false; // set to true if -doe was specified on the command line boolean doe = false; // debugging boolean dontexit = false; // timings boolean measureTime = false; long timeStart = 0, timeEnd = 0; // needed for evaluating parameter assignments int index; // serializer SAX -> XML text StreamEmitter emitter = null; // filenames for the usage and version info final String USAGE = "usage.txt", VERSION = "version.txt"; try { // parse command line argument list for (int i = 0; i < args.length; i++) { if (args[i].trim().length() == 0) { // empty parameter? ingore } // all options start with a '-', but a single '-' means stdin else if (args[i].charAt(0) == '-' && args[i].length() > 1) { if ("-help".equals(args[i])) { printHelp = true; continue; } else if ("-version".equals(args[i])) { printResource(VERSION); logInfoAndExit(); } else if ("-pdf".equals(args[i])) { doFOP = true; continue; } else if ("-nodecl".equals(args[i])) { nodecl = true; continue; } else if ("-noext".equals(args[i])) { noext = true; continue; } else if ("-doe".equals(args[i])) { doe = true; continue; } else if ("-wait".equals(args[i])) { dontexit = true; // undocumented continue; } else if ("-time".equals(args[i])) { measureTime = true; continue; } else if ("-o".equals(args[i])) { // this option needs a parameter if (++i < args.length && args[i].charAt(0) != '-') { if (outFile != null) { System.err.println("Option -o already specified with " + outFile); wrongParameter = true; } else outFile = args[i]; continue; } else { if (outFile != null) System.err.println("Option -o already specified with " + outFile); else System.err.println("Option -o requires a filename"); i--; wrongParameter = true; } } else if ("-m".equals(args[i])) { // this option needs a parameter if (++i < args.length && args[i].charAt(0) != '-') { if (meClassname != null) { System.err.println("Option -m already specified with " + meClassname); wrongParameter = true; } else meClassname = args[i]; continue; } else { if (meClassname != null) System.err.println("Option -m already specified with " + meClassname); else System.err.println("Option -m requires a classname"); i--; wrongParameter = true; } } else if (DEBUG && "-log-properties".equals(args[i])) { // this option needs a parameter if (++i < args.length && args[i].charAt(0) != '-') { log4jProperties = args[i]; continue; } else { System.err.println("Option -log-properties requires " + "a filename"); wrongParameter = true; } } else if (DEBUG && "-log-level".equals(args[i])) { // this option needs a parameter if (++i < args.length && args[i].charAt(0) != '-') { if ("off".equals(args[i])) { log4jLevel = Level.OFF; continue; } else if ("debug".equals(args[i])) { log4jLevel = Level.DEBUG; continue; } else if ("info".equals(args[i])) { log4jLevel = Level.INFO; continue; } else if ("warn".equals(args[i])) { log4jLevel = Level.WARN; continue; } else if ("error".equals(args[i])) { log4jLevel = Level.ERROR; continue; } else if ("fatal".equals(args[i])) { log4jLevel = Level.FATAL; continue; } else if ("all".equals(args[i])) { log4jLevel = Level.ALL; continue; } else { System.err.println("Unknown parameter for -log-level: " + args[i]); wrongParameter = true; continue; } } else { System.err.println("Option -log-level requires a " + "parameter"); wrongParameter = true; } } else { System.err.println("Unknown option " + args[i]); wrongParameter = true; } } // command line argument is not an option with a leading '-' else if ((index = args[i].indexOf('=')) != -1) { // parameter assignment if (processor != null) processor.setParameter(args[i].substring(0, index), args[i].substring(index + 1)); else { System.err.println("Assignment " + args[i] + " must follow an stx-sheet parameter"); wrongParameter = true; } continue; } else if (xmlFile == null) { xmlFile = args[i]; continue; } else { // xmlFile != null, i.e. this is an STX sheet ParseContext pContext = new ParseContext(); pContext.allowExternalFunctions = !noext; if (measureTime) timeStart = System.currentTimeMillis(); Processor proc = new Processor(new InputSource(args[i]), pContext); if (nodecl) proc.outputProperties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); if (measureTime) { timeEnd = System.currentTimeMillis(); System.err.println("Parsing " + args[i] + ": " + (timeEnd - timeStart) + " ms"); } if (processor != null) proc.setParent(processor); // XMLFilter chain processor = proc; } } // PDF creation requested if (doFOP && outFile == null) { System.err.println("Option -pdf requires option -o"); wrongParameter = true; } // missing filenames if (!printHelp && processor == null) { if (xmlFile == null) System.err.println("Missing filenames for XML source and " + "STX transformation sheet"); else System.err.println("Missing filename for STX transformation " + "sheet"); wrongParameter = true; } if (meClassname != null && !wrongParameter) { // create object StxEmitter messageEmitter = null; try { messageEmitter = (StxEmitter) Class.forName(meClassname).newInstance(); } catch (ClassNotFoundException ex) { System.err.println("Class not found: " + ex.getMessage()); wrongParameter = true; } catch (InstantiationException ex) { System.err.println("Instantiation failed: " + ex.getMessage()); wrongParameter = true; } catch (IllegalAccessException ex) { System.err.println("Illegal access: " + ex.getMessage()); wrongParameter = true; } catch (ClassCastException ex) { System.err.println( "Wrong message emitter: " + meClassname + " doesn't implement the " + StxEmitter.class); wrongParameter = true; } if (messageEmitter != null) { // i.e. no exception occurred // set message emitter for all processors in the filter chain Processor p = processor; do { p.setMessageEmitter(messageEmitter); Object o = p.getParent(); if (o instanceof Processor) p = (Processor) o; else p = null; } while (p != null); } } if (printHelp) { printResource(VERSION); printResource(USAGE); logInfoAndExit(); } if (wrongParameter) { System.err.println("Specify -help to get a detailed help message"); System.exit(1); } if (DEBUG) { // use specified log4j properties file if (log4jProperties != null) PropertyConfigurator.configure(log4jProperties); // set log level specified on the the command line if (log4jLevel != null) Logger.getRootLogger().setLevel(log4jLevel); } // The first processor re-uses its XMLReader for parsing the input // xmlFile. // For a real XMLFilter usage you have to call // processor.setParent(yourXMLReader) // Connect a SAX consumer if (doFOP) { // pass output events to FOP // // Version 1: use a FOPEmitter object as XMLFilter // processor.setContentHandler( // new FOPEmitter( // new java.io.FileOutputStream(outFile))); // Version 2: use a static method to retrieve FOP's content // handler and use it directly processor.setContentHandler(FOPEmitter.getFOPContentHandler(new java.io.FileOutputStream(outFile))); } else { // Create XML output if (outFile != null) { emitter = StreamEmitter.newEmitter(outFile, processor.outputProperties); emitter.setSystemId(new File(outFile).toURI().toString()); } else emitter = StreamEmitter.newEmitter(System.out, processor.outputProperties); processor.setContentHandler(emitter); processor.setLexicalHandler(emitter); // the previous line is a short-cut for // processor.setProperty( // "http://xml.org/sax/properties/lexical-handler", emitter); emitter.setSupportDisableOutputEscaping(doe); } InputSource is; if (xmlFile.equals("-")) { is = new InputSource(System.in); is.setSystemId("<stdin>"); is.setPublicId(""); } else is = new InputSource(xmlFile); // Ready for take-off if (measureTime) timeStart = System.currentTimeMillis(); processor.parse(is); if (measureTime) { timeEnd = System.currentTimeMillis(); System.err.println("Processing " + xmlFile + ": " + (timeEnd - timeStart) + " ms"); } // // check if the Processor copy constructor works // Processor pr = new Processor(processor); // java.util.Properties props = new java.util.Properties(); // props.put("encoding", "ISO-8859-2"); // StreamEmitter em = // StreamEmitter.newEmitter(System.err, props); // pr.setContentHandler(em); // pr.setLexicalHandler(em); // pr.parse(is); // // end check // this is for debugging with the Java Memory Profiler if (dontexit) { System.err.println("Press Enter to exit"); System.in.read(); } } catch (java.io.IOException ex) { System.err.println(ex.toString()); System.exit(1); } catch (SAXException ex) { if (emitter != null) { try { // flushes the internal BufferedWriter, i.e. outputs // the intermediate result emitter.endDocument(); } catch (SAXException exx) { // ignore } } Exception embedded = ex.getException(); if (embedded != null) { if (embedded instanceof TransformerException) { TransformerException te = (TransformerException) embedded; SourceLocator sl = te.getLocator(); String systemId; // ensure that systemId is not null; is this a bug? if (sl != null && (systemId = sl.getSystemId()) != null) { // remove the "file://" scheme prefix if it is present if (systemId.startsWith("file://")) systemId = systemId.substring(7); else if (systemId.startsWith("file:")) // bug in JDK 1.4 / Crimson? (see rfc1738) systemId = systemId.substring(5); System.err.println(systemId + ":" + sl.getLineNumber() + ":" + sl.getColumnNumber() + ": " + te.getMessage()); } else System.err.println(te.getMessage()); } else { // Fatal: this mustn't happen embedded.printStackTrace(System.err); } } else System.err.println(ex.toString()); System.exit(1); } }
From source file:ca.nines.ise.Main.java
/** * Entry point for the application. Catches all exceptions. * * @param args command line arguments.//from ww w. ja v a 2 s. c o m */ public static void main(String[] args) { String version = "unknown"; try { if (args.length == 0) { args = new String[] { "help" }; } version = version(); execute(args); } catch (ClassNotFoundException ex) { System.err.println("Cannot find command class " + args[0]); System.err.println("iTools version " + version); ex.printStackTrace(System.err); } catch (IllegalAccessException ex) { System.err.println("Cannot access command class " + args[0]); System.err.println("iTools version " + version); ex.printStackTrace(System.err); } catch (InstantiationException ex) { System.err.println("Cannot create command class " + args[0]); System.err.println("iTools version " + version); ex.printStackTrace(System.err); } catch (ParseException ex) { System.err.println("Cannot parse command line arguments " + args[0]); System.err.println(ex.getMessage()); System.err.println("iTools version " + version); ex.printStackTrace(System.err); } catch (IOException ex) { System.err.println("I/O error " + args[0]); System.err.println("iTools version " + version); ex.printStackTrace(System.err); } catch (Exception ex) { System.err.println("Internal error " + args[0]); System.err.println("iTools version " + version); ex.printStackTrace(System.err); } }
From source file:com.codejumble.opentube.Main.java
/** * Starts the program off./* w w w.j av a 2s .com*/ * * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { logger.error("Java error with text {}", ex.getMessage()); } catch (InstantiationException ex) { logger.error("Java error with text {}", ex.getMessage()); } catch (IllegalAccessException ex) { logger.error("Java error with text {}", ex.getMessage()); } catch (javax.swing.UnsupportedLookAndFeelException ex) { logger.error("Java error with text {}", ex.getMessage()); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { logger.info("Starting the main frame"); new Main().setVisible(true); } }); }
From source file:tuit.java
@SuppressWarnings("ConstantConditions") public static void main(String[] args) { System.out.println(licence);//from w w w.j a va 2 s. c o 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..."); } }