List of usage examples for java.io File mkdir
public boolean mkdir()
From source file:net.sf.firemox.xml.XmlConfiguration.java
/** * <ul>// w w w . j a v a2s .c o m * 2 modes: * <li>Update the a MDB for specified TBS against the XML files (main file, * cards and fragments). Arguments are : TBS_NAME</li> * <li>Rebuild completely the MDB for specified TBS. Arguments are : -full * TBS_NAME</li> * </ul> * * @param args * main arguments. */ public static void main(String... args) { options = new Options(); final CmdLineParser parser = new CmdLineParser(options); try { parser.parseArgument(args); } catch (CmdLineException e) { // Display help info(e.getMessage()); parser.setUsageWidth(80); parser.printUsage(System.out); System.exit(-1); return; } if (options.isVersion()) { // Display version info("Version is " + IdConst.VERSION); System.exit(-1); return; } if (options.isHelp()) { // Display help parser.setUsageWidth(80); parser.printUsage(System.out); System.exit(-1); return; } warning = 0; uncompleted = 0; error = 0; long start = System.currentTimeMillis(); XmlTools.initHashMaps(); MToolKit.tbsName = options.getMdb(); String xmlFile = MToolKit.getFile(IdConst.TBS_DIR + "/" + MToolKit.tbsName + ".xml", false) .getAbsolutePath(); try { if (options.isForce()) { final File recycledDir = MToolKit.getTbsFile("recycled"); if (!recycledDir.exists() || !recycledDir.isDirectory()) { recycledDir.mkdir(); } parseRules(xmlFile, MToolKit.getTbsFile("recycled").getAbsolutePath(), new FileOutputStream(MToolKit.getTbsFile(MToolKit.tbsName + ".mdb", false))); } else { // Check the up-to-date state of MDB final File file = MToolKit .getFile(IdConst.TBS_DIR + "/" + MToolKit.tbsName + "/" + MToolKit.tbsName + ".mdb"); final long lastModifiedMdb; if (file == null) { lastModifiedMdb = 0; } else { lastModifiedMdb = file.lastModified(); } boolean update = false; // Check the up-to-date state of MDB against the main XML file if (MToolKit.getFile(xmlFile).lastModified() > lastModifiedMdb) { // The main XML file is newer than MDB System.out.println("MDB is out of date, " + xmlFile + " is newer"); update = true; } else { final File fragmentDir = MToolKit.getTbsFile(""); for (File frament : fragmentDir.listFiles( (FilenameFilter) FileFilterUtils.andFileFilter(FileFilterUtils.suffixFileFilter("xml"), FileFilterUtils.prefixFileFilter("fragment-")))) { if (frament.lastModified() > lastModifiedMdb) { // One card is newer than MDB System.out.println( "MDB is out of date, at least one fragment found : " + frament.getName()); update = true; break; } } if (!update) { // Check the up-to-date state of MDB against the cards final File recycledDir = MToolKit.getTbsFile("recycled"); if (!recycledDir.exists() || !recycledDir.isDirectory()) { recycledDir.mkdir(); } if (recycledDir.lastModified() > lastModifiedMdb) { // The recycled XML file is newer than MDB System.out.println("MDB is out of date, the recycled directory is new"); update = true; } else { for (File card : recycledDir.listFiles((FilenameFilter) FileFilterUtils.andFileFilter( FileFilterUtils.suffixFileFilter("xml"), FileFilterUtils.notFileFilter( FileFilterUtils.suffixFileFilter(IdConst.FILE_DATABASE_SAVED))))) { if (card.lastModified() > lastModifiedMdb) { // One card is newer than MDB System.out.println("MDB is out of date, at least one new card found : " + card); update = true; break; } } } } } if (!update) { return; } // Need to update the whole MDB parseRules(xmlFile, MToolKit.getTbsFile("recycled").getAbsolutePath(), new FileOutputStream(MToolKit.getTbsFile(MToolKit.tbsName + ".mdb", false))); } } catch (SAXParseException e) { // Ignore this error } catch (Exception e) { e.printStackTrace(); } if (warning > 0) { System.out.println("\t" + warning + " warning" + (warning > 1 ? "s" : "")); } if (error > 0) { System.out.println("\t" + error + " error" + (error > 1 ? "s" : "")); System.out.println("Some cards have not been built correctly. Fix them."); } else { System.out.println("\tSuccessfull build"); } System.out.println("\tTime : " + (System.currentTimeMillis() - start) / 1000 + " s"); }
From source file:ca.twoducks.vor.ossindex.report.Assistant.java
/** Main method. Very simple, does not perform sanity checks on input. * /*from ww w . ja v a 2 s. co m*/ * @param args * @throws IOException */ public static void main(String[] args) throws IOException { CommandLineParser parser = new BasicParser(); try { // parse the command line arguments CommandLine line = parser.parse(getOptions(), args); if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("assistant", getOptions()); return; } // Instantiate assistant Assistant assistant = new Assistant(); // Add default plugins assistant.addScanPlugin(ChecksumPlugin.class); assistant.addScanPlugin(HtmlDependencyPlugin.class); assistant.addScanPlugin(NodeDependencyPlugin.class); assistant.addScanPlugin(MavenDependencyPlugin.class); assistant.addScanPlugin(GemfileDependencyPlugin.class); if (line.hasOption(NO_DEPENDENCIES_OPTION)) { assistant.setExportDependencies(false); } else { assistant.setExportDependencies(true); } assistant.setIncludeImages(!line.hasOption(NO_IMAGES_OPTION)); assistant.setIncludeArtifacts(!line.hasOption(NO_ARTIFACTS_OPTION)); // Determine operation type boolean doScan = line.hasOption("scan"); boolean doMerge = line.hasOption("merge"); boolean doImport = line.hasOption("import"); int count = 0; if (doScan) count++; if (doMerge) count++; if (doImport) count++; if (count > 1) { System.err.println("Only one of 'scan', 'merge', or import may be selected"); return; } if (doScan) { // Get the output directory if (!line.hasOption("D")) { System.err.println("An output directory must be specified"); return; } File outputDir = new File(line.getOptionValue("D")); if (!outputDir.exists()) outputDir.mkdir(); if (!outputDir.isDirectory()) { System.err.println("Output option is not a directory: " + outputDir); return; } doScan(assistant, line.getOptionValue("scan"), outputDir, line.hasOption(VERBOSE_OUTPUT_OPTION)); return; } if (doMerge) { // Get the output directory if (!line.hasOption("D")) { System.err.println("An output directory must be specified"); return; } File outputDir = new File(line.getOptionValue("D")); if (!outputDir.exists()) outputDir.mkdir(); if (!outputDir.isDirectory()) { System.err.println("Output option is not a directory: " + outputDir); return; } doMerge(assistant, line.getOptionValues("merge"), outputDir); return; } if (doImport) { // Get the output directory if (!line.hasOption("D")) { System.err.println("An output directory must be specified"); return; } File outputDir = new File(line.getOptionValue("D")); if (!outputDir.exists()) outputDir.mkdir(); if (!outputDir.isDirectory()) { System.err.println("Output option is not a directory: " + outputDir); return; } doImport(assistant, line.getOptionValue("import"), outputDir); return; } } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); } HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("assistant", getOptions()); return; }
From source file:br.bireme.tb.URLS.java
public static void main(final String[] args) throws IOException { if (args.length != 1) { usage();//from ww w .ja v a2 s . c o m } final String out = args[0].trim(); final String outDir = (out.endsWith("/")) ? out : out + "/"; final String LOG_DIR = "log"; final File logDir = new File(LOG_DIR); if (!logDir.exists()) { if (!logDir.mkdir()) { throw new IOException("log directory [" + LOG_DIR + "] creation error"); } } final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); final FileHandler fh = new FileHandler(getLogFileName(LOG_DIR), false); logger.addHandler(fh); final String URL = URLS.ROOT_URL; final TimeString time = new TimeString(); time.start(); generateFileStructure(URL, outDir + "celulasIDB"); System.out.println("Total time: " + time.getTime()); }
From source file:Logi.GSeries.Service.LogiGSKService.java
/** * @param args the command line arguments *///from w w w .j a v a 2 s . c o 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:act.installer.reachablesexplorer.FreemarkerRenderer.java
public static void main(String[] args) throws Exception { CLIUtil cliUtil = new CLIUtil(Loader.class, HELP_MESSAGE, OPTION_BUILDERS); CommandLine cl = cliUtil.parseCommandLine(args); File baseOutputDir = new File(cl.getOptionValue(OPTION_OUTPUT_DEST)); if (!baseOutputDir.exists()) { cliUtil.failWithMessage("Unable to find output directory at %s", baseOutputDir.getAbsolutePath()); return;//from w w w .java 2s . com } 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:fr.inria.edelweiss.kgimport.RdfSplitter.java
/** * The application entrypoint, configured through the command line input * arguments.// w w w.java2 s . co m * * @param args the input command line arguments. */ public static void main(String args[]) { RdfSplitter rdfSplitter = new RdfSplitter(); Options options = new Options(); Option helpOpt = new Option("h", "help", false, "Print usage information."); Option inDirOpt = new Option("i", "input-dir", true, "The directory containing RDF files to be loaded."); Option outDirOpt = new Option("o", "output-dir", true, "The directory containing the generated RDF fragments"); Option predFiltOpt = new Option("p", "predicate-filter", true, "Predicate filter used to segment the dataset. " + "You can use multiple filters, typically one per fragment."); Option fragNbOpt = new Option("n", "number-of-fragments", true, "Number of fragments generated for the whole input dataset."); Option fragRepOpt = new Option("f", "fractionning-percentage", true, "Percentage of the whole input dataset for this fragment."); Option tdbOpt = new Option("tdb", "tdb-storage", false, "RDF fragments are persisted into a Jena TDB backend."); Option versionOpt = new Option("v", "version", false, "Print the version information and exit."); options.addOption(inDirOpt); options.addOption(outDirOpt); options.addOption(predFiltOpt); options.addOption(helpOpt); options.addOption(versionOpt); options.addOption(fragNbOpt); options.addOption(fragRepOpt); options.addOption(tdbOpt); String header = "RDF data fragmentation tool command line interface"; String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr"; CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar [].jar", header, options, footer, true); System.exit(0); } if (!cmd.hasOption("i")) { logger.warn("You must specify a valid input directory !"); System.exit(-1); } else { rdfSplitter.setInputDirPath(cmd.getOptionValue("i")); } if (!cmd.hasOption("o")) { logger.warn("You must specify a valid output directory !"); System.exit(-1); } else { rdfSplitter.setOutputDirPath(cmd.getOptionValue("o")); } if (cmd.hasOption("p")) { rdfSplitter.setInputPredicates(new ArrayList<String>(Arrays.asList(cmd.getOptionValues("p")))); } if (cmd.hasOption("f")) { ArrayList<String> opts = new ArrayList<String>(Arrays.asList(cmd.getOptionValues("f"))); for (String opt : opts) { try { rdfSplitter.getFragList().add(Integer.parseInt(opt)); } catch (NumberFormatException e) { logger.error(opt + " cannot be pased as an percentage value."); System.exit(-1); } } } if (cmd.hasOption("n")) { try { rdfSplitter.setFragNb(Integer.parseInt(cmd.getOptionValue("n"))); } catch (NumberFormatException e) { logger.error(cmd.getOptionValue("n") + " cannot be pased as an integer value."); System.exit(-1); } } File oDir = new File(rdfSplitter.getOutputDirPath()); if (oDir.exists()) { logger.warn(rdfSplitter.getOutputDirPath() + " already exists !"); oDir = Files.createTempDir(); logger.warn(oDir.getAbsolutePath() + " created."); rdfSplitter.setOutputDirPath(oDir.getAbsolutePath()); } else { if (oDir.mkdir()) { logger.info(rdfSplitter.getOutputDirPath() + " created."); } } if (!cmd.hasOption("n") && !cmd.hasOption("f") && !cmd.hasOption("p")) { logger.error("You must specify just one fragmentation type through '-n', '-f', or 'p' options"); for (String arg : args) { logger.trace(arg); } System.exit(-1); } String fragName = rdfSplitter.getInputDirPath() .substring(rdfSplitter.getInputDirPath().lastIndexOf("/") + 1); //Input data loading Model model = ModelFactory.createDefaultModel(); File inputDir = new File(rdfSplitter.getInputDirPath()); if (inputDir.isDirectory()) { for (File f : inputDir.listFiles()) { logger.info("Loading " + f.getAbsolutePath()); if (f.isDirectory()) { String directory = f.getAbsolutePath(); Dataset dataset = TDBFactory.createDataset(directory); dataset.begin(ReadWrite.READ); // Get model inside the transaction model.add(dataset.getDefaultModel()); dataset.end(); } else { InputStream iS; try { iS = new FileInputStream(f); if (f.getAbsolutePath().endsWith(".n3")) { model.read(iS, null, "N3"); } else if (f.getAbsolutePath().endsWith(".nt")) { model.read(iS, null, "N-TRIPLES"); } else if (f.getAbsolutePath().endsWith(".rdf")) { model.read(iS, null); } } catch (FileNotFoundException ex) { LogManager.getLogger(RdfSplitter.class.getName()).log(Level.ERROR, "", ex); } } } logger.info("Loaded " + model.size() + " triples"); } else { System.exit(0); } StopWatch sw = new StopWatch(); if (cmd.hasOption("n")) { sw.start(); if (cmd.hasOption("tdb")) { rdfSplitter.saveFragmentsTDB(rdfSplitter.getFragHoriz(model, rdfSplitter.getFragNb()), "Homog-" + fragName); } else { rdfSplitter.saveFragmentsRDF(rdfSplitter.getFragHoriz(model, rdfSplitter.getFragNb()), "Homog-" + fragName); } logger.info("Homog horiz frag in " + sw.getTime() + "ms"); sw.reset(); } else if (cmd.hasOption("f")) { sw.start(); if (cmd.hasOption("tdb")) { rdfSplitter.saveFragmentsTDB(rdfSplitter.getFragHoriz(model, rdfSplitter.getFragList()), "Inhomog-" + fragName); } else { rdfSplitter.saveFragmentsRDF(rdfSplitter.getFragHoriz(model, rdfSplitter.getFragList()), "Inhomog-" + fragName); } logger.info("Inhomog horiz frag in " + sw.getTime() + "ms"); sw.reset(); } else if (cmd.hasOption("p")) { sw.start(); if (cmd.hasOption("tdb")) { rdfSplitter.saveFragmentsTDB(rdfSplitter.getFragVert(model, rdfSplitter.getInputPredicates())); } else { rdfSplitter.saveFragmentsRDF(rdfSplitter.getFragVert(model, rdfSplitter.getInputPredicates())); } logger.info("Vert frag in " + sw.getTime() + "ms"); sw.reset(); } } catch (ParseException ex) { logger.error("Impossible to parse the input command line " + cmd.toString()); } }
From source file:ms1quant.MS1Quant.java
/** * @param args the command line arguments MS1Quant parameterfile *///w ww .ja v a 2s. c om 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:de.prozesskraft.pkraft.Perlcode.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try//from w w w .j ava 2s . c o m // { // if (args.length != 3) // { // System.out.println("Please specify processdefinition file (xml) and an outputfilename"); // } // // } // catch (ArrayIndexOutOfBoundsException e) // { // System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString()); // } /*---------------------------- get options from ini-file ----------------------------*/ File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Perlcode.class) + "/" + "../etc/pkraft-perlcode.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 ostep = OptionBuilder.withArgName("STEPNAME").hasArg().withDescription( "[optional] stepname of step to generate a script for. if this parameter is omitted, a script for the process will be generated.") // .isRequired() .create("step"); Option ooutput = OptionBuilder.withArgName("DIR").hasArg() .withDescription("[mandatory] directory for generated files. must not exist when calling.") // .isRequired() .create("output"); Option odefinition = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory] process definition file.") // .isRequired() .create("definition"); Option onolist = OptionBuilder.withArgName("") // .hasArg() .withDescription( "[optional] with this parameter the multiple use of multi-optionis is forced. otherwise it is possible to use an integrated comma-separeated list.") // .isRequired() .create("nolist"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(ostep); options.addOption(ooutput); options.addOption(odefinition); options.addOption(onolist); /*---------------------------- 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("perlcode", options); System.exit(0); } else if (commandline.hasOption("v")) { System.out.println("web: www.prozesskraft.de"); System.out.println("version: [% version %]"); System.out.println("date: [% date %]"); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ if (!(commandline.hasOption("definition"))) { System.err.println("option -definition is mandatory."); exiter(); } if (!(commandline.hasOption("output"))) { System.err.println("option -output is mandatory."); exiter(); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ Process p1 = new Process(); java.io.File outputDir = new java.io.File(commandline.getOptionValue("output")); java.io.File outputDirProcessScript = new java.io.File(commandline.getOptionValue("output")); java.io.File outputDirBin = new java.io.File(commandline.getOptionValue("output") + "/bin"); java.io.File outputDirLib = new java.io.File(commandline.getOptionValue("output") + "/lib"); boolean nolist = false; if (commandline.hasOption("nolist")) { nolist = true; } if (outputDir.exists()) { System.err.println("fatal: directory already exists: " + outputDir.getCanonicalPath()); exiter(); } else { outputDir.mkdir(); } p1.setInfilexml(commandline.getOptionValue("definition")); System.err.println("info: reading process definition " + commandline.getOptionValue("definition")); Process p2 = null; try { p2 = p1.readXml(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); System.err.println("error"); exiter(); } // perlcode generieren fuer einen bestimmten step if (commandline.hasOption("step")) { outputDirBin.mkdir(); String stepname = commandline.getOptionValue("step"); writeStepAsPerlcode(p2, stepname, outputDirBin, nolist); } // perlcode generieren fuer den gesamten process else { outputDirBin.mkdir(); writeProcessAsPerlcode(p2, outputDirProcessScript, outputDirBin, nolist); // copy all perllibs from the lib directory outputDirLib.mkdir(); final Path source = Paths.get(WhereAmI.getInstallDirectoryAbsolutePath(Perlcode.class) + "/../perllib"); final Path target = Paths.get(outputDirLib.toURI()); copyDirectoryTree.copyDirectoryTree(source, target); } }
From source file:ch.kostceco.tools.kostsimy.KOSTSimy.java
/** Die Eingabe besteht aus 2 Parameter: [0] Original-Ordner [1] Replica-Ordner * /*from www .ja v a 2 s. c o m*/ * @param args * @throws IOException */ public static void main(String[] args) throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:config/applicationContext.xml"); // Zeitstempel Start java.util.Date nowStart = new java.util.Date(); java.text.SimpleDateFormat sdfStart = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); String ausgabeStart = sdfStart.format(nowStart); KOSTSimy kostsimy = (KOSTSimy) context.getBean("kostsimy"); File configFile = new File("configuration" + File.separator + "kostsimy.conf.xml"); // Ueberprfung des Parameters (Log-Verzeichnis) String pathToLogfile = kostsimy.getConfigurationService().getPathToLogfile(); File directoryOfLogfile = new File(pathToLogfile); if (!directoryOfLogfile.exists()) { directoryOfLogfile.mkdir(); } // Im Logverzeichnis besteht kein Schreibrecht if (!directoryOfLogfile.canWrite()) { System.out.println( kostsimy.getTextResourceService().getText(ERROR_LOGDIRECTORY_NOTWRITABLE, directoryOfLogfile)); System.exit(1); } if (!directoryOfLogfile.isDirectory()) { System.out.println(kostsimy.getTextResourceService().getText(ERROR_LOGDIRECTORY_NODIRECTORY)); System.exit(1); } // Ist die Anzahl Parameter (2) korrekt? if (args.length > 3) { System.out.println(kostsimy.getTextResourceService().getText(ERROR_PARAMETER_USAGE)); System.exit(1); } File origDir = new File(args[0]); File repDir = new File(args[1]); File logDatei = null; logDatei = origDir; // Informationen zum Arbeitsverzeichnis holen String pathToWorkDir = kostsimy.getConfigurationService().getPathToWorkDir(); /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim * entsprechenden Modul die property anzugeben: <property name="configurationService" * ref="configurationService" /> */ // Konfiguration des Loggings, ein File Logger wird zustzlich erstellt LogConfigurator logConfigurator = (LogConfigurator) context.getBean("logconfigurator"); String logFileName = logConfigurator.configure(directoryOfLogfile.getAbsolutePath(), logDatei.getName()); File logFile = new File(logFileName); // Ab hier kann ins log geschrieben werden... LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_HEADER)); LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_START, ausgabeStart)); LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_END)); LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_INFO)); System.out.println("KOST-Simy"); System.out.println(""); if (!origDir.exists()) { // Das Original-Verzeichnis existiert nicht LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE, kostsimy.getTextResourceService().getText(ERROR_NOORIGDIR, origDir.getAbsolutePath()))); System.out .println(kostsimy.getTextResourceService().getText(ERROR_NOORIGDIR, origDir.getAbsolutePath())); System.exit(1); } if (!repDir.exists()) { // Das Replica-Verzeichnis existiert nicht LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE, kostsimy.getTextResourceService().getText(ERROR_NOREPDIR1, repDir.getAbsolutePath()))); System.out .println(kostsimy.getTextResourceService().getText(ERROR_NOREPDIR1, repDir.getAbsolutePath())); System.exit(1); } File xslOrig = new File("resources" + File.separator + "kost-simy.xsl"); File xslCopy = new File(directoryOfLogfile.getAbsolutePath() + File.separator + "kost-simy.xsl"); if (!xslCopy.exists()) { Util.copyFile(xslOrig, xslCopy); } // Informationen zur prozentualen Stichprobe holen String randomTest = kostsimy.getConfigurationService().getRandomTest(); /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim * entsprechenden Modul die property anzugeben: <property name="configurationService" * ref="configurationService" /> */ int iRandomTest = 100; try { iRandomTest = Integer.parseInt(randomTest); } catch (Exception ex) { // unzulaessige Eingabe --> 50 wird gesetzt iRandomTest = 50; } if (iRandomTest > 100 || iRandomTest < 1) { // unzulaessige Eingabe --> 50 wird gesetzt iRandomTest = 50; } File tmpDir = new File(pathToWorkDir); /* bestehendes Workverzeichnis Abbruch wenn nicht leer, da am Schluss das Workverzeichnis * gelscht wird und entsprechend bestehende Dateien gelscht werden knnen */ if (tmpDir.exists()) { if (tmpDir.isDirectory()) { // Get list of file in the directory. When its length is not zero the folder is not empty. String[] files = tmpDir.list(); if (files.length > 0) { LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE, kostsimy.getTextResourceService().getText(ERROR_WORKDIRECTORY_EXISTS, pathToWorkDir))); System.out.println( kostsimy.getTextResourceService().getText(ERROR_WORKDIRECTORY_EXISTS, pathToWorkDir)); System.exit(1); } } } // Im Pfad keine Sonderzeichen Programme knnen evtl abstrzen String patternStr = "[^!#\\$%\\(\\)\\+,\\-_\\.=@\\[\\]\\{\\}\\~:\\\\a-zA-Z0-9 ]"; Pattern pattern = Pattern.compile(patternStr); String name = tmpDir.getAbsolutePath(); String[] pathElements = name.split("/"); for (int i = 0; i < pathElements.length; i++) { String element = pathElements[i]; Matcher matcher = pattern.matcher(element); boolean matchFound = matcher.find(); if (matchFound) { LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE, kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name))); System.out.println(kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name)); System.exit(1); } } // die Anwendung muss mindestens unter Java 6 laufen String javaRuntimeVersion = System.getProperty("java.vm.version"); if (javaRuntimeVersion.compareTo("1.6.0") < 0) { LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE, kostsimy.getTextResourceService().getText(ERROR_WRONG_JRE))); System.out.println(kostsimy.getTextResourceService().getText(ERROR_WRONG_JRE)); System.exit(1); } // bestehendes Workverzeichnis wieder anlegen if (!tmpDir.exists()) { tmpDir.mkdir(); File origDirTmp = new File(tmpDir.getAbsolutePath() + File.separator + "orig"); File repDirTmp = new File(tmpDir.getAbsolutePath() + File.separator + "rep"); origDirTmp.mkdir(); repDirTmp.mkdir(); } // Im workverzeichnis besteht kein Schreibrecht if (!tmpDir.canWrite()) { LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE, kostsimy.getTextResourceService().getText(ERROR_WORKDIRECTORY_NOTWRITABLE, tmpDir))); System.out.println(kostsimy.getTextResourceService().getText(ERROR_WORKDIRECTORY_NOTWRITABLE, tmpDir)); System.exit(1); } // Im Pfad keine Sonderzeichen --> Absturzgefahr name = origDir.getAbsolutePath(); pathElements = name.split("/"); for (int i = 0; i < pathElements.length; i++) { String element = pathElements[i]; Matcher matcher = pattern.matcher(element); boolean matchFound = matcher.find(); if (matchFound) { LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE, kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name))); System.out.println(kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name)); System.exit(1); } } name = repDir.getAbsolutePath(); pathElements = name.split("/"); for (int i = 0; i < pathElements.length; i++) { String element = pathElements[i]; Matcher matcher = pattern.matcher(element); boolean matchFound = matcher.find(); if (matchFound) { LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE, kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name))); System.out.println(kostsimy.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name)); System.exit(1); } } LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_IMAGE1)); float count = 0; int countNio = 0; int countIo = 0; float countVal = 0; int countNotVal = 0; float percentage = (float) 0.0; if (!origDir.isDirectory()) { // TODO: Bildervergleich zweier Dateien --> erledigt --> nur Marker if (repDir.isDirectory()) { // Das Replica-ist ein Verzeichnis, aber Original eine Datei LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE, kostsimy.getTextResourceService().getText(ERROR_NOREPDIR2, repDir.getAbsolutePath()))); System.out.println( kostsimy.getTextResourceService().getText(ERROR_NOREPDIR2, repDir.getAbsolutePath())); System.exit(1); } boolean compFile = compFile(origDir, logFileName, directoryOfLogfile, repDir, tmpDir); float statIo = 0; int statNio = 0; float statUn = 0; if (compFile) { statIo = 100; } else { statNio = 100; } LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_IMAGE2)); LOGGER.logError( kostsimy.getTextResourceService().getText(MESSAGE_XML_STATISTICS, statIo, statNio, statUn)); LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_LOGEND)); // Zeitstempel End java.util.Date nowEnd = new java.util.Date(); java.text.SimpleDateFormat sdfEnd = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); String ausgabeEnd = sdfEnd.format(nowEnd); ausgabeEnd = "<End>" + ausgabeEnd + "</End>"; Util.valEnd(ausgabeEnd, logFile); Util.amp(logFile); // Die Konfiguration hereinkopieren try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setExpandEntityReferences(false); Document docConfig = factory.newDocumentBuilder().parse(configFile); NodeList list = docConfig.getElementsByTagName("configuration"); Element element = (Element) list.item(0); Document docLog = factory.newDocumentBuilder().parse(logFile); Node dup = docLog.importNode(element, true); docLog.getDocumentElement().appendChild(dup); FileWriter writer = new FileWriter(logFile); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ElementToStream(docLog.getDocumentElement(), baos); String stringDoc2 = new String(baos.toByteArray()); writer.write(stringDoc2); writer.close(); // Der Header wird dabei leider verschossen, wieder zurck ndern String newstring = kostsimy.getTextResourceService().getText(MESSAGE_XML_HEADER); String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTSimyLog>"; Util.oldnewstring(oldstring, newstring, logFile); } catch (Exception e) { LOGGER.logError( "<Error>" + kostsimy.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); System.out.println("Exception: " + e.getMessage()); } if (compFile) { // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } // Validierte Datei valide System.exit(0); } else { // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } // Fehler in Validierte Datei --> invalide System.exit(2); } } else { // TODO: Bildervergleich zweier Verzeichnisse --> in Arbeit --> nur Marker if (!repDir.isDirectory()) { // Das Replica-ist eine Datei, aber Original ein Ordner LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_IOE, kostsimy.getTextResourceService().getText(ERROR_NOREPDIR3, repDir.getAbsolutePath()))); System.out.println( kostsimy.getTextResourceService().getText(ERROR_NOREPDIR3, repDir.getAbsolutePath())); System.exit(1); } Map<String, File> fileMap = Util.getFileMap(origDir, false); Set<String> fileMapKeys = fileMap.keySet(); boolean other = false; for (Iterator<String> iterator = fileMapKeys.iterator(); iterator.hasNext();) { String entryName = iterator.next(); File newFile = fileMap.get(entryName); if (!newFile.isDirectory()) { origDir = newFile; count = count + 1; if ((origDir.getAbsolutePath().toLowerCase().endsWith(".pdf") || origDir.getAbsolutePath().toLowerCase().endsWith(".pdfa") || origDir.getAbsolutePath().toLowerCase().endsWith(".tif") || origDir.getAbsolutePath().toLowerCase().endsWith(".tiff") || origDir.getAbsolutePath().toLowerCase().endsWith(".jpeg") || origDir.getAbsolutePath().toLowerCase().endsWith(".jpg") || origDir.getAbsolutePath().toLowerCase().endsWith(".jpe") || origDir.getAbsolutePath().toLowerCase().endsWith(".jp2") || origDir.getAbsolutePath().toLowerCase().endsWith(".gif") || origDir.getAbsolutePath().toLowerCase().endsWith(".png") || origDir.getAbsolutePath().toLowerCase().endsWith(".bmp"))) { percentage = 100 / count * countVal; if (percentage < iRandomTest) { // if ( 100 / count * (countVal + 1) <= iRandomTest ) { countVal = countVal + 1; String origWithOutExt = FilenameUtils.removeExtension(origDir.getName()); File repFile = new File( repDir.getAbsolutePath() + File.separator + origWithOutExt + ".pdf"); if (!repFile.exists()) { repFile = new File( repDir.getAbsolutePath() + File.separator + origWithOutExt + ".pdfa"); if (!repFile.exists()) { repFile = new File( repDir.getAbsolutePath() + File.separator + origWithOutExt + ".tif"); if (!repFile.exists()) { repFile = new File(repDir.getAbsolutePath() + File.separator + origWithOutExt + ".tiff"); if (!repFile.exists()) { repFile = new File(repDir.getAbsolutePath() + File.separator + origWithOutExt + ".jpeg"); if (!repFile.exists()) { repFile = new File(repDir.getAbsolutePath() + File.separator + origWithOutExt + ".jpg"); if (!repFile.exists()) { repFile = new File(repDir.getAbsolutePath() + File.separator + origWithOutExt + ".jpe"); if (!repFile.exists()) { repFile = new File(repDir.getAbsolutePath() + File.separator + origWithOutExt + ".jp2"); if (!repFile.exists()) { repFile = new File(repDir.getAbsolutePath() + File.separator + origWithOutExt + ".gif"); if (!repFile.exists()) { repFile = new File(repDir.getAbsolutePath() + File.separator + origWithOutExt + ".png"); if (!repFile.exists()) { repFile = new File(repDir.getAbsolutePath() + File.separator + origWithOutExt + ".bmp"); if (!repFile.exists()) { other = true; LOGGER.logError(kostsimy .getTextResourceService() .getText(MESSAGE_XML_VALERGEBNIS)); LOGGER.logError(kostsimy .getTextResourceService() .getText(MESSAGE_XML_COMPFILE, origDir)); LOGGER.logError(kostsimy .getTextResourceService().getText( MESSAGE_XML_VALERGEBNIS_NOTVALIDATED)); LOGGER.logError( kostsimy.getTextResourceService() .getText(ERROR_NOREP, origDir.getName())); LOGGER.logError(kostsimy .getTextResourceService().getText( MESSAGE_XML_VALERGEBNIS_CLOSE)); } } } } } } } } } } } if (!other) { boolean compFile = compFile(origDir, logFileName, directoryOfLogfile, repFile, tmpDir); if (compFile) { // Vergleich bestanden countIo = countIo + 1; } else { // Vergleich nicht bestanden countNio = countNio + 1; } } } else { countNotVal = countNotVal + 1; LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS)); LOGGER.logError( kostsimy.getTextResourceService().getText(MESSAGE_XML_COMPFILE, origDir)); LOGGER.logError(kostsimy.getTextResourceService() .getText(MESSAGE_XML_VALERGEBNIS_NOTVALIDATED)); LOGGER.logError( kostsimy.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE)); } } else { countNotVal = countNotVal + 1; LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS)); LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_COMPFILE, origDir)); LOGGER.logError( kostsimy.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_NOTVALIDATED)); LOGGER.logError( kostsimy.getTextResourceService().getText(ERROR_INCORRECTFILEENDING, origDir)); LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE)); } } } if (countNio == 0 && countIo == 0) { // keine Dateien verglichen LOGGER.logError(kostsimy.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS)); System.out.println(kostsimy.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS)); } float statIo = 100 / (float) count * (float) countIo; float statNio = 100 / (float) count * (float) countNio; float statUn = 100 - statIo - statNio; LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_IMAGE2)); LOGGER.logError( kostsimy.getTextResourceService().getText(MESSAGE_XML_STATISTICS, statIo, statNio, statUn)); LOGGER.logError(kostsimy.getTextResourceService().getText(MESSAGE_XML_LOGEND)); // Zeitstempel End java.util.Date nowEnd = new java.util.Date(); java.text.SimpleDateFormat sdfEnd = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); String ausgabeEnd = sdfEnd.format(nowEnd); ausgabeEnd = "<End>" + ausgabeEnd + "</End>"; Util.valEnd(ausgabeEnd, logFile); Util.amp(logFile); // Die Konfiguration hereinkopieren try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setExpandEntityReferences(false); Document docConfig = factory.newDocumentBuilder().parse(configFile); NodeList list = docConfig.getElementsByTagName("configuration"); Element element = (Element) list.item(0); Document docLog = factory.newDocumentBuilder().parse(logFile); Node dup = docLog.importNode(element, true); docLog.getDocumentElement().appendChild(dup); FileWriter writer = new FileWriter(logFile); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ElementToStream(docLog.getDocumentElement(), baos); String stringDoc2 = new String(baos.toByteArray()); writer.write(stringDoc2); writer.close(); // Der Header wird dabei leider verschossen, wieder zurck ndern String newstring = kostsimy.getTextResourceService().getText(MESSAGE_XML_HEADER); String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTSimyLog>"; Util.oldnewstring(oldstring, newstring, logFile); } catch (Exception e) { LOGGER.logError( "<Error>" + kostsimy.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); System.out.println("Exception: " + e.getMessage()); } if (countNio == 0 && countIo == 0) { // keine Dateien verglichen bestehendes Workverzeichnis ggf. lschen if (tmpDir.exists()) { Util.deleteDir(tmpDir); } System.exit(1); } else if (countNio == 0) { // bestehendes Workverzeichnis ggf. lschen if (tmpDir.exists()) { Util.deleteDir(tmpDir); } // alle Validierten Dateien valide System.exit(0); } else { // bestehendes Workverzeichnis ggf. lschen if (tmpDir.exists()) { Util.deleteDir(tmpDir); } // Fehler in Validierten Dateien --> invalide System.exit(2); } if (tmpDir.exists()) { Util.deleteDir(tmpDir); tmpDir.deleteOnExit(); } } }
From source file:com.clustercontrol.agent.Agent.java
/** * ?/*from w w w . j a va 2s. co 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); } }