List of usage examples for java.io File exists
public boolean exists()
From source file:edu.msu.cme.rdp.abundstats.cli.AbundMain.java
public static void main(String[] args) throws IOException { File inputFile;/*w ww .ja v a 2 s . c o m*/ File resultDir = new File("."); RPlotter plotter = null; boolean isClusterFile = true; List<AbundStatsCalculator> statCalcs = new ArrayList(); double clustCutoffFrom = Double.MIN_VALUE, clustCutoffTo = Double.MAX_VALUE; String usage = "Main [options] <cluster file>"; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("result-dir")) { resultDir = new File(line.getOptionValue("result-dir")); if (!resultDir.exists() && !resultDir.mkdirs()) { throw new Exception( "Result directory " + resultDir + " does not exist and could not be created"); } } if (line.hasOption("R-location")) { plotter = new RPlotter(); plotter.setCommandTemplate(rplotterTemplate); plotter.setRPath(line.getOptionValue("R-location")); plotter.setOutFileExt(".png"); if (!new File(plotter.getRPath()).canExecute()) { throw new Exception(plotter.getRPath() + " does not exist or is not exectuable"); } } if (line.hasOption("lower-cutoff")) { clustCutoffFrom = Double.valueOf(line.getOptionValue("lower-cutoff")); } if (line.hasOption("upper-cutoff")) { clustCutoffTo = Double.valueOf(line.getOptionValue("upper-cutoff")); } if (line.hasOption("jaccard")) { statCalcs.add(new Jaccard(true)); } if (line.hasOption("sorensen")) { statCalcs.add(new Sorensen(true)); } if (line.hasOption("otu-table")) { isClusterFile = false; } if (statCalcs.isEmpty()) { throw new Exception("Must specify at least one stat to compute (jaccard, sorensen)"); } args = line.getArgs(); if (args.length != 1) { throw new Exception("Unexpected number of command line arguments"); } inputFile = new File(args[0]); } catch (Exception e) { new HelpFormatter().printHelp(usage, options); System.err.println("Error: " + e.getMessage()); return; } if (isClusterFile) { RDPClustParser parser; parser = new RDPClustParser(inputFile); try { if (parser.getClusterSamples().size() == 1) { throw new IOException("Cluster file must have more than one sample"); } List<Cutoff> cutoffs = parser.getCutoffs(clustCutoffFrom, clustCutoffTo); if (cutoffs.isEmpty()) { throw new IOException( "No cutoffs in cluster file in range [" + clustCutoffFrom + "-" + clustCutoffTo + "]"); } for (Cutoff cutoff : cutoffs) { List<Sample> samples = new ArrayList(); for (ClusterSample clustSample : parser.getClusterSamples()) { Sample s = new Sample(clustSample.getName()); for (Cluster clust : cutoff.getClusters().get(clustSample.getName())) { s.addSpecies(clust.getNumberOfSeqs()); } samples.add(s); } processSamples(samples, statCalcs, resultDir, cutoff.getCutoff() + "_", plotter); } } finally { parser.close(); } } else { List<Sample> samples = new ArrayList(); BufferedReader reader = new BufferedReader(new FileReader(inputFile)); String line = reader.readLine(); if (line == null || line.split("\\s+").length < 2) { throw new IOException("Must be 2 or more samples for abundance statistic calculations!"); } int numSamples = line.split("\\s+").length; boolean header = true; try { Integer.valueOf(line.split("\\s+")[0]); header = false; } catch (Exception e) { } if (header) { for (String s : line.split("\\s+")) { samples.add(new Sample(s)); } } else { int sample = 0; for (String s : line.split("\\s+")) { samples.add(new Sample("" + sample)); samples.get(sample).addSpecies(Integer.valueOf(s)); sample++; } } int lineno = 2; while ((line = reader.readLine()) != null) { if (line.trim().equals("")) { continue; } int sample = 0; if (line.split("\\s+").length != numSamples) { System.err.println( "Line number " + lineno + " didn't have the expected number of samples (contained " + line.split("\\s+").length + ", expected " + numSamples + ")"); } for (String s : line.split("\\s+")) { samples.get(sample).addSpecies(Integer.valueOf(s)); sample++; } lineno++; } processSamples(samples, statCalcs, resultDir, inputFile.getName(), plotter); } }
From source file:Logi.GSeries.Service.LogiGSKService.java
/** * @param args the command line arguments *///from ww w. jav a 2s .co m public static void main(String[] args) { SystemTray.DEBUG = false; Settings settings; if (IOOperations.currentSettingsExist()) { settings = IOOperations.loadCurrentSettingsObjectFromFile(); } else { settings = new Settings(); } LogiGSKService l = new LogiGSKService(); if (settings.getShowSystemTray()) { l.showSystemTray(); } else { l.hideSystemTray(); } l.begin(); try { String dataFolderPath = IOOperations.getLocalDataDirectoryPath(); File dataFolder = new File(dataFolderPath); if (!dataFolder.exists()) { dataFolder.mkdir(); } String logFolderPath = IOOperations.getLogDirectoryPath(); File logFolder = new File(logFolderPath); if (!logFolder.exists()) { logFolder.mkdir(); } FileHandler fileHandler = new FileHandler(logFolderPath + "LogiGSK.log", FILE_SIZE, 3); fileHandler.setLevel(Level.ALL); logger.setLevel(Level.ALL); logger.addHandler(fileHandler); } catch (IOException | SecurityException ex) { Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex); } int clientNumber = 0; ServerSocket listener = null; PropertyConfigurator.configure(LogiGSKService.class.getResource("/Logi/GSeries/Service/log4j.properties")); reloading = true; boolean firstTime = true; while (reloading) { listener = null; if (reloading && !firstTime) { if (IOOperations.currentSettingsExist()) { settings = IOOperations.loadCurrentSettingsObjectFromFile(); } else { settings = new Settings(); } } firstTime = false; reloading = false; running = true; try { listener = new ServerSocket(settings.getPort(), 0, InetAddress.getByName(null)); while (running) { new Manager(listener.accept(), clientNumber++, logger).start(); } } catch (IOException ex) { Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex); } finally { if (listener != null) { try { listener.close(); } catch (IOException ex) { Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex); } } } } }
From source file:com.clustercontrol.agent.Agent.java
/** * ?/* w w w . j av a 2 s . c o m*/ * * @param args ?? */ public static void main(String[] args) throws Exception { // ? if (args.length != 1) { System.out.println("Usage : java Agent [Agent.properties File Path]"); System.exit(1); } try { // System m_log.info("starting Hinemos Agent..."); m_log.info("java.vm.version = " + System.getProperty("java.vm.version")); m_log.info("java.vm.vendor = " + System.getProperty("java.vm.vendor")); m_log.info("java.home = " + System.getProperty("java.home")); m_log.info("os.name = " + System.getProperty("os.name")); m_log.info("os.arch = " + System.getProperty("os.arch")); m_log.info("os.version = " + System.getProperty("os.version")); m_log.info("user.name = " + System.getProperty("user.name")); m_log.info("user.dir = " + System.getProperty("user.dir")); m_log.info("user.country = " + System.getProperty("user.country")); m_log.info("user.language = " + System.getProperty("user.language")); m_log.info("file.encoding = " + System.getProperty("file.encoding")); // System(SET) String limitKey = "jdk.xml.entityExpansionLimit"; // TODO JRE??????????????????? System.setProperty(limitKey, "0"); m_log.info(limitKey + " = " + System.getProperty(limitKey)); // TODO ???agentHome // ?????????? File file = new File(args[0]); agentHome = file.getParentFile().getParent() + "/"; m_log.info("agentHome=" + agentHome); // long startDate = HinemosTime.currentTimeMillis(); m_log.info("start date = " + new Date(startDate) + "(" + startDate + ")"); agentInfo.setStartupTime(startDate); // Agent?? m_log.info("Agent.properties = " + args[0]); // ? File scriptDir = new File(agentHome + "script/"); if (scriptDir.exists()) { File[] listFiles = scriptDir.listFiles(); if (listFiles != null) { for (File f : listFiles) { boolean ret = f.delete(); if (ret) { m_log.debug("delete script : " + f.getName()); } else { m_log.warn("delete script error : " + f.getName()); } } } else { m_log.warn("listFiles is null"); } } else { //???????? boolean ret = scriptDir.mkdir(); if (!ret) { m_log.warn("mkdir error " + scriptDir.getPath()); } } // queue? m_sendQueue = new SendQueue(); // Agent? Agent agent = new Agent(args[0]); //----------------- //-- //----------------- m_log.debug("exec() : create topic "); m_receiveTopic = new ReceiveTopic(m_sendQueue); m_receiveTopic.setName("ReceiveTopicThread"); m_log.info("receiveTopic start 1"); m_receiveTopic.start(); m_log.info("receiveTopic start 2"); // ? agent.exec(); m_log.info("Hinemos Agent started"); // ? agent.waitAwakeAgent(); } catch (Throwable e) { m_log.error("Agent.java: Runtime Exception Occurred. " + e.getClass().getName() + ", " + e.getMessage(), e); } }
From source file:DIA_Umpire_Quant.DIA_Umpire_ProtQuant.java
/** * @param args the command line arguments *///from w ww .j av a 2 s .co 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:net.sf.jhylafax.addressbook.AddressBook.java
/** * @param args//from ww w .j a v a2 s . co m */ public static void main(String[] args) { final AddressBook app = new AddressBook(); app.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); app.restoreLayout(new SettingStore(Settings.backstore)); try { File file = JHylaFAX.getAddressBookFile(); if (file.exists()) { app.load(file); } } catch (Exception e) { ErrorDialog.showError(null, i18n.tr("Could not load address book"), i18n.tr("JHylaFAX Error"), e); } app.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent event) { try { File file = JHylaFAX.getAddressBookFile(); app.store(file); } catch (Exception e) { ErrorDialog.showError(null, i18n.tr("Could not store address book"), i18n.tr("JHylaFAX Error"), e); } } }); app.setVisible(true); }
From source file:com.act.biointerpretation.metadata.ProteinMetadataFactory.java
public static void main(String[] args) throws Exception { // TODO: This is referencing a temporary collection. Change it! // TODO: FIX THIS BEFORE MERGE! NoSQLAPI api = new NoSQLAPI("actv01_vijay_proteins", "actv01_vijay_proteins"); Iterator<Reaction> iterator = api.readRxnsFromInKnowledgeGraph(); //Create a single instance of the factory method to use for all json ProteinMetadataFactory factory = ProteinMetadataFactory.initiate(); //Run some tests try {// w w w . j a va2s. co m if (factory.testHandlesubunits() == true) { System.out.println("Subunit test OK"); } } catch (Exception err) { System.err.println("Failed to test subunits"); } //Create a list to aggregate the results of the database scan List<ProteinMetadata> agg = new ArrayList<>(); //Scan the database and store ProteinMetadata objects while (iterator.hasNext()) { Reaction rxn = iterator.next(); Reaction.RxnDataSource source = rxn.getDataSource(); if (!source.equals(Reaction.RxnDataSource.BRENDA)) { continue; } Set<JSONObject> jsons = rxn.getProteinData(); for (JSONObject json : jsons) { ProteinMetadata meta = factory.create(json); agg.add(meta); } } //Write out any messages to file StringBuilder sb = new StringBuilder(); for (String aline : factory.dataList) { sb.append(aline).append("\n"); } File outfile = new File("output/ProteinMetadata/Factory_output.txt"); if (outfile.exists()) { outfile.delete(); } FileUtils.writeStringToFile(outfile, sb.toString()); sb = new StringBuilder(); for (String key : factory.dataMap.keySet()) { int value = factory.dataMap.get(key); sb.append(key + "\t" + value + "\n"); } outfile = new File("output/ProteinMetadata/Factory_output_map.txt"); if (outfile.exists()) { outfile.delete(); } FileUtils.writeStringToFile(outfile, sb.toString()); //Count up the results of modifications to get statistics int falsecount = 0; int truecount = 0; int nullcount = 0; for (ProteinMetadata datum : agg) { if (datum == null) { System.err.println("null datum"); continue; } if (datum.modifications == null) { nullcount++; } else if (datum.modifications == false) { falsecount++; } else if (datum.modifications == true) { truecount++; } } System.out.println("Total # protein metadata: " + agg.size()); System.out.println(); System.out.println("modification true count: " + truecount); System.out.println("modification false count: " + falsecount); System.out.println("modification null count: " + nullcount); System.out.println(); //Get some statistics for cloned nullcount = 0; int emptycount = 0; int colicount = 0; int humancount = 0; int bothcount = 0; for (ProteinMetadata datum : agg) { if (datum == null) { System.err.println("null datum"); continue; } if (datum.cloned == null) { nullcount++; continue; } if (datum.cloned.isEmpty()) { emptycount++; continue; } Integer human = datum.cloned.get(Host.Hsapiens); if (human != null && human > 0) { humancount++; } Integer coli = datum.cloned.get(Host.Ecoli); if (coli != null && coli > 0) { colicount++; if (human != null && human > 0) { bothcount++; } } } System.out.println("cloned null count: " + nullcount); System.out.println("cloned empty count: " + emptycount); System.out.println("cloned coli count: " + colicount); System.out.println("cloned human count: " + humancount); System.out.println("cloned both count: " + bothcount); System.out.println(); }
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 www. j a v a2s . 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); }
From source file:de.prozesskraft.ptest.Launch.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try//from w ww.j ava 2s. com // { // if (args.length != 3) // { // System.out.println("Please specify processdefinition file (xml) and an outputfilename"); // } // // } // catch (ArrayIndexOutOfBoundsException e) // { // System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString()); // } /*---------------------------- get options from ini-file ----------------------------*/ File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Launch.class) + "/" + "../etc/ptest-launch.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); Option ov = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option ospl = OptionBuilder.withArgName("DIR").hasArg() .withDescription("[mandatory] directory with sample input data") // .isRequired() .create("spl"); Option oinstancedir = OptionBuilder.withArgName("DIR").hasArg() .withDescription("[mandatory, default: .] directory where the test will be performed") // .isRequired() .create("instancedir"); Option ocall = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory, default: random call in spl-directory] file with call-string") // .isRequired() .create("call"); Option oaltapp = OptionBuilder.withArgName("STRING").hasArg() .withDescription( "[optional] alternative app. this String replaces the first line of the .call-file.") // .isRequired() .create("altapp"); Option oaddopt = OptionBuilder.withArgName("STRING").hasArg() .withDescription("[optional] add an option to the call.") // .isRequired() .create("addopt"); Option onolaunch = new Option("nolaunch", "only create instance directory, copy all spl files, but do NOT launch the process"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(ospl); options.addOption(oinstancedir); options.addOption(ocall); options.addOption(oaltapp); options.addOption(oaddopt); options.addOption(onolaunch); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments commandline = parser.parse(options, args); } catch (Exception exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); exiter(); } /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("launch", options); System.exit(0); } else if (commandline.hasOption("v")) { System.out.println("web: " + web); System.out.println("author: " + author); System.out.println("version:" + version); System.out.println("date: " + date); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ boolean error = false; String spl = null; String instancedir = null; String call = null; String altapp = null; ArrayList<String> addopt = new ArrayList<String>(); // spl initialisieren if (commandline.hasOption("spl")) { spl = commandline.getOptionValue("spl"); } else { System.err.println("option -spl is mandatory"); error = true; } // instancedir initialisieren if (commandline.hasOption("instancedir")) { instancedir = commandline.getOptionValue("instancedir"); } else { instancedir = System.getProperty("user.dir"); } // call initialisieren if (commandline.hasOption("call")) { call = commandline.getOptionValue("call"); } // altapp initialisieren if (commandline.hasOption("altapp")) { altapp = commandline.getOptionValue("altapp"); } // addopt initialisieren if (commandline.hasOption("addopt")) { for (String actString : commandline.getOptionValues("addopt")) { addopt.add(actString); } } // wenn fehler, dann exit if (error) { exiter(); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ // das erste spl-objekt geben lassen Spl actSpl = new Splset(spl).getSpl().get(0); // den call, result und altapp ueberschreiben actSpl.setName("default"); if (call != null) { actSpl.setCall(new java.io.File(call)); } if (actSpl.getCall() == null) { System.err.println("error: no call information found"); System.exit(1); } if (altapp != null) { actSpl.setAltapp(altapp); } if (addopt.size() > 0) { actSpl.setAddopt(addopt); } actSpl.setResult(null); // das instancedir erstellen java.io.File actSplInstanceDir = new java.io.File(instancedir); System.err.println("info: creating directory " + actSplInstanceDir.getCanonicalPath()); actSplInstanceDir.mkdirs(); // Inputdaten in das InstanceDir exportieren actSpl.exportInput(actSplInstanceDir); // exit, wenn --nolaunch if (commandline.hasOption("nolaunch")) { System.err.println("info: exiting, because of -nolaunch"); System.exit(0); } // das logfile des Syscalls (zum debuggen des programms "process syscall" gedacht) String AbsLogSyscallWrapper = actSplInstanceDir.getCanonicalPath() + "/.log"; String AbsStdout = actSplInstanceDir.getCanonicalPath() + "/.stdout.txt"; String AbsStderr = actSplInstanceDir.getCanonicalPath() + "/.stderr.txt"; String AbsPid = actSplInstanceDir.getCanonicalPath() + "/.pid"; // beim starten von syscall werden parameter mit whitespaces an diesen auseinandergeschnitten und der nachfolgende aufruf schlaeft fehl // deshalb sollen whitespaces durch eine 'zeichensequenz' ersetzt werden // syscall ersetzt die zeichensequenz wieder zurueck in ein " " ArrayList<String> callFuerSyscall = actSpl.getCallAsArrayList(); ArrayList<String> callFuerSyscallMitTrennzeichen = new ArrayList<String>(); for (String actString : callFuerSyscall) { callFuerSyscallMitTrennzeichen.add(actString.replaceAll("\\s+", "%WHITESPACE%")); } try { // den Aufrufstring fuer die externe App (process syscall --version 0.6.0)) splitten // beim aufruf muss das erste argument im path zu finden sein, sonst gibt die fehlermeldung 'no such file or directory' ArrayList<String> processSyscallWithArgs = new ArrayList<String>( Arrays.asList(ini.get("apps", "pkraft-syscall").split(" "))); // die sonstigen argumente hinzufuegen processSyscallWithArgs.add("-call"); processSyscallWithArgs.add(String.join(" ", callFuerSyscallMitTrennzeichen)); // processSyscallWithArgs.add("\""+call+"\""); processSyscallWithArgs.add("-stdout"); processSyscallWithArgs.add(AbsStdout); processSyscallWithArgs.add("-stderr"); processSyscallWithArgs.add(AbsStderr); processSyscallWithArgs.add("-pid"); processSyscallWithArgs.add(AbsPid); processSyscallWithArgs.add("-mylog"); processSyscallWithArgs.add(AbsLogSyscallWrapper); processSyscallWithArgs.add("-maxrun"); processSyscallWithArgs.add("" + 3000); // erstellen prozessbuilder ProcessBuilder pb = new ProcessBuilder(processSyscallWithArgs); // erweitern des PATHs um den prozesseigenen path // Map<String,String> env = pb.environment(); // String path = env.get("PATH"); // log("debug", "$PATH="+path); // path = this.parent.getAbsPath()+":"+path; // env.put("PATH", path); // log("info", "path: "+path); // setzen der aktuellen directory (in der syscall ausgefuehrt werden soll) java.io.File directory = new java.io.File(instancedir); System.err.println("info: setting execution directory to: " + directory.getCanonicalPath()); pb.directory(directory); // zum debuggen ein paar ausgaben // java.lang.Process p1 = Runtime.getRuntime().exec("date >> ~/tmp.debug.work.txt"); // p1.waitFor(); // java.lang.Process p2 = Runtime.getRuntime().exec("ls -la "+this.getParent().getAbsdir()+" >> ~/tmp.debug.work.txt"); // p2.waitFor(); // java.lang.Process pro = Runtime.getRuntime().exec("nautilus"); // java.lang.Process superpro = Runtime.getRuntime().exec(processSyscallWithArgs.toArray(new String[processSyscallWithArgs.size()])); // p3.waitFor(); System.err.println("info: calling: " + pb.command()); // starten des prozesses java.lang.Process sysproc = pb.start(); // einfangen der stdout- und stderr des subprozesses InputStream is_stdout = sysproc.getInputStream(); InputStream is_stderr = sysproc.getErrorStream(); // Send your InputStream to an InputStreamReader: InputStreamReader isr_stdout = new InputStreamReader(is_stdout); InputStreamReader isr_stderr = new InputStreamReader(is_stderr); // That needs to go to a BufferedReader: BufferedReader br_stdout = new BufferedReader(isr_stdout); BufferedReader br_stderr = new BufferedReader(isr_stderr); // // oeffnen der OutputStreams zu den Ausgabedateien // FileWriter fw_stdout = new FileWriter(sStdout); // FileWriter fw_stderr = new FileWriter(sStderr); // zeilenweise in die files schreiben String line_out = new String(); String line_err = new String(); while (br_stdout.readLine() != null) { } // while (((line_out = br_stdout.readLine()) != null) || ((line_err = br_stderr.readLine()) != null)) // { // if (!(line_out == null)) // { // System.out.println(line_out); // System.out.flush(); // } // if (!(line_err == null)) // { // System.err.println(line_err); // System.err.flush(); // } // } int exitValue = sysproc.waitFor(); // fw_stdout.close(); // fw_stderr.close(); System.err.println("exitvalue: " + exitValue); sysproc.destroy(); System.exit(exitValue); // alternativer aufruf // java.lang.Process sysproc = Runtime.getRuntime().exec(StringUtils.join(args_for_syscall, " ")); // log("info", "call executed. pid="+sysproc.hashCode()); // wait 2 seconds for becoming the pid-file visible // Thread.sleep(2000); // int exitValue = sysproc.waitFor(); // // der prozess soll bis laengstens // if(exitValue != 0) // { // System.err.println("error: call returned a value indicating an error: "+exitValue); // } // else // { // System.err.println("info: call returned value: "+exitValue); // } // System.err.println("info: "+new Date().toString()); // System.err.println("info: bye"); // // sysproc.destroy(); // // System.exit(sysproc.exitValue()); } catch (Exception e2) { System.err.println("error: " + e2.getMessage()); System.exit(1); } }
From source file:edu.stanford.epadd.launcher.Main.java
public static void main(String args[]) throws Exception { setupLogging();/*from w ww . j ava2 s . c om*/ basicSetup(args); setupResources(); out.println("Starting up ePADD on the local computer at " + BASE_URL + ", " + formatDateLong(new GregorianCalendar())); out.println("***For troubleshooting information, see this file: " + debugFile + "***\n"); out.println("Current directory = " + System.getProperty("user.dir") + ", home directory = " + System.getProperty("user.home")); out.println("Memory status at the beginning: " + getMemoryStats()); if (Runtime.getRuntime().maxMemory() / MB < 512) aggressiveWarn( "You are probably running ePADD without enough memory. \nIf you launched ePADD from the command line, you can increase memory with an option like java -Xmx1g", 2000); // handle frequent error of user trying to launch another server when its already on // server.start() usually takes a few seconds to return // after that it takes a few seconds for the webapp to deploy // ignore any exceptions along the way and assume not if we can't prove it is alive boolean urlAlive = false; try { urlAlive = isURLAlive(MUSE_CHECK_URL); } catch (Exception e) { out.println("Exception: e"); e.printStackTrace(out); } boolean disableStart = false; if (urlAlive) { out.println("Oh! ePADD is already running at the URL: " + BASE_URL + ", will have to kill it!"); killRunningServer(BASE_URL); Thread.sleep(3000); try { urlAlive = isURLAlive(MUSE_CHECK_URL); } catch (Exception e) { out.println("Exception: e"); e.printStackTrace(out); } if (!urlAlive) out.println("Good. Kill succeeded, will restart"); else { String message = "Previously running ePADD still alive despite attempt to kill it, disabling fresh restart!\n"; message += "If you just want to use the previous instance of ePADD, please go to " + BASE_URL; message += "\nTo kill this instance, please go to your computer's task manager and kill running java or javaw processes.\nThen try launching ePADD again.\n"; aggressiveWarn(message, 2000); return; } } // else // out.println ("Muse not already alive at URL: ..." + URL); if (!disableStart) { out.println("Starting ePADD at URL: ..." + BASE_URL); try { server.start(); } catch (BindException be) { out.println("port busy, but webapp not alive: " + BASE_URL + "\n" + be); throw new RuntimeException("Error: Port in use (Please kill ePADD if its already running!)\n" + be); } } // webapp1.start(); -- not needed PrintStream debugOut1 = System.err; try { File f = new File(debugFile); if (f.exists()) f.delete(); // particular problem on windows :-( debugOut1 = new PrintStream(new FileOutputStream(debugFile), false, "UTF-8"); } catch (IOException ioe) { System.err.println("Warning: failed to delete debug file " + debugFile + " : " + ioe); } final PrintStream debugOut = debugOut1; Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { try { server.stop(); server.destroy(); debugOut.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } })); // InfoFrame frame = new InfoFrame(); // frame.doShow(); boolean success = waitTillPageAlive(MUSE_CHECK_URL, TIMEOUT_SECS); // frame.updateText ("Opening a browser window"); if (success) { // best effort to start shutdown thread // out.println ("Starting Muse shutdown listener at port " + JettyShutdownThread.SHUTDOWN_PORT); try { int shutdownPort = PORT + 1; // shut down port is arbitrarily set to port + 1. it is ASSUMED to be free. new JettyShutdownThread(server, shutdownPort).start(); out.println("Listening for ePADD shutdown message on port " + shutdownPort); } catch (Exception e) { out.println( "Unable to start shutdown listener, you will have to stop the server manually using Cmd-Q on Mac OS or kill javaw processes on Windows"); } try { setupSystemTrayIcon(); } catch (Exception e) { System.err.println("Unable to setup system tray icon: " + e); e.printStackTrace(System.err); } // open browser window if (browserOpen) { preferredBrowser = null; // launch a browser here try { String link; link = "http://localhost:" + PORT + "/epadd/index.jsp"; if (startPage != null) { // startPage has to be absolute link = "http://localhost:" + PORT + "/epadd/" + startPage; } if (baseDir != null) link = link + "?cacheDir=" + baseDir; // typically this is used when starting from command line. note: still using name, cacheDir out.println("Launching URL in browser: " + link); launchBrowser(link); } catch (Exception e) { out.println( "Warning: Unable to launch browser due to exception (use the -n option to prevent ePADD from trying to launch a browser):"); e.printStackTrace(out); } } if (!noShutdown) { // arrange to kill Muse after a period of time, we don't want the server to run forever // i clearly have too much time on my hands right now... long secs = KILL_AFTER_MILLIS / 1000; long hh = secs / 3600; long mm = (secs % 3600) / 60; long ss = secs % (60); out.print("ePADD will shut down automatically after "); if (hh != 0) out.print(hh + " hours "); if (mm != 0 || (hh != 0 && ss != 0)) out.print(mm + " minutes"); if (ss != 0) out.print(ss + " seconds"); out.println(); Timer timer = new Timer(); TimerTask tt = new ShutdownTimerTask(); timer.schedule(tt, KILL_AFTER_MILLIS); } } else { out.println("\n\n\nSORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING\n\n\n"); // frame.updateText("Sorry, looks like we are having trouble starting the jetty server\n"); } savedSystemOut = out; savedSystemErr = System.err; System.setOut(debugOut); System.setErr(debugOut); }
From source file:org.waarp.common.filemonitor.FileMonitor.java
public static void main(String[] args) { if (args.length < 3) { System.err.println("Need a statusfile, a stopfile and a directory to test"); return;//w w w . ja v a2s.c o m } File file = new File(args[0]); if (file.exists() && !file.isFile()) { System.err.println("Not a correct status file"); return; } File stopfile = new File(args[1]); if (file.exists() && !file.isFile()) { System.err.println("Not a correct stop file"); return; } File dir = new File(args[2]); if (!dir.isDirectory()) { System.err.println("Not a directory"); return; } FileMonitorCommandRunnableFuture filemonitor = new FileMonitorCommandRunnableFuture() { public void run(FileItem file) { System.out.println("File New: " + file.file.getAbsolutePath()); finalize(true, 0); } }; FileMonitor monitor = new FileMonitor("test", file, stopfile, dir, null, 0, new RegexFileFilter(RegexFileFilter.REGEX_XML_EXTENSION), false, filemonitor, new FileMonitorCommandRunnableFuture() { public void run(FileItem file) { System.err.println("File Del: " + file.file.getAbsolutePath()); } }, new FileMonitorCommandRunnableFuture() { public void run(FileItem unused) { System.err.println("Check done"); } }); filemonitor.setMonitor(monitor); monitor.start(); monitor.waitForStopFile(); }