List of usage examples for java.io File getAbsolutePath
public String getAbsolutePath()
From source file:edu.harvard.hul.ois.drs.pdfaconvert.PdfaConvert.java
public static void main(String[] args) throws IOException { if (logger == null) { System.out.println("About to initialize Log4j"); logger = LogManager.getLogger(); System.out.println("Finished initializing Log4j"); }//from w w w . j a v a 2 s . c o m logger.debug("Entering main()"); // WIP: the following command line code was pulled from FITS Options options = new Options(); Option inputFileOption = new Option(PARAM_I, true, "input file"); options.addOption(inputFileOption); options.addOption(PARAM_V, false, "print version information"); options.addOption(PARAM_H, false, "help information"); options.addOption(PARAM_O, true, "output sub-directory"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args, true); } catch (ParseException e) { System.err.println(e.getMessage()); System.exit(1); } // print version info if (cmd.hasOption(PARAM_V)) { if (StringUtils.isEmpty(applicationVersion)) { applicationVersion = "<not set>"; System.exit(1); } System.out.println("Version: " + applicationVersion); System.exit(0); } // print help info if (cmd.hasOption(PARAM_H)) { displayHelp(); System.exit(0); } // input parameter if (cmd.hasOption(PARAM_I)) { String input = cmd.getOptionValue(PARAM_I); boolean hasValue = cmd.hasOption(PARAM_I); logger.debug("Has option {} value: [{}]", PARAM_I, hasValue); String paramVal = cmd.getOptionValue(PARAM_I); logger.debug("value of option: [{}] ****", paramVal); File inputFile = new File(input); if (!inputFile.exists()) { logger.warn("{} does not exist or is not readable.", input); System.exit(1); } String subDir = cmd.getOptionValue(PARAM_O); PdfaConvert convert; if (!StringUtils.isEmpty(subDir)) { convert = new PdfaConvert(subDir); } else { convert = new PdfaConvert(); } if (inputFile.isDirectory()) { if (inputFile.listFiles() == null || inputFile.listFiles().length < 1) { logger.warn("Input directory is empty, nothing to process."); System.exit(1); } else { logger.debug("Have directory: [{}] with file count: {}", inputFile.getAbsolutePath(), inputFile.listFiles().length); DirectoryStream<Path> dirStream = null; dirStream = Files.newDirectoryStream(inputFile.toPath()); for (Path filePath : dirStream) { logger.debug("Have file name: {}", filePath.toString()); // Note: only handling files, not recursively going into sub-directories if (filePath.toFile().isFile()) { // Catch possible exception for each file so can handle other files in directory. try { convert.examine(filePath.toFile()); } catch (Exception e) { logger.error("Problem processing file: {} -- Error message: {}", filePath.getFileName(), e.getMessage()); } } else { logger.warn("Not a file so not processing: {}", filePath.toString()); // could be a directory but not recursing } } dirStream.close(); } } else { logger.debug("About to process file: {}", inputFile.getPath()); try { convert.examine(inputFile); } catch (Exception e) { logger.error("Problem processing file: {} -- Error message: {}", inputFile.getName(), e.getMessage()); logger.debug("Problem processing file: {} -- Error message: {}", inputFile.getName(), e.getMessage(), e); } } } else { System.err.println("Missing required option: " + PARAM_I); displayHelp(); System.exit(-1); } System.exit(0); }
From source file:es.upm.dit.xsdinferencer.XSDInferencer.java
/** * Main method, executed when the tool is invoked as a standalone application * @param args an array with all the arguments passed to the application * @throws XSDConfigurationException if there is a problem regarding the configuration * @throws IOException if there is an I/O problem while reading the input XML files or writing the output files * @throws JDOMException if there is any problem while parsing the input XML files *//*from w w w.j a v a2 s . c om*/ public static void main(String[] args) throws Exception { if (Arrays.asList(args).contains("--help")) { printHelp(); System.exit(0); } try { XSDInferencer inferencer = new XSDInferencer(); Results results = inferencer.inferSchema(args); Map<String, String> xsdsAsXMLStrings = results.getXSDsAsStrings(); Map<String, String> jsonsAsStrings = results.getJsonSchemasAsStrings(); Map<String, String> schemasAsStrings = xsdsAsXMLStrings != null ? xsdsAsXMLStrings : jsonsAsStrings; Map<String, String> statisticsDocumentsAsXMLStrings = results.getStatisticsAsStrings(); File outputDirectory = null; for (int i = 0; i < args.length; i++) { if (!args[i].equalsIgnoreCase("--" + KEY_OUTPUT_DIRECTORY)) continue; if (args[i + 1].startsWith("--") || i == args.length - 1) throw new IllegalArgumentException("Output directory parameter bad specified"); outputDirectory = new File(args[i + 1]); if (!outputDirectory.exists()) throw new FileNotFoundException("Output directory not found."); if (!outputDirectory.isDirectory()) throw new NotDirectoryException(outputDirectory.getPath()); } if (outputDirectory != null) { System.out.println("Writing results to " + outputDirectory.getAbsolutePath()); for (String name : schemasAsStrings.keySet()) { File currentOutpuFile = new File(outputDirectory, name); FileOutputStream fOs = new FileOutputStream(currentOutpuFile); BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(fOs, Charsets.UTF_8)); bWriter.write(schemasAsStrings.get(name)); bWriter.flush(); bWriter.close(); } if (statisticsDocumentsAsXMLStrings != null) { for (String name : statisticsDocumentsAsXMLStrings.keySet()) { File currentOutpuFile = new File(outputDirectory, name); FileWriter fWriter = new FileWriter(currentOutpuFile); BufferedWriter bWriter = new BufferedWriter(fWriter); bWriter.write(statisticsDocumentsAsXMLStrings.get(name)); bWriter.flush(); bWriter.close(); } } System.out.println("Results written"); } else { for (String name : schemasAsStrings.keySet()) { System.out.println(name + ":"); System.out.println(schemasAsStrings.get(name)); System.out.println(); } if (statisticsDocumentsAsXMLStrings != null) { for (String name : statisticsDocumentsAsXMLStrings.keySet()) { System.out.println(name + ":"); System.out.println(statisticsDocumentsAsXMLStrings.get(name)); System.out.println(); } } } } catch (XSDInferencerException e) { System.err.println(); System.err.println("Error at inference proccess: " + e.getMessage()); e.printStackTrace(); System.exit(1); } }
From source file:io.anserini.search.SearchTweets.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option(RM3_OPTION, "apply relevance feedback with rm3")); options.addOption(// ww w . j a v a 2s .c om OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return") .create(NUM_RESULTS_OPTION)); options.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("file containing topics in TREC format").create(QUERIES_OPTION)); options.addOption(OptionBuilder.withArgName("similarity").hasArg() .withDescription("similarity to use (BM25, LM)").create(SIMILARITY_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION)); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(QUERIES_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(SearchTweets.class.getName(), options); System.exit(-1); } File indexLocation = new File(cmdline.getOptionValue(INDEX_OPTION)); if (!indexLocation.exists()) { System.err.println("Error: " + indexLocation + " does not exist!"); System.exit(-1); } String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG; String topicsFile = cmdline.getOptionValue(QUERIES_OPTION); int numResults = 1000; try { if (cmdline.hasOption(NUM_RESULTS_OPTION)) { numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION)); } } catch (NumberFormatException e) { System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION)); System.exit(-1); } String similarity = "LM"; if (cmdline.hasOption(SIMILARITY_OPTION)) { similarity = cmdline.getOptionValue(SIMILARITY_OPTION); } PrintStream out = new PrintStream(System.out, true, "UTF-8"); IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexLocation.getAbsolutePath()))); IndexSearcher searcher = new IndexSearcher(reader); if (similarity.equalsIgnoreCase("BM25")) { searcher.setSimilarity(new BM25Similarity()); } else if (similarity.equalsIgnoreCase("LM")) { searcher.setSimilarity(new LMDirichletSimilarity(2500.0f)); } MicroblogTopicSet topics = MicroblogTopicSet.fromFile(new File(topicsFile)); for (MicroblogTopic topic : topics) { Filter filter = NumericRangeFilter.newLongRange(StatusField.ID.name, 0L, topic.getQueryTweetTime(), true, true); Query query = AnalyzerUtils.buildBagOfWordsQuery(StatusField.TEXT.name, IndexTweets.ANALYZER, topic.getQuery()); TopDocs rs = searcher.search(query, filter, numResults); RerankerContext context = new RerankerContext(searcher, query, topic.getQuery(), filter); RerankerCascade cascade = new RerankerCascade(context); if (cmdline.hasOption(RM3_OPTION)) { cascade.add(new Rm3Reranker(IndexTweets.ANALYZER, StatusField.TEXT.name)); cascade.add(new RemoveRetweetsTemporalTiebreakReranker()); } else { cascade.add(new RemoveRetweetsTemporalTiebreakReranker()); } ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher)); for (int i = 0; i < docs.documents.length; i++) { String qid = topic.getId().replaceFirst("^MB0*", ""); out.println(String.format("%s Q0 %s %d %f %s", qid, docs.documents[i].getField(StatusField.ID.name).numericValue(), (i + 1), docs.scores[i], runtag)); } } reader.close(); out.close(); }
From source file:de.prozesskraft.ptest.Launch.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try/*from w w w . jav a 2 s . co m*/ // { // if (args.length != 3) // { // System.out.println("Please specify processdefinition file (xml) and an outputfilename"); // } // // } // catch (ArrayIndexOutOfBoundsException e) // { // System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString()); // } /*---------------------------- get options from ini-file ----------------------------*/ File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Launch.class) + "/" + "../etc/ptest-launch.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); Option ov = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option ospl = OptionBuilder.withArgName("DIR").hasArg() .withDescription("[mandatory] directory with sample input data") // .isRequired() .create("spl"); Option oinstancedir = OptionBuilder.withArgName("DIR").hasArg() .withDescription("[mandatory, default: .] directory where the test will be performed") // .isRequired() .create("instancedir"); Option ocall = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory, default: random call in spl-directory] file with call-string") // .isRequired() .create("call"); Option oaltapp = OptionBuilder.withArgName("STRING").hasArg() .withDescription( "[optional] alternative app. this String replaces the first line of the .call-file.") // .isRequired() .create("altapp"); Option oaddopt = OptionBuilder.withArgName("STRING").hasArg() .withDescription("[optional] add an option to the call.") // .isRequired() .create("addopt"); Option onolaunch = new Option("nolaunch", "only create instance directory, copy all spl files, but do NOT launch the process"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(ospl); options.addOption(oinstancedir); options.addOption(ocall); options.addOption(oaltapp); options.addOption(oaddopt); options.addOption(onolaunch); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments commandline = parser.parse(options, args); } catch (Exception exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); exiter(); } /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("launch", options); System.exit(0); } else if (commandline.hasOption("v")) { System.out.println("web: " + web); System.out.println("author: " + author); System.out.println("version:" + version); System.out.println("date: " + date); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ boolean error = false; String spl = null; String instancedir = null; String call = null; String altapp = null; ArrayList<String> addopt = new ArrayList<String>(); // spl initialisieren if (commandline.hasOption("spl")) { spl = commandline.getOptionValue("spl"); } else { System.err.println("option -spl is mandatory"); error = true; } // instancedir initialisieren if (commandline.hasOption("instancedir")) { instancedir = commandline.getOptionValue("instancedir"); } else { instancedir = System.getProperty("user.dir"); } // call initialisieren if (commandline.hasOption("call")) { call = commandline.getOptionValue("call"); } // altapp initialisieren if (commandline.hasOption("altapp")) { altapp = commandline.getOptionValue("altapp"); } // addopt initialisieren if (commandline.hasOption("addopt")) { for (String actString : commandline.getOptionValues("addopt")) { addopt.add(actString); } } // wenn fehler, dann exit if (error) { exiter(); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ // das erste spl-objekt geben lassen Spl actSpl = new Splset(spl).getSpl().get(0); // den call, result und altapp ueberschreiben actSpl.setName("default"); if (call != null) { actSpl.setCall(new java.io.File(call)); } if (actSpl.getCall() == null) { System.err.println("error: no call information found"); System.exit(1); } if (altapp != null) { actSpl.setAltapp(altapp); } if (addopt.size() > 0) { actSpl.setAddopt(addopt); } actSpl.setResult(null); // das instancedir erstellen java.io.File actSplInstanceDir = new java.io.File(instancedir); System.err.println("info: creating directory " + actSplInstanceDir.getCanonicalPath()); actSplInstanceDir.mkdirs(); // Inputdaten in das InstanceDir exportieren actSpl.exportInput(actSplInstanceDir); // exit, wenn --nolaunch if (commandline.hasOption("nolaunch")) { System.err.println("info: exiting, because of -nolaunch"); System.exit(0); } // das logfile des Syscalls (zum debuggen des programms "process syscall" gedacht) String AbsLogSyscallWrapper = actSplInstanceDir.getCanonicalPath() + "/.log"; String AbsStdout = actSplInstanceDir.getCanonicalPath() + "/.stdout.txt"; String AbsStderr = actSplInstanceDir.getCanonicalPath() + "/.stderr.txt"; String AbsPid = actSplInstanceDir.getCanonicalPath() + "/.pid"; // beim starten von syscall werden parameter mit whitespaces an diesen auseinandergeschnitten und der nachfolgende aufruf schlaeft fehl // deshalb sollen whitespaces durch eine 'zeichensequenz' ersetzt werden // syscall ersetzt die zeichensequenz wieder zurueck in ein " " ArrayList<String> callFuerSyscall = actSpl.getCallAsArrayList(); ArrayList<String> callFuerSyscallMitTrennzeichen = new ArrayList<String>(); for (String actString : callFuerSyscall) { callFuerSyscallMitTrennzeichen.add(actString.replaceAll("\\s+", "%WHITESPACE%")); } try { // den Aufrufstring fuer die externe App (process syscall --version 0.6.0)) splitten // beim aufruf muss das erste argument im path zu finden sein, sonst gibt die fehlermeldung 'no such file or directory' ArrayList<String> processSyscallWithArgs = new ArrayList<String>( Arrays.asList(ini.get("apps", "pkraft-syscall").split(" "))); // die sonstigen argumente hinzufuegen processSyscallWithArgs.add("-call"); processSyscallWithArgs.add(String.join(" ", callFuerSyscallMitTrennzeichen)); // processSyscallWithArgs.add("\""+call+"\""); processSyscallWithArgs.add("-stdout"); processSyscallWithArgs.add(AbsStdout); processSyscallWithArgs.add("-stderr"); processSyscallWithArgs.add(AbsStderr); processSyscallWithArgs.add("-pid"); processSyscallWithArgs.add(AbsPid); processSyscallWithArgs.add("-mylog"); processSyscallWithArgs.add(AbsLogSyscallWrapper); processSyscallWithArgs.add("-maxrun"); processSyscallWithArgs.add("" + 3000); // erstellen prozessbuilder ProcessBuilder pb = new ProcessBuilder(processSyscallWithArgs); // erweitern des PATHs um den prozesseigenen path // Map<String,String> env = pb.environment(); // String path = env.get("PATH"); // log("debug", "$PATH="+path); // path = this.parent.getAbsPath()+":"+path; // env.put("PATH", path); // log("info", "path: "+path); // setzen der aktuellen directory (in der syscall ausgefuehrt werden soll) java.io.File directory = new java.io.File(instancedir); System.err.println("info: setting execution directory to: " + directory.getCanonicalPath()); pb.directory(directory); // zum debuggen ein paar ausgaben // java.lang.Process p1 = Runtime.getRuntime().exec("date >> ~/tmp.debug.work.txt"); // p1.waitFor(); // java.lang.Process p2 = Runtime.getRuntime().exec("ls -la "+this.getParent().getAbsdir()+" >> ~/tmp.debug.work.txt"); // p2.waitFor(); // java.lang.Process pro = Runtime.getRuntime().exec("nautilus"); // java.lang.Process superpro = Runtime.getRuntime().exec(processSyscallWithArgs.toArray(new String[processSyscallWithArgs.size()])); // p3.waitFor(); System.err.println("info: calling: " + pb.command()); // starten des prozesses java.lang.Process sysproc = pb.start(); // einfangen der stdout- und stderr des subprozesses InputStream is_stdout = sysproc.getInputStream(); InputStream is_stderr = sysproc.getErrorStream(); // Send your InputStream to an InputStreamReader: InputStreamReader isr_stdout = new InputStreamReader(is_stdout); InputStreamReader isr_stderr = new InputStreamReader(is_stderr); // That needs to go to a BufferedReader: BufferedReader br_stdout = new BufferedReader(isr_stdout); BufferedReader br_stderr = new BufferedReader(isr_stderr); // // oeffnen der OutputStreams zu den Ausgabedateien // FileWriter fw_stdout = new FileWriter(sStdout); // FileWriter fw_stderr = new FileWriter(sStderr); // zeilenweise in die files schreiben String line_out = new String(); String line_err = new String(); while (br_stdout.readLine() != null) { } // while (((line_out = br_stdout.readLine()) != null) || ((line_err = br_stderr.readLine()) != null)) // { // if (!(line_out == null)) // { // System.out.println(line_out); // System.out.flush(); // } // if (!(line_err == null)) // { // System.err.println(line_err); // System.err.flush(); // } // } int exitValue = sysproc.waitFor(); // fw_stdout.close(); // fw_stderr.close(); System.err.println("exitvalue: " + exitValue); sysproc.destroy(); System.exit(exitValue); // alternativer aufruf // java.lang.Process sysproc = Runtime.getRuntime().exec(StringUtils.join(args_for_syscall, " ")); // log("info", "call executed. pid="+sysproc.hashCode()); // wait 2 seconds for becoming the pid-file visible // Thread.sleep(2000); // int exitValue = sysproc.waitFor(); // // der prozess soll bis laengstens // if(exitValue != 0) // { // System.err.println("error: call returned a value indicating an error: "+exitValue); // } // else // { // System.err.println("info: call returned value: "+exitValue); // } // System.err.println("info: "+new Date().toString()); // System.err.println("info: bye"); // // sysproc.destroy(); // // System.exit(sysproc.exitValue()); } catch (Exception e2) { System.err.println("error: " + e2.getMessage()); System.exit(1); } }
From source file:com.jug.MotherMachine.java
/** * PROJECT MAIN/*from ww w .j av a2 s . c om*/ * ============ * * @param args * muh! */ public static void main(final String[] args) { try { final MotherMachine main = new MotherMachine(); guiFrame = new JFrame("Interactive MotherMachine"); main.initMainWindow(guiFrame); props = main.loadParams(); BGREM_TEMPLATE_XMIN = Integer .parseInt(props.getProperty("BGREM_TEMPLATE_XMIN", Integer.toString(BGREM_TEMPLATE_XMIN))); BGREM_TEMPLATE_XMAX = Integer .parseInt(props.getProperty("BGREM_TEMPLATE_XMAX", Integer.toString(BGREM_TEMPLATE_XMAX))); BGREM_X_OFFSET = Integer .parseInt(props.getProperty("BGREM_X_OFFSET", Integer.toString(BGREM_X_OFFSET))); GL_OFFSET_BOTTOM = Integer .parseInt(props.getProperty("GL_OFFSET_BOTTOM", Integer.toString(GL_OFFSET_BOTTOM))); GL_OFFSET_TOP = Integer.parseInt(props.getProperty("GL_OFFSET_TOP", Integer.toString(GL_OFFSET_TOP))); GL_OFFSET_LATERAL = Integer .parseInt(props.getProperty("GL_OFFSET_LATERAL", Integer.toString(GL_OFFSET_LATERAL))); MIN_CELL_LENGTH = Integer .parseInt(props.getProperty("MIN_CELL_LENGTH", Integer.toString(MIN_CELL_LENGTH))); MIN_GAP_CONTRAST = Double .parseDouble(props.getProperty("MIN_GAP_CONTRAST", Double.toString(MIN_GAP_CONTRAST))); SIGMA_PRE_SEGMENTATION_X = Double.parseDouble( props.getProperty("SIGMA_PRE_SEGMENTATION_X", Double.toString(SIGMA_PRE_SEGMENTATION_X))); SIGMA_PRE_SEGMENTATION_Y = Double.parseDouble( props.getProperty("SIGMA_PRE_SEGMENTATION_Y", Double.toString(SIGMA_PRE_SEGMENTATION_Y))); SIGMA_GL_DETECTION_X = Double .parseDouble(props.getProperty("SIGMA_GL_DETECTION_X", Double.toString(SIGMA_GL_DETECTION_X))); SIGMA_GL_DETECTION_Y = Double .parseDouble(props.getProperty("SIGMA_GL_DETECTION_Y", Double.toString(SIGMA_GL_DETECTION_Y))); DEFAULT_PATH = props.getProperty("DEFAULT_PATH", DEFAULT_PATH); GUI_POS_X = Integer.parseInt(props.getProperty("GUI_POS_X", Integer.toString(DEFAULT_GUI_POS_X))); GUI_POS_Y = Integer.parseInt(props.getProperty("GUI_POS_Y", Integer.toString(DEFAULT_GUI_POS_X))); GUI_WIDTH = Integer.parseInt(props.getProperty("GUI_WIDTH", Integer.toString(GUI_WIDTH))); GUI_HEIGHT = Integer.parseInt(props.getProperty("GUI_HEIGHT", Integer.toString(GUI_HEIGHT))); GUI_CONSOLE_WIDTH = Integer .parseInt(props.getProperty("GUI_CONSOLE_WIDTH", Integer.toString(GUI_CONSOLE_WIDTH))); // Iterate over all currently attached monitors and check if sceen position is actually possible, // otherwise fall back to the DEFAULT values and ignore the ones coming from the properties-file. boolean pos_ok = false; final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); final GraphicsDevice[] gs = ge.getScreenDevices(); for (int i = 0; i < gs.length; i++) { final DisplayMode dm = gs[i].getDisplayMode(); if (gs[i].getDefaultConfiguration().getBounds() .contains(new java.awt.Point(GUI_POS_X, GUI_POS_Y))) { pos_ok = true; } } // None of the screens contained the top-left window coordinates --> fall back onto default values... if (!pos_ok) { GUI_POS_X = DEFAULT_GUI_POS_X; GUI_POS_Y = DEFAULT_GUI_POS_Y; } String path = props.getProperty("import_path", System.getProperty("user.home")); final File fPath = main.showStartupDialog(guiFrame, path); path = fPath.getAbsolutePath(); props.setProperty("import_path", fPath.getAbsolutePath()); // Setting up console window and window snapper... main.initConsoleWindow(); main.showConsoleWindow(); final JFrameSnapper snapper = new JFrameSnapper(); snapper.addFrame(main.frameConsoleWindow); snapper.addFrame(guiFrame); // --------------------------------------------------- main.processDataFromFolder(path); // --------------------------------------------------- System.out.print("Build and show GUI..."); // show loaded and annotated data ImageJFunctions.show(main.imgRaw, "Rotated & cropped raw data"); ImageJFunctions.show(main.imgTemp, "Temporary"); ImageJFunctions.show(main.imgAnnotated, "Annotated ARGB data"); final MotherMachineGui gui = new MotherMachineGui(new MotherMachineModel(main)); gui.setVisible(true); main.ij = new ImageJ(); guiFrame.add(gui); guiFrame.setSize(GUI_WIDTH, GUI_HEIGHT); guiFrame.setLocation(GUI_POS_X, GUI_POS_Y); guiFrame.setVisible(true); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { snapper.snapFrames(main.frameConsoleWindow, guiFrame, JFrameSnapper.EAST); } }); System.out.println(" done!"); } catch (final UnsatisfiedLinkError ulr) { JOptionPane.showMessageDialog(MotherMachine.guiFrame, "Could initialize Gurobi.\n" + "You might not have installed Gurobi properly or you miss a valid license.\n" + "Please visit 'www.gurobi.com' for further information.\n\n" + ulr.getMessage(), "Gurobi Error?", JOptionPane.ERROR_MESSAGE); } }
From source file:DIA_Umpire_Quant.DIA_Umpire_Quant.java
/** * @param args the command line arguments *//* w w w . j a v a 2s . co m*/ public static void main(String[] args) throws FileNotFoundException, IOException, Exception { System.out.println( "================================================================================================="); System.out.println("DIA-Umpire quantitation with targeted re-extraction analysis (version: " + UmpireInfo.GetInstance().Version + ")"); if (args.length != 1) { System.out.println( "command format error, it should be like: java -jar -Xmx10G DIA_Umpire_Quant.jar diaumpire_quant.params"); return; } try { ConsoleLogger.SetConsoleLogger(Level.INFO); ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_quant.log"); } catch (Exception e) { } try { Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version); Logger.getRootLogger().info("Parameter file:" + args[0]); BufferedReader reader = new BufferedReader(new FileReader(args[0])); String line = ""; String WorkFolder = ""; int NoCPUs = 2; String UserMod = ""; String Combined_Prot = ""; String InternalLibID = ""; String ExternalLibPath = ""; String ExternalLibDecoyTag = "DECOY"; boolean DefaultProtFiltering = true; boolean DataSetLevelPepFDR = false; float ProbThreshold = 0.99f; float ExtProbThreshold = 0.99f; float Freq = 0f; int TopNPep = 6; int TopNFrag = 6; float MinFragMz = 200f; String FilterWeight = "GW"; float MinWeight = 0.9f; float RTWindow_Int = -1f; float RTWindow_Ext = -1f; TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600); HashMap<String, File> AssignFiles = new HashMap<>(); boolean InternalLibSearch = false; boolean ExternalLibSearch = false; boolean ExportSaint = false; boolean SAINT_MS1 = false; boolean SAINT_MS2 = true; HashMap<String, String[]> BaitList = new HashMap<>(); HashMap<String, String> BaitName = new HashMap<>(); HashMap<String, String[]> ControlList = new HashMap<>(); HashMap<String, String> ControlName = new HashMap<>(); //<editor-fold defaultstate="collapsed" desc="Reading parameter file"> while ((line = reader.readLine()) != null) { line = line.trim(); Logger.getRootLogger().info(line); if (!"".equals(line) && !line.startsWith("#")) { //System.out.println(line); if (line.equals("==File list begin")) { do { line = reader.readLine(); line = line.trim(); if (line.equals("==File list end")) { continue; } else if (!"".equals(line)) { File newfile = new File(line); if (newfile.exists()) { AssignFiles.put(newfile.getAbsolutePath(), newfile); } else { Logger.getRootLogger().info("File: " + newfile + " does not exist."); } } } while (!line.equals("==File list end")); } if (line.split("=").length < 2) { continue; } String type = line.split("=")[0].trim(); String value = line.split("=")[1].trim(); switch (type) { case "TargetedExtraction": { InternalLibSearch = Boolean.parseBoolean(value); break; } case "InternalLibSearch": { InternalLibSearch = Boolean.parseBoolean(value); break; } case "ExternalLibSearch": { ExternalLibSearch = Boolean.parseBoolean(value); break; } case "Path": { WorkFolder = value; break; } case "path": { WorkFolder = value; break; } case "Thread": { NoCPUs = Integer.parseInt(value); break; } case "Fasta": { tandemPara.FastaPath = value; break; } case "Combined_Prot": { Combined_Prot = value; break; } case "DefaultProtFiltering": { DefaultProtFiltering = Boolean.parseBoolean(value); break; } case "DecoyPrefix": { if (!"".equals(value)) { tandemPara.DecoyPrefix = value; } break; } case "UserMod": { UserMod = value; break; } case "ProteinFDR": { tandemPara.ProtFDR = Float.parseFloat(value); break; } case "PeptideFDR": { tandemPara.PepFDR = Float.parseFloat(value); break; } case "DataSetLevelPepFDR": { DataSetLevelPepFDR = Boolean.parseBoolean(value); break; } case "InternalLibID": { InternalLibID = value; break; } case "ExternalLibPath": { ExternalLibPath = value; break; } case "ExtProbThreshold": { ExtProbThreshold = Float.parseFloat(value); break; } case "RTWindow_Int": { RTWindow_Int = Float.parseFloat(value); break; } case "RTWindow_Ext": { RTWindow_Ext = Float.parseFloat(value); break; } case "ExternalLibDecoyTag": { ExternalLibDecoyTag = value; if (ExternalLibDecoyTag.endsWith("_")) { ExternalLibDecoyTag = ExternalLibDecoyTag.substring(0, ExternalLibDecoyTag.length() - 1); } break; } case "ProbThreshold": { ProbThreshold = Float.parseFloat(value); break; } case "ReSearchProb": { //ReSearchProb = Float.parseFloat(value); break; } case "FilterWeight": { FilterWeight = value; break; } case "MinWeight": { MinWeight = Float.parseFloat(value); break; } case "TopNFrag": { TopNFrag = Integer.parseInt(value); break; } case "TopNPep": { TopNPep = Integer.parseInt(value); break; } case "Freq": { Freq = Float.parseFloat(value); break; } case "MinFragMz": { MinFragMz = Float.parseFloat(value); break; } //<editor-fold defaultstate="collapsed" desc="SaintOutput"> case "ExportSaintInput": { ExportSaint = Boolean.parseBoolean(value); break; } case "QuantitationType": { switch (value) { case "MS1": { SAINT_MS1 = true; SAINT_MS2 = false; break; } case "MS2": { SAINT_MS1 = false; SAINT_MS2 = true; break; } case "BOTH": { SAINT_MS1 = true; SAINT_MS2 = true; break; } } break; } // case "BaitInputFile": { // SaintBaitFile = value; // break; // } // case "PreyInputFile": { // SaintPreyFile = value; // break; // } // case "InterationInputFile": { // SaintInteractionFile = value; // break; // } default: { if (type.startsWith("BaitName_")) { BaitName.put(type.substring(9), value); } if (type.startsWith("BaitFile_")) { BaitList.put(type.substring(9), value.split("\t")); } if (type.startsWith("ControlName_")) { ControlName.put(type.substring(12), value); } if (type.startsWith("ControlFile_")) { ControlList.put(type.substring(12), value.split("\t")); } break; } //</editor-fold> } } } //</editor-fold> //Initialize PTM manager using compomics library PTMManager.GetInstance(); if (!UserMod.equals("")) { PTMManager.GetInstance().ImportUserMod(UserMod); } //Check if the fasta file can be found if (!new File(tandemPara.FastaPath).exists()) { Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath + " cannot be found, the process will be terminated, please check."); System.exit(1); } //Check if the prot.xml file can be found if (!new File(Combined_Prot).exists()) { Logger.getRootLogger().info("ProtXML file: " + Combined_Prot + " cannot be found, the export protein summary table will be empty."); } LCMSID protID = null; //Parse prot.xml and generate protein master list given an FDR if (Combined_Prot != null && !Combined_Prot.equals("")) { protID = LCMSID.ReadLCMSIDSerialization(Combined_Prot); if (!"".equals(Combined_Prot) && protID == null) { protID = new LCMSID(Combined_Prot, tandemPara.DecoyPrefix, tandemPara.FastaPath); ProtXMLParser protxmlparser = new ProtXMLParser(protID, Combined_Prot, 0f); //Use DIA-Umpire default protein FDR calculation if (DefaultProtFiltering) { protID.RemoveLowLocalPWProtein(0.8f); protID.RemoveLowMaxIniProbProtein(0.9f); protID.FilterByProteinDecoyFDRUsingMaxIniProb(tandemPara.DecoyPrefix, tandemPara.ProtFDR); } //Get protein FDR calculation without other filtering else { protID.FilterByProteinDecoyFDRUsingLocalPW(tandemPara.DecoyPrefix, tandemPara.ProtFDR); } protID.LoadSequence(); protID.WriteLCMSIDSerialization(Combined_Prot); } Logger.getRootLogger().info("Protein No.:" + protID.ProteinList.size()); } HashMap<String, HashMap<String, FragmentPeak>> IDSummaryFragments = new HashMap<>(); //Generate DIA file list ArrayList<DIAPack> FileList = new ArrayList<>(); File folder = new File(WorkFolder); if (!folder.exists()) { Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found."); System.exit(1); } for (final File fileEntry : folder.listFiles()) { if (fileEntry.isFile() && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml") | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml")) && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml") && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml") && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) { AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry); } if (fileEntry.isDirectory()) { for (final File fileEntry2 : fileEntry.listFiles()) { if (fileEntry2.isFile() && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml") | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml")) && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml") && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml") && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) { AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2); } } } } Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size()); for (File fileEntry : AssignFiles.values()) { Logger.getRootLogger().info(fileEntry.getAbsolutePath()); String mzXMLFile = fileEntry.getAbsolutePath(); if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) { DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs); FileList.add(DiaFile); HashMap<String, FragmentPeak> FragMap = new HashMap<>(); IDSummaryFragments.put(FilenameUtils.getBaseName(mzXMLFile), FragMap); Logger.getRootLogger().info( "================================================================================================="); Logger.getRootLogger().info("Processing " + mzXMLFile); if (!DiaFile.LoadDIASetting()) { Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete"); System.exit(1); } if (!DiaFile.LoadParams()) { Logger.getRootLogger().info("Loading parameters failed, job is incomplete"); System.exit(1); } } } LCMSID combinePepID = null; if (DataSetLevelPepFDR) { combinePepID = LCMSID.ReadLCMSIDSerialization(WorkFolder + "combinePepID.SerFS"); if (combinePepID == null) { FDR_DataSetLevel fdr = new FDR_DataSetLevel(); fdr.GeneratePepIonList(FileList, tandemPara, WorkFolder + "combinePepID.SerFS"); combinePepID = fdr.combineID; combinePepID.WriteLCMSIDSerialization(WorkFolder + "combinePepID.SerFS"); } } //process each DIA file for quantification based on untargeted identifications for (DIAPack DiaFile : FileList) { long time = System.currentTimeMillis(); Logger.getRootLogger().info("Loading identification results " + DiaFile.Filename + "...."); //If the LCMSID serialization is found if (!DiaFile.ReadSerializedLCMSID()) { DiaFile.ParsePepXML(tandemPara, combinePepID); DiaFile.BuildStructure(); if (!DiaFile.MS1FeatureMap.ReadPeakCluster()) { Logger.getRootLogger().info("Loading peak and structure failed, job is incomplete"); System.exit(1); } DiaFile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster(); //Generate mapping between index of precursor feature and pseudo MS/MS scan index DiaFile.GenerateClusterScanNomapping(); //Doing quantification DiaFile.AssignQuant(); DiaFile.ClearStructure(); } DiaFile.IDsummary.ReduceMemoryUsage(); time = System.currentTimeMillis() - time; Logger.getRootLogger().info(DiaFile.Filename + " processed time:" + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time), TimeUnit.MILLISECONDS.toMinutes(time) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)), TimeUnit.MILLISECONDS.toSeconds(time) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)))); } //<editor-fold defaultstate="collapsed" desc="Targete re-extraction using internal library"> Logger.getRootLogger().info( "================================================================================================="); if (InternalLibSearch && FileList.size() > 1) { Logger.getRootLogger().info("Module C: Targeted extraction using internal library"); FragmentLibManager libManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder, InternalLibID); if (libManager == null) { Logger.getRootLogger().info("Building internal spectral library"); libManager = new FragmentLibManager(InternalLibID); ArrayList<LCMSID> LCMSIDList = new ArrayList<>(); for (DIAPack dia : FileList) { LCMSIDList.add(dia.IDsummary); } libManager.ImportFragLibTopFrag(LCMSIDList, Freq, TopNFrag); libManager.WriteFragmentLibSerialization(WorkFolder); } libManager.ReduceMemoryUsage(); Logger.getRootLogger() .info("Building retention time prediction model and generate candidate peptide list"); for (int i = 0; i < FileList.size(); i++) { FileList.get(i).IDsummary.ClearMappedPep(); } for (int i = 0; i < FileList.size(); i++) { for (int j = i + 1; j < FileList.size(); j++) { RTAlignedPepIonMapping alignment = new RTAlignedPepIonMapping(WorkFolder, FileList.get(i).GetParameter(), FileList.get(i).IDsummary, FileList.get(j).IDsummary); alignment.GenerateModel(); alignment.GenerateMappedPepIon(); } FileList.get(i).ExportID(); FileList.get(i).IDsummary = null; } Logger.getRootLogger().info("Targeted matching........"); for (DIAPack diafile : FileList) { if (diafile.IDsummary == null) { diafile.ReadSerializedLCMSID(); } if (!diafile.IDsummary.GetMappedPepIonList().isEmpty()) { diafile.UseMappedIon = true; diafile.FilterMappedIonByProb = false; diafile.BuildStructure(); diafile.MS1FeatureMap.ReadPeakCluster(); diafile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster(); diafile.GenerateMassCalibrationRTMap(); diafile.TargetedExtractionQuant(false, libManager, 1.1f, RTWindow_Int); diafile.MS1FeatureMap.ClearAllPeaks(); diafile.IDsummary.ReduceMemoryUsage(); diafile.IDsummary.RemoveLowProbMappedIon(ProbThreshold); diafile.ExportID(); Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size() + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size()); diafile.ClearStructure(); } diafile.IDsummary = null; System.gc(); } Logger.getRootLogger().info( "================================================================================================="); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Targeted re-extraction using external library"> //External library search if (ExternalLibSearch) { Logger.getRootLogger().info("Module C: Targeted extraction using external library"); //Read exteranl library FragmentLibManager ExlibManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder, FilenameUtils.getBaseName(ExternalLibPath)); if (ExlibManager == null) { ExlibManager = new FragmentLibManager(FilenameUtils.getBaseName(ExternalLibPath)); //Import traML file ExlibManager.ImportFragLibByTraML(ExternalLibPath, ExternalLibDecoyTag); //Check if there are decoy spectra ExlibManager.CheckDecoys(); //ExlibManager.ImportFragLibBySPTXT(ExternalLibPath); ExlibManager.WriteFragmentLibSerialization(WorkFolder); } Logger.getRootLogger() .info("No. of peptide ions in external lib:" + ExlibManager.PeptideFragmentLib.size()); for (DIAPack diafile : FileList) { if (diafile.IDsummary == null) { diafile.ReadSerializedLCMSID(); } //Generate RT mapping RTMappingExtLib RTmap = new RTMappingExtLib(diafile.IDsummary, ExlibManager, diafile.GetParameter()); RTmap.GenerateModel(); RTmap.GenerateMappedPepIon(); diafile.BuildStructure(); diafile.MS1FeatureMap.ReadPeakCluster(); diafile.GenerateMassCalibrationRTMap(); //Perform targeted re-extraction diafile.TargetedExtractionQuant(false, ExlibManager, ProbThreshold, RTWindow_Ext); diafile.MS1FeatureMap.ClearAllPeaks(); diafile.IDsummary.ReduceMemoryUsage(); //Remove target IDs below the defined probability threshold diafile.IDsummary.RemoveLowProbMappedIon(ExtProbThreshold); diafile.ExportID(); diafile.ClearStructure(); Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size() + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size()); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Peptide and fragment selection"> Logger.getRootLogger().info("Peptide and fragment selection across the whole dataset"); ArrayList<LCMSID> SummaryList = new ArrayList<>(); for (DIAPack diafile : FileList) { if (diafile.IDsummary == null) { diafile.ReadSerializedLCMSID(); diafile.IDsummary.ClearAssignPeakCluster(); //diafile.IDsummary.ClearPSMs(); } if (protID != null) { //Generate protein list according to mapping of peptide ions for each DIA file to the master protein list diafile.IDsummary.GenerateProteinByRefIDByPepSeq(protID, true); diafile.IDsummary.ReMapProPep(); } if ("GW".equals(FilterWeight)) { diafile.IDsummary.SetFilterByGroupWeight(); } else if ("PepW".equals(FilterWeight)) { diafile.IDsummary.SetFilterByWeight(); } SummaryList.add(diafile.IDsummary); } FragmentSelection fragselection = new FragmentSelection(SummaryList); fragselection.freqPercent = Freq; fragselection.MinFragMZ = MinFragMz; fragselection.GeneratePepFragScoreMap(); fragselection.GenerateTopFragMap(TopNFrag); fragselection.GenerateProtPepScoreMap(MinWeight); fragselection.GenerateTopPepMap(TopNPep); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Writing general reports"> ExportTable export = new ExportTable(WorkFolder, SummaryList, IDSummaryFragments, protID, fragselection); export.Export(TopNPep, TopNFrag, Freq); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="//<editor-fold defaultstate="collapsed" desc="Generate SAINT input files"> if (ExportSaint && protID != null) { HashMap<String, DIAPack> Filemap = new HashMap<>(); for (DIAPack DIAfile : FileList) { Filemap.put(DIAfile.GetBaseName(), DIAfile); } FileWriter baitfile = new FileWriter(WorkFolder + "SAINT_Bait_" + DateTimeTag.GetTag() + ".txt"); FileWriter preyfile = new FileWriter(WorkFolder + "SAINT_Prey_" + DateTimeTag.GetTag() + ".txt"); FileWriter interactionfileMS1 = null; FileWriter interactionfileMS2 = null; if (SAINT_MS1) { interactionfileMS1 = new FileWriter( WorkFolder + "SAINT_Interaction_MS1_" + DateTimeTag.GetTag() + ".txt"); } if (SAINT_MS2) { interactionfileMS2 = new FileWriter( WorkFolder + "SAINT_Interaction_MS2_" + DateTimeTag.GetTag() + ".txt"); } HashMap<String, String> PreyID = new HashMap<>(); for (String samplekey : ControlName.keySet()) { String name = ControlName.get(samplekey); for (String file : ControlList.get(samplekey)) { baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "C\n"); LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary; if (SAINT_MS1) { SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID, 1); } if (SAINT_MS2) { SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID, 2); } } } for (String samplekey : BaitName.keySet()) { String name = BaitName.get(samplekey); for (String file : BaitList.get(samplekey)) { baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "T\n"); LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary; if (SAINT_MS1) { SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID, 1); } if (SAINT_MS2) { SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID, 2); } } } baitfile.close(); if (SAINT_MS1) { interactionfileMS1.close(); } if (SAINT_MS2) { interactionfileMS2.close(); } for (String AccNo : PreyID.keySet()) { preyfile.write(AccNo + "\t" + PreyID.get(AccNo) + "\n"); } preyfile.close(); } //</editor-fold> Logger.getRootLogger().info("Job done"); Logger.getRootLogger().info( "================================================================================================="); } catch (Exception e) { Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e)); throw e; } }
From source file:fll.scheduler.TableOptimizer.java
/** * @param args//from w ww .j a v a 2 s . c o m */ public static void main(final String[] args) { LogUtils.initializeLogging(); File schedfile = null; final Options options = buildOptions(); try { final CommandLineParser parser = new PosixParser(); final CommandLine cmd = parser.parse(options, args); schedfile = new File(cmd.getOptionValue(SCHED_FILE_OPTION)); } catch (final org.apache.commons.cli.ParseException pe) { LOGGER.error(pe.getMessage()); usage(options); System.exit(1); } FileInputStream fis = null; try { if (!schedfile.canRead()) { LOGGER.fatal(schedfile.getAbsolutePath() + " is not readable"); System.exit(4); } final boolean csv = schedfile.getName().endsWith("csv"); final CellFileReader reader; final String sheetName; if (csv) { reader = new CSVCellReader(schedfile); sheetName = null; } else { sheetName = SchedulerUI.promptForSheetName(schedfile); if (null == sheetName) { return; } fis = new FileInputStream(schedfile); reader = new ExcelCellReader(fis, sheetName); } final ColumnInformation columnInfo = TournamentSchedule.findColumns(reader, new LinkedList<String>()); if (null != fis) { fis.close(); fis = null; } final List<SubjectiveStation> subjectiveStations = SchedulerUI.gatherSubjectiveStationInformation(null, columnInfo); // not bothering to get the schedule params as we're just tweaking table // assignments, which wont't be effected by the schedule params. final SchedParams params = new SchedParams(subjectiveStations, SchedParams.DEFAULT_PERFORMANCE_MINUTES, SchedParams.MINIMUM_CHANGETIME_MINUTES, SchedParams.MINIMUM_PERFORMANCE_CHANGETIME_MINUTES); final List<String> subjectiveHeaders = new LinkedList<String>(); for (final SubjectiveStation station : subjectiveStations) { subjectiveHeaders.add(station.getName()); } final String name = Utilities.extractBasename(schedfile); final TournamentSchedule schedule; if (csv) { schedule = new TournamentSchedule(name, schedfile, subjectiveHeaders); } else { fis = new FileInputStream(schedfile); schedule = new TournamentSchedule(name, fis, sheetName, subjectiveHeaders); } final TableOptimizer optimizer = new TableOptimizer(params, schedule, schedfile.getAbsoluteFile().getParentFile()); final long start = System.currentTimeMillis(); optimizer.optimize(null); final long stop = System.currentTimeMillis(); LOGGER.info("Optimization took: " + (stop - start) / 1000.0 + " seconds"); } catch (final ParseException e) { LOGGER.fatal(e, e); System.exit(5); } catch (final ScheduleParseException e) { LOGGER.fatal(e, e); System.exit(6); } catch (final IOException e) { LOGGER.fatal("Error reading file", e); System.exit(4); } catch (final RuntimeException e) { LOGGER.fatal(e, e); throw e; } catch (InvalidFormatException e) { LOGGER.fatal(e, e); System.exit(7); } finally { try { if (null != fis) { fis.close(); } } catch (final IOException e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Error closing stream", e); } } } }
From source file:de.prozesskraft.pkraft.Startinstance.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { /*---------------------------- get options from ini-file//from w w w . j ava2 s .c om ----------------------------*/ java.io.File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Startinstance.class) + "/" + "../etc/pkraft-startinstance.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); Option ov = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option obasedir = OptionBuilder.withArgName("DIR").hasArg() .withDescription("[optional, default .] base directory where instance shourd run.") // .isRequired() .create("basedir"); Option odefinition = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[optional] definition file of the process you want to start an instance from.") // .isRequired() .create("definition"); Option onostart = OptionBuilder.withArgName("") // .hasArg() .withDescription( "[optional] oppresses the start of the instance. (only create the process-instance)") // .isRequired() .create("nostart"); Option opdomain = OptionBuilder.withArgName("STRING").hasArg() .withDescription("[optional] domain of the process (mandatory if you omit -definition)") // .isRequired() .create("pdomain"); Option opname = OptionBuilder.withArgName("STRING").hasArg().withDescription( "[optional] name of the process you want to start an instance from (mandatory if you omit -definition)") // .isRequired() .create("pname"); Option opversion = OptionBuilder.withArgName("STRING").hasArg().withDescription( "[optional] version of the process you want to start an instance from (mandatory if you omit -definition)") // .isRequired() .create("pversion"); Option ocommitfile = OptionBuilder.withArgName("KEY=FILE; FILE").hasArg() .withDescription("[optional] this file will be committed as file. omit KEY= if KEY==FILENAME.") // .isRequired() .create("commitfile"); Option ocommitvariable = OptionBuilder.withArgName("KEY=VALUE; VALUE").hasArg() .withDescription("[optional] this string will be committed as a variable. omit KEY= if KEY==VALUE") // .isRequired() .create("commitvariable"); Option ocommitfiledummy = OptionBuilder.withArgName("KEY=FILE; FILE").hasArg().withDescription( "[optional] use this parameter like --commitfile. the file will not be checked against the process interface and therefore allows to commit files which are not expected by the process definition. use this parameter only for test purposes e.g. to commit dummy output files for accelerated tests of complex processes or the like.") // .isRequired() .create("commitfiledummy"); Option ocommitvariabledummy = OptionBuilder.withArgName("KEY=VALUE; VALUE").hasArg().withDescription( "[optional] use this parameter like --commitvariable. the variable will not be checked against the process interface and therefore allows to commit variables which are not expected by the process definition. use this parameter only for test purposes e.g. to commit dummy output variables for accelerated tests of complex processes or the like.") // .isRequired() .create("commitvariabledummy"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(obasedir); options.addOption(odefinition); options.addOption(onostart); options.addOption(opname); options.addOption(opversion); options.addOption(ocommitfile); options.addOption(ocommitvariable); options.addOption(ocommitfiledummy); options.addOption(ocommitvariabledummy); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); // parse the command line arguments commandline = parser.parse(options, args); /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("startinstance", options); System.exit(0); } if (commandline.hasOption("v")) { System.out.println("author: alexander.vogel@caegroup.de"); System.out.println("version: [% version %]"); System.out.println("date: [% date %]"); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ if (!(commandline.hasOption("definition")) && (!(commandline.hasOption("pname")) || !(commandline.hasOption("pversion")) || !(commandline.hasOption("pdomain")))) { System.err.println("option -definition or the options -pname & -pversion & -pdomain are mandatory"); exiter(); } if ((commandline.hasOption("definition") && ((commandline.hasOption("pversion")) || (commandline.hasOption("pname")) || (commandline.hasOption("pdomain"))))) { System.err.println("you must not use option -definition with -pversion or -pname or -pdomain"); exiter(); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ Process p1 = new Process(); String pathToDefinition = ""; if (commandline.hasOption("definition")) { pathToDefinition = commandline.getOptionValue("definition"); } else if (commandline.hasOption("pname") && commandline.hasOption("pversion") && commandline.hasOption("pdomain")) { pathToDefinition.replaceAll("/+$", ""); pathToDefinition = ini.get("process", "domain-installation-directory") + "/" + commandline.getOptionValue("pdomain") + "/" + commandline.getOptionValue("pname") + "/" + commandline.getOptionValue("pversion") + "/process.xml"; } else { System.err.println("option -definition or the options -pname & -pversion & -pdomain are mandatory"); exiter(); } // check ob das ermittelte oder uebergebene xml-file ueberhaupt existiert java.io.File xmlDefinition = new java.io.File(pathToDefinition); if (!(xmlDefinition.exists()) || !(xmlDefinition.isFile())) { System.err.println("process definition does not exist: " + pathToDefinition); exiter(); } p1.setInfilexml(xmlDefinition.getCanonicalPath()); Process p2 = null; try { p2 = p1.readXml(); } catch (JAXBException e1) { System.err.println(e1.getMessage()); } // das processBinary vorneweg schon mal erstellen, da es sein kann das das committen laenger dauert und ein pradar-attend den neuen prozess schon mal aufnehmen will // root-verzeichnis erstellen if (commandline.hasOption("basedir")) { p2.setBaseDir(commandline.getOptionValue("basedir")); } p2.makeRootdir(); // den pfad fuers binary setzen p2.setOutfilebinary(p2.getRootdir() + "/process.pmb"); System.err.println("info: writing process instance " + p2.getOutfilebinary()); // binary schreiben p2.writeBinary(); // step, an den die commits gehen, soll 'root' sein. Step stepRoot = p2.getRootStep(); // committen von files (ueber einen glob) if (commandline.hasOption("commitfile")) { for (String actOptionCommitfile : commandline.getOptionValues("commitfile")) { String[] parts = actOptionCommitfile.split("="); File userFile = new File(); if (parts.length == 1) { userFile.setKey(new java.io.File(parts[0]).getName()); userFile.setGlob(parts[0]); } else if (parts.length == 2) { userFile.setKey(parts[0]); userFile.setGlob(parts[1]); } else { System.err.println("error in option -commitfile " + actOptionCommitfile); exiter(); } // die auf der kommandozeile uebergebenen Informationen sollen in die vorhandenen commits im rootStep gemappt werden // alle vorhandenen commits in step root durchgehen und dem passenden file zuordnen for (Commit actCommit : stepRoot.getCommit()) { // alle files des aktuellen commits for (File actFile : actCommit.getFile()) { if (actFile.getKey().equals(userFile.getKey())) { // wenn actFile schon ein valider eintrag ist, dann soll ein klon befuellt werden if (actFile.getGlob() != null) { // wenn die maximale erlaubte anzahl noch nicht erreicht ist if (actCommit.getFile(actFile.getKey()).size() < actFile.getMaxoccur()) { File newFile = actFile.clone(); newFile.setGlob(userFile.getGlob()); System.err.println("entering file into commit '" + actCommit.getName() + "' (" + newFile.getKey() + "=" + newFile.getGlob() + ")"); actCommit.addFile(newFile); break; } else { System.err.println("fatal: you only may commit " + actFile.getMaxoccur() + " " + actFile.getKey() + "-files into commit " + actCommit.getName()); exiter(); } } // ansonsten das bereits vorhandene file im commit mit den daten befuellen else { actFile.setGlob(userFile.getGlob()); actFile.setGlobdir(p2.getBaseDir()); System.err.println("entering file into commit '" + actCommit.getName() + "' (" + actFile.getKey() + "=" + actFile.getGlob() + ")"); break; } } } } } } // committen von files (ueber einen glob) if (commandline.hasOption("commitfiledummy")) { // diese files werden nicht in bestehende commits der prozessdefinition eingetragen, sondern in ein spezielles commit Commit commitFiledummy = new Commit(); commitFiledummy.setName("fileDummy"); stepRoot.addCommit(commitFiledummy); for (String actOptionCommitfiledummy : commandline.getOptionValues("commitfiledummy")) { String[] parts = actOptionCommitfiledummy.split("="); File userFile = new File(); commitFiledummy.addFile(userFile); if (parts.length == 1) { userFile.setKey(new java.io.File(parts[0]).getName()); userFile.setGlob(parts[0]); } else if (parts.length == 2) { userFile.setKey(parts[0]); userFile.setGlob(parts[1]); } else { System.err.println("error in option -commitfiledummy " + actOptionCommitfiledummy); exiter(); } userFile.setGlobdir(p2.getBaseDir()); System.err.println("entering (dummy-)file into commit '" + commitFiledummy.getName() + "' (" + userFile.getKey() + "=" + userFile.getGlob() + ")"); } } if (commandline.hasOption("commitvariable")) { for (String actOptionCommitvariable : commandline.getOptionValues("commitvariable")) { if (actOptionCommitvariable.matches(".+=.+")) { String[] parts = actOptionCommitvariable.split("="); Variable userVariable = new Variable(); if (parts.length == 1) { userVariable.setKey("default"); userVariable.setValue(parts[0]); } else if (parts.length == 2) { userVariable.setKey(parts[0]); userVariable.setValue(parts[1]); } else { System.err.println("error in option -commitvariable"); exiter(); } // commit.addVariable(variable); // die auf der kommandozeile uebergebenen Informationen sollen in die vorhandenen commits im rootStep gemappt werden // alle vorhandenen commits in step root durchgehen und dem passenden file zuordnen for (Commit actCommit : stepRoot.getCommit()) { // alle files des aktuellen commits for (Variable actVariable : actCommit.getVariable()) { if (actVariable.getKey().equals(userVariable.getKey())) { // wenn actFile schon ein valider eintrag ist, dann soll ein klon befuellt werden if (actVariable.getGlob() != null) { // wenn die maximale erlaubte anzahl noch nicht erreicht ist if (actCommit.getVariable(actVariable.getKey()).size() < actVariable .getMaxoccur()) { Variable newVariable = actVariable.clone(); newVariable.setValue(userVariable.getValue()); System.err.println("entering variable into commit '" + actCommit.getName() + "' (" + newVariable.getKey() + "=" + newVariable.getValue() + ")"); actCommit.addVariable(newVariable); break; } else { System.err.println("fatal: you only may commit " + actVariable.getMaxoccur() + " " + actVariable.getKey() + "-variable(s) into commit " + actCommit.getName()); exiter(); } } // ansonsten das bereits vorhandene file im commit mit den daten befuellen else { actVariable.setValue(userVariable.getValue()); System.err.println("entering variable into commit '" + actCommit.getName() + "' (" + actVariable.getKey() + "=" + actVariable.getValue() + ")"); break; } } } } } else { System.err.println("-commitvariable " + actOptionCommitvariable + " does not match pattern \"NAME=VALUE\"."); exiter(); } } } if (commandline.hasOption("commitvariabledummy")) { // diese files werden nicht in bestehende commits der prozessdefinition eingetragen, sondern in ein spezielles commit Commit commitVariabledummy = new Commit(); commitVariabledummy.setName("variableDummy"); stepRoot.addCommit(commitVariabledummy); for (String actOptionCommitvariabledummy : commandline.getOptionValues("commitvariabledummy")) { String[] parts = actOptionCommitvariabledummy.split("="); Variable userVariable = new Variable(); commitVariabledummy.addVariable(userVariable); if (parts.length == 1) { userVariable.setKey(parts[0]); userVariable.setValue(parts[0]); } else if (parts.length == 2) { userVariable.setKey(parts[0]); userVariable.setValue(parts[1]); } else { System.err.println("error in option -commitvariabledummy"); exiter(); } System.err.println("entering variable into commit '" + commitVariabledummy.getName() + "' (" + userVariable.getKey() + "=" + userVariable.getValue() + ")"); } } // if (commandline.hasOption("basedir")) // { // p2.setBaseDir(commandline.getOptionValue("basedir")); // } // commit.doIt(); stepRoot.commit(); // root-verzeichnis erstellen p2.makeRootdir(); // den pfad fuers binary setzen // p2.setOutfilebinary(p2.getRootdir() + "/process.pmb"); System.err.println("info: writing process instance " + p2.getOutfilebinary()); // binary schreiben p2.writeBinary(); try { Thread.sleep(1500, 0); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Runtime.getRuntime().exec("process-manager -help"); // starten nur, falls es nicht abgewaehlt wurde if (!commandline.hasOption("nostart")) { System.err.println("info: starting processmanager for instance " + p2.getOutfilebinary()); String aufrufString = ini.get("apps", "pkraft-manager") + " -instance " + p2.getOutfilebinary(); System.err.println("calling: " + aufrufString); ArrayList<String> processSyscallWithArgs = new ArrayList<String>( Arrays.asList(aufrufString.split(" "))); ProcessBuilder pb = new ProcessBuilder(processSyscallWithArgs); // ProcessBuilder pb = new ProcessBuilder("processmanager -instance "+p2.getOutfilebinary()); // Map<String,String> env = pb.environment(); // String path = env.get("PATH"); // System.out.println("PATH: "+path); // java.lang.Process p = pb.start(); System.err.println("pid: " + p.hashCode()); } else { System.err.println("info: NOT starting processmanager for instance " + p2.getOutfilebinary()); } }
From source file:de.ipbhalle.metfusion.main.SubstructureSearch.java
public static void main(String[] args) { String token = "eeca1d0f-4c03-4d81-aa96-328cdccf171a"; //String token = "a1004d0f-9d37-47e0-acdd-35e58e34f603"; //test();//from w w w .ja v a2 s . c o m //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/136m0498_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/148m0859_MSMS.mf"); // File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/164m0445a_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/192m0757a_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/naringenin.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/Known_BT_MSMS_ChemSp/1MeBT_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/150m0655a_MSMS.mf"); File file = new File( "C:/Users/Michael/Dropbox/Eawag_IPB_Shared_MassBank/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/192m0757b_MSMS.mf"); MetFusionBatchFileHandler mbf = new MetFusionBatchFileHandler(file); try { mbf.readFile(); } catch (IOException e) { //System.out.println(e.getMessage()); System.err.println( "Error reading from MetFusion settings file [" + file.getAbsolutePath() + "]. Aborting!"); System.exit(-1); } MetFusionBatchSettings settings = mbf.getBatchSettings(); List<String> absent = settings.getSubstrucAbsent(); List<String> present = settings.getSubstrucPresent(); for (String s : present) { System.out.println("present -> " + s); } for (String s : absent) { System.out.println("absent -> " + s); } String formula = settings.getMfFormula(); System.out.println("formula -> " + formula); boolean useFormulaAsQuery = true; boolean useSDF = false; String sdfFile = ""; if (useSDF) { sdfFile = "C:/Users/Michael/Dropbox/Eawag_IPB_Shared_MassBank/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/results_afterFormulaQuery/192m0757b_MSMS.sdf"; if (sdfFile.isEmpty()) { // TODO alternatively use SDF file from query file? System.err.println("SDF file needs to be specified! Exiting."); System.exit(-1); } } SubstructureSearch ss = new SubstructureSearch(present, absent, token, formula, mbf, useFormulaAsQuery, useSDF, sdfFile); ss.run(); List<ResultSubstructure> remaining = ss.getResultsRemaining(); List<Result> resultsForSDF = new ArrayList<Result>(); StringBuilder sb = new StringBuilder(); String sep = ","; for (ResultSubstructure rs : remaining) { sb.append(rs.getId()).append(sep); Result r = new Result(rs.getPort(), rs.getId(), rs.getName(), rs.getScore()); r.setMol(rs.getMol()); r.setSmiles(rs.getSmiles()); r.setInchi(rs.getInchi()); r.setInchikey(rs.getInchikey()); resultsForSDF.add(r); } String ids = sb.toString(); String fileSep = System.getProperty("file.separator"); if (!ids.isEmpty()) { ids = ids.substring(0, ids.length() - 1); System.out.println("ids -> " + ids); settings.setMfDatabaseIDs(ids); String filename = file.getName(); String prefix = filename.substring(0, filename.lastIndexOf(".")); filename = filename.replace(prefix, prefix + "_ids"); String dir = file.getParent(); System.out.println("dir -> " + dir); if (!dir.endsWith(fileSep)) dir += fileSep; File output = new File(file.getParent(), filename); mbf.writeFile(output, settings); SDFOutputHandler so = new SDFOutputHandler(dir + prefix + ".sdf"); boolean writeOK = so.writeOriginalResults(resultsForSDF, false); if (!writeOK) System.err.println("Error writing SDF [" + so.getFilename()); } }
From source file:gov.noaa.ncdc.iosp.avhrr.util.AvhrrLevel1B2Netcdf.java
/** * @param args// w w w . j a va2s . co m * the command line arguments */ public static void main(String args[]) throws Exception { // create the Options object Options options = new Options(); options.addOption(OPTION_NOGUI, false, "command line mode"); options.addOption(OPTION_ALLVAR, false, "Process all channels"); options.addOption(OPTION_CH1, false, "Process channel 1"); options.addOption(OPTION_CH2, false, "Process channel 2"); options.addOption(OPTION_CH3, false, "Process channel 3"); options.addOption(OPTION_CH4, false, "Process channel 4"); options.addOption(OPTION_CH5, false, "Process channel 5"); options.addOption(OPTION_DEFAULT, false, "Output All Channels, Brightness Temperature and Latitude and Longitude"); options.addOption(OPTION_TEMP, false, "Output calibrated temperatures/albedos"); options.addOption(OPTION_RAW, false, "Output raw values"); options.addOption(OPTION_RADIANCE, false, "Output radiance values"); options.addOption(OPTION_LATLON, false, "Output latitude and longitude"); options.addOption(OPTION_ALLVAR, false, "Output all variables)"); options.addOption(OPTION_CLOBBER, false, "Overwrite existing netCDF file."); options.addOption(OPTION_CALIBRATION, false, "Output calibration variables"); options.addOption(OPTION_QUALITY, false, "Output quality variables."); options.addOption(OPTION_METADATA, false, "Output metadata variables."); options.addOption("memory", false, "java heap space."); Option logOption = new Option("logFile", true, "Send output to file"); options.addOption(logOption); Option outdirOption = new Option("outputdir", true, "Output Directory."); options.addOption(outdirOption); // 2nd way is by creating an Option and then adding it Option timeOption = new Option(OPTION_AVHRR, true, "Process the Level1B file"); timeOption.setRequired(false); options.addOption(timeOption); // now lets parse the input CommandLineParser parser = new BasicParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException pe) { usage(options); return; } // now lets interrogate the options and execute the relevant parts if (cmd.hasOption(OPTION_NOGUI)) { // process command line args - need to refactor this (doing this // twice--BAD!!!!!) List<String> list = processCommandLineArgs(cmd); String file = cmd.getOptionValue(OPTION_AVHRR); if (null == file) { System.out.println("You must specify a file to convert!! missing -avhrr argument"); usage(options); return; } String outdir = cmd.getOptionValue("outputdir"); if (null == outdir || outdir.trim().length() < 1) { File f = new File("."); outdir = f.getAbsolutePath(); } // try { Avhrr2Netcdf.convert(file, list, outdir); // } catch (Exception e) { // System.out.println("this blew up"); // TODO Auto-generated catch block // e.printStackTrace(); // } } else { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels(); for (int i = 0; i < info.length; i++) { // Get the name of the look and feel that is suitable // for // display to the user String className = info[i].getClassName(); } String javaLF = UIManager.getSystemLookAndFeelClassName(); try { // UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); UIManager.setLookAndFeel(javaLF); } catch (ClassNotFoundException e) { // log.error(e.getMessage()); } catch (InstantiationException e) { // log.error(e.getMessage()); } catch (IllegalAccessException e) { // log.error(e.getMessage()); } catch (UnsupportedLookAndFeelException e) { // log.error(e.getMessage()); } mFrame = new AvhrrLevel1B2Netcdf(); mFrame.setVisible(true); } }); } }