List of usage examples for java.lang String startsWith
public boolean startsWith(String prefix)
From source file:com.diversityarrays.dal.server.DalServer.java
public static void main(String[] args) { String host = null;//from w w w . j ava 2s .c o m int port = DalServerUtil.DEFAULT_DAL_SERVER_PORT; int inactiveMins = DalServerUtil.DEFAULT_MAX_INACTIVE_MINUTES; File docRoot = null; String serviceName = null; for (int i = 0; i < args.length; ++i) { String argi = args[i]; if (argi.startsWith("-")) { if ("--".equals(argi)) { break; } if ("-version".equals(argi)) { System.out.println(DAL_SERVER_VERSION); System.exit(0); } if ("-help".equals(argi)) { giveHelpThenExit(0); } if ("-docroot".equals(argi)) { if (++i >= args.length || args[i].startsWith("-")) { fatal("missing value for " + argi); } docRoot = new File(args[i]); } else if ("-sqllog".equals(argi)) { SqlUtil.logger = Logger.getLogger(SqlUtil.class.getName()); } else if ("-expire".equals(argi)) { if (++i >= args.length || args[i].startsWith("-")) { fatal("missing value for " + argi); } try { inactiveMins = Integer.parseInt(args[i], 10); if (inactiveMins <= 0) { fatal("invalid minutes: " + args[i]); } } catch (NumberFormatException e) { fatal("invalid minutes: " + args[i]); } } else if ("-localhost".equals(argi)) { host = "localhost"; } else if ("-port".equals(argi)) { if (++i >= args.length || args[i].startsWith("-")) { fatal("missing value for " + argi); } try { port = Integer.parseInt(args[i], 10); if (port < 0 || port > 65535) { fatal("invalid port number: " + args[i]); } } catch (NumberFormatException e) { fatal("invalid port number: " + args[i]); } } else { fatal("invalid option: " + argi); } } else { if (serviceName != null) { fatal("multiple serviceNames not supported: " + argi); } serviceName = argi; } } final DalServerPreferences preferences = new DalServerPreferences( Preferences.userNodeForPackage(DalServer.class)); if (docRoot == null) { docRoot = preferences.getWebRoot(new File(System.getProperty("user.dir"), "www")); } DalServer server = null; if (serviceName != null && docRoot.isDirectory()) { try { DalDatabase db = createDalDatabase(serviceName, preferences); if (db.isInitialiseRequired()) { Closure<String> progress = new Closure<String>() { @Override public void execute(String msg) { System.out.println("Database Initialisation: " + msg); } }; db.initialise(progress); } server = create(preferences, host, port, docRoot, db); } catch (NoServiceException e) { throw new RuntimeException(e); } catch (DalDbException e) { throw new RuntimeException(e); } } Image serverIconImage = null; InputStream imageIs = DalServer.class.getResourceAsStream("dalserver-24.png"); if (imageIs != null) { try { serverIconImage = ImageIO.read(imageIs); if (Util.isMacOS()) { try { MacApplication macapp = new MacApplication(null); macapp.setDockIconImage(serverIconImage); } catch (MacApplicationException e) { System.err.println(e.getMessage()); } } } catch (IOException ignore) { } } if (server != null) { server.setMaxInactiveMinutes(inactiveMins); } else { AskServerParams asker = new AskServerParams(serverIconImage, null, "DAL Server Start", docRoot, preferences); GuiUtil.centreOnScreen(asker); asker.setVisible(true); if (asker.cancelled) { System.exit(0); } host = asker.dalServerHostName; port = asker.dalServerPort; inactiveMins = asker.maxInactiveMinutes; server = create(preferences, host, port, asker.wwwRoot, asker.dalDatabase); // server.setUseSimpleDatabase(asker.useSimpleDatabase); } final DalServer f_server = server; final File f_wwwRoot = docRoot; final Image f_serverIconImage = serverIconImage; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { DalServerFactory factory = new DalServerFactory() { @Override public DalServer create(String hostName, int port, File wwwRoot, DalDatabase dalDatabase) { return DalServer.create(preferences, hostName, port, wwwRoot, dalDatabase); } }; ServerGui gui = new ServerGui(f_serverIconImage, f_server, factory, f_wwwRoot, preferences); gui.setVisible(true); } }); }
From source file:ms1quant.MS1Quant.java
/** * @param args the command line arguments MS1Quant parameterfile *//*from ww w. ja v a2s . 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:Gen.java
public static void main(String[] args) throws Exception { try {//from ww w. j a v a2 s . co m File[] files = null; if (System.getProperty("dir") != null && !System.getProperty("dir").equals("")) { files = new File(System.getProperty("dir")).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toUpperCase().endsWith(".XML"); }; }); } else { String fileName = System.getProperty("file") != null && !System.getProperty("file").equals("") ? System.getProperty("file") : "rjmap.xml"; files = new File[] { new File(fileName) }; } log.info("files : " + Arrays.toString(files)); if (files == null || files.length == 0) { log.info("no files to parse"); System.exit(0); } boolean formatsource = true; if (System.getProperty("formatsource") != null && !System.getProperty("formatsource").equals("") && System.getProperty("formatsource").equalsIgnoreCase("false")) { formatsource = false; } GEN_ROOT = System.getProperty("outputdir"); if (GEN_ROOT == null || GEN_ROOT.equals("")) { GEN_ROOT = new File(files[0].getAbsolutePath()).getParent() + FILE_SEPARATOR + "distrib"; } GEN_ROOT = new File(GEN_ROOT).getAbsolutePath().replace('\\', '/'); if (GEN_ROOT.endsWith("/")) GEN_ROOT = GEN_ROOT.substring(0, GEN_ROOT.length() - 1); System.out.println("GEN ROOT:" + GEN_ROOT); MAPPING_JAR_NAME = System.getProperty("mappingjar") != null && !System.getProperty("mappingjar").equals("") ? System.getProperty("mappingjar") : "mapping.jar"; if (!MAPPING_JAR_NAME.endsWith(".jar")) MAPPING_JAR_NAME += ".jar"; GEN_ROOT_SRC = GEN_ROOT + FILE_SEPARATOR + "src"; GEN_ROOT_LIB = GEN_ROOT + FILE_SEPARATOR + ""; DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); domFactory.setValidating(false); DocumentBuilder documentBuilder = domFactory.newDocumentBuilder(); for (int f = 0; f < files.length; ++f) { log.info("parsing file : " + files[f]); Document document = documentBuilder.parse(files[f]); Vector<Node> initNodes = new Vector<Node>(); Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "initScript", initNodes); for (int i = 0; i < initNodes.size(); ++i) { NamedNodeMap attrs = initNodes.elementAt(i).getAttributes(); boolean embed = attrs.getNamedItem("embed") != null && attrs.getNamedItem("embed").getNodeValue().equalsIgnoreCase("true"); StringBuffer vbuffer = new StringBuffer(); if (attrs.getNamedItem("inline") != null) { vbuffer.append(attrs.getNamedItem("inline").getNodeValue()); vbuffer.append('\n'); } else { String fname = attrs.getNamedItem("name").getNodeValue(); if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') { String path = files[f].getAbsolutePath(); path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR)); fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath(); } vbuffer.append(Utils.getFileAsStringBuffer(fname)); } initScriptBuffer.append(vbuffer); if (embed) embedScriptBuffer.append(vbuffer); } Vector<Node> packageInitNodes = new Vector<Node>(); Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "packageScript", packageInitNodes); for (int i = 0; i < packageInitNodes.size(); ++i) { NamedNodeMap attrs = packageInitNodes.elementAt(i).getAttributes(); String packageName = attrs.getNamedItem("package").getNodeValue(); if (packageName.equals("")) packageName = "rGlobalEnv"; if (!packageName.endsWith("Function")) packageName += "Function"; if (packageEmbedScriptHashMap.get(packageName) == null) { packageEmbedScriptHashMap.put(packageName, new StringBuffer()); } StringBuffer vbuffer = packageEmbedScriptHashMap.get(packageName); // if (!packageName.equals("rGlobalEnvFunction")) { // vbuffer.append("library("+packageName.substring(0,packageName.lastIndexOf("Function"))+")\n"); // } if (attrs.getNamedItem("inline") != null) { vbuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n"); initScriptBuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n"); } else { String fname = attrs.getNamedItem("name").getNodeValue(); if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') { String path = files[f].getAbsolutePath(); path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR)); fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath(); } StringBuffer fileBuffer = Utils.getFileAsStringBuffer(fname); vbuffer.append(fileBuffer); initScriptBuffer.append(fileBuffer); } } Vector<Node> functionsNodes = new Vector<Node>(); Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "functions"), "function", functionsNodes); for (int i = 0; i < functionsNodes.size(); ++i) { NamedNodeMap attrs = functionsNodes.elementAt(i).getAttributes(); String functionName = attrs.getNamedItem("name").getNodeValue(); boolean forWeb = attrs.getNamedItem("forWeb") != null && attrs.getNamedItem("forWeb").getNodeValue().equalsIgnoreCase("true"); String signature = (attrs.getNamedItem("signature") == null ? "" : attrs.getNamedItem("signature").getNodeValue() + ","); String renameTo = (attrs.getNamedItem("renameTo") == null ? null : attrs.getNamedItem("renameTo").getNodeValue()); HashMap<String, FAttributes> sigMap = Globals._functionsToPublish.get(functionName); if (sigMap == null) { sigMap = new HashMap<String, FAttributes>(); Globals._functionsToPublish.put(functionName, sigMap); if (attrs.getNamedItem("returnType") == null) { _functionsVector.add(new String[] { functionName }); } else { _functionsVector.add( new String[] { functionName, attrs.getNamedItem("returnType").getNodeValue() }); } } sigMap.put(signature, new FAttributes(renameTo, forWeb)); if (forWeb) _webPublishingEnabled = true; } if (System.getProperty("targetjdk") != null && !System.getProperty("targetjdk").equals("") && System.getProperty("targetjdk").compareTo("1.5") < 0) { if (_webPublishingEnabled || (System.getProperty("ws.r.api") != null && System.getProperty("ws.r.api").equalsIgnoreCase("true"))) { log.info("be careful, web publishing disabled beacuse target JDK<1.5"); } _webPublishingEnabled = false; } else { if (System.getProperty("ws.r.api") == null || System.getProperty("ws.r.api").equals("") || !System.getProperty("ws.r.api").equalsIgnoreCase("false")) { _webPublishingEnabled = true; } if (_webPublishingEnabled && System.getProperty("java.version").compareTo("1.5") < 0) { log.info("be careful, web publishing disabled beacuse a JDK<1.5 is in use"); _webPublishingEnabled = false; } } Vector<Node> s4Nodes = new Vector<Node>(); Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "s4classes"), "class", s4Nodes); if (s4Nodes.size() > 0) { String formalArgs = ""; String signature = ""; for (int i = 0; i < s4Nodes.size(); ++i) { NamedNodeMap attrs = s4Nodes.elementAt(i).getAttributes(); String s4Name = attrs.getNamedItem("name").getNodeValue(); formalArgs += "p" + i + (i == s4Nodes.size() - 1 ? "" : ","); signature += "'" + s4Name + "'" + (i == s4Nodes.size() - 1 ? "" : ","); } String genBeansScriptlet = "setGeneric('" + PUBLISH_S4_HEADER + "', function(" + formalArgs + ") standardGeneric('" + PUBLISH_S4_HEADER + "'));" + "setMethod('" + PUBLISH_S4_HEADER + "', signature(" + signature + ") , function(" + formalArgs + ") { })"; initScriptBuffer.append(genBeansScriptlet); _functionsVector.add(new String[] { PUBLISH_S4_HEADER, "numeric" }); } } if (!new File(GEN_ROOT_LIB).exists()) regenerateDir(GEN_ROOT_LIB); else { clean(GEN_ROOT_LIB, true); } for (int i = 0; i < rwebservicesScripts.length; ++i) DirectJNI.getInstance().getRServices().sourceFromResource(rwebservicesScripts[i]); String lastStatus = DirectJNI.getInstance().runR(new ExecutionUnit() { public void run(Rengine e) { DirectJNI.getInstance().toggleMarker(); DirectJNI.getInstance().sourceFromBuffer(initScriptBuffer.toString()); log.info(" init script status : " + DirectJNI.getInstance().cutStatusSinceMarker()); for (int i = 0; i < _functionsVector.size(); ++i) { String[] functionPair = _functionsVector.elementAt(i); log.info("dealing with : " + functionPair[0]); regenerateDir(GEN_ROOT_SRC); String createMapStr = "createMap("; boolean isGeneric = e.rniGetBoolArrayI( e.rniEval(e.rniParse("isGeneric(\"" + functionPair[0] + "\")", 1), 0))[0] == 1; log.info("is Generic : " + isGeneric); if (isGeneric) { createMapStr += functionPair[0]; } else { createMapStr += "\"" + functionPair[0] + "\""; } createMapStr += ", outputDirectory=\"" + GEN_ROOT_SRC .substring(0, GEN_ROOT_SRC.length() - "/src".length()).replace('\\', '/') + "\""; createMapStr += ", typeMode=\"robject\""; createMapStr += (functionPair.length == 1 || functionPair[1] == null || functionPair[1].trim().equals("") ? "" : ", S4DefaultTypedSig=TypedSignature(returnType=\"" + functionPair[1] + "\")"); createMapStr += ")"; log.info("------------------------------------------"); log.info("-- createMapStr=" + createMapStr); DirectJNI.getInstance().toggleMarker(); e.rniEval(e.rniParse(createMapStr, 1), 0); String createMapStatus = DirectJNI.getInstance().cutStatusSinceMarker(); log.info(" createMap status : " + createMapStatus); log.info("------------------------------------------"); deleteDir(GEN_ROOT_SRC + "/org/kchine/r/rserviceJms"); compile(GEN_ROOT_SRC); jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", null); URL url = null; try { url = new URL( "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar") .replace('\\', '/') + "!/"); } catch (Exception ex) { ex.printStackTrace(); } DirectJNI.generateMaps(url, true); } } }); log.info(lastStatus); log.info(DirectJNI._rPackageInterfacesHash); regenerateDir(GEN_ROOT_SRC); for (int i = 0; i < _functionsVector.size(); ++i) { unjar(GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", GEN_ROOT_SRC); } regenerateRPackageClass(true); generateS4BeanRef(); if (formatsource) applyJalopy(GEN_ROOT_SRC); compile(GEN_ROOT_SRC); for (String k : DirectJNI._rPackageInterfacesHash.keySet()) { Rmic rmicTask = new Rmic(); rmicTask.setProject(_project); rmicTask.setTaskName("rmic_packages"); rmicTask.setClasspath(new Path(_project, GEN_ROOT_SRC)); rmicTask.setBase(new File(GEN_ROOT_SRC)); rmicTask.setClassname(k + "ImplRemote"); rmicTask.init(); rmicTask.execute(); } // DirectJNI._rPackageInterfacesHash=new HashMap<String, // Vector<Class<?>>>(); // DirectJNI._rPackageInterfacesHash.put("org.bioconductor.packages.rGlobalEnv.rGlobalEnvFunction",new // Vector<Class<?>>()); if (_webPublishingEnabled) { jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar", null); URL url = new URL( "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").replace('\\', '/') + "!/"); ClassLoader cl = new URLClassLoader(new URL[] { url }, Globals.class.getClassLoader()); for (String className : DirectJNI._rPackageInterfacesHash.keySet()) { if (cl.loadClass(className + "Web").getDeclaredMethods().length == 0) continue; log.info("######## " + className); WsGen wsgenTask = new WsGen(); wsgenTask.setProject(_project); wsgenTask.setTaskName("wsgen"); FileSet rjb_fileSet = new FileSet(); rjb_fileSet.setProject(_project); rjb_fileSet.setDir(new File(".")); rjb_fileSet.setIncludes("RJB.jar"); DirSet src_dirSet = new DirSet(); src_dirSet.setDir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/")); Path classPath = new Path(_project); classPath.addFileset(rjb_fileSet); classPath.addDirset(src_dirSet); wsgenTask.setClasspath(classPath); wsgenTask.setKeep(true); wsgenTask.setDestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/")); wsgenTask.setResourcedestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/")); wsgenTask.setSei(className + "Web"); wsgenTask.init(); wsgenTask.execute(); } new File(GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").delete(); } embedRScripts(); HashMap<String, String> marker = new HashMap<String, String>(); marker.put("RJBMAPPINGJAR", "TRUE"); Properties props = new Properties(); props.put("PACKAGE_NAMES", PoolUtils.objectToHex(DirectJNI._packageNames)); props.put("S4BEANS_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMapping)); props.put("S4BEANS_REVERT_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMappingRevert)); props.put("FACTORIES_MAPPING", PoolUtils.objectToHex(DirectJNI._factoriesMapping)); props.put("S4BEANS_HASH", PoolUtils.objectToHex(DirectJNI._s4BeansHash)); props.put("R_PACKAGE_INTERFACES_HASH", PoolUtils.objectToHex(DirectJNI._rPackageInterfacesHash)); props.put("ABSTRACT_FACTORIES", PoolUtils.objectToHex(DirectJNI._abstractFactories)); new File(GEN_ROOT_SRC + "/" + "maps").mkdirs(); FileOutputStream fos = new FileOutputStream(GEN_ROOT_SRC + "/" + "maps/rjbmaps.xml"); props.storeToXML(fos, null); fos.close(); jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + MAPPING_JAR_NAME, marker); if (_webPublishingEnabled) genWeb(); DirectJNI._mappingClassLoader = null; } finally { System.exit(0); } }
From source file:com.genentech.chemistry.tool.align.SDFAlign.java
public static void main(String... args) { Options options = new Options(); Option opt = new Option("in", true, "input sd file"); opt.setRequired(true);/*from w ww .j a v a 2s . co m*/ options.addOption(opt); opt = new Option("out", true, "output file"); opt.setRequired(true); options.addOption(opt); opt = new Option("method", true, "fss|sss|MCS|clique (default mcs)."); options.addOption(opt); opt = new Option("ref", true, "reference molecule if not given first in file is used. If multiple ref molecules are read the min RMSD is reported"); options.addOption(opt); opt = new Option("mirror", false, "If given and the molecule is not chiral, return best mirror image."); options.addOption(opt); opt = new Option("rmsdTag", true, "Tagname for output of rmsd, default: no output."); options.addOption(opt); opt = new Option("atomMatch", true, "Sequence of none|default|hcount|noAromatic specifing how atoms are matched cf. oe document.\n" + "noAromatic can be used to make terminal atoms match aliphatic and aromatic atoms.\n" + "Queryfeatures are considered only if default is used."); options.addOption(opt); opt = new Option("bondMatch", true, "Sequence of none|default specifing how bonds are matched cf. oe document."); options.addOption(opt); opt = new Option("keepCoreHydrogens", false, "If not specified the hydrigen atoms are removed from the core."); options.addOption(opt); opt = new Option("outputMol", true, "aligned|original (def: aligned) use original to just compute rmsd."); options.addOption(opt); opt = new Option("doNotOptimize", false, "If specified the RMSD is computed without moving optimizing the overlay."); options.addOption(opt); opt = new Option("quiet", false, "Reduced warining messages"); options.addOption(opt); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { exitWithHelp(e.getMessage(), options); } if (cmd.getArgs().length > 0) exitWithHelp("To many arguments", options); // do not check aromaticity on atoms so that a terminal atom matches aromatic and non aromatic atoms int atomExpr = OEExprOpts.DefaultAtoms; int bondExpr = OEExprOpts.DefaultBonds; String atomMatch = cmd.getOptionValue("atomMatch"); if (atomMatch == null) atomMatch = ""; atomMatch = '|' + atomMatch.toLowerCase() + '|'; String bondMatch = cmd.getOptionValue("bondMatch"); if (bondMatch == null) bondMatch = ""; bondMatch = '|' + bondMatch.toLowerCase() + '|'; String inFile = cmd.getOptionValue("in"); String outFile = cmd.getOptionValue("out"); String refFile = cmd.getOptionValue("ref"); String method = cmd.getOptionValue("method"); String rmsdTag = cmd.getOptionValue("rmsdTag"); String oMol = cmd.getOptionValue("outputMol"); boolean doMirror = cmd.hasOption("mirror"); boolean doOptimize = !cmd.hasOption("doNotOptimize"); boolean quiet = cmd.hasOption("quiet"); OUTType outputMol = oMol == null ? OUTType.ALIGNED : OUTType.valueOf(oMol.toUpperCase()); if (atomMatch.startsWith("|none")) atomExpr = 0; if (atomMatch.contains("|hcount|")) atomExpr |= OEExprOpts.HCount; if (atomMatch.contains("|noAromatic|")) atomExpr &= (~OEExprOpts.Aromaticity); if (bondMatch.startsWith("|none")) bondExpr = 0; ArrayList<OEMol> refmols = new ArrayList<OEMol>(); if (refFile != null) { oemolistream reffs = new oemolistream(refFile); if (!is3DFormat(reffs.GetFormat())) oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates"); reffs.SetFormat(OEFormat.MDL); int aromodel = OEIFlavor.Generic.OEAroModelOpenEye; int qflavor = reffs.GetFlavor(reffs.GetFormat()); reffs.SetFlavor(reffs.GetFormat(), (qflavor | aromodel)); OEMol rmol = new OEMol(); while (oechem.OEReadMDLQueryFile(reffs, rmol)) { if (!cmd.hasOption("keepCoreHydrogens")) oechem.OESuppressHydrogens(rmol); refmols.add(rmol); rmol = new OEMol(); } rmol.delete(); if (refmols.size() == 0) throw new Error("reference file had no entries"); reffs.close(); } oemolistream fitfs = new oemolistream(inFile); if (!is3DFormat(fitfs.GetFormat())) oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates"); oemolostream ofs = new oemolostream(outFile); if (!is3DFormat(ofs.GetFormat())) oechem.OEThrow.Fatal("Invalid output format: need 3D coordinates"); AlignInterface aligner = null; OEGraphMol fitmol = new OEGraphMol(); if (oechem.OEReadMolecule(fitfs, fitmol)) { if (refmols.size() == 0) { OEMol rmol = new OEMol(fitmol); if (!cmd.hasOption("keepCoreHydrogens")) oechem.OESuppressHydrogens(rmol); refmols.add(rmol); } if ("sss".equalsIgnoreCase(method)) { aligner = new SSSAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr, quiet); } else if ("clique".equalsIgnoreCase(method)) { aligner = new CliqueAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr, quiet); } else if ("fss".equalsIgnoreCase(method)) { if (cmd.hasOption("atomMatch") || cmd.hasOption("bondMatch")) exitWithHelp("method fss does not support '-atomMatch' or '-bondMatch'", options); aligner = new FSSAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror); } else { aligner = new McsAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr, quiet); } do { aligner.align(fitmol); oechem.OEWriteMolecule(ofs, fitmol); } while (oechem.OEReadMolecule(fitfs, fitmol)); } fitmol.delete(); if (aligner != null) aligner.close(); for (OEMolBase mol : refmols) mol.delete(); fitfs.close(); ofs.close(); }
From source file:LamportBasicVersion.java
public static void main(String[] args) throws FileNotFoundException, IOException, InterruptedException { totalMessageCount = 0;/* w w w .j a v a 2 s . com*/ //For parsing the file and storing the information String line; String configurationFile = "configuration.txt"; int lineCountInFile = 0; myProcessId = Integer.parseInt(args[0]); FileReader fileReader = new FileReader(configurationFile); BufferedReader bufferedReader = new BufferedReader(fileReader); while ((line = bufferedReader.readLine()) != null) { if ((!(line.startsWith("#"))) && (!(line.isEmpty()))) { lineCountInFile = lineCountInFile + 1; String[] splitLine = line.split(" "); switch (lineCountInFile) { case 1: numberOfProcesses = Integer.parseInt(splitLine[0]); interRequestDelay = Integer.parseInt(splitLine[1]); csExecutionTime = Integer.parseInt(splitLine[2]); maxNumberOfRequest = Integer.parseInt(splitLine[3]); machineNames = new String[Integer.parseInt(splitLine[0])]; portNumbers = new int[Integer.parseInt(splitLine[0])]; break; default: machineNames[lineCountInFile - 2] = splitLine[1]; portNumbers[lineCountInFile - 2] = Integer.parseInt(splitLine[2]); break; } } } conditionArray = new int[numberOfProcesses]; finishFlagArray = new int[numberOfProcesses]; //Initializing vector class VectorClass.initialize(numberOfProcesses); //Fill the arrays with zero false value for (int o = 0; o < numberOfProcesses; o++) { conditionArray[o] = 0; finishFlagArray[o] = 0; } // Write output to file filename = filename + Integer.toString(myProcessId) + ".out"; file = new File(filename); file.createNewFile(); writer = new FileWriter(file); // Write clocks to file filenameClock = filenameClock + Integer.toString(myProcessId) + ".out"; fileClock = new File(filenameClock); fileClock.createNewFile(); //writerClock = new FileWriter(fileClock); fw = new FileWriter(fileClock); bw = new BufferedWriter(fw); // // Expo mean insert csExecutionExpoDelay = new ExponentialDistribution(csExecutionTime); interRequestExpoDelay = new ExponentialDistribution(interRequestDelay); // System.out.println("********************************************************"); System.out.println("My process id : " + myProcessId); System.out.println("Number of processes : " + numberOfProcesses); System.out.println("Inter-request delay : " + interRequestDelay); System.out.println("Critical section execution time : " + csExecutionTime); System.out.println("Maximum number of request : " + maxNumberOfRequest); System.out.println( "My process name : " + machineNames[myProcessId] + " My port number : " + portNumbers[myProcessId]); for (int i = 0; i < numberOfProcesses; i++) { System.out.println("Process name : " + machineNames[i] + " Port number : " + portNumbers[i]); } System.out.println("********************************************************"); //For hosting server localhost SctpServerChannel sctpServerChannel = SctpServerChannel.open(); InetSocketAddress serverAddr = new InetSocketAddress(portNumbers[myProcessId]); sctpServerChannel.bind(serverAddr); System.out.println("********************************************************"); System.out.println("Local server hosted"); System.out.println("********************************************************"); //For creating neighbor SCTP channels Thread.sleep(30000); socketAddress = new SocketAddress[numberOfProcesses]; sctpChannel = new SctpChannel[numberOfProcesses]; System.out.println("********************************************************"); System.out.println("Neighbor channels created"); System.out.println("********************************************************"); //Thread spanned for generating critical section request new Thread(new LamportBasicVersion()).start(); //while loop to receive all the requests and other messages while (true) { try (SctpChannel sctpChannelFromClient = sctpServerChannel.accept()) { mutex.acquire(); byteBufferFromNeighbor.clear(); String receiveMessage; MessageInfo messageInfoFromNeighbor = sctpChannelFromClient.receive(byteBufferFromNeighbor, null, null); //System.out.println("Raw Message : " + messageInfoFromNeighbor); receiveMessage = byteToString(byteBufferFromNeighbor, messageInfoFromNeighbor); //write to file start writer.write("Received Message : " + receiveMessage); writer.write("\n"); writer.flush(); //write to file end System.out.println("Received Message : " + receiveMessage); if (receiveMessage.contains("Request")) { String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // int requestMade = Integer.parseInt(parseMessage[3] + parseMessage[1]); queue.add(requestMade); //Send reply messages to that process for entering CS lamportClock++; //vector clock construction int[] vector = VectorClass.increment(myProcessId); String vectorClockConstruction = ""; for (int g = 0; g < vector.length; g++) { if (g == 0) { vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]); } else { vectorClockConstruction = vectorClockConstruction + "," + Integer.toString(vector[g]); } } // for (int k = 0; k < numberOfProcesses; k++) { if (k == Integer.parseInt(parseMessage[1])) { try { byteBufferToNeighbor.clear(); initializeChannels(); sctpChannel[k].connect(socketAddress[k]); String sendMessage = "Reply from Process-" + myProcessId + "-" + Integer.toString(requestMade) + "-" + lamportClock + "-" + vectorClockConstruction; System.out.println("Message sent is : " + sendMessage); //write to file start writer.write("Message sent is : " + sendMessage); writer.write("\n"); writer.flush(); //write to file end MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0); byteBufferToNeighbor.put(sendMessage.getBytes()); byteBufferToNeighbor.flip(); sctpChannel[k].send(byteBufferToNeighbor, messageInfoToNeighbor); totalMessageCount++; sctpChannel[k].close(); } catch (IOException ex) { Logger.getLogger(LamportBasicVersion.class.getName()).log(Level.SEVERE, null, ex); } } } } else if (receiveMessage.contains("Reply")) { conditionArray[myProcessId] = 1; String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // conditionArray[Integer.parseInt(parseMessage[1])] = 1; int count = 0; for (int v = 0; v < numberOfProcesses; v++) { if (conditionArray[v] == 1) { count = count + 1; } } if (count == numberOfProcesses) { L1ConditionFlag = 1; System.out.println("Inside L1"); blockingQueue.put("L1"); //Clearing condition array after receiving all REPLY for (int z = 0; z < numberOfProcesses; z++) { conditionArray[z] = 0; } if (L2ConditionFlag == 0 && outstandingRequest == 1) { Integer[] queueArray = new Integer[queue.size()]; queue.toArray(queueArray); Arrays.sort(queueArray); if (queueArray[0] == currentRequestBeingServed) { System.out.println("Inside L2"); L2ConditionFlag = 1; blockingQueue.put("L2"); } } } } else if (receiveMessage.contains("Release")) { int present = 0; int delete = 0; String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // if (queue.size() != 0) { Integer[] queueArray = new Integer[queue.size()]; queue.toArray(queueArray); Arrays.sort(queueArray); for (int a = 0; a < queueArray.length; a++) { if (queueArray[a] == Integer.parseInt(parseMessage[2])) { present = 1; delete = a; } } if (present == 1) { for (int s = 0; s <= delete; s++) { queue.remove(); } } } if (L2ConditionFlag == 0 && outstandingRequest == 1) { if (queue.size() != 0) { Integer[] queueArray1 = new Integer[queue.size()]; queue.toArray(queueArray1); Arrays.sort(queueArray1); if (currentRequestBeingServed == queueArray1[0]) { L2ConditionFlag = 1; System.out.println("Inside L2"); blockingQueue.put("L2"); } } } } else if (receiveMessage.contains("Finish")) { String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // finishFlagArray[Integer.parseInt(parseMessage[1])] = 1; int count = 0; for (int v = 0; v < numberOfProcesses; v++) { if (finishFlagArray[v] == 1) { count = count + 1; } } if (count == numberOfProcesses) { break; } } //logic for other messages //Print the queue to check System.out.println("********************************************************"); for (Object item : queue) { System.out.print(item); System.out.print("\t"); } System.out.println("********************************************************"); } mutex.release(); } }
From source file:DocumentTracer.java
/** Main. */ public static void main(String[] argv) throws Exception { // is there anything to do? if (argv.length == 0) { printUsage();/* w w w .j a v a2s.co m*/ System.exit(1); } // variables DocumentTracer tracer = new DocumentTracer(); PrintWriter out = new PrintWriter(System.out); XMLReader parser = null; boolean namespaces = DEFAULT_NAMESPACES; boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES; boolean validation = DEFAULT_VALIDATION; boolean externalDTD = DEFAULT_LOAD_EXTERNAL_DTD; boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION; boolean xincludeProcessing = DEFAULT_XINCLUDE; boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS; boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE; // process arguments for (int i = 0; i < argv.length; i++) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("p")) { // get parser name if (++i == argv.length) { System.err.println("error: Missing argument to -p option."); } String parserName = argv[i]; // create parser try { parser = XMLReaderFactory.createXMLReader(parserName); } catch (Exception e) { try { Parser sax1Parser = ParserFactory.makeParser(parserName); parser = new ParserAdapter(sax1Parser); System.err.println("warning: Features and properties not supported on SAX1 parsers."); } catch (Exception ex) { parser = null; System.err.println("error: Unable to instantiate parser (" + parserName + ")"); } } continue; } if (option.equalsIgnoreCase("n")) { namespaces = option.equals("n"); continue; } if (option.equalsIgnoreCase("np")) { namespacePrefixes = option.equals("np"); continue; } if (option.equalsIgnoreCase("v")) { validation = option.equals("v"); continue; } if (option.equalsIgnoreCase("xd")) { externalDTD = option.equals("xd"); continue; } if (option.equalsIgnoreCase("s")) { schemaValidation = option.equals("s"); continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("dv")) { dynamicValidation = option.equals("dv"); continue; } if (option.equalsIgnoreCase("xi")) { xincludeProcessing = option.equals("xi"); continue; } if (option.equalsIgnoreCase("xb")) { xincludeFixupBaseURIs = option.equals("xb"); continue; } if (option.equalsIgnoreCase("xl")) { xincludeFixupLanguage = option.equals("xl"); continue; } if (option.equals("h")) { printUsage(); continue; } } // use default parser? if (parser == null) { // create parser try { parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME); } catch (Exception e) { System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")"); continue; } } // set parser features try { parser.setFeature(NAMESPACES_FEATURE_ID, namespaces); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")"); } try { parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes); } catch (SAXException e) { System.err.println( "warning: Parser does not support feature (" + NAMESPACE_PREFIXES_FEATURE_ID + ")"); } try { parser.setFeature(VALIDATION_FEATURE_ID, validation); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(LOAD_EXTERNAL_DTD_FEATURE_ID, externalDTD); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err .println("warning: Parser does not support feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")"); } try { parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Parser does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing); } catch (SAXNotRecognizedException e) { System.err.println("warning: Parser does not recognize feature (" + XINCLUDE_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")"); } // set handlers parser.setDTDHandler(tracer); parser.setErrorHandler(tracer); if (parser instanceof XMLReader) { parser.setContentHandler(tracer); try { parser.setProperty("http://xml.org/sax/properties/declaration-handler", tracer); } catch (SAXException e) { e.printStackTrace(System.err); } try { parser.setProperty("http://xml.org/sax/properties/lexical-handler", tracer); } catch (SAXException e) { e.printStackTrace(System.err); } } else { ((Parser) parser).setDocumentHandler(tracer); } // parse file try { parser.parse(arg); } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - " + e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException) e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } } }
From source file:com.spinn3r.api.Main.java
public static void main(String[] args) throws Exception { // NOTE this could be cleaned up to pass the values into the config // object directly. // parse out propeties. String api = null;//from www . j a v a 2s.co m for (int i = 0; i < args.length; ++i) { String v = args[i]; if (v.startsWith("--api")) { api = getOpt(v); } } if (api == null) api = "permalink"; // First. Determine which API you'd like to use. long after = -1; Format format = Format.PROTOSTREAM; String vendor = null; String remoteFilter = null; Long sleep_duration = null; boolean skip_description = false; String host = "api.spinn3r.com"; for (int i = 0; i < args.length; ++i) { String v = args[i]; if (v.startsWith("--vendor")) { vendor = getOpt(v); continue; } if (v.startsWith("--filter")) { filter = getOpt(v); continue; } if (v.startsWith("--remote-filter")) { remoteFilter = getOpt(v); continue; } if (v.startsWith("--show_results")) { show_results = Integer.parseInt(getOpt(v)); continue; } /* * The code for the --afterTimestamp must come * before the code for --after because --afterTimestamp * also matches startsWith("after"); */ if (v.startsWith("--afterTimestamp")) { after = Long.parseLong(getOpt(v)); continue; } if (v.startsWith("--after")) { after = getOptAsTimeInMillis(v); continue; } /* * The code for the --beforeTimestamp must come * before the code for --before because --beforeTimestamp * also matches startsWith("before"); */ if (v.startsWith("--beforeTimestamp")) { before = Long.parseLong(getOpt(v)); continue; } if (v.startsWith("--before")) { before = getOptAsTimeInMillis(v); continue; } if (v.startsWith("--range")) { range = Long.parseLong(getOpt(v)); continue; } if (v.startsWith("--recover")) { restore = true; continue; } if (v.startsWith("--sleep_duration")) { sleep_duration = Long.parseLong(getOpt(v)); continue; } if (v.startsWith("--save=")) { save = getOpt(v); continue; } if (v.startsWith("--save_method=")) { save_method = getOpt(v); continue; } if (v.startsWith("--skip_description=")) { skip_description = Boolean.parseBoolean(getOpt(v)); continue; } if (v.startsWith("--save_compressed=")) { saveCompressed = Boolean.parseBoolean(getOpt(v)); continue; } if (v.startsWith("--timing")) { timing = "true".equals(getOpt(v)); continue; } if (v.startsWith("--debug")) { logLevel = Level.FINE; debugLogFilePath = getOpt(v); continue; } /* * if ( v.startsWith( "--spam_probability" ) ) { * config.setSpamProbability( Double.parseDouble( getOpt( v ) ) ); * continue; } */ if (v.startsWith("--dump_fields=")) { dumpFields = Boolean.parseBoolean(getOpt(v)); continue; } if (v.startsWith("--dump=")) { dump = Boolean.parseBoolean(getOpt(v)); continue; } if (v.startsWith("--csv=")) { csv = Boolean.parseBoolean(getOpt(v)); continue; } if (v.startsWith("--memory")) { System.out.printf("max memory: %s\n", Runtime.getRuntime().maxMemory()); System.exit(0); } if (v.startsWith("--host")) { host = getOpt(v); continue; } if (v.startsWith("--enable3")) { // is now default continue; } if (v.startsWith("com.spinn3r")) continue; if (v.startsWith("--api")) continue; // That's an unknown command line option. Exit. System.err.printf("Unknown command line option: %s\n", v); syntax(); System.exit(1); } /* * Set the log level */ Logger anonymousLogger = Logger.getAnonymousLogger(); anonymousLogger.setLevel(logLevel); if (debugLogFilePath != null) { anonymousLogger.addHandler(new FileHandler(debugLogFilePath)); } Factory factory = new Factory(); String restoreURL = null; if (save != null && restore) { File savedir = new File(save); Collection<File> logFiles = getLogFiles(savedir); PermalinkLogReaderAdapter adapter = getRestoreURLS(logFiles); restoreURL = adapter.getLastUrl(); long ctr = adapter.getLastCtr(); for (File file : logFiles) { if (!file.delete()) throw new IOException("Failed to delete " + file.toString()); } factory.enableLogging(savedir, 1000000); if (restoreURL != null) { factory.enableRestart(ctr, restoreURL); } logManager = factory.getInjector().getInstance(TransactionHistoryManager.class); } else { logManager = factory.getInjector().getInstance(TransactionHistoryManager.class); } Config<? extends BaseResult> config = null; BaseClient<? extends BaseResult> client = null; if (api.startsWith("feed")) { config = new FeedConfig(); client = new FeedClient(); } else if (api.startsWith("comment")) { config = new CommentConfig(); client = new CommentClient(); } else { config = new PermalinkConfig(); client = new PermalinkClient( restoreURL != null ? ImmutableList.of(restoreURL) : Collections.<String>emptyList()); } config.setCommandLine(StringUtils.join(args, " ")); config.setApi(api); config.setFormat(format); config.setVendor(vendor); config.setHost(host); config.setFilter(remoteFilter); config.setSkipDescription(skip_description); if (sleep_duration != null) client.setSleepDuration(sleep_duration); // assert that we have all required options. if (config.getVendor() == null) { syntax(); System.exit(1); } long maxMemory = Runtime.getRuntime().maxMemory(); long requiredMemory = (save == null) ? PARSE_REQUIRED_MEMORY : SAVE_REQUIRED_MEMORY; if (maxMemory < requiredMemory) { System.out.printf("ERROR: Reference client requires at least 2GB of memory.\n"); System.out.printf("\n"); System.out.printf("Now running with: %s vs %s required\n", maxMemory, requiredMemory); System.out.printf("\n"); System.out.printf("Add -Xmx%dM to your command line and run again.\n", requiredMemory / (1024 * 1024)); System.exit(1); } // use defaults System.out.println("Using vendor: " + config.getVendor()); System.out.println("Using api: " + api); if (after > -1) System.out.printf("After: %s (%s)\n", ISO8601DateParser.toString(Config.timestampToDate(after)), after); if (before > -1) System.out.printf("Before: %s (%s)\n", ISO8601DateParser.toString(Config.timestampToDate(before)), before); System.out.println("Saving results to disk: " + save); // Fetch for the last 5 minutes and then try to get up to date. In // production you'd want to call setFirstRequestURL from the // getLastRequestURL returned from fetch() below if (after == -1) { after = Config.millisecondsToTimestamp(System.currentTimeMillis()); after = after - INTERVAL; } config.setAfterTimestamp(after); new Main().exec(client, config); }
From source file:ImageInfo.java
/** * To use this class as a command line application, give it either * some file names as parameters (information on them will be * printed to standard output, one line per file) or call * it with no parameters. It will then check data given to it * via standard input.//from w w w . ja va2 s . c o m * * @param args the program arguments which must be file names */ public static void main(String[] args) { ImageInfo imageInfo = new ImageInfo(); imageInfo.setDetermineImageNumber(true); boolean verbose = determineVerbosity(args); if (args.length == 0) { run(null, System.in, imageInfo, verbose); } else { int index = 0; while (index < args.length) { InputStream in = null; try { String name = args[index++]; System.out.print(name + ";"); if (name.startsWith("http://")) { in = new URL(name).openConnection().getInputStream(); } else { in = new FileInputStream(name); } run(name, in, imageInfo, verbose); in.close(); } catch (Exception e) { System.out.println(e); try { in.close(); } catch (Exception ee) { } } } } }
From source file:luisjosediez.Ejercicio2.java
/** * @param args the command line arguments *///w ww . j a v a2 s. c o m public static void main(String[] args) { // TODO code application logic here System.out.println("Introduce la direccin de un servidor ftp: "); FTPClient cliente = new FTPClient(); String servFTP = cadena(); String clave = ""; System.out.println("Introduce usuario (vaco para conexin annima): "); String usuario = cadena(); String opcion; if (usuario.equals("")) { clave = ""; } else { System.out.println("Introduce contrasea: "); clave = cadena(); } try { cliente.setPassiveNatWorkaround(false); cliente.connect(servFTP, 21); boolean login = cliente.login(usuario, clave); if (login) { System.out.println("Conexin ok"); } else { System.out.println("Login incorrecto"); cliente.disconnect(); System.exit(1); } do { System.out.println("Orden [exit para salir]: "); opcion = cadena(); if (opcion.equals("ls")) { FTPFile[] files = cliente.listFiles(); String tipos[] = { "Fichero", "Directorio", "Enlace" }; for (int i = 0; i < files.length; i++) { System.out.println("\t" + files[i].getName() + "\t=> " + tipos[files[i].getType()]); } } else if (opcion.startsWith("cd ")) { try { cliente.changeWorkingDirectory(opcion.substring(3)); } catch (IOException e) { } } else if (opcion.equals("help")) { System.out.println( "Puede ejecutar los comandos 'exit', 'ls', 'cd', 'get' y 'upload'. Para ms detalles utilice 'help <comando>'."); } else if (opcion.startsWith("help ")) { if (opcion.endsWith(" get")) { System.out.println( "Permite descargar un archivo concreto. Uso: 'get <rutaArchivoADescargar>'."); } else if (opcion.endsWith(" ls")) { System.out.println("Lista los ficheros y directorios en la ubicacin actual. Uso: 'ls'."); } else if (opcion.endsWith(" cd")) { System.out.println("Permite cambiar la ubicacin actual. Uso: 'cd <rutaDestino>'."); } else if (opcion.endsWith(" put")) { System.out.println( "Permite subir un archivo al directorio actual. Uso: 'put <rutaArchivoASubir>'."); } } else if (opcion.startsWith("get ")) { try { System.out.println("Indique la carpeta de descarga: "); try (FileOutputStream fos = new FileOutputStream(cadena() + opcion.substring(4))) { cliente.retrieveFile(opcion.substring(4), fos); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } } else if (opcion.startsWith("put ")) { try { try { System.out.println(opcion.substring(4)); File local = new File(opcion.substring(4)); System.out.println(local.getName()); InputStream is = new FileInputStream(opcion.substring(4)); OutputStream os = cliente.storeFileStream(local.getName()); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = is.read(bytesIn)) != -1) { os.write(bytesIn, 0, read); } is.close(); os.close(); boolean completed = cliente.completePendingCommand(); if (completed) { System.out.println("The file is uploaded successfully."); } } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } } } while (!(opcion.equals("exit"))); boolean logout = cliente.logout(); if (logout) System.out.println("Logout..."); else System.out.println("Logout incorrecto"); cliente.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
From source file:DIA_Umpire_SE.DIA_Umpire_SE.java
/** * @param args the command line arguments DIA_Umpire parameterfile *///from www . j a v a2s . co m public static void main(String[] args) throws InterruptedException, FileNotFoundException, ExecutionException, IOException, ParserConfigurationException, DataFormatException, SAXException, Exception { System.out.println( "================================================================================================="); System.out.println( "DIA-Umpire singal extraction analysis (version: " + UmpireInfo.GetInstance().Version + ")"); if (args.length < 2 || args.length > 3) { System.out.println( "command format error, the correct format is: java -jar -Xmx8G DIA_Umpire_SE.jar mzMXL_file diaumpire_se.params"); System.out.println( "To fix DIA setting, use : java -jar -Xmx8G DIA_Umpire_SE.jar mzMXL_file diaumpire_se.params -f"); return; } try { //Define logger level for console ConsoleLogger.SetConsoleLogger(Level.INFO); //Define logger level and file path for text log file ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_se.log"); } catch (Exception e) { } boolean Fix = false; boolean Resume = false; if (args.length == 3 && args[2].equals("-f")) { Fix = true; } String parameterfile = args[1]; String MSFilePath = args[0]; Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version); Logger.getRootLogger().info("Parameter file:" + parameterfile); Logger.getRootLogger().info("Spectra file:" + MSFilePath); BufferedReader reader = new BufferedReader(new FileReader(parameterfile)); String line = ""; InstrumentParameter param = new InstrumentParameter(InstrumentParameter.InstrumentType.TOF5600); param.DetermineBGByID = false; param.EstimateBG = true; int NoCPUs = 2; SpectralDataType.DataType dataType = SpectralDataType.DataType.DIA_F_Window; String WindowType = ""; int WindowSize = 25; ArrayList<XYData> WindowList = new ArrayList<>(); boolean ExportPrecursorPeak = false; boolean ExportFragmentPeak = false; //<editor-fold defaultstate="collapsed" desc="Read parameter file"> while ((line = reader.readLine()) != null) { Logger.getRootLogger().info(line); if (!"".equals(line) && !line.startsWith("#")) { //System.out.println(line); if (line.equals("==window setting begin")) { while (!(line = reader.readLine()).equals("==window setting end")) { if (!"".equals(line)) { WindowList.add(new XYData(Float.parseFloat(line.split("\t")[0]), Float.parseFloat(line.split("\t")[1]))); } } 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; } case "ExportPrecursorPeak": { ExportPrecursorPeak = Boolean.parseBoolean(value); break; } case "ExportFragmentPeak": { ExportFragmentPeak = Boolean.parseBoolean(value); break; } //<editor-fold defaultstate="collapsed" desc="instrument parameters"> case "RPmax": { param.PrecursorRank = Integer.parseInt(value); break; } case "RFmax": { param.FragmentRank = Integer.parseInt(value); break; } case "CorrThreshold": { param.CorrThreshold = Float.parseFloat(value); break; } case "DeltaApex": { param.ApexDelta = Float.parseFloat(value); break; } case "RTOverlap": { param.RTOverlapThreshold = Float.parseFloat(value); break; } case "BoostComplementaryIon": { param.BoostComplementaryIon = Boolean.parseBoolean(value); break; } case "AdjustFragIntensity": { param.AdjustFragIntensity = Boolean.parseBoolean(value); break; } 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); break; } case "SE.EndRT": { param.endRT = Float.valueOf(value); break; } case "SE.RemoveGroupedPeaksRTOverlap": { param.RemoveGroupedPeaksRTOverlap = Float.valueOf(value); break; } case "SE.RemoveGroupedPeaksCorr": { param.RemoveGroupedPeaksCorr = Float.valueOf(value); break; } case "SE.MinMZ": { param.MinMZ = Float.valueOf(value); break; } case "SE.MinPrecursorMass": { param.MinPrecursorMass = Float.valueOf(value); break; } case "SE.MaxPrecursorMass": { param.MaxPrecursorMass = Float.valueOf(value); break; } case "SE.IsoCorrThreshold": { param.IsoCorrThreshold = Float.valueOf(value); break; } case "SE.MassDefectFilter": { param.MassDefectFilter = Boolean.parseBoolean(value); break; } case "SE.MassDefectOffset": { param.MassDefectOffset = Float.valueOf(value); break; } //</editor-fold>//</editor-fold> case "WindowType": { WindowType = value; switch (WindowType) { case "SWATH": { dataType = SpectralDataType.DataType.DIA_F_Window; break; } case "V_SWATH": { dataType = SpectralDataType.DataType.DIA_V_Window; break; } case "MSX": { dataType = SpectralDataType.DataType.MSX; break; } case "MSE": { dataType = SpectralDataType.DataType.MSe; break; } } break; } case "WindowSize": { WindowSize = Integer.parseInt(value); break; } } } } //</editor-fold> try { File MSFile = new File(MSFilePath); if (MSFile.exists()) { long time = System.currentTimeMillis(); Logger.getRootLogger().info( "================================================================================================="); Logger.getRootLogger().info("Processing " + MSFilePath + "...."); //Initialize a DIA file data structure DIAPack DiaFile = new DIAPack(MSFile.getAbsolutePath(), NoCPUs); DiaFile.Resume = Resume; DiaFile.SetDataType(dataType); DiaFile.SetParameter(param); //Set DIA isolation window setting if (dataType == SpectralDataType.DataType.DIA_F_Window) { DiaFile.SetWindowSize(WindowSize); } else if (dataType == SpectralDataType.DataType.DIA_V_Window) { for (XYData window : WindowList) { DiaFile.AddVariableWindow(window); } } DiaFile.SaveDIASetting(); DiaFile.SaveParams(); if (Fix) { DiaFile.FixScanidx(); return; } DiaFile.ExportPrecursorPeak = ExportPrecursorPeak; DiaFile.ExportFragmentPeak = ExportFragmentPeak; Logger.getRootLogger().info("Module A: Signal extraction"); //Start DIA signal extraction process to generate pseudo MS/MS files DiaFile.process(); time = System.currentTimeMillis() - time; Logger.getRootLogger().info(MSFilePath + " 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)))); } else { throw new RuntimeException("file: " + MSFile + "? does not exist!"); } Logger.getRootLogger().info("Job complete"); Logger.getRootLogger().info( "================================================================================================="); } catch (Exception e) { Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e)); throw e; } }