List of usage examples for java.io File getAbsolutePath
public String getAbsolutePath()
From source file:fr.inria.edelweiss.kgimport.RdfSplitter.java
/** * The application entrypoint, configured through the command line input * arguments./*from ww w .ja v a2s .c o m*/ * * @param args the input command line arguments. */ public static void main(String args[]) { RdfSplitter rdfSplitter = new RdfSplitter(); Options options = new Options(); Option helpOpt = new Option("h", "help", false, "Print usage information."); Option inDirOpt = new Option("i", "input-dir", true, "The directory containing RDF files to be loaded."); Option outDirOpt = new Option("o", "output-dir", true, "The directory containing the generated RDF fragments"); Option predFiltOpt = new Option("p", "predicate-filter", true, "Predicate filter used to segment the dataset. " + "You can use multiple filters, typically one per fragment."); Option fragNbOpt = new Option("n", "number-of-fragments", true, "Number of fragments generated for the whole input dataset."); Option fragRepOpt = new Option("f", "fractionning-percentage", true, "Percentage of the whole input dataset for this fragment."); Option tdbOpt = new Option("tdb", "tdb-storage", false, "RDF fragments are persisted into a Jena TDB backend."); Option versionOpt = new Option("v", "version", false, "Print the version information and exit."); options.addOption(inDirOpt); options.addOption(outDirOpt); options.addOption(predFiltOpt); options.addOption(helpOpt); options.addOption(versionOpt); options.addOption(fragNbOpt); options.addOption(fragRepOpt); options.addOption(tdbOpt); String header = "RDF data fragmentation tool command line interface"; String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr"; CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar [].jar", header, options, footer, true); System.exit(0); } if (!cmd.hasOption("i")) { logger.warn("You must specify a valid input directory !"); System.exit(-1); } else { rdfSplitter.setInputDirPath(cmd.getOptionValue("i")); } if (!cmd.hasOption("o")) { logger.warn("You must specify a valid output directory !"); System.exit(-1); } else { rdfSplitter.setOutputDirPath(cmd.getOptionValue("o")); } if (cmd.hasOption("p")) { rdfSplitter.setInputPredicates(new ArrayList<String>(Arrays.asList(cmd.getOptionValues("p")))); } if (cmd.hasOption("f")) { ArrayList<String> opts = new ArrayList<String>(Arrays.asList(cmd.getOptionValues("f"))); for (String opt : opts) { try { rdfSplitter.getFragList().add(Integer.parseInt(opt)); } catch (NumberFormatException e) { logger.error(opt + " cannot be pased as an percentage value."); System.exit(-1); } } } if (cmd.hasOption("n")) { try { rdfSplitter.setFragNb(Integer.parseInt(cmd.getOptionValue("n"))); } catch (NumberFormatException e) { logger.error(cmd.getOptionValue("n") + " cannot be pased as an integer value."); System.exit(-1); } } File oDir = new File(rdfSplitter.getOutputDirPath()); if (oDir.exists()) { logger.warn(rdfSplitter.getOutputDirPath() + " already exists !"); oDir = Files.createTempDir(); logger.warn(oDir.getAbsolutePath() + " created."); rdfSplitter.setOutputDirPath(oDir.getAbsolutePath()); } else { if (oDir.mkdir()) { logger.info(rdfSplitter.getOutputDirPath() + " created."); } } if (!cmd.hasOption("n") && !cmd.hasOption("f") && !cmd.hasOption("p")) { logger.error("You must specify just one fragmentation type through '-n', '-f', or 'p' options"); for (String arg : args) { logger.trace(arg); } System.exit(-1); } String fragName = rdfSplitter.getInputDirPath() .substring(rdfSplitter.getInputDirPath().lastIndexOf("/") + 1); //Input data loading Model model = ModelFactory.createDefaultModel(); File inputDir = new File(rdfSplitter.getInputDirPath()); if (inputDir.isDirectory()) { for (File f : inputDir.listFiles()) { logger.info("Loading " + f.getAbsolutePath()); if (f.isDirectory()) { String directory = f.getAbsolutePath(); Dataset dataset = TDBFactory.createDataset(directory); dataset.begin(ReadWrite.READ); // Get model inside the transaction model.add(dataset.getDefaultModel()); dataset.end(); } else { InputStream iS; try { iS = new FileInputStream(f); if (f.getAbsolutePath().endsWith(".n3")) { model.read(iS, null, "N3"); } else if (f.getAbsolutePath().endsWith(".nt")) { model.read(iS, null, "N-TRIPLES"); } else if (f.getAbsolutePath().endsWith(".rdf")) { model.read(iS, null); } } catch (FileNotFoundException ex) { LogManager.getLogger(RdfSplitter.class.getName()).log(Level.ERROR, "", ex); } } } logger.info("Loaded " + model.size() + " triples"); } else { System.exit(0); } StopWatch sw = new StopWatch(); if (cmd.hasOption("n")) { sw.start(); if (cmd.hasOption("tdb")) { rdfSplitter.saveFragmentsTDB(rdfSplitter.getFragHoriz(model, rdfSplitter.getFragNb()), "Homog-" + fragName); } else { rdfSplitter.saveFragmentsRDF(rdfSplitter.getFragHoriz(model, rdfSplitter.getFragNb()), "Homog-" + fragName); } logger.info("Homog horiz frag in " + sw.getTime() + "ms"); sw.reset(); } else if (cmd.hasOption("f")) { sw.start(); if (cmd.hasOption("tdb")) { rdfSplitter.saveFragmentsTDB(rdfSplitter.getFragHoriz(model, rdfSplitter.getFragList()), "Inhomog-" + fragName); } else { rdfSplitter.saveFragmentsRDF(rdfSplitter.getFragHoriz(model, rdfSplitter.getFragList()), "Inhomog-" + fragName); } logger.info("Inhomog horiz frag in " + sw.getTime() + "ms"); sw.reset(); } else if (cmd.hasOption("p")) { sw.start(); if (cmd.hasOption("tdb")) { rdfSplitter.saveFragmentsTDB(rdfSplitter.getFragVert(model, rdfSplitter.getInputPredicates())); } else { rdfSplitter.saveFragmentsRDF(rdfSplitter.getFragVert(model, rdfSplitter.getInputPredicates())); } logger.info("Vert frag in " + sw.getTime() + "ms"); sw.reset(); } } catch (ParseException ex) { logger.error("Impossible to parse the input command line " + cmd.toString()); } }
From source file:ms1quant.MS1Quant.java
/** * @param args the command line arguments MS1Quant parameterfile *///w w w .j ava 2 s . c o m public static void main(String[] args) throws Exception { BufferedReader reader = null; try { System.out.println( "================================================================================================="); System.out.println("Umpire MS1 quantification and feature detection analysis (version: " + UmpireInfo.GetInstance().Version + ")"); if (args.length < 3 || !args[1].startsWith("-mode")) { System.out .println("command : java -jar -Xmx10G MS1Quant.jar ms1quant.params -mode[1 or 2] [Option]"); System.out.println("\n-mode"); System.out.println("\t1:Single file mode--> mzXML_file PepXML_file"); System.out.println("\t\tEx: -mode1 file1.mzXML file1.pep.xml"); System.out.println( "\t2:Folder mode--> mzXML_Folder PepXML_Folder, all generated csv tables will be merged into a single csv file"); System.out.println("\t\tEx: -mode2 /data/mzxml/ /data/pepxml/"); System.out.println("\nOptions"); System.out.println( "\t-C\tNo of concurrent files to be processed (only for folder mode), Ex. -C5, default:1"); System.out.println("\t-p\tMinimum probability, Ex. -p0.9, default:0.9"); System.out.println("\t-ID\tDetect identified feature only"); System.out.println("\t-O\toutput folder, Ex. -O/data/"); return; } ConsoleLogger consoleLogger = new ConsoleLogger(); consoleLogger.SetConsoleLogger(Level.DEBUG); consoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "ms1quant_debug.log"); Logger logger = Logger.getRootLogger(); logger.debug("Command: " + Arrays.toString(args)); logger.info("MS1Quant version: " + UmpireInfo.GetInstance().Version); String parameterfile = args[0]; logger.info("Parameter file: " + parameterfile); File paramfile = new File(parameterfile); if (!paramfile.exists()) { logger.error("Parameter file " + paramfile.getAbsolutePath() + " cannot be found. The program will exit."); } reader = new BufferedReader(new FileReader(paramfile.getAbsolutePath())); String line = ""; InstrumentParameter param = new InstrumentParameter(InstrumentParameter.InstrumentType.TOF5600); int NoCPUs = 2; int NoFile = 1; param.DetermineBGByID = false; param.EstimateBG = true; //<editor-fold defaultstate="collapsed" desc="Read parameter file"> while ((line = reader.readLine()) != null) { if (!"".equals(line) && !line.startsWith("#")) { logger.info(line); //System.out.println(line); if (line.split("=").length < 2) { continue; } if (line.split("=").length < 2) { continue; } String type = line.split("=")[0].trim(); if (type.startsWith("para.")) { type = type.replace("para.", "SE."); } String value = line.split("=")[1].trim(); switch (type) { case "Thread": { NoCPUs = Integer.parseInt(value); break; } //<editor-fold defaultstate="collapsed" desc="instrument parameters"> case "SE.MS1PPM": { param.MS1PPM = Float.parseFloat(value); break; } case "SE.MS2PPM": { param.MS2PPM = Float.parseFloat(value); break; } case "SE.SN": { param.SNThreshold = Float.parseFloat(value); break; } case "SE.MS2SN": { param.MS2SNThreshold = Float.parseFloat(value); break; } case "SE.MinMSIntensity": { param.MinMSIntensity = Float.parseFloat(value); break; } case "SE.MinMSMSIntensity": { param.MinMSMSIntensity = Float.parseFloat(value); break; } case "SE.MinRTRange": { param.MinRTRange = Float.parseFloat(value); break; } case "SE.MaxNoPeakCluster": { param.MaxNoPeakCluster = Integer.parseInt(value); param.MaxMS2NoPeakCluster = Integer.parseInt(value); break; } case "SE.MinNoPeakCluster": { param.MinNoPeakCluster = Integer.parseInt(value); param.MinMS2NoPeakCluster = Integer.parseInt(value); break; } case "SE.MinMS2NoPeakCluster": { param.MinMS2NoPeakCluster = Integer.parseInt(value); break; } case "SE.MaxCurveRTRange": { param.MaxCurveRTRange = Float.parseFloat(value); break; } case "SE.Resolution": { param.Resolution = Integer.parseInt(value); break; } case "SE.RTtol": { param.RTtol = Float.parseFloat(value); break; } case "SE.NoPeakPerMin": { param.NoPeakPerMin = Integer.parseInt(value); break; } case "SE.StartCharge": { param.StartCharge = Integer.parseInt(value); break; } case "SE.EndCharge": { param.EndCharge = Integer.parseInt(value); break; } case "SE.MS2StartCharge": { param.MS2StartCharge = Integer.parseInt(value); break; } case "SE.MS2EndCharge": { param.MS2EndCharge = Integer.parseInt(value); break; } case "SE.NoMissedScan": { param.NoMissedScan = Integer.parseInt(value); break; } case "SE.Denoise": { param.Denoise = Boolean.valueOf(value); break; } case "SE.EstimateBG": { param.EstimateBG = Boolean.valueOf(value); break; } case "SE.RemoveGroupedPeaks": { param.RemoveGroupedPeaks = Boolean.valueOf(value); break; } case "SE.MinFrag": { param.MinFrag = Integer.parseInt(value); break; } case "SE.IsoPattern": { param.IsoPattern = Float.valueOf(value); break; } case "SE.StartRT": { param.startRT = Float.valueOf(value); } case "SE.EndRT": { param.endRT = Float.valueOf(value); } //</editor-fold> } } } //</editor-fold> int mode = 1; if (args[1].equals("-mode2")) { mode = 2; } else if (args[1].equals("-mode1")) { mode = 1; } else { logger.error("-mode number not recongized. The program will exit."); } String mzXML = ""; String pepXML = ""; String mzXMLPath = ""; String pepXMLPath = ""; File mzXMLfile = null; File pepXMLfile = null; File mzXMLfolder = null; File pepXMLfolder = null; int idx = 0; if (mode == 1) { mzXML = args[2]; logger.info("Mode1 mzXML file: " + mzXML); mzXMLfile = new File(mzXML); if (!mzXMLfile.exists()) { logger.error("Mode1 mzXML file " + mzXMLfile.getAbsolutePath() + " cannot be found. The program will exit."); return; } pepXML = args[3]; logger.info("Mode1 pepXML file: " + pepXML); pepXMLfile = new File(pepXML); if (!pepXMLfile.exists()) { logger.error("Mode1 pepXML file " + pepXMLfile.getAbsolutePath() + " cannot be found. The program will exit."); return; } idx = 4; } else if (mode == 2) { mzXMLPath = args[2]; logger.info("Mode2 mzXML folder: " + mzXMLPath); mzXMLfolder = new File(mzXMLPath); if (!mzXMLfolder.exists()) { logger.error("Mode2 mzXML folder " + mzXMLfolder.getAbsolutePath() + " does not exist. The program will exit."); return; } pepXMLPath = args[3]; logger.info("Mode2 pepXML folder: " + pepXMLPath); pepXMLfolder = new File(pepXMLPath); if (!pepXMLfolder.exists()) { logger.error("Mode2 pepXML folder " + pepXMLfolder.getAbsolutePath() + " does not exist. The program will exit."); return; } idx = 4; } String outputfolder = ""; float MinProb = 0f; for (int i = idx; i < args.length; i++) { if (args[i].startsWith("-")) { if (args[i].equals("-ID")) { param.TargetIDOnly = true; logger.info("Detect ID feature only: true"); } if (args[i].startsWith("-O")) { outputfolder = args[i].substring(2); logger.info("Output folder: " + outputfolder); File outputfile = new File(outputfolder); if (!outputfolder.endsWith("\\") | outputfolder.endsWith("/")) { outputfolder += "/"; } if (!outputfile.exists()) { outputfile.mkdir(); } } if (args[i].startsWith("-C")) { try { NoFile = Integer.parseInt(args[i].substring(2)); logger.info("No of concurrent files: " + NoFile); } catch (Exception ex) { logger.error(args[i] + " is not a correct integer format, will process only one file at a time."); } } if (args[i].startsWith("-p")) { try { MinProb = Float.parseFloat(args[i].substring(2)); logger.info("probability threshold: " + MinProb); } catch (Exception ex) { logger.error(args[i] + " is not a correct format, will use 0 as threshold instead."); } } } } reader.close(); TandemParam tandemparam = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600); PTMManager.GetInstance(); if (param.TargetIDOnly) { param.EstimateBG = false; param.ApexDelta = 1.5f; param.NoMissedScan = 10; param.MiniOverlapP = 0.2f; param.RemoveGroupedPeaks = false; param.CheckMonoIsotopicApex = false; param.DetectByCWT = false; param.FillGapByBK = false; param.IsoCorrThreshold = -1f; param.SmoothFactor = 3; } if (mode == 1) { logger.info("Processing " + mzXMLfile.getAbsolutePath() + "...."); long time = System.currentTimeMillis(); LCMSPeakMS1 LCMS1 = new LCMSPeakMS1(mzXMLfile.getAbsolutePath(), NoCPUs); LCMS1.SetParameter(param); LCMS1.Resume = false; if (!param.TargetIDOnly) { LCMS1.CreatePeakFolder(); } LCMS1.ExportPeakClusterTable = true; if (pepXMLfile.exists()) { tandemparam.InteractPepXMLPath = pepXMLfile.getAbsolutePath(); LCMS1.ParsePepXML(tandemparam, MinProb); logger.info("No. of PSMs included: " + LCMS1.IDsummary.PSMList.size()); logger.info("No. of Peptide ions included: " + LCMS1.IDsummary.GetPepIonList().size()); } if (param.TargetIDOnly) { LCMS1.SaveSerializationFile = false; } if (param.TargetIDOnly || !LCMS1.ReadPeakCluster()) { LCMS1.PeakClusterDetection(); } if (pepXMLfile.exists()) { LCMS1.AssignQuant(false); LCMS1.IDsummary.ExportPepID(outputfolder); } time = System.currentTimeMillis() - time; logger.info(LCMS1.ParentmzXMLName + " 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)))); LCMS1.BaseClearAllPeaks(); LCMS1.SetSpectrumParser(null); LCMS1.IDsummary = null; LCMS1 = null; System.gc(); } else if (mode == 2) { LCMSID IDsummary = new LCMSID("", "", ""); logger.info("Parsing all pepXML files in " + pepXMLPath + "...."); for (File file : pepXMLfolder.listFiles()) { if (file.getName().toLowerCase().endsWith("pep.xml") || file.getName().toLowerCase().endsWith("pepxml")) { PepXMLParser pepXMLParser = new PepXMLParser(IDsummary, file.getAbsolutePath(), MinProb); } } HashMap<String, LCMSID> LCMSIDMap = IDsummary.GetLCMSIDFileMap(); ExecutorService executorPool = null; executorPool = Executors.newFixedThreadPool(NoFile); logger.info("Processing all mzXML files in " + mzXMLPath + "...."); for (File file : mzXMLfolder.listFiles()) { if (file.getName().toLowerCase().endsWith("mzxml")) { LCMSID id = LCMSIDMap.get(FilenameUtils.getBaseName(file.getName())); if (id == null || id.PSMList == null) { logger.warn("No IDs found in :" + FilenameUtils.getBaseName(file.getName()) + ". Quantification for this file is skipped"); continue; } if (!id.PSMList.isEmpty()) { MS1TargetQuantThread thread = new MS1TargetQuantThread(file, id, NoCPUs, outputfolder, param); executorPool.execute(thread); } } } LCMSIDMap.clear(); LCMSIDMap = null; IDsummary = null; executorPool.shutdown(); try { executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { logger.info("interrupted.."); } if (outputfolder == null | outputfolder.equals("")) { outputfolder = mzXMLPath; } logger.info("Merging PSM files.."); File output = new File(outputfolder); FileWriter writer = new FileWriter(output.getAbsolutePath() + "/PSM_merge.csv"); boolean header = false; for (File csvfile : output.listFiles()) { if (csvfile.getName().toLowerCase().endsWith("_psms.csv")) { BufferedReader outreader = new BufferedReader(new FileReader(csvfile)); String outline = outreader.readLine(); if (!header) { writer.write(outline + "\n"); header = true; } while ((outline = outreader.readLine()) != null) { writer.write(outline + "\n"); } outreader.close(); csvfile.delete(); } } writer.close(); } logger.info("MS1 quant module is complete."); } catch (Exception e) { Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e)); throw e; } }
From source file:com.bericotech.clavin.index.IndexDirectoryBuilder.java
/** * Turns a GeoNames gazetteer file into a Lucene index, and adds * some supplementary gazetteer records at the end. * * @param args not used/*from w w w . ja v a 2 s .co m*/ * @throws IOException */ public static void main(String[] args) throws IOException { Options options = getOptions(); CommandLine cmd = null; CommandLineParser parser = new GnuParser(); try { cmd = parser.parse(options, args); } catch (ParseException pe) { LOG.error(pe.getMessage()); printHelp(options); System.exit(-1); } if (cmd.hasOption(HELP_OPTION)) { printHelp(options); System.exit(0); } String indexPath = cmd.getOptionValue(INDEX_PATH_OPTION, DEFAULT_INDEX_DIRECTORY); String[] gazetteerPaths = cmd.getOptionValues(GAZETTEER_FILES_OPTION); if (gazetteerPaths == null || gazetteerPaths.length == 0) { gazetteerPaths = DEFAULT_GAZETTEER_FILES; } boolean replaceIndex = cmd.hasOption(REPLACE_INDEX_OPTION); boolean fullAncestry = cmd.hasOption(FULL_ANCESTRY_OPTION); File idir = new File(indexPath); // if the index directory exists, delete it if we are replacing, otherwise // exit gracefully if (idir.exists()) { if (replaceIndex) { LOG.info("Replacing index: {}", idir.getAbsolutePath()); FileUtils.deleteDirectory(idir); } else { LOG.info("{} exists. Remove the directory and try again.", idir.getAbsolutePath()); System.exit(-1); } } List<File> gazetteerFiles = new ArrayList<File>(); for (String gp : gazetteerPaths) { File gf = new File(gp); if (gf.isFile() && gf.canRead()) { gazetteerFiles.add(gf); } else { LOG.info("Unable to read Gazetteer file: {}", gf.getAbsolutePath()); } } if (gazetteerFiles.isEmpty()) { LOG.error("No Gazetteer files found."); System.exit(-1); } String altNamesPath = cmd.getOptionValue(ALTERNATE_NAMES_OPTION); File altNamesFile = altNamesPath != null ? new File(altNamesPath) : null; if (altNamesFile != null && !(altNamesFile.isFile() && altNamesFile.canRead())) { LOG.error("Unable to read alternate names file: {}", altNamesPath); System.exit(-1); } new IndexDirectoryBuilder(fullAncestry).buildIndex(idir, gazetteerFiles, altNamesFile); }
From source file:com.cohesionforce.AvroToParquet.java
public static void main(String[] args) { String inputFile = null;//from w w w .j a va 2 s . c o m String outputFile = null; HelpFormatter formatter = new HelpFormatter(); // create Options object Options options = new Options(); // add t option options.addOption("i", true, "input avro file"); options.addOption("o", true, "ouptut Parquet file"); CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); inputFile = cmd.getOptionValue("i"); if (inputFile == null) { formatter.printHelp("AvroToParquet", options); return; } outputFile = cmd.getOptionValue("o"); } catch (ParseException exc) { System.err.println("Problem with command line parameters: " + exc.getMessage()); return; } File avroFile = new File(inputFile); if (!avroFile.exists()) { System.err.println("Could not open file: " + inputFile); return; } try { DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(); DataFileReader<GenericRecord> dataFileReader; dataFileReader = new DataFileReader<GenericRecord>(avroFile, datumReader); Schema avroSchema = dataFileReader.getSchema(); // choose compression scheme CompressionCodecName compressionCodecName = CompressionCodecName.SNAPPY; // set Parquet file block size and page size values int blockSize = 256 * 1024 * 1024; int pageSize = 64 * 1024; String base = FilenameUtils.removeExtension(avroFile.getAbsolutePath()) + ".parquet"; if (outputFile != null) { File file = new File(outputFile); base = file.getAbsolutePath(); } Path outputPath = new Path("file:///" + base); // the ParquetWriter object that will consume Avro GenericRecords ParquetWriter<GenericRecord> parquetWriter; parquetWriter = new AvroParquetWriter<GenericRecord>(outputPath, avroSchema, compressionCodecName, blockSize, pageSize); for (GenericRecord record : dataFileReader) { parquetWriter.write(record); } dataFileReader.close(); parquetWriter.close(); } catch (IOException e) { System.err.println("Caught exception: " + e.getMessage()); } }
From source file:de.prozesskraft.pkraft.Clone.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { /*---------------------------- get options from ini-file//from w ww. ja va 2s . c o m ----------------------------*/ java.io.File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Clone.class) + "/" + "../etc/pkraft-clone.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 oinstance = OptionBuilder.withArgName("File").hasArg() .withDescription("[mandatory] process you want to clone.") // .isRequired() .create("instance"); Option obasedir = OptionBuilder.withArgName("DIR").hasArg().withDescription( "[optional, default: <basedirOfInstance>] base directory you want to place the root directory of the clone. this directory must exist at call time.") // .isRequired() .create("basedir"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(oinstance); options.addOption(obasedir); /*---------------------------- 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("clone", options); System.exit(0); } if (commandline.hasOption("v")) { System.out.println("author: alexander.vogel@prozesskraft.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("instance"))) { System.err.println("option -instance is mandatory"); 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 ----------------------------*/ String pathToInstance = commandline.getOptionValue("instance"); java.io.File fileInstance = new java.io.File(pathToInstance); java.io.File fileBaseDir = null; // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen if (!fileInstance.exists()) { System.err.println("instance file does not exist."); exiter(); } // testen ob eventuell vorhandene angaben basedir if (commandline.hasOption("basedir")) { fileBaseDir = new java.io.File(commandline.getOptionValue("basedir")); if (!fileBaseDir.exists()) { System.err.println("error: -basedir: directory does not exist"); exiter(); } if (!fileBaseDir.isDirectory()) { System.err.println("error: -basedir: is not a directory"); exiter(); } } // den main-prozess trotzdem nochmal einlesen um subprozesse extrahieren zu koennen Process p1 = new Process(); p1.setInfilebinary(pathToInstance); Process process = p1.readBinary(); // directories setzen, falls angegeben if (fileBaseDir != null) { process.setBaseDir(fileBaseDir.getCanonicalPath()); } // den main-prozess ueber die static function klonen Process clonedProcess = cloneProcess(process, null); // alle steps durchgehen und falls subprocesses existieren auch fuer diese ein cloning durchfuehren for (Step actStep : process.getStep()) { if (actStep.getSubprocess() != null) { Process pDummy = new Process(); pDummy.setInfilebinary(actStep.getAbsdir() + "/process.pmb"); Process processInSubprocess = pDummy.readBinary(); // System.err.println("info: reading process freshly from file: " + actStep.getAbsdir() + "/process.pmb"); if (processInSubprocess != null) { cloneProcess(processInSubprocess, clonedProcess); } } } }
From source file:DIA_Umpire_Quant.DIA_Umpire_ProtQuant.java
/** * @param args the command line arguments */// w ww. jav a2 s . c o m public static void main(String[] args) throws FileNotFoundException, IOException, Exception { System.out.println( "================================================================================================="); System.out.println( "DIA-Umpire protein quantitation module (version: " + UmpireInfo.GetInstance().Version + ")"); if (args.length != 1) { System.out.println( "command format error, the correct format should be: java -jar -Xmx10G DIA_Umpire_PortQuant.jar diaumpire_module.params"); return; } try { ConsoleLogger.SetConsoleLogger(Level.INFO); ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_orotquant.log"); } catch (Exception e) { } 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 Combined_Prot = ""; boolean DefaultProtFiltering = true; float Freq = 0f; int TopNPep = 6; int TopNFrag = 6; String FilterWeight = "GW"; float MinWeight = 0.9f; TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600); HashMap<String, File> AssignFiles = new HashMap<>(); 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 "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 "ProteinFDR": { tandemPara.ProtFDR = 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; } //<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(); //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<>(); try { 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()); } for (File fileEntry : AssignFiles.values()) { String mzXMLFile = fileEntry.getAbsolutePath(); if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) { DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs); 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); } Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "...."); //If the serialization file for ID file existed if (DiaFile.ReadSerializedLCMSID()) { DiaFile.IDsummary.ReduceMemoryUsage(); DiaFile.IDsummary.ClearAssignPeakCluster(); FileList.add(DiaFile); HashMap<String, FragmentPeak> FragMap = new HashMap<>(); IDSummaryFragments.put(FilenameUtils.getBaseName(mzXMLFile), FragMap); } } } //<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 (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.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:de.fatalix.book.importer.CalibriImporter.java
public static void main(String[] args) throws IOException, URISyntaxException, SolrServerException { Gson gson = new Gson(); CalibriImporterConfiguration config = gson.fromJson(args[0], CalibriImporterConfiguration.class); File importFolder = new File(config.getImportFolder()); if (importFolder.isDirectory()) { File[] zipFiles = importFolder.listFiles(new FilenameFilter() { @Override/*from ww w . j ava 2 s.c om*/ public boolean accept(File dir, String name) { return name.endsWith(".zip"); } }); for (File zipFile : zipFiles) { try { processBooks(zipFile.toPath(), config.getSolrCore(), config.getSolrCore(), config.getBatchSize()); System.out.println("Processed file " + zipFile.getName()); } catch (IOException ex) { ex.printStackTrace(); } } } else { System.out.println("Import folder: " + importFolder.getAbsolutePath() + " cannot be read!"); } }
From source file:licenseUtil.LicenseUtil.java
public static void main(String[] args) throws IOException, IncompleteLicenseObjectException { if (args.length == 0) { logger.error("Missing parameters. Use --help to get a list of the possible options."); } else if (args[0].equals("--addPomToTsv")) { if (args.length < 4) logger.error(/* w w w. j a v a 2 s . c o m*/ "Missing arguments for option --addPomToTsv. Please specify <pomFileName> <licenses.stub.tsv> <currentVersion> or use the option --help for further information."); String pomFN = args[1]; String spreadSheetFN = args[2]; String currentVersion = args[3]; MavenProject project = null; try { project = Utils.readPom(new File(pomFN)); } catch (XmlPullParserException e) { logger.error("Could not parse pom file: \"" + pomFN + "\""); } LicensingList licensingList = new LicensingList(); File f = new File(spreadSheetFN); if (f.exists() && !f.isDirectory()) { licensingList.readFromSpreadsheet(spreadSheetFN); } licensingList.addMavenProject(project, currentVersion); licensingList.writeToSpreadsheet(spreadSheetFN); } else if (args[0].equals("--writeLicense3rdParty")) { if (args.length < 4) logger.error( "Missing arguments for option --writeLicense3rdParty. Please provide <licenses.enhanced.tsv> <processModule> <currentVersion> [and <targetDir>] or use the option --help for further information."); String spreadSheetFN = args[1]; String processModule = args[2]; String currentVersion = args[3]; HashMap<String, String> targetDirs = new HashMap<>(); if (args.length > 4) { File targetDir = new File(args[4]); logger.info("scan pom files in direct subdirectories of \"" + targetDir.getPath() + "\" to obtain target locations for 3rd party license files..."); File[] subdirs = targetDir.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY); for (File subdir : subdirs) { File pomFile = new File(subdir.getPath() + File.separator + POM_FN); if (!pomFile.exists()) continue; MavenProject mavenProject; try { mavenProject = Utils.readPom(pomFile); } catch (Exception e) { logger.warn("Could not read from pom file: \"" + pomFile.getPath() + "\" because of " + e.getMessage()); continue; } targetDirs.put(mavenProject.getModel().getArtifactId(), subdir.getAbsolutePath()); } } LicensingList licensingList = new LicensingList(); licensingList.readFromSpreadsheet(spreadSheetFN); if (processModule.toUpperCase().equals("ALL")) { for (String module : licensingList.getNonFixedHeaders()) { try { writeLicense3rdPartyFile(module, licensingList, currentVersion, targetDirs.get(module)); } catch (NoLicenseTemplateSetException e) { logger.error("Could not write file for module \"" + module + "\". There is no template specified for \"" + e.getLicensingObject() + "\". Please add an existing template filename to the column \"" + LicensingObject.ColumnHeader.LICENSE_TEMPLATE.value() + "\" of \"" + spreadSheetFN + "\"."); } } } else { try { writeLicense3rdPartyFile(processModule, licensingList, currentVersion, targetDirs.get(processModule)); } catch (NoLicenseTemplateSetException e) { logger.error("Could not write file for module \"" + processModule + "\". There is no template specified for \"" + e.getLicensingObject() + "\". Please add an existing template filename to the column \"" + LicensingObject.ColumnHeader.LICENSE_TEMPLATE.value() + "\" of \"" + spreadSheetFN + "\"."); } } } else if (args[0].equals("--buildEffectivePom")) { Utils.writeEffectivePom(new File(args[1]), (new File(EFFECTIVE_POM_FN)).getAbsolutePath()); } else if (args[0].equals("--updateTsvWithProjectsInFolder")) { if (args.length < 4) logger.error( "Missing arguments for option --processProjectsInFolder. Please provide <superDirectory> <licenses.stub.tsv> and <currentVersion> or use the option --help for further information."); File directory = new File(args[1]); String spreadSheetFN = args[2]; String currentVersion = args[3]; LicensingList licensingList = new LicensingList(); File f = new File(spreadSheetFN); if (f.exists() && !f.isDirectory()) { licensingList.readFromSpreadsheet(spreadSheetFN); } licensingList.addAll(processProjectsInFolder(directory, currentVersion, false)); licensingList.writeToSpreadsheet(spreadSheetFN); } else if (args[0].equals("--purgeTsv")) { if (args.length < 3) logger.error( "Missing arguments for option --purgeTsv. Please provide <spreadSheetIN.tsv>, <spreadSheetOUT.tsv> and <currentVersion> or use the option --help for further information."); String spreadSheetIN = args[1]; String spreadSheetOUT = args[2]; String currentVersion = args[3]; LicensingList licensingList = new LicensingList(); licensingList.readFromSpreadsheet(spreadSheetIN); licensingList.purge(currentVersion); licensingList.writeToSpreadsheet(spreadSheetOUT); } else if (args[0].equals("--help")) { InputStream in = LicenseUtil.class.getClassLoader().getResourceAsStream(README_PATH); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } else { logger.error("Unknown parameter: " + args[0] + ". Use --help to get a list of the possible options."); } }
From source file:de.prozesskraft.pkraft.Commitit.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try// ww w . j a v a 2s .c o 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 ----------------------------*/ java.io.File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Commitit.class) + "/" + "../etc/pkraft-commitit.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"); /*---------------------------- create argument options ----------------------------*/ Option oinstance = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory] process instance file") // .isRequired() .create("instance"); Option ostep = OptionBuilder.withArgName("STEPNAME").hasArg() .withDescription("[optional, default: root] process step to commit to") // .isRequired() .create("step"); Option ofile = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[optional] this file will be committed as file. key will be set to 'default'") // .isRequired() .create("file"); Option okey = OptionBuilder.withArgName("KEY").hasArg() .withDescription( "[optional, default: default] this string will be considered as the key for the commit.") // .isRequired() .create("key"); Option ovariable = OptionBuilder.withArgName("VALUE").hasArg() .withDescription("[optional] this string will be committed as a variable.") // .isRequired() .create("variable"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(oinstance); options.addOption(ostep); options.addOption(ofile); options.addOption(okey); options.addOption(ovariable); /*---------------------------- 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("commit", options); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ if (!(commandline.hasOption("instance"))) { System.out.println("option -instance is mandatory."); exiter(); } else if (!(commandline.hasOption("dir")) && !(commandline.hasOption("file")) && !(commandline.hasOption("varfile")) && !(commandline.hasOption("varname")) && !(commandline.hasOption("varvalue")) && !(commandline.hasOption("variable"))) { System.out.println( "at least one of these options needed. -dir -file -varfile -variable -varname -varvalue."); exiter(); } else if ((commandline.hasOption("varname") && !(commandline.hasOption("varvalue"))) || (!(commandline.hasOption("varname")) && commandline.hasOption("varvalue"))) { System.out.println("use options -varname and -varvalue only in combination with each other."); 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 ----------------------------*/ // setzen des steps String stepname = "root"; if (commandline.hasOption("step")) { stepname = commandline.getOptionValue("step"); } // setzen des key String key = "default"; if (commandline.hasOption("key")) { key = commandline.getOptionValue("key"); } Process p1 = new Process(); p1.setInfilebinary(commandline.getOptionValue("instance")); System.out.println("info: reading process instance " + commandline.getOptionValue("instance")); Process p2 = p1.readBinary(); p2.setOutfilebinary(commandline.getOptionValue("instance")); // step ueber den namen heraussuchen Step step = p2.getStep(stepname); if (step == null) { System.err.println("step not found: " + stepname); exiter(); } // den Commit 'by-process-commitit' heraussuchen oder einen neuen Commit dieses Namens erstellen Commit commit = step.getCommit("by-hand"); if (commit == null) { commit = new Commit(step); commit.setName("by-process-commitit"); } // committen if (commandline.hasOption("file")) { File file = new File(); file.setKey(key); file.setGlob(commandline.getOptionValue("file")); commit.addFile(file); commit.doIt(); } if (commandline.hasOption("variable")) { Variable variable = new Variable(); variable.setKey(key); variable.setValue(commandline.getOptionValue("variable")); commit.addVariable(variable); commit.doIt(); } p2.writeBinary(); System.out.println("info: writing process instance " + p2.getOutfilebinary()); }
From source file:act.installer.reachablesexplorer.FreemarkerRenderer.java
public static void main(String[] args) throws Exception { CLIUtil cliUtil = new CLIUtil(Loader.class, HELP_MESSAGE, OPTION_BUILDERS); CommandLine cl = cliUtil.parseCommandLine(args); File baseOutputDir = new File(cl.getOptionValue(OPTION_OUTPUT_DEST)); if (!baseOutputDir.exists()) { cliUtil.failWithMessage("Unable to find output directory at %s", baseOutputDir.getAbsolutePath()); return;/*from w w w .j av a 2s. c o m*/ } File reachablesOut = new File(baseOutputDir, "Reachables"); File pathsOut = new File(baseOutputDir, "Paths"); File seqsOut = new File(baseOutputDir, "Sequences"); for (File subdir : Arrays.asList(reachablesOut, pathsOut, seqsOut)) { if (!subdir.exists()) { LOGGER.info("Creating output directory at %s", subdir.getAbsolutePath()); subdir.mkdir(); } else if (!subdir.isDirectory()) { cliUtil.failWithMessage("Output directory at %s is not a directory", subdir.getAbsolutePath()); return; } } FreemarkerRenderer renderer = FreemarkerRendererFactory.build( cl.getOptionValue(OPTION_DB_HOST, DEFAULT_HOST), Integer.valueOf(cl.getOptionValue(OPTION_DB_PORT, DEFAULT_PORT.toString())), cl.getOptionValue(OPTION_DB_NAME, DEFAULT_DB_NAME), cl.getOptionValue(OPTION_REACHABLES_COLLECTION, DEFAULT_REACHABLES_COLLECTION), cl.getOptionValue(OPTION_SEQUENCES_COLLECTION, DEFAULT_SEQUENCES_COLLECTION), cl.getOptionValue(OPTION_DNA_COLLECTION, DEFAULT_DNA_COLLECTION), cl.getOptionValue(OPTION_RENDERING_CACHE, DEFAULT_RENDERING_CACHE), cl.getOptionValue(OPTION_INSTALLER_SOURCE_DB, DEFAULT_CHEMICALS_DATABASE), cl.getOptionValue(OPTION_PATHWAY_COLLECTION, DEFAULT_PATHWAY_COLLECTION), cl.hasOption(OPTION_OMIT_PATHWAYS_AND_DESIGNS), reachablesOut, pathsOut, seqsOut); LOGGER.info("Page generation starting"); List<Long> idsToRender = Collections.emptyList(); if (cl.hasOption(OPTION_RENDER_SOME)) { idsToRender = Arrays.stream(cl.getOptionValues(OPTION_RENDER_SOME)).map(renderer::lookupMolecule) .collect(Collectors.toList()); } renderer.generatePages(idsToRender); }