List of usage examples for java.io File exists
public boolean exists()
From source file:com.tmo.swagger.main.GenrateSwaggerJson.java
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException, EmptyXlsRows { PropertyReader pr = new PropertyReader(); Properties prop = pr.readPropertiesFile(args[0]); //Properties prop =pr.readClassPathPropertyFile("common.properties"); String swaggerFile = prop.getProperty("swagger.json"); String sw = ""; if (swaggerFile != null && swaggerFile.length() > 0) { Swagger swagger = populatePropertiesOnlyPaths(prop, new SwaggerParser().read(swaggerFile)); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); sw = mapper.writeValueAsString(swagger); } else {//from w ww . j a va 2 s . c o m ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); Swagger swagger = populateProperties(prop); sw = mapper.writeValueAsString(swagger); } try { File file = new File(args[1] + prop.getProperty("path.operation.tags") + ".json"); //File file = new File("src/main/resources/"+prop.getProperty("path.operation.tags")+".json"); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(sw); logger.info("Swagger Genration Done!"); bw.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:net.itransformers.postDiscoverer.core.ReportManager.java
public static void main(String[] args) throws IOException { File projectDir = new File("."); File scriptPath = new File("postDiscoverer/src/main/resources/postDiscoverer/conf/groovy/"); ResourceManagerFactory resourceManagerFactory = new XmlResourceManagerFactory( "iDiscover/resourceManager/xmlResourceManager/src/main/resources/xmlResourceManager/conf/xml/resource.xml"); Map<String, String> resourceManagerParams = new HashMap<>(); resourceManagerParams.put("projectPath", projectDir.getAbsolutePath()); ResourceManager resourceManager = resourceManagerFactory.createResourceManager("xml", resourceManagerParams);//from w w w . j av a 2 s.c o m Map<String, String> params = new HashMap<String, String>(); params.put("protocol", "telnet"); params.put("deviceName", "R1"); params.put("deviceType", "CISCO"); params.put("address", "10.17.1.5"); params.put("port", "23"); ResourceType resource = resourceManager.findFirstResourceBy(params); List connectParameters = resource.getConnectionParams(); for (int i = 0; i < connectParameters.size(); i++) { ConnectionParamsType connParamsType = (ConnectionParamsType) connectParameters.get(i); String connectionType = connParamsType.getConnectionType(); if (connectionType.equalsIgnoreCase(params.get("protocol"))) { for (ParamType param : connParamsType.getParam()) { params.put(param.getName(), param.getValue()); } } } File postDiscoveryConfing = new File( projectDir + "/postDiscoverer/src/main/resources/postDiscoverer/conf/xml/reportGenerator.xml"); if (!postDiscoveryConfing.exists()) { System.out.println("File missing: " + postDiscoveryConfing.getAbsolutePath()); return; } ReportGeneratorType reportGenerator = null; FileInputStream is = new FileInputStream(postDiscoveryConfing); try { reportGenerator = JaxbMarshalar.unmarshal(ReportGeneratorType.class, is); } catch (JAXBException e) { logger.info(e); //To change body of catch statement use File | Settings | File Templates. } finally { is.close(); } ReportManager reportManager = new ReportManager(reportGenerator, scriptPath.getPath(), projectDir, "postDiscoverer/conf/xslt/table_creator.xslt"); StringBuffer report = null; HashMap<String, Object> groovyExecutorParams = new HashMap<String, Object>(); for (String s : params.keySet()) { groovyExecutorParams.put(s, params.get(s)); } try { report = reportManager.reportExecutor( new File("/Users/niau/Projects/Projects/netTransformer10/version1/post-discovery"), groovyExecutorParams); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } if (report != null) { System.out.println(report.toString()); } else { System.out.println("Report generation failed!"); } }
From source file:edu.ucdenver.ccp.nlp.ae.dict_util.GeneInfoToDictionary.java
public static void main(String args[]) { BasicConfigurator.configure();//from w w w .j a v a 2 s . co m if (args.length < 2) { usage(); } else { try { File geneFile = new File(args[0]); File outputFile = new File(args[1]); if (!geneFile.canRead()) { System.out.println("can't read input file;" + geneFile.getAbsolutePath()); usage(); System.exit(-2); } if (outputFile.exists() && !outputFile.canWrite()) { System.out.println("can't write output file;" + outputFile.getAbsolutePath()); usage(); System.exit(-3); } logger.warn("running with: " + geneFile.getAbsolutePath()); GeneInfoToDictionary converter = new GeneInfoToDictionary(geneFile); converter.convert(geneFile, outputFile); } catch (Exception e) { System.out.println("error:" + e); e.printStackTrace(); System.exit(-1); } } }
From source file:net.schweerelos.parrot.CombinedParrotApp.java
/** * @param args//from w w w .j a v a 2 s . c o m */ @SuppressWarnings("static-access") public static void main(String[] args) { CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("help") .withDescription("Shows usage information and quits the program").create("h")); options.addOption( OptionBuilder.withLongOpt("datafile").withDescription("The file with instances to use (required)") .hasArg().withArgName("file").isRequired().create("f")); options.addOption(OptionBuilder.withLongOpt("properties") .withDescription("Properties file to use. Default: " + System.getProperty("user.home") + File.separator + ".digital-parrot" + File.separator + "parrot.properties") .hasArg().withArgName("prop").create("p")); try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption("h")) { // this is only executed when all required options are present _and_ the help option is specified! printHelp(options); return; } String datafile = line.getOptionValue("f"); if (!datafile.startsWith("file:") || !datafile.startsWith("http:")) { datafile = "file:" + datafile; } String propertiesPath = System.getProperty("user.home") + File.separator + ".digital-parrot" + File.separator + "parrot.properties"; if (line.hasOption("p")) { propertiesPath = line.getOptionValue("p"); } final Properties properties = new Properties(); File propertiesFile = new File(propertiesPath); if (propertiesFile.exists() && propertiesFile.canRead()) { try { properties.load(new FileReader(propertiesFile)); } catch (FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); } catch (IOException e) { e.printStackTrace(System.err); System.exit(1); } } final String url = datafile; // we need a "final" var for the anonymous class SwingUtilities.invokeLater(new Runnable() { public void run() { CombinedParrotApp inst = null; try { inst = new CombinedParrotApp(properties); inst.loadModel(url); } catch (Exception e) { JOptionPane.showMessageDialog(null, "There has been an error while starting the program.\nThe program will exit now.", APP_TITLE + " Error", JOptionPane.ERROR_MESSAGE); e.printStackTrace(System.err); System.exit(1); } if (inst != null) { inst.setLocationRelativeTo(null); inst.setVisible(true); } } }); } catch (ParseException exp) { printHelp(options); } }
From source file:edu.msu.cme.rdp.multicompare.Main.java
public static void main(String[] args) throws Exception { PrintStream hier_out = null;/*from ww w. j a va2s . co m*/ PrintWriter assign_out = new PrintWriter(new NullWriter()); PrintStream bootstrap_out = null; File hier_out_filename = null; String propFile = null; File biomFile = null; File metadataFile = null; PrintWriter shortseq_out = null; List<MCSample> samples = new ArrayList(); ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank; float conf = CmdOptions.DEFAULT_CONF; String gene = null; int min_bootstrap_words = Classifier.MIN_BOOTSTRSP_WORDS; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) { assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT)); } else { throw new IllegalArgumentException("Require the output file for classification assignment"); } if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) { hier_out_filename = new File(line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT)); hier_out = new PrintStream(hier_out_filename); } if (line.hasOption(CmdOptions.BIOMFILE_SHORT_OPT)) { biomFile = new File(line.getOptionValue(CmdOptions.BIOMFILE_SHORT_OPT)); } if (line.hasOption(CmdOptions.METADATA_SHORT_OPT)) { metadataFile = new File(line.getOptionValue(CmdOptions.METADATA_SHORT_OPT)); } if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) { if (gene != null) { throw new IllegalArgumentException( "Already specified the gene from the default location. Can not specify train_propfile"); } else { propFile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT); } } if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) { String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT); if (f.equalsIgnoreCase("allrank")) { format = ClassificationResultFormatter.FORMAT.allRank; } else if (f.equalsIgnoreCase("fixrank")) { format = ClassificationResultFormatter.FORMAT.fixRank; } else if (f.equalsIgnoreCase("filterbyconf")) { format = ClassificationResultFormatter.FORMAT.filterbyconf; } else if (f.equalsIgnoreCase("db")) { format = ClassificationResultFormatter.FORMAT.dbformat; } else if (f.equalsIgnoreCase("biom")) { format = ClassificationResultFormatter.FORMAT.biom; } else { throw new IllegalArgumentException( "Not an valid output format, only allrank, fixrank, biom, filterbyconf and db allowed"); } } if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) { if (propFile != null) { throw new IllegalArgumentException( "Already specified train_propfile. Can not specify gene any more"); } gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase(); if (!gene.equals(ClassifierFactory.RRNA_16S_GENE) && !gene.equals(ClassifierFactory.FUNGALLSU_GENE) && !gene.equals(ClassifierFactory.FUNGALITS_warcup_GENE) && !gene.equals(ClassifierFactory.FUNGALITS_unite_GENE)) { throw new IllegalArgumentException(gene + " not found, choose from" + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", " + ClassifierFactory.FUNGALITS_warcup_GENE + ", " + ClassifierFactory.FUNGALITS_unite_GENE); } } if (line.hasOption(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)) { min_bootstrap_words = Integer .parseInt(line.getOptionValue(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)); if (min_bootstrap_words < Classifier.MIN_BOOTSTRSP_WORDS) { throw new IllegalArgumentException(CmdOptions.MIN_BOOTSTRAP_WORDS_LONG_OPT + " must be at least " + Classifier.MIN_BOOTSTRSP_WORDS); } } if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) { String confString = line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT); try { conf = Float.valueOf(confString); } catch (NumberFormatException e) { throw new IllegalArgumentException("Confidence must be a decimal number"); } if (conf < 0 || conf > 1) { throw new IllegalArgumentException("Confidence must be in the range [0,1]"); } } if (line.hasOption(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT)) { shortseq_out = new PrintWriter(line.getOptionValue(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT)); } if (line.hasOption(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT)) { bootstrap_out = new PrintStream(line.getOptionValue(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT)); } if (format.equals(ClassificationResultFormatter.FORMAT.biom) && biomFile == null) { throw new IllegalArgumentException("biom format requires an input biom file"); } if (biomFile != null) { // if input biom file provided, use biom format format = ClassificationResultFormatter.FORMAT.biom; } args = line.getArgs(); for (String arg : args) { String[] inFileNames = arg.split(","); File inputFile = new File(inFileNames[0]); File idmappingFile = null; if (!inputFile.exists()) { throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[0] + "\""); } if (inFileNames.length == 2) { idmappingFile = new File(inFileNames[1]); if (!idmappingFile.exists()) { throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[1] + "\""); } } MCSample nextSample = new MCSample(inputFile, idmappingFile); samples.add(nextSample); } if (propFile == null && gene == null) { gene = CmdOptions.DEFAULT_GENE; } if (samples.size() < 1) { throw new IllegalArgumentException("Require at least one sample files"); } } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(80, " [options] <samplefile>[,idmappingfile] ...", "", options, ""); return; } MultiClassifier multiClassifier = new MultiClassifier(propFile, gene, biomFile, metadataFile); MultiClassifierResult result = multiClassifier.multiCompare(samples, conf, assign_out, format, min_bootstrap_words); assign_out.close(); if (hier_out != null) { DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(hier_out, samples); result.getRoot().topDownVisit(printVisitor); hier_out.close(); if (multiClassifier.hasCopyNumber()) { // print copy number corrected counts File cn_corrected_s = new File(hier_out_filename.getParentFile(), "cnadjusted_" + hier_out_filename.getName()); PrintStream cn_corrected_hier_out = new PrintStream(cn_corrected_s); printVisitor = new DefaultPrintVisitor(cn_corrected_hier_out, samples, true); result.getRoot().topDownVisit(printVisitor); cn_corrected_hier_out.close(); } } if (bootstrap_out != null) { for (MCSample sample : samples) { MCSamplePrintUtil.printBootstrapCountTable(bootstrap_out, sample); } bootstrap_out.close(); } if (shortseq_out != null) { for (String id : result.getBadSequences()) { shortseq_out.write(id + "\n"); } shortseq_out.close(); } }
From source file:org.apache.s4.client.Adapter.java
@SuppressWarnings("static-access") public static void main(String args[]) throws IOException, InterruptedException { Options options = new Options(); options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c")); options.addOption(/*ww w. j a v a 2 s . c om*/ OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i")); options.addOption( OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t")); options.addOption(OptionBuilder.withArgName("userconfig").hasArg() .withDescription("user-defined legacy data adapter configuration file").create("d")); CommandLineParser parser = new GnuParser(); CommandLine commandLine = null; try { commandLine = parser.parse(options, args); } catch (ParseException pe) { System.err.println(pe.getLocalizedMessage()); System.exit(1); } int instanceId = -1; if (commandLine.hasOption("i")) { String instanceIdStr = commandLine.getOptionValue("i"); try { instanceId = Integer.parseInt(instanceIdStr); } catch (NumberFormatException nfe) { System.err.println("Bad instance id: %s" + instanceIdStr); System.exit(1); } } if (commandLine.hasOption("c")) { coreHome = commandLine.getOptionValue("c"); } String configType = "typical"; if (commandLine.hasOption("t")) { configType = commandLine.getOptionValue("t"); } String userConfigFilename = null; if (commandLine.hasOption("d")) { userConfigFilename = commandLine.getOptionValue("d"); } File userConfigFile = new File(userConfigFilename); if (!userConfigFile.isFile()) { System.err.println("Bad user configuration file: " + userConfigFilename); System.exit(1); } File coreHomeFile = new File(coreHome); if (!coreHomeFile.isDirectory()) { System.err.println("Bad core home: " + coreHome); System.exit(1); } if (instanceId > -1) { System.setProperty("instanceId", "" + instanceId); } else { System.setProperty("instanceId", "" + S4Util.getPID()); } String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType; String configPath = configBase + File.separatorChar + "client-adapter-conf.xml"; File configFile = new File(configPath); if (!configFile.exists()) { System.err.printf("adapter config file %s does not exist\n", configPath); System.exit(1); } // load adapter config xml ApplicationContext coreContext; coreContext = new FileSystemXmlApplicationContext("file:" + configPath); ApplicationContext context = coreContext; Adapter adapter = (Adapter) context.getBean("client_adapter"); ApplicationContext appContext = new FileSystemXmlApplicationContext( new String[] { "file:" + userConfigFilename }, context); Map<?, ?> inputStubBeanMap = appContext.getBeansOfType(InputStub.class); Map<?, ?> outputStubBeanMap = appContext.getBeansOfType(OutputStub.class); if (inputStubBeanMap.size() == 0 && outputStubBeanMap.size() == 0) { System.err.println("No user-defined input/output stub beans"); System.exit(1); } ArrayList<InputStub> inputStubs = new ArrayList<InputStub>(inputStubBeanMap.size()); ArrayList<OutputStub> outputStubs = new ArrayList<OutputStub>(outputStubBeanMap.size()); // add all input stubs for (Map.Entry<?, ?> e : inputStubBeanMap.entrySet()) { String beanName = (String) e.getKey(); System.out.println("Adding InputStub " + beanName); inputStubs.add((InputStub) e.getValue()); } // add all output stubs for (Map.Entry<?, ?> e : outputStubBeanMap.entrySet()) { String beanName = (String) e.getKey(); System.out.println("Adding OutputStub " + beanName); outputStubs.add((OutputStub) e.getValue()); } adapter.setInputStubs(inputStubs); adapter.setOutputStubs(outputStubs); }
From source file:DIA_Umpire_Quant.DIA_Umpire_ExtLibSearch.java
/** * @param args the command line arguments *//*from w ww . j a v a 2 s .c o m*/ public static void main(String[] args) throws FileNotFoundException, IOException, Exception { System.out.println( "================================================================================================="); System.out.println("DIA-Umpire targeted re-extraction analysis using external library (version: " + UmpireInfo.GetInstance().Version + ")"); if (args.length != 1) { System.out.println( "command format error, the correct format should be: java -jar -Xmx10G DIA_Umpire_ExtLibSearch.jar diaumpire_module.params"); return; } try { ConsoleLogger.SetConsoleLogger(Level.INFO); ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_extlibsearch.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 ExternalLibPath = ""; String ExternalLibDecoyTag = "DECOY"; float ExtProbThreshold = 0.99f; float RTWindow_Ext = -1f; TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600); HashMap<String, File> AssignFiles = 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 "DecoyPrefix": { if (!"".equals(value)) { tandemPara.DecoyPrefix = value; } break; } case "ExternalLibPath": { ExternalLibPath = value; break; } case "ExtProbThreshold": { ExtProbThreshold = 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; } } } } //</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); } //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()); } 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.FastaPath = tandemPara.FastaPath; FileList.add(DiaFile); } } } //<editor-fold defaultstate="collapsed" desc="Targeted re-extraction using external library"> //External library search Logger.getRootLogger().info("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, ExtProbThreshold, 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> Logger.getRootLogger().info("Job done"); Logger.getRootLogger().info( "================================================================================================="); }
From source file:com.mapr.synth.Synth.java
public static void main(String[] args) throws IOException, CmdLineException, InterruptedException, ExecutionException { final Options opts = new Options(); CmdLineParser parser = new CmdLineParser(opts); try {//from w ww . j av a 2 s. c o m parser.parseArgument(args); } catch (CmdLineException e) { System.err.println("Usage: " + "[ -count <number>G|M|K ] " + "-schema schema-file " + "[-quote DOUBLE_QUOTE|BACK_SLASH|OPTIMISTIC] " + "[-format JSON|TSV|CSV|XML ] " + "[-threads n] " + "[-output output-directory-name] "); throw e; } Preconditions.checkArgument(opts.threads > 0 && opts.threads <= 2000, "Must have at least one thread and no more than 2000"); if (opts.threads > 1) { Preconditions.checkArgument(!"-".equals(opts.output), "If more than on thread is used, you have to use -output to set the output directory"); } File outputDir = new File(opts.output); if (!"-".equals(opts.output)) { if (!outputDir.exists()) { Preconditions.checkState(outputDir.mkdirs(), String.format("Couldn't create output directory %s", opts.output)); } Preconditions.checkArgument(outputDir.exists() && outputDir.isDirectory(), String.format("Couldn't create directory %s", opts.output)); } if (opts.schema == null) { throw new IllegalArgumentException("Must specify schema file using [-schema filename] option"); } final SchemaSampler sampler = new SchemaSampler(opts.schema); final AtomicLong rowCount = new AtomicLong(); final List<ReportingWorker> tasks = Lists.newArrayList(); int limit = (opts.count + opts.threads - 1) / opts.threads; int remaining = opts.count; for (int i = 0; i < opts.threads; i++) { final int count = Math.min(limit, remaining); remaining -= count; tasks.add(new ReportingWorker(opts, sampler, rowCount, count, i)); } final double t0 = System.nanoTime() * 1e-9; ExecutorService pool = Executors.newFixedThreadPool(opts.threads); ScheduledExecutorService blinker = Executors.newScheduledThreadPool(1); final AtomicBoolean finalRun = new AtomicBoolean(false); final PrintStream sideLog = new PrintStream(new FileOutputStream("side-log")); Runnable blink = new Runnable() { public double oldT; private long oldN; @Override public void run() { double t = System.nanoTime() * 1e-9; long n = rowCount.get(); System.err.printf("%s\t%d\t%.1f\t%d\t%.1f\t%.3f\n", finalRun.get() ? "F" : "R", opts.threads, t - t0, n, n / (t - t0), (n - oldN) / (t - oldT)); for (ReportingWorker task : tasks) { ReportingWorker.ThreadReport r = task.report(); sideLog.printf("\t%d\t%.2f\t%.2f\t%.2f\t%.1f\t%.1f\n", r.fileNumber, r.threadTime, r.userTime, r.wallTime, r.rows / r.threadTime, r.rows / r.wallTime); } oldN = n; oldT = t; } }; if (!"-".equals(opts.output)) { blinker.scheduleAtFixedRate(blink, 0, 10, TimeUnit.SECONDS); } List<Future<Integer>> results = pool.invokeAll(tasks); int total = 0; for (Future<Integer> result : results) { total += result.get(); } Preconditions.checkState(total == opts.count, String .format("Expected to generate %d lines of output, but actually generated %d", opts.count, total)); pool.shutdownNow(); blinker.shutdownNow(); finalRun.set(true); sideLog.close(); blink.run(); }
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"); }//w w w .j a v a 2s . c om 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:Pathway2RDFv2.java
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, ServiceException, ClassNotFoundException, IDMapperException, ParseException { int softwareVersion = 0; int schemaVersion = 0; int latestRevision = 0; BioDataSource.init();// w w w . j a v a2 s . co m Class.forName("org.bridgedb.rdb.IDMapperRdb"); File dir = new File("/Users/andra/Downloads/bridge"); File[] bridgeDbFiles = dir.listFiles(); IDMapperStack mapper = new IDMapperStack(); for (File bridgeDbFile : bridgeDbFiles) { System.out.println(bridgeDbFile.getAbsolutePath()); mapper.addIDMapper("idmapper-pgdb:" + bridgeDbFile.getAbsolutePath()); } Model bridgeDbmodel = ModelFactory.createDefaultModel(); InputStream in = new FileInputStream("/tmp/BioDataSource.ttl"); bridgeDbmodel.read(in, "", "TURTLE"); WikiPathwaysClient client = new WikiPathwaysClient( new URL("http://www.wikipathways.org/wpi/webservice/webservice.php")); basicCalls.printMemoryStatus(); //Map wikipathway organisms to NCBI organisms HashMap<String, String> organismTaxonomy = wpRelatedCalls.getOrganismsTaxonomyMapping(); //HashMap<String, String> miriamSources = new HashMap<String, String>(); // HashMap<String, Str ing> miriamLinks = basicCalls.getMiriamUriBridgeDb(); //Document wikiPathwaysDom = basicCalls.openXmlFile(args[0]); Document wikiPathwaysDom = basicCalls.openXmlFile("/tmp/WpGPML.xml"); //initiate the Jena model to be populated Model model = ModelFactory.createDefaultModel(); Model voidModel = ModelFactory.createDefaultModel(); voidModel.setNsPrefix("xsd", XSD.getURI()); voidModel.setNsPrefix("void", Void.getURI()); voidModel.setNsPrefix("wprdf", "http://rdf.wikipathways.org/"); voidModel.setNsPrefix("pav", Pav.getURI()); voidModel.setNsPrefix("prov", Prov.getURI()); voidModel.setNsPrefix("dcterms", DCTerms.getURI()); voidModel.setNsPrefix("biopax", Biopax_level3.getURI()); voidModel.setNsPrefix("gpml", Gpml.getURI()); voidModel.setNsPrefix("wp", Wp.getURI()); voidModel.setNsPrefix("foaf", FOAF.getURI()); voidModel.setNsPrefix("hmdb", "http://identifiers.org/hmdb/"); voidModel.setNsPrefix("freq", Freq.getURI()); voidModel.setNsPrefix("dc", DC.getURI()); setModelPrefix(model); //Populate void.ttl Calendar now = Calendar.getInstance(); Literal nowLiteral = voidModel.createTypedLiteral(now); Literal titleLiteral = voidModel.createLiteral("WikiPathways-RDF VoID Description", "en"); Literal descriptionLiteral = voidModel .createLiteral("This is the VoID description for a WikiPathwyas-RDF dataset.", "en"); Resource voidBase = voidModel.createResource("http://rdf.wikipathways.org/"); Resource identifiersOrg = voidModel.createResource("http://identifiers.org"); Resource wpHomeBase = voidModel.createResource("http://www.wikipathways.org/"); Resource authorResource = voidModel .createResource("http://semantics.bigcat.unimaas.nl/figshare/search_author.php?author=waagmeester"); Resource apiResource = voidModel .createResource("http://www.wikipathways.org/wpi/webservice/webservice.php"); Resource mainDatadump = voidModel.createResource("http://rdf.wikipathways.org/wpContent.ttl.gz"); Resource license = voidModel.createResource("http://creativecommons.org/licenses/by/3.0/"); Resource instituteResource = voidModel.createResource("http://dbpedia.org/page/Maastricht_University"); voidBase.addProperty(RDF.type, Void.Dataset); voidBase.addProperty(DCTerms.title, titleLiteral); voidBase.addProperty(DCTerms.description, descriptionLiteral); voidBase.addProperty(FOAF.homepage, wpHomeBase); voidBase.addProperty(DCTerms.license, license); voidBase.addProperty(Void.uriSpace, voidBase); voidBase.addProperty(Void.uriSpace, identifiersOrg); voidBase.addProperty(Pav.importedBy, authorResource); voidBase.addProperty(Pav.importedFrom, apiResource); voidBase.addProperty(Pav.importedOn, nowLiteral); voidBase.addProperty(Void.dataDump, mainDatadump); voidBase.addProperty(Voag.frequencyOfChange, Freq.Irregular); voidBase.addProperty(Pav.createdBy, authorResource); voidBase.addProperty(Pav.createdAt, instituteResource); voidBase.addLiteral(Pav.createdOn, nowLiteral); voidBase.addProperty(DCTerms.subject, Biopax_level3.Pathway); voidBase.addProperty(Void.exampleResource, voidModel.createResource("http://identifiers.org/ncbigene/2678")); voidBase.addProperty(Void.exampleResource, voidModel.createResource("http://identifiers.org/pubmed/15215856")); voidBase.addProperty(Void.exampleResource, voidModel.createResource("http://identifiers.org/hmdb/HMDB02005")); voidBase.addProperty(Void.exampleResource, voidModel.createResource("http://rdf.wikipathways.org/WP15")); voidBase.addProperty(Void.exampleResource, voidModel.createResource("http://identifiers.org/obo.chebi/17242")); for (String organism : organismTaxonomy.values()) { voidBase.addProperty(DCTerms.subject, voidModel.createResource("http://dbpedia.org/page/" + organism.replace(" ", "_"))); } voidBase.addProperty(Void.vocabulary, Biopax_level3.NAMESPACE); voidBase.addProperty(Void.vocabulary, voidModel.createResource(Wp.getURI())); voidBase.addProperty(Void.vocabulary, voidModel.createResource(Gpml.getURI())); voidBase.addProperty(Void.vocabulary, FOAF.NAMESPACE); voidBase.addProperty(Void.vocabulary, Pav.NAMESPACE); //Custom Properties String baseUri = "http://rdf.wikipathways.org/"; NodeList pathwayElements = wikiPathwaysDom.getElementsByTagName("Pathway"); //BioDataSource.init(); for (int i = 0; i < pathwayElements.getLength(); i++) { Model pathwayModel = createPathwayModel(); String wpId = pathwayElements.item(i).getAttributes().getNamedItem("identifier").getTextContent(); String revision = pathwayElements.item(i).getAttributes().getNamedItem("revision").getTextContent(); String pathwayOrganism = ""; if (pathwayElements.item(i).getAttributes().getNamedItem("Organism") != null) pathwayOrganism = pathwayElements.item(i).getAttributes().getNamedItem("Organism").getTextContent() .trim(); if (Integer.valueOf(revision) > latestRevision) { latestRevision = Integer.valueOf(revision); } File f = new File("/tmp/" + args[0] + "/" + wpId + "_r" + revision + ".ttl"); System.out.println(f.getName()); if (!f.exists()) { Resource voidPwResource = wpRelatedCalls.addVoidTriples(voidModel, voidBase, pathwayElements.item(i), client); Resource pwResource = wpRelatedCalls.addPathwayLevelTriple(pathwayModel, pathwayElements.item(i), organismTaxonomy); // Get the comments NodeList commentElements = ((Element) pathwayElements.item(i)).getElementsByTagName("Comment"); wpRelatedCalls.addCommentTriples(pathwayModel, pwResource, commentElements, wpId, revision); // Get the Groups NodeList groupElements = ((Element) pathwayElements.item(i)).getElementsByTagName("Group"); for (int n = 0; n < groupElements.getLength(); n++) { wpRelatedCalls.addGroupTriples(pathwayModel, pwResource, groupElements.item(n), wpId, revision); } // Get all the Datanodes NodeList dataNodesElement = ((Element) pathwayElements.item(i)).getElementsByTagName("DataNode"); for (int j = 0; j < dataNodesElement.getLength(); j++) { wpRelatedCalls.addDataNodeTriples(pathwayModel, pwResource, dataNodesElement.item(j), wpId, revision, bridgeDbmodel, mapper); } // Get all the lines NodeList linesElement = ((Element) pathwayElements.item(i)).getElementsByTagName("Line"); for (int k = 0; k < linesElement.getLength(); k++) { wpRelatedCalls.addLineTriples(pathwayModel, pwResource, linesElement.item(k), wpId, revision); } //Get all the labels NodeList labelsElement = ((Element) pathwayElements.item(i)).getElementsByTagName("Label"); for (int l = 0; l < labelsElement.getLength(); l++) { wpRelatedCalls.addLabelTriples(pathwayModel, pwResource, labelsElement.item(l), wpId, revision); } NodeList referenceElements = ((Element) pathwayElements.item(i)) .getElementsByTagName("bp:PublicationXref"); for (int m = 0; m < referenceElements.getLength(); m++) { wpRelatedCalls.addReferenceTriples(pathwayModel, pwResource, referenceElements.item(m), wpId, revision); } NodeList referenceElements2 = ((Element) pathwayElements.item(i)) .getElementsByTagName("bp:publicationXref"); for (int m = 0; m < referenceElements2.getLength(); m++) { wpRelatedCalls.addReferenceTriples(pathwayModel, pwResource, referenceElements2.item(m), wpId, revision); } NodeList referenceElements3 = ((Element) pathwayElements.item(i)) .getElementsByTagName("bp:PublicationXRef"); for (int m = 0; m < referenceElements3.getLength(); m++) { wpRelatedCalls.addReferenceTriples(pathwayModel, pwResource, referenceElements3.item(m), wpId, revision); } NodeList ontologyElements = ((Element) pathwayElements.item(i)) .getElementsByTagName("bp:openControlledVocabulary"); for (int n = 0; n < ontologyElements.getLength(); n++) { wpRelatedCalls.addPathwayOntologyTriples(pathwayModel, pwResource, ontologyElements.item(n)); } System.out.println(wpId); basicCalls.saveRDF2File(pathwayModel, "/tmp/" + args[0] + "/" + wpId + "_r" + revision + ".ttl", "TURTLE"); model.add(pathwayModel); pathwayModel.removeAll(); } } Date myDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String myDateString = sdf.format(myDate); FileUtils.writeStringToFile(new File("latestVersion.txt"), "v" + schemaVersion + "." + softwareVersion + "." + latestRevision + "_" + myDateString); basicCalls.saveRDF2File(model, "/tmp/wpContent_v" + schemaVersion + "." + softwareVersion + "." + latestRevision + "_" + myDateString + ".ttl", "TURTLE"); basicCalls.saveRDF2File(voidModel, "/tmp/void.ttl", "TURTLE"); }