List of usage examples for java.io File exists
public boolean exists()
From source file:ca.twoducks.vor.ossindex.report.Assistant.java
/** Main method. Very simple, does not perform sanity checks on input. * /*from w ww. j a va 2s . 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:ensai.RMQtestKmeans.java
public static void main(String[] args) throws Exception { //TODO javadoc : expliquer ce bloc metadata et pourquoi !file.exists Metadata metadata = new Metadata(); File file = new File(cheminConfiguration); if (!file.exists()) { metadata.readData();/*from ww w . j a v a 2 s . c om*/ } /** * Cration de la map qui contient la nombre de clusters pour le KMean et le seuil de dtection d'anomalies pour chaque capteurs. * @see Metadata */ Map<Integer, Tuple2<Integer, Double>> mapSensors_ClustersSeuils = new HashMap<Integer, Tuple2<Integer, Double>>(); mapSensors_ClustersSeuils = metadata.load(); /** * Cration de l'environnement de streaming de Flink * @see https://ci.apache.org/projects/flink/flink-docs-release-1.2/dev/api_concepts.html */ final StreamExecutionEnvironment environnementStream = StreamExecutionEnvironment.getExecutionEnvironment(); //TODO javadoc, expliquer demarche, expliquer localhost, port, guest, guest final RMQConnectionConfig connectionConfig = new RMQConnectionConfig.Builder().setHost("localhost") .setPort(5672).setUserName("guest").setPassword("guest").setVirtualHost("/").build(); //TODO Changer coucou dans tout le systme, et dans la javadoc en dessous, expliquer true et simple schema /** * Cration du datastream grce la source RabbitMQ * connectionConfig : Configuration de la connection de RabbitMQ * coucou : le nom de la queue RabbitMQ consommer * true : * @see StreamExecutionEnvironment.addSource() */ final DataStream<String> streamFromRabbitMQ = environnementStream .addSource(new RMQSource<String>(connectionConfig, "coucou", true, // use correlation ids; can be false if only at-least-once is required new SimpleStringSchema())); // deserialization schema to turn messages into Java objects /** * Application de la map LineSplitter * @see LineSplitter */ DataStream<Tuple3<String, String, String>> streamAfterSplit = streamFromRabbitMQ .flatMap(new LineSplitter1()).flatMap(new LineSplitter2()).flatMap(new LineSplitter3()) .flatMap(new LineSplitter4()).flatMap(new LineSplitter5()); /** * Application de la flatMap InputAnalyze * @see InputAnalyze */ DataStream<Tuple4<Integer, Integer, Float, String>> streamAfterAnalyze = streamAfterSplit .flatMap(new InputAnalyze(mapSensors_ClustersSeuils)); //streamAfterAnalyze.print(); /** * Application du keyBy pour sparer le stream selon la valeur du couple (field0, field1) de chaque tuple du stream * Mise en place d'une window glissante de taille countWindowSize. L'apparition de chaque nouveau input trigger la fonction apply. * @see https://ci.apache.org/projects/flink/flink-docs-release-1.2/dev/api_concepts.html * * Application de la fonction KMean * @see KMean */ DataStream<ArrayList<Tuple5<Integer, Integer, Float, String, Integer>>> streamAfterKMean = streamAfterAnalyze .keyBy(0, 1).countWindow(countWindowSize, 1).apply(new KMean(mapSensors_ClustersSeuils)); /** * Application de la map Markov * @see Markov */ DataStream<Tuple5<Integer, Integer, Float, String, Double>> streamAfterMarkov = streamAfterKMean .flatMap(new Markov(mapSensors_ClustersSeuils)); /** * Application du filter FilterAnomalies * @see FilterAnomalies */ DataStream<Tuple5<Integer, Integer, Float, String, Double>> streamAfterFilterAnomalies = streamAfterMarkov .filter(new FilterAnomalies(mapSensors_ClustersSeuils)); //TODO streamAfterFilterAnomalies.print(); /** * Application de la flatMap SortieTransformation * @see SortieTransformation */ DataStream<String> streamAfterSortieTransformation = streamAfterFilterAnomalies .flatMap(new SortieTransformation()); //TODO enlever ce print //streamAfterSortieTransformation.print(); /** * Cration de la sortie du stream dans RabbitMQ * connectionConfig : Configuration de la connection de RabbitMQ * voila : le nom de la queue RabbitMQ laquelle envoyer des messages * true : * @see StreamExecutionEnvironment.addSink() */ streamAfterSortieTransformation.addSink(new RMQSink<String>(connectionConfig, // config for the RabbitMQ connection "voila", // name of the RabbitMQ queue to send messages to new SimpleStringSchema())); /** * Excution de l'environnement de streaming * @see https://ci.apache.org/projects/flink/flink-docs-release-1.2/dev/api_concepts.html */ environnementStream.execute("DEBS 2017 ENSAI SOLUTION"); }
From source file:com.blackducksoftware.tools.vuln_collector.VCRunner.java
public static void main(String[] args) throws Exception { System.out.println(TITLE);/* w ww . j a v a 2 s . co m*/ CommandLineParser parser = new DefaultParser(); options.addOption("h", "help", false, "show help."); Option projectNameOption = new Option("projectName", true, "Name of Project (optional)"); projectNameOption.setRequired(false); options.addOption(projectNameOption); Option configFileOption = new Option("config", true, "Location of configuration file (required)"); configFileOption.setRequired(true); options.addOption(configFileOption); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) help(); String[] projectNameList = null; File configFile = null; if (cmd.hasOption(VCConstants.CL_PROJECT_NAME)) { String projectName = cmd.getOptionValue(VCConstants.CL_PROJECT_NAME); log.info("Project name: " + projectName); // Could be a single project or comma delim projectNameList = VCProcessor.getProjectList(projectName); } // Config File if (cmd.hasOption(VCConstants.CL_CONFIG)) { String configFilePath = cmd.getOptionValue(VCConstants.CL_CONFIG); log.info("Config file location: " + configFilePath); configFile = new File(configFilePath); if (!configFile.exists()) { log.error("Configuration file does not exist at location: " + configFile); System.exit(-1); } } else { log.error("Must specify configuration file!"); help(); } VCProcessor processor = new VCProcessor(configFile.toString(), projectNameList); processor.processReport(); } catch (ParseException e) { log.error("Error parsing: " + e.getMessage()); help(); } catch (Exception e) { log.error("General error: " + e.getMessage()); } }
From source file:br.bireme.tb.URLS.java
public static void main(final String[] args) throws IOException { if (args.length != 1) { usage();/*from w w w. j ava 2 s . com*/ } 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:de.tudarmstadt.ukp.dariah.pipeline.RunPipeline.java
public static void main(String[] args) { Date startDate = new Date(); PrintStream ps;/* w ww .j a va 2 s . c o m*/ try { ps = new PrintStream("error.log"); System.setErr(ps); } catch (FileNotFoundException e) { System.out.println("Errors cannot be redirected"); } try { if (!parseArgs(args)) { System.out.println("Usage: java -jar pipeline.jar -help"); System.out.println("Usage: java -jar pipeline.jar -input <Input File> -output <Output Folder>"); System.out.println( "Usage: java -jar pipeline.jar -config <Config File> -input <Input File> -output <Output Folder>"); return; } } catch (ParseException e) { e.printStackTrace(); System.out.println( "Error when parsing command line arguments. Use\njava -jar pipeline.jar -help\n to get further information"); System.out.println("See error.log for further details"); return; } LinkedList<String> configFiles = new LinkedList<>(); String configFolder = "configs/"; configFiles.add(configFolder + "default.properties"); //Language dependent properties file String path = configFolder + "default_" + optLanguage + ".properties"; File f = new File(path); if (f.exists()) { configFiles.add(path); } else { System.out.println("Language config file: " + path + " not found"); } String[] configFileArg = new String[0]; for (int i = 0; i < args.length - 1; i++) { if (args[i].equals("-config")) { configFileArg = args[i + 1].split("[,;]"); break; } } for (String configFile : configFileArg) { f = new File(configFile); if (f.exists()) { configFiles.add(configFile); } else { //Check in configs folder path = configFolder + configFile; f = new File(path); if (f.exists()) { configFiles.add(path); } else { System.out.println("Config file: " + configFile + " not found"); return; } } } for (String configFile : configFiles) { try { parseConfig(configFile); } catch (Exception e) { e.printStackTrace(); System.out.println("Exception when parsing config file: " + configFile); System.out.println("See error.log for further details"); } } printConfiguration(configFiles.toArray(new String[0])); try { // Read in the input files String defaultFileExtension = (optReader == ReaderType.XML) ? ".xml" : ".txt"; GlobalFileStorage.getInstance().readFilePaths(optInput, defaultFileExtension, optOutput, optResume); System.out.println("Process " + GlobalFileStorage.getInstance().size() + " files"); CollectionReaderDescription reader; if (optReader == ReaderType.XML) { reader = createReaderDescription(XmlReader.class, XmlReader.PARAM_LANGUAGE, optLanguage); } else { reader = createReaderDescription(TextReaderWithInfo.class, TextReaderWithInfo.PARAM_LANGUAGE, optLanguage); } AnalysisEngineDescription paragraph = createEngineDescription(ParagraphSplitter.class, ParagraphSplitter.PARAM_SPLIT_PATTERN, (optParagraphSingleLineBreak) ? ParagraphSplitter.SINGLE_LINE_BREAKS_PATTERN : ParagraphSplitter.DOUBLE_LINE_BREAKS_PATTERN); AnalysisEngineDescription seg = createEngineDescription(optSegmenterCls, optSegmenterArguments); AnalysisEngineDescription paragraphSentenceCorrector = createEngineDescription( ParagraphSentenceCorrector.class); AnalysisEngineDescription frenchQuotesSeg = createEngineDescription(PatternBasedTokenSegmenter.class, PatternBasedTokenSegmenter.PARAM_PATTERNS, "+|[]"); AnalysisEngineDescription quotesSeg = createEngineDescription(PatternBasedTokenSegmenter.class, PatternBasedTokenSegmenter.PARAM_PATTERNS, "+|[\"\"]"); AnalysisEngineDescription posTagger = createEngineDescription(optPOSTaggerCls, optPOSTaggerArguments); AnalysisEngineDescription lemma = createEngineDescription(optLemmatizerCls, optLemmatizerArguments); AnalysisEngineDescription chunker = createEngineDescription(optChunkerCls, optChunkerArguments); AnalysisEngineDescription morph = createEngineDescription(optMorphTaggerCls, optMorphTaggerArguments); AnalysisEngineDescription hyphenation = createEngineDescription(optHyphenationCls, optHyphenationArguments); AnalysisEngineDescription depParser = createEngineDescription(optDependencyParserCls, optDependencyParserArguments); AnalysisEngineDescription constituencyParser = createEngineDescription(optConstituencyParserCls, optConstituencyParserArguments); AnalysisEngineDescription ner = createEngineDescription(optNERCls, optNERArguments); AnalysisEngineDescription directSpeech = createEngineDescription(DirectSpeechAnnotator.class, DirectSpeechAnnotator.PARAM_START_QUOTE, optStartQuote); AnalysisEngineDescription srl = createEngineDescription(optSRLCls, optSRLArguments); //Requires DKPro 1.8.0 AnalysisEngineDescription coref = createEngineDescription(optCorefCls, optCorefArguments); //StanfordCoreferenceResolver.PARAM_POSTPROCESSING, true AnalysisEngineDescription writer = createEngineDescription(DARIAHWriter.class, DARIAHWriter.PARAM_TARGET_LOCATION, optOutput, DARIAHWriter.PARAM_OVERWRITE, true); AnalysisEngineDescription annWriter = createEngineDescription(AnnotationWriter.class); AnalysisEngineDescription noOp = createEngineDescription(NoOpAnnotator.class); System.out.println("\nStart running the pipeline (this may take a while)..."); while (!GlobalFileStorage.getInstance().isEmpty()) { try { SimplePipeline.runPipeline(reader, paragraph, (optSegmenter) ? seg : noOp, paragraphSentenceCorrector, frenchQuotesSeg, quotesSeg, (optPOSTagger) ? posTagger : noOp, (optLemmatizer) ? lemma : noOp, (optChunker) ? chunker : noOp, (optMorphTagger) ? morph : noOp, (optHyphenation) ? hyphenation : noOp, directSpeech, (optDependencyParser) ? depParser : noOp, (optConstituencyParser) ? constituencyParser : noOp, (optNER) ? ner : noOp, (optSRL) ? srl : noOp, //Requires DKPro 1.8.0 (optCoref) ? coref : noOp, writer // ,annWriter ); } catch (OutOfMemoryError e) { System.out.println("Out of Memory at file: " + GlobalFileStorage.getInstance().getLastPolledFile().getAbsolutePath()); } } Date enddate = new Date(); double duration = (enddate.getTime() - startDate.getTime()) / (1000 * 60.0); System.out.println("---- DONE -----"); System.out.printf("All files processed in %.2f minutes", duration); } catch (ResourceInitializationException e) { System.out.println("Error when initializing the pipeline."); if (e.getCause() instanceof FileNotFoundException) { System.out.println("File not found. Maybe the input / output path is incorrect?"); System.out.println(e.getCause().getMessage()); } e.printStackTrace(); System.out.println("See error.log for further details"); } catch (UIMAException e) { e.printStackTrace(); System.out.println("Error in the pipeline."); System.out.println("See error.log for further details"); } catch (IOException e) { e.printStackTrace(); System.out .println("Error while reading or writing to the file system. Maybe some paths are incorrect?"); System.out.println("See error.log for further details"); } }
From source file:com.milaboratory.mitcr.cli.Main.java
public static void main(String[] args) { int o = 0;/*from w w w .j ava2 s . c om*/ BuildInformation buildInformation = BuildInformationProvider.get(); final boolean isProduction = "default".equals(buildInformation.scmBranch); // buildInformation.version != null && buildInformation.version.lastIndexOf("SNAPSHOT") < 0; orderingMap.put(PARAMETERS_SET_OPTION, o++); orderingMap.put(SPECIES_OPTION, o++); orderingMap.put(GENE_OPTION, o++); orderingMap.put(ERROR_CORECTION_LEVEL_OPTION, o++); orderingMap.put(QUALITY_THRESHOLD_OPTION, o++); orderingMap.put(AVERAGE_QUALITY_OPTION, o++); orderingMap.put(LQ_OPTION, o++); orderingMap.put(CLUSTERIZATION_OPTION, o++); orderingMap.put(INCLUDE_CYS_PHE_OPTION, o++); orderingMap.put(LIMIT_OPTION, o++); orderingMap.put(EXPORT_OPTION, o++); orderingMap.put(REPORT_OPTION, o++); orderingMap.put(REPORTING_LEVEL_OPTION, o++); orderingMap.put(PHRED33_OPTION, o++); orderingMap.put(PHRED64_OPTION, o++); orderingMap.put(THREADS_OPTION, o++); orderingMap.put(COMPRESSED_OPTION, o++); orderingMap.put(PRINT_HELP_OPTION, o++); orderingMap.put(PRINT_VERSION_OPTION, o++); orderingMap.put(PRINT_DEBUG_OPTION, o++); options.addOption(OptionBuilder.withArgName("preset name").hasArg() .withDescription("preset of pipeline parameters to use").create(PARAMETERS_SET_OPTION)); options.addOption(OptionBuilder.withArgName("species").hasArg() .withDescription("overrides species ['hs' for Homo sapiens, 'mm' for us Mus musculus] " + "(default for built-in presets is 'hs')") .create(SPECIES_OPTION)); options.addOption(OptionBuilder.withArgName("gene").hasArg() .withDescription("overrides gene: TRB or TRA (default value for built-in parameter sets is TRB)") .create(GENE_OPTION)); options.addOption(OptionBuilder.withArgName("0|1|2").hasArg() .withDescription( "overrides error correction level (0 = don't correct errors, 1 = correct sequenecing " + "errors only (see -" + QUALITY_THRESHOLD_OPTION + " and -" + LQ_OPTION + " options for details), " + "2 = also correct PCR errors (see -" + CLUSTERIZATION_OPTION + " option)") .create(ERROR_CORECTION_LEVEL_OPTION)); options.addOption(OptionBuilder.withArgName("value").hasArg().withDescription( "overrides quality threshold value for segment alignment and bad quality sequences " + "correction algorithms. 0 tells the program not to process quality information. (default is 25)") .create(QUALITY_THRESHOLD_OPTION)); if (!isProduction) options.addOption(OptionBuilder.hasArg(false) .withDescription("use this option to output average instead of " + "maximal, quality for CDR3 nucleotide sequences. (Experimental option, use with caution.)") .create(AVERAGE_QUALITY_OPTION)); options.addOption(OptionBuilder.withArgName("map | drop").hasArg() .withDescription("overrides low quality CDR3s processing strategy (drop = filter off, " + "map = map onto clonotypes created from the high quality CDR3s). This option makes no difference if " + "quality threshold (-" + QUALITY_THRESHOLD_OPTION + " option) is set to 0, or error correction " + "level (-" + ERROR_CORECTION_LEVEL_OPTION + ") is 0.") .create(LQ_OPTION)); options.addOption(OptionBuilder.withArgName("smd | ete").hasArg() .withDescription("overrides the PCR error correction algorithm: smd = \"save my diversity\", " + "ete = \"eliminate these errors\". Default value for built-in parameters is ete.") .create(CLUSTERIZATION_OPTION)); options.addOption(OptionBuilder.withArgName("0|1").hasArg() .withDescription("overrides weather include bounding Cys & Phe into CDR3 sequence") .create(INCLUDE_CYS_PHE_OPTION)); options.addOption( OptionBuilder.withArgName("# of reads").hasArg() .withDescription("limits the number of input sequencing reads, use this parameter to " + "normalize several datasets or to have a glance at the data") .create(LIMIT_OPTION)); options.addOption(OptionBuilder.withArgName("new name").hasArg() .withDescription("use this option to export presets to a local xml files").create(EXPORT_OPTION)); options.addOption(OptionBuilder.withArgName("file name").hasArg() .withDescription("use this option to write analysis report (summary) to file") .create(REPORT_OPTION)); options.addOption(OptionBuilder.withArgName("1|2|3").hasArg(true) .withDescription("output detalization level (1 = simple, 2 = medium, 3 = full, this format " + "could be deserialized using mitcr API). Affects only tab-delimited output. Default value is 3.") .create(REPORTING_LEVEL_OPTION)); options.addOption(OptionBuilder.hasArg(false).withDescription( "add this option if input file is in old illumina format with 64 byte offset for quality " + "string (MiTCR will try to automatically detect file format if one of the \"-phredXX\" options is not provided)") .create(PHRED64_OPTION)); options.addOption(OptionBuilder.hasArg(false) .withDescription("add this option if input file is in Phred+33 format for quality values " + "(MiTCR will try to automatically detect file format if one of the \"-phredXX\" options is not provided)") .create(PHRED33_OPTION)); options.addOption(OptionBuilder.withArgName("threads").hasArg() .withDescription( "specifies the number of CDR3 extraction threads (default = number of available CPU cores)") .create(THREADS_OPTION)); if (!isProduction) options.addOption(OptionBuilder.hasArg(false) .withDescription("use compressed data structures for storing individual " + "clone segments statistics (from which arises the clone segment information). This option reduces required " + "amount of memory, but introduces small stochastic errors into the algorithm which determines clone " + "segments. (Experimental option, use with caution.)") .create(COMPRESSED_OPTION)); options.addOption( OptionBuilder.hasArg(false).withDescription("print this message").create(PRINT_HELP_OPTION)); options.addOption(OptionBuilder.hasArg(false).withDescription("print version information") .create(PRINT_VERSION_OPTION)); options.addOption(OptionBuilder.hasArg(false) .withDescription("print additional information about analysis process").create(PRINT_DEBUG_OPTION)); PosixParser parser = new PosixParser(); try { long input_limit = -1; int threads = Runtime.getRuntime().availableProcessors(); int reporting_level = 3; int ec_level = 2; CommandLine cl = parser.parse(options, args, true); if (cl.hasOption(PRINT_HELP_OPTION)) { printHelp(); return; } boolean averageQuality = cl.hasOption(AVERAGE_QUALITY_OPTION), compressedAggregators = cl.hasOption(COMPRESSED_OPTION); if (cl.hasOption(PRINT_VERSION_OPTION)) { System.out.println("MiTCR by MiLaboratory, version: " + buildInformation.version); System.out.println("Branch: " + buildInformation.scmBranch); System.out.println("Built: " + buildInformation.buildDate + ", " + buildInformation.jdk + " JDK, " + "build machine: " + buildInformation.builtBy); System.out.println("SCM changeset: " + buildInformation.scmChangeset + " (" + buildInformation.scmDate.replace("\"", "") + ")"); return; } //Normal execution String paramName = cl.getOptionValue(PARAMETERS_SET_OPTION); if (paramName == null) { err.println("No parameters set is specified."); return; } Parameters params = ParametersIO.getParameters(paramName); if (params == null) { err.println("No parameters set found with name '" + paramName + "'."); return; } String value; if ((value = cl.getOptionValue(THREADS_OPTION)) != null) threads = Integer.decode(value); if ((value = cl.getOptionValue(REPORTING_LEVEL_OPTION)) != null) reporting_level = Integer.decode(value); if ((value = cl.getOptionValue(LIMIT_OPTION)) != null) input_limit = Long.decode(value); if ((value = cl.getOptionValue(GENE_OPTION)) != null) params.setGene(Gene.fromXML(value)); if ((value = cl.getOptionValue(SPECIES_OPTION)) != null) params.setSpecies(Species.getFromShortName(value)); if ((value = cl.getOptionValue(INCLUDE_CYS_PHE_OPTION)) != null) { if (value.equals("1")) params.getCDR3ExtractorParameters().setIncludeCysPhe(true); else if (value.equals("0")) params.getCDR3ExtractorParameters().setIncludeCysPhe(false); else { err.println("Illegal value for -" + INCLUDE_CYS_PHE_OPTION + " parameter."); return; } } if ((value = cl.getOptionValue(ERROR_CORECTION_LEVEL_OPTION)) != null) { int v = Integer.decode(value); ec_level = v; if (v == 0) { params.setCloneGeneratorParameters(new BasicCloneGeneratorParameters()); params.setClusterizationType(CloneClusterizationType.None); } else if (v == 1) { params.setCloneGeneratorParameters(new LQMappingCloneGeneratorParameters()); params.setClusterizationType(CloneClusterizationType.None); } else if (v == 2) { params.setCloneGeneratorParameters(new LQMappingCloneGeneratorParameters()); params.setClusterizationType(CloneClusterizationType.OneMismatch, .1f); } else throw new RuntimeException("This (" + v + ") error correction level is not supported."); } if ((value = cl.getOptionValue(QUALITY_THRESHOLD_OPTION)) != null) { int v = Integer.decode(value); if (v == 0) params.setQualityInterpretationStrategy(new DummyQualityInterpretationStrategy()); else params.setQualityInterpretationStrategy(new IlluminaQualityInterpretationStrategy((byte) v)); } if ((value = cl.getOptionValue(LQ_OPTION)) != null) if (ec_level > 0) switch (value) { case "map": params.setCloneGeneratorParameters(new LQMappingCloneGeneratorParameters( ((BasicCloneGeneratorParameters) params.getCloneGeneratorParameters()) .getSegmentInformationAggregationFactor(), 3, true)); break; case "drop": params.setCloneGeneratorParameters(new LQFilteringOffCloneGeneratorParameters( ((BasicCloneGeneratorParameters) params.getCloneGeneratorParameters()) .getSegmentInformationAggregationFactor())); break; default: throw new RuntimeException("Wrong value for -" + LQ_OPTION + " option."); } if ((value = cl.getOptionValue(CLUSTERIZATION_OPTION)) != null) if (ec_level > 1) // == 2 switch (value) { case "smd": params.setClusterizationType(CloneClusterizationType.V2D1J2T3Explicit); break; case "ete": params.setClusterizationType(CloneClusterizationType.OneMismatch); break; default: throw new RuntimeException("Wrong value for -" + CLUSTERIZATION_OPTION + " option."); } ((BasicCloneGeneratorParameters) params.getCloneGeneratorParameters()) .setAccumulatorType(AccumulatorType.get(compressedAggregators, averageQuality)); if ((value = cl.getOptionValue(EXPORT_OPTION)) != null) { //Exporting parameters ParametersIO.exportParameters(params, value); return; } String[] offArgs = cl.getArgs(); if (offArgs.length == 0) { err.println("Input file not specified."); return; } else if (offArgs.length == 1) { err.println("Output file not specified."); return; } else if (offArgs.length > 2) { err.println("Unrecognized argument."); return; } String inputFileName = offArgs[0]; String outputFileName = offArgs[1]; File input = new File(inputFileName); if (!input.exists()) { err.println("Input file not found."); return; } //TODO This also done inside SFastqReader constructor CompressionType compressionType = CompressionType.None; if (inputFileName.endsWith(".gz")) compressionType = CompressionType.GZIP; QualityFormat format = null; // If variable remains null file format will be detected automatically if (cl.hasOption(PHRED33_OPTION)) format = QualityFormat.Phred33; if (cl.hasOption(PHRED64_OPTION)) if (format == null) format = QualityFormat.Phred64; else { err.println( "Options: -" + PHRED33_OPTION + " and -" + PHRED64_OPTION + " are mutually exclusive"); return; } SFastqReader reads = format == null ? new SFastqReader(input, compressionType) : new SFastqReader(input, format, compressionType); OutputPort<SSequencingRead> inputToPipeline = reads; if (input_limit >= 0) inputToPipeline = new CountLimitingOutputPort<>(inputToPipeline, input_limit); SegmentLibrary library = DefaultSegmentLibrary.load(); AnalysisStatisticsAggregator statisticsAggregator = new AnalysisStatisticsAggregator(); FullPipeline pipeline = new FullPipeline(inputToPipeline, params, false, library); pipeline.setThreads(threads); pipeline.setAnalysisListener(statisticsAggregator); new Thread(new SmartProgressReporter(pipeline, err)).start(); // Printing status to the standard error stream pipeline.run(); if (cl.hasOption(PRINT_DEBUG_OPTION)) { err.println("Memory = " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); err.println("Clusterization: " + pipeline.getQC().getReadsClusterized() + "% of reads, " + pipeline.getQC().getClonesClusterized() + " % clones"); } CloneSetClustered cloneSet = pipeline.getResult(); if ((value = cl.getOptionValue(REPORT_OPTION)) != null) { File file = new File(value); TablePrintStreamAdapter table; if (file.exists()) table = new TablePrintStreamAdapter(new FileOutputStream(file, true)); else { table = new TablePrintStreamAdapter(file); ReportExporter.printHeader(table); } //CloneSetQualityControl qc = new CloneSetQualityControl(library, params.getSpecies(), params.getGene(), cloneSet); ReportExporter.printRow(table, inputFileName, outputFileName, pipeline.getQC(), statisticsAggregator); table.close(); } if (outputFileName.endsWith(".cls")) ClsExporter.export(pipeline, outputFileName.replace(".cls", "") + " " + new Date().toString(), input.getName(), outputFileName); else { //Dry run if (outputFileName.startsWith("-")) return; ExportDetalizationLevel detalization = ExportDetalizationLevel.fromLevel(reporting_level); CompressionType compressionType1 = CompressionType.None; if (outputFileName.endsWith(".gz")) compressionType1 = CompressionType.GZIP; CloneSetIO.exportCloneSet(outputFileName, cloneSet, detalization, params, input.getAbsolutePath(), compressionType1); } } catch (ParseException | RuntimeException | IOException e) { err.println("Error occurred in the analysis pipeline."); err.println(); e.printStackTrace(); //printHelp(); } }
From source file:com.bericotech.clavin.index.IndexDirectoryBuilder.java
/** * Turns a GeoNames gazetteer file into a Lucene index, and adds * some supplementary gazetteer records at the end. * * @param args not used//from w w w . j av a2s . co m * @throws IOException */ public static void main(String[] args) throws IOException { Options options = getOptions(); CommandLine cmd = null; CommandLineParser parser = new GnuParser(); try { cmd = parser.parse(options, args); } catch (ParseException pe) { LOG.error(pe.getMessage()); printHelp(options); System.exit(-1); } if (cmd.hasOption(HELP_OPTION)) { printHelp(options); System.exit(0); } String indexPath = cmd.getOptionValue(INDEX_PATH_OPTION, DEFAULT_INDEX_DIRECTORY); String[] gazetteerPaths = cmd.getOptionValues(GAZETTEER_FILES_OPTION); if (gazetteerPaths == null || gazetteerPaths.length == 0) { gazetteerPaths = DEFAULT_GAZETTEER_FILES; } boolean replaceIndex = cmd.hasOption(REPLACE_INDEX_OPTION); boolean fullAncestry = cmd.hasOption(FULL_ANCESTRY_OPTION); File idir = new File(indexPath); // if the index directory exists, delete it if we are replacing, otherwise // exit gracefully if (idir.exists()) { if (replaceIndex) { LOG.info("Replacing index: {}", idir.getAbsolutePath()); FileUtils.deleteDirectory(idir); } else { LOG.info("{} exists. Remove the directory and try again.", idir.getAbsolutePath()); System.exit(-1); } } List<File> gazetteerFiles = new ArrayList<File>(); for (String gp : gazetteerPaths) { File gf = new File(gp); if (gf.isFile() && gf.canRead()) { gazetteerFiles.add(gf); } else { LOG.info("Unable to read Gazetteer file: {}", gf.getAbsolutePath()); } } if (gazetteerFiles.isEmpty()) { LOG.error("No Gazetteer files found."); System.exit(-1); } String altNamesPath = cmd.getOptionValue(ALTERNATE_NAMES_OPTION); File altNamesFile = altNamesPath != null ? new File(altNamesPath) : null; if (altNamesFile != null && !(altNamesFile.isFile() && altNamesFile.canRead())) { LOG.error("Unable to read alternate names file: {}", altNamesPath); System.exit(-1); } new IndexDirectoryBuilder(fullAncestry).buildIndex(idir, gazetteerFiles, altNamesFile); }
From source file:ms1quant.MS1Quant.java
/** * @param args the command line arguments MS1Quant parameterfile *//*from w ww. j a v a 2 s.c o m*/ public static void main(String[] args) throws Exception { BufferedReader reader = null; try { System.out.println( "================================================================================================="); System.out.println("Umpire MS1 quantification and feature detection analysis (version: " + UmpireInfo.GetInstance().Version + ")"); if (args.length < 3 || !args[1].startsWith("-mode")) { System.out .println("command : java -jar -Xmx10G MS1Quant.jar ms1quant.params -mode[1 or 2] [Option]"); System.out.println("\n-mode"); System.out.println("\t1:Single file mode--> mzXML_file PepXML_file"); System.out.println("\t\tEx: -mode1 file1.mzXML file1.pep.xml"); System.out.println( "\t2:Folder mode--> mzXML_Folder PepXML_Folder, all generated csv tables will be merged into a single csv file"); System.out.println("\t\tEx: -mode2 /data/mzxml/ /data/pepxml/"); System.out.println("\nOptions"); System.out.println( "\t-C\tNo of concurrent files to be processed (only for folder mode), Ex. -C5, default:1"); System.out.println("\t-p\tMinimum probability, Ex. -p0.9, default:0.9"); System.out.println("\t-ID\tDetect identified feature only"); System.out.println("\t-O\toutput folder, Ex. -O/data/"); return; } ConsoleLogger consoleLogger = new ConsoleLogger(); consoleLogger.SetConsoleLogger(Level.DEBUG); consoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "ms1quant_debug.log"); Logger logger = Logger.getRootLogger(); logger.debug("Command: " + Arrays.toString(args)); logger.info("MS1Quant version: " + UmpireInfo.GetInstance().Version); String parameterfile = args[0]; logger.info("Parameter file: " + parameterfile); File paramfile = new File(parameterfile); if (!paramfile.exists()) { logger.error("Parameter file " + paramfile.getAbsolutePath() + " cannot be found. The program will exit."); } reader = new BufferedReader(new FileReader(paramfile.getAbsolutePath())); String line = ""; InstrumentParameter param = new InstrumentParameter(InstrumentParameter.InstrumentType.TOF5600); int NoCPUs = 2; int NoFile = 1; param.DetermineBGByID = false; param.EstimateBG = true; //<editor-fold defaultstate="collapsed" desc="Read parameter file"> while ((line = reader.readLine()) != null) { if (!"".equals(line) && !line.startsWith("#")) { logger.info(line); //System.out.println(line); if (line.split("=").length < 2) { continue; } if (line.split("=").length < 2) { continue; } String type = line.split("=")[0].trim(); if (type.startsWith("para.")) { type = type.replace("para.", "SE."); } String value = line.split("=")[1].trim(); switch (type) { case "Thread": { NoCPUs = Integer.parseInt(value); break; } //<editor-fold defaultstate="collapsed" desc="instrument parameters"> case "SE.MS1PPM": { param.MS1PPM = Float.parseFloat(value); break; } case "SE.MS2PPM": { param.MS2PPM = Float.parseFloat(value); break; } case "SE.SN": { param.SNThreshold = Float.parseFloat(value); break; } case "SE.MS2SN": { param.MS2SNThreshold = Float.parseFloat(value); break; } case "SE.MinMSIntensity": { param.MinMSIntensity = Float.parseFloat(value); break; } case "SE.MinMSMSIntensity": { param.MinMSMSIntensity = Float.parseFloat(value); break; } case "SE.MinRTRange": { param.MinRTRange = Float.parseFloat(value); break; } case "SE.MaxNoPeakCluster": { param.MaxNoPeakCluster = Integer.parseInt(value); param.MaxMS2NoPeakCluster = Integer.parseInt(value); break; } case "SE.MinNoPeakCluster": { param.MinNoPeakCluster = Integer.parseInt(value); param.MinMS2NoPeakCluster = Integer.parseInt(value); break; } case "SE.MinMS2NoPeakCluster": { param.MinMS2NoPeakCluster = Integer.parseInt(value); break; } case "SE.MaxCurveRTRange": { param.MaxCurveRTRange = Float.parseFloat(value); break; } case "SE.Resolution": { param.Resolution = Integer.parseInt(value); break; } case "SE.RTtol": { param.RTtol = Float.parseFloat(value); break; } case "SE.NoPeakPerMin": { param.NoPeakPerMin = Integer.parseInt(value); break; } case "SE.StartCharge": { param.StartCharge = Integer.parseInt(value); break; } case "SE.EndCharge": { param.EndCharge = Integer.parseInt(value); break; } case "SE.MS2StartCharge": { param.MS2StartCharge = Integer.parseInt(value); break; } case "SE.MS2EndCharge": { param.MS2EndCharge = Integer.parseInt(value); break; } case "SE.NoMissedScan": { param.NoMissedScan = Integer.parseInt(value); break; } case "SE.Denoise": { param.Denoise = Boolean.valueOf(value); break; } case "SE.EstimateBG": { param.EstimateBG = Boolean.valueOf(value); break; } case "SE.RemoveGroupedPeaks": { param.RemoveGroupedPeaks = Boolean.valueOf(value); break; } case "SE.MinFrag": { param.MinFrag = Integer.parseInt(value); break; } case "SE.IsoPattern": { param.IsoPattern = Float.valueOf(value); break; } case "SE.StartRT": { param.startRT = Float.valueOf(value); } case "SE.EndRT": { param.endRT = Float.valueOf(value); } //</editor-fold> } } } //</editor-fold> int mode = 1; if (args[1].equals("-mode2")) { mode = 2; } else if (args[1].equals("-mode1")) { mode = 1; } else { logger.error("-mode number not recongized. The program will exit."); } String mzXML = ""; String pepXML = ""; String mzXMLPath = ""; String pepXMLPath = ""; File mzXMLfile = null; File pepXMLfile = null; File mzXMLfolder = null; File pepXMLfolder = null; int idx = 0; if (mode == 1) { mzXML = args[2]; logger.info("Mode1 mzXML file: " + mzXML); mzXMLfile = new File(mzXML); if (!mzXMLfile.exists()) { logger.error("Mode1 mzXML file " + mzXMLfile.getAbsolutePath() + " cannot be found. The program will exit."); return; } pepXML = args[3]; logger.info("Mode1 pepXML file: " + pepXML); pepXMLfile = new File(pepXML); if (!pepXMLfile.exists()) { logger.error("Mode1 pepXML file " + pepXMLfile.getAbsolutePath() + " cannot be found. The program will exit."); return; } idx = 4; } else if (mode == 2) { mzXMLPath = args[2]; logger.info("Mode2 mzXML folder: " + mzXMLPath); mzXMLfolder = new File(mzXMLPath); if (!mzXMLfolder.exists()) { logger.error("Mode2 mzXML folder " + mzXMLfolder.getAbsolutePath() + " does not exist. The program will exit."); return; } pepXMLPath = args[3]; logger.info("Mode2 pepXML folder: " + pepXMLPath); pepXMLfolder = new File(pepXMLPath); if (!pepXMLfolder.exists()) { logger.error("Mode2 pepXML folder " + pepXMLfolder.getAbsolutePath() + " does not exist. The program will exit."); return; } idx = 4; } String outputfolder = ""; float MinProb = 0f; for (int i = idx; i < args.length; i++) { if (args[i].startsWith("-")) { if (args[i].equals("-ID")) { param.TargetIDOnly = true; logger.info("Detect ID feature only: true"); } if (args[i].startsWith("-O")) { outputfolder = args[i].substring(2); logger.info("Output folder: " + outputfolder); File outputfile = new File(outputfolder); if (!outputfolder.endsWith("\\") | outputfolder.endsWith("/")) { outputfolder += "/"; } if (!outputfile.exists()) { outputfile.mkdir(); } } if (args[i].startsWith("-C")) { try { NoFile = Integer.parseInt(args[i].substring(2)); logger.info("No of concurrent files: " + NoFile); } catch (Exception ex) { logger.error(args[i] + " is not a correct integer format, will process only one file at a time."); } } if (args[i].startsWith("-p")) { try { MinProb = Float.parseFloat(args[i].substring(2)); logger.info("probability threshold: " + MinProb); } catch (Exception ex) { logger.error(args[i] + " is not a correct format, will use 0 as threshold instead."); } } } } reader.close(); TandemParam tandemparam = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600); PTMManager.GetInstance(); if (param.TargetIDOnly) { param.EstimateBG = false; param.ApexDelta = 1.5f; param.NoMissedScan = 10; param.MiniOverlapP = 0.2f; param.RemoveGroupedPeaks = false; param.CheckMonoIsotopicApex = false; param.DetectByCWT = false; param.FillGapByBK = false; param.IsoCorrThreshold = -1f; param.SmoothFactor = 3; } if (mode == 1) { logger.info("Processing " + mzXMLfile.getAbsolutePath() + "...."); long time = System.currentTimeMillis(); LCMSPeakMS1 LCMS1 = new LCMSPeakMS1(mzXMLfile.getAbsolutePath(), NoCPUs); LCMS1.SetParameter(param); LCMS1.Resume = false; if (!param.TargetIDOnly) { LCMS1.CreatePeakFolder(); } LCMS1.ExportPeakClusterTable = true; if (pepXMLfile.exists()) { tandemparam.InteractPepXMLPath = pepXMLfile.getAbsolutePath(); LCMS1.ParsePepXML(tandemparam, MinProb); logger.info("No. of PSMs included: " + LCMS1.IDsummary.PSMList.size()); logger.info("No. of Peptide ions included: " + LCMS1.IDsummary.GetPepIonList().size()); } if (param.TargetIDOnly) { LCMS1.SaveSerializationFile = false; } if (param.TargetIDOnly || !LCMS1.ReadPeakCluster()) { LCMS1.PeakClusterDetection(); } if (pepXMLfile.exists()) { LCMS1.AssignQuant(false); LCMS1.IDsummary.ExportPepID(outputfolder); } time = System.currentTimeMillis() - time; logger.info(LCMS1.ParentmzXMLName + " processed time:" + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time), TimeUnit.MILLISECONDS.toMinutes(time) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)), TimeUnit.MILLISECONDS.toSeconds(time) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)))); LCMS1.BaseClearAllPeaks(); LCMS1.SetSpectrumParser(null); LCMS1.IDsummary = null; LCMS1 = null; System.gc(); } else if (mode == 2) { LCMSID IDsummary = new LCMSID("", "", ""); logger.info("Parsing all pepXML files in " + pepXMLPath + "...."); for (File file : pepXMLfolder.listFiles()) { if (file.getName().toLowerCase().endsWith("pep.xml") || file.getName().toLowerCase().endsWith("pepxml")) { PepXMLParser pepXMLParser = new PepXMLParser(IDsummary, file.getAbsolutePath(), MinProb); } } HashMap<String, LCMSID> LCMSIDMap = IDsummary.GetLCMSIDFileMap(); ExecutorService executorPool = null; executorPool = Executors.newFixedThreadPool(NoFile); logger.info("Processing all mzXML files in " + mzXMLPath + "...."); for (File file : mzXMLfolder.listFiles()) { if (file.getName().toLowerCase().endsWith("mzxml")) { LCMSID id = LCMSIDMap.get(FilenameUtils.getBaseName(file.getName())); if (id == null || id.PSMList == null) { logger.warn("No IDs found in :" + FilenameUtils.getBaseName(file.getName()) + ". Quantification for this file is skipped"); continue; } if (!id.PSMList.isEmpty()) { MS1TargetQuantThread thread = new MS1TargetQuantThread(file, id, NoCPUs, outputfolder, param); executorPool.execute(thread); } } } LCMSIDMap.clear(); LCMSIDMap = null; IDsummary = null; executorPool.shutdown(); try { executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { logger.info("interrupted.."); } if (outputfolder == null | outputfolder.equals("")) { outputfolder = mzXMLPath; } logger.info("Merging PSM files.."); File output = new File(outputfolder); FileWriter writer = new FileWriter(output.getAbsolutePath() + "/PSM_merge.csv"); boolean header = false; for (File csvfile : output.listFiles()) { if (csvfile.getName().toLowerCase().endsWith("_psms.csv")) { BufferedReader outreader = new BufferedReader(new FileReader(csvfile)); String outline = outreader.readLine(); if (!header) { writer.write(outline + "\n"); header = true; } while ((outline = outreader.readLine()) != null) { writer.write(outline + "\n"); } outreader.close(); csvfile.delete(); } } writer.close(); } logger.info("MS1 quant module is complete."); } catch (Exception e) { Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e)); throw e; } }
From source file:de.prozesskraft.pkraft.PkraftPartUi1.java
/** * @param args//from w w w. j a va2 s . c o m */ public static void main(String[] args) { /*---------------------------- get options from ini-file ----------------------------*/ File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(PkraftPartUi1.class) + "/" + "../etc/pkraft-gui.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 help = new Option("help", "print this message"); Option v = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(help); options.addOption(v); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments line = parser.parse(options, args); } catch (Exception exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); } /*---------------------------- usage/help ----------------------------*/ if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); // formatter.printHelp("checkin --version [% version %]", options); formatter.printHelp("pkraft-gui", options); System.exit(0); } if (line.hasOption("v")) { System.err.println("author: [% email %]"); System.err.println("version: [% version %]"); System.err.println("date: [% date %]"); System.exit(0); } /*---------------------------- 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")); // muss final sein - wird sonst beim installieren mit maven angemeckert (nicht so aus eclipse heraus) final 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); } /*---------------------------- other things ----------------------------*/ // gui final Display display = new Display(); Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() { public void run() { try { // SPLASHSCREEN // final Image image = new Image(display, 300, 300); Image image = null; // set an image. die 2 versionen sind dazu da um von eclipse aus und in der installierten version zu funktionieren if (this.getClass().getResourceAsStream("/logo_beschnitten_transparent_small.png") != null) { image = new Image(display, this.getClass().getResourceAsStream("/logo_beschnitten_transparent_small.png")); } else if ((new java.io.File("logo_beschnitten_transparent_small.png")).exists()) { image = new Image(display, "logo_beschnitten_transparent_small.png"); } final Shell splash = new Shell(SWT.ON_TOP); splash.setLayout(new GridLayout(1, false)); splash.setSize(300, 300); splash.setBackground(new Color(display, 255, 255, 255)); // Weiss Label labelImage = new Label(splash, SWT.NONE); labelImage.setImage(image); // labelImage.setLayout(new GridLayout(1, false)); GridData gd_labelImage = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); gd_labelImage.widthHint = 300; gd_labelImage.minimumWidth = 300; // gd_labelImage.minimumHeight = 10; labelImage.setLayoutData(gd_labelImage); Label labelZeile1 = new Label(splash, SWT.NONE | SWT.BORDER | SWT.CENTER); String text = "version [% version %]"; text += "\nlicense status: " + lic.getLicense().getValidationStatus(); switch (lic.getLicense().getValidationStatus()) { case LICENSE_VALID: text += "\nlicensee: " + lic.getLicense().getLicenseText().getUserEMail(); text += "\nexpires in: " + lic.getLicense().getLicenseText().getLicenseExpireDaysRemaining(null) + " day(s)."; break; case LICENSE_INVALID: break; default: text += "\nno valid license found"; } text += "\nsupport: support@prozesskraft.de"; Button buttonOk = new Button(splash, SWT.NONE); GridData gd_buttonOk = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd_buttonOk.widthHint = 62; buttonOk.setLayoutData(gd_buttonOk); buttonOk.setText("Ok"); buttonOk.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { splash.close(); } }); labelZeile1.setText(text); // labelImage.setLayout(new GridLayout(1, false)); GridData gd_labelZeile1 = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); gd_labelZeile1.horizontalAlignment = SWT.CENTER; gd_labelZeile1.widthHint = 300; gd_labelZeile1.minimumWidth = 300; // gd_labelImage.minimumHeight = 10; labelZeile1.setLayoutData(gd_labelZeile1); splash.pack(); Rectangle splashRect = splash.getBounds(); Rectangle displayRect = display.getBounds(); int x = (displayRect.width - splashRect.width) / 2; int y = (displayRect.height - splashRect.height) / 2; splash.setLocation(x, y); splash.open(); // DAS HAUPTFENSTER Shell shell = new Shell(display); // shell.setSize(1200, 800); shell.setMaximized(true); shell.setText("pkraft " + "v[% version %]"); // set an icon. die 2 versionen sind dazu da um von eclipse aus und in der installierten version zu funktionieren if (this.getClass().getResourceAsStream("/logoSymbol50Transp.png") != null) { shell.setImage( new Image(display, this.getClass().getResourceAsStream("/logoSymbol50Transp.png"))); } else if ((new java.io.File("logoSymbol50Transp.png")).exists()) { shell.setImage(new Image(display, "logoSymbol50Transp.png")); } shell.setLayout(new FillLayout()); Composite composite = new Composite(shell, SWT.NO_FOCUS); GridLayout gl_composite = new GridLayout(2, false); gl_composite.marginWidth = 0; gl_composite.marginHeight = 0; new PkraftPartUi1(composite); try { shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } finally { if (!shell.isDisposed()) { shell.dispose(); } } } finally { display.dispose(); } } }); System.exit(0); }
From source file:act.installer.reachablesexplorer.Loader.java
public static void main(String[] args) throws IOException { CLIUtil cliUtil = new CLIUtil(Loader.class, HELP_MESSAGE, OPTION_BUILDERS); CommandLine cl = cliUtil.parseCommandLine(args); File reachablesDir = new File(cl.getOptionValue(OPTION_REACHABLES_SOURCE_DATA, DEFAULT_REACHABLES_PATH)); if (!(reachablesDir.exists() && reachablesDir.isDirectory())) { cliUtil.failWithMessage("Reachables directory at %s does not exist or is not a directory", reachablesDir.getAbsolutePath()); }//from www.j a v a2s. c o m Loader loader = new Loader(cl.getOptionValue(OPTION_DB_HOST, DEFAULT_HOST), Integer.parseInt(cl.getOptionValue(OPTION_DB_PORT, DEFAULT_PORT.toString())), cl.getOptionValue(OPTION_INSTALLER_SOURCE_DB, DEFAULT_CHEMICALS_DATABASE), cl.getOptionValue(OPTION_TARGET_DB, DEFAULT_TARGET_DATABASE), cl.getOptionValue(OPTION_TARGET_REACHABLES_COLLECTION), cl.getOptionValue(OPTION_TARGET_SEQUENCES_COLLECTION), cl.getOptionValue(OPTION_RENDERING_CACHE, DEFAULT_ASSETS_LOCATION)); loader.updateFromReachableDir(reachablesDir); if (cl.hasOption(OPTION_PROJECTIONS_SOURCE_DATA)) { File projectionFile = new File( cl.getOptionValue(OPTION_PROJECTIONS_SOURCE_DATA, DEFAULT_PROJECTIONS_PATH)); if (!projectionFile.exists() || projectionFile.isDirectory()) { cliUtil.failWithMessage("Projection file at %s does not exist or is a directory", projectionFile.getAbsolutePath()); } loader.updateFromProjectionFile(projectionFile); } if (cl.hasOption(OPTION_PROJECTED_INCHIS_SOURCE_DATA)) { File projectedInchisFile = new File(cl.getOptionValue(OPTION_PROJECTED_INCHIS_SOURCE_DATA)); if (!projectedInchisFile.exists() || projectedInchisFile.isDirectory()) { cliUtil.failWithMessage("InChI file at %s does not exist or is a directory", projectedInchisFile.getAbsolutePath()); } loader.updateFromProjectedInchiFile(projectedInchisFile); } }