List of usage examples for java.io File exists
public boolean exists()
From source file:scalespace.filter.Gaussian_Derivative_.java
public static void main(String[] args) { try {//from w w w. ja v a2s . c o m File f = new File(args[0]); if (f.exists() && f.isDirectory()) { System.setProperty("plugins.dir", args[0]); new ImageJ(); } else { throw new IllegalArgumentException(); } } catch (Exception ex) { IJ.log("plugins.dir misspecified\n"); ex.printStackTrace(); } }
From source file:io.anserini.index.IndexTweetsUpdatePlace.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option(HELP_OPTION, "show help")); options.addOption(new Option(OPTIMIZE_OPTION, "merge indexes into a single segment")); options.addOption(new Option(STORE_TERM_VECTORS_OPTION, "store term vectors")); options.addOption(OptionBuilder.withArgName("collection").hasArg() .withDescription("source collection directory").create(COLLECTION_OPTION)); options.addOption(/* ww w .j a va 2 s . co m*/ OptionBuilder.withArgName("dir").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("file with deleted tweetids") .create(DELETES_OPTION)); options.addOption(OptionBuilder.withArgName("id").hasArg().withDescription("max id").create(MAX_ID_OPTION)); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(COLLECTION_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(IndexTweetsUpdatePlace.class.getName(), options); System.exit(-1); } String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION); String indexPath = cmdline.getOptionValue(INDEX_OPTION); System.out.println(collectionPath + " " + indexPath); LOG.info("collection: " + collectionPath); LOG.info("index: " + indexPath); long startTime = System.currentTimeMillis(); File file = new File(collectionPath); if (!file.exists()) { System.err.println("Error: " + file + " does not exist!"); System.exit(-1); } final FieldType textOptions = new FieldType(); textOptions.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); textOptions.setStored(true); textOptions.setTokenized(true); if (cmdline.hasOption(STORE_TERM_VECTORS_OPTION)) { textOptions.setStoreTermVectors(true); } final StatusStream stream = new JsonStatusCorpusReader(file); final Directory dir = new SimpleFSDirectory(Paths.get(cmdline.getOptionValue(INDEX_OPTION))); final IndexWriterConfig config = new IndexWriterConfig(ANALYZER); config.setOpenMode(IndexWriterConfig.OpenMode.APPEND); final IndexWriter writer = new IndexWriter(dir, config); System.out.print("Original # of docs " + writer.numDocs()); int updateCount = 0; Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { stream.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { dir.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Shutting down"); } }); int cnt = 0; Status status; try { while ((status = stream.next()) != null) { if (status.getPlace() != null) { // Query q = NumericRangeQuery.newLongRange(TweetStreamReader.StatusField.ID.name, status.getId(), // status.getId(), true, true); // System.out.print("Deleting docCount="+writer.numDocs()); // writer.deleteDocuments(q); // writer.commit(); // System.out.print(" Deleted docCount="+writer.numDocs()); Document doc = new Document(); doc.add(new LongField(StatusField.ID.name, status.getId(), Field.Store.YES)); doc.add(new LongField(StatusField.EPOCH.name, status.getEpoch(), Field.Store.YES)); doc.add(new TextField(StatusField.SCREEN_NAME.name, status.getScreenname(), Store.YES)); doc.add(new Field(StatusField.TEXT.name, status.getText(), textOptions)); doc.add(new IntField(StatusField.FRIENDS_COUNT.name, status.getFollowersCount(), Store.YES)); doc.add(new IntField(StatusField.FOLLOWERS_COUNT.name, status.getFriendsCount(), Store.YES)); doc.add(new IntField(StatusField.STATUSES_COUNT.name, status.getStatusesCount(), Store.YES)); doc.add(new DoubleField(StatusField.LONGITUDE.name, status.getLongitude(), Store.YES)); doc.add(new DoubleField(StatusField.LATITUDE.name, status.getlatitude(), Store.YES)); doc.add(new StringField(StatusField.PLACE.name, status.getPlace(), Store.YES)); long inReplyToStatusId = status.getInReplyToStatusId(); if (inReplyToStatusId > 0) { doc.add(new LongField(StatusField.IN_REPLY_TO_STATUS_ID.name, inReplyToStatusId, Field.Store.YES)); doc.add(new LongField(StatusField.IN_REPLY_TO_USER_ID.name, status.getInReplyToUserId(), Field.Store.YES)); } String lang = status.getLang(); if (!lang.equals("unknown")) { doc.add(new TextField(StatusField.LANG.name, status.getLang(), Store.YES)); } long retweetStatusId = status.getRetweetedStatusId(); if (retweetStatusId > 0) { doc.add(new LongField(StatusField.RETWEETED_STATUS_ID.name, retweetStatusId, Field.Store.YES)); doc.add(new LongField(StatusField.RETWEETED_USER_ID.name, status.getRetweetedUserId(), Field.Store.YES)); doc.add(new IntField(StatusField.RETWEET_COUNT.name, status.getRetweetCount(), Store.YES)); if (status.getRetweetCount() < 0 || status.getRetweetedStatusId() < 0) { LOG.warn("Error parsing retweet fields of " + status.getId()); } } long id = status.getId(); BytesRefBuilder brb = new BytesRefBuilder(); NumericUtils.longToPrefixCodedBytes(id, 0, brb); Term term = new Term(StatusField.ID.name, brb.get()); writer.updateDocument(term, doc); // writer.addDocument(doc); updateCount += 1; if (updateCount % 10000 == 0) { LOG.info(updateCount + " statuses updated"); writer.commit(); System.out.println("Updated docCount=" + writer.numDocs()); } } } LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms"); } catch (Exception e) { e.printStackTrace(); } finally { writer.close(); dir.close(); stream.close(); } }
From source file:com.hs.mail.deliver.Deliver.java
public static void main(String[] args) { CommandLine cli = null;/*from w w w. j ava2s . c om*/ try { cli = new PosixParser().parse(OPTS, args); } catch (ParseException e) { usage(); System.exit(EX_USAGE); } // Configuration file path String config = cli.getOptionValue("c", DEFAULT_CONFIG_LOCATION); // Message file path File file = new File(cli.getOptionValue("p")); // Envelope sender address String from = cli.getOptionValue("f"); // Destination mailboxes String[] rcpts = cli.getOptionValues("r"); if (!file.exists()) { // Message file must exist logger.error("File not exist: " + file.getAbsolutePath()); System.exit(EX_TEMPFAIL); } if (from == null || rcpts == null) { // If sender or recipients address was not specified, get the // addresses from the message header. InputStream is = null; try { is = new FileInputStream(file); MessageHeader header = new MessageHeader(is); if (from == null && header.getFrom() != null) { from = header.getFrom().getAddress(); } if (rcpts == null) { rcpts = getRecipients(header); } } catch (IOException ex) { logger.error(ex.getMessage(), ex); System.exit(EX_TEMPFAIL); } finally { IOUtils.closeQuietly(is); } } if (from == null || ArrayUtils.isEmpty(rcpts)) { usage(); System.exit(EX_USAGE); } Deliver deliver = new Deliver(); deliver.init(config); // Spool the incoming message deliver.deliver(from, rcpts, file); System.exit(EX_OK); }
From source file:com.bluexml.tools.miscellaneous.PrepareSIDEModulesMigration.java
/** * @param args/*from w w w .j a v a 2 s . c o m*/ */ public static void main(String[] args) { boolean inplace = false; String workspace = "/Users/davidabad/workspaces/SIDE-Modules/"; String frameworkmodulesPath = "/Volumes/Data/SVN/side/HEAD/S-IDE/FrameworksModules/trunk/"; String classifier_base = "enterprise"; String version_base = "3.4.6"; String classifier_target = "enterprise"; String version_target = "3.4.11"; String frameworkmodulesInplace = "/Volumes/Data/SVN/projects/Ifremer/IfremerV5/src/modules/mavenProjects"; Properties props = new Properties(); try { InputStream resourceAsStream = PrepareSIDEModulesMigration.class .getResourceAsStream("config.properties"); if (resourceAsStream != null) { props.load(resourceAsStream); inplace = Boolean.parseBoolean(props.getProperty("inplace", Boolean.toString(inplace))); workspace = props.getProperty("workspace", workspace); frameworkmodulesPath = props.getProperty("frameworkmodulesPath", frameworkmodulesPath); classifier_base = props.getProperty("classifier_base", classifier_base); version_base = props.getProperty("version_base", version_base); classifier_target = props.getProperty("classifier_target", classifier_target); version_target = props.getProperty("version_target", version_target); frameworkmodulesInplace = props.getProperty("frameworkmodulesInplace", frameworkmodulesInplace); } else { System.out.println("no configuration founded in classpath config.properties"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } System.out.println("properties :"); Enumeration<?> propertyNames = props.propertyNames(); while (propertyNames.hasMoreElements()) { String nextElement = propertyNames.nextElement().toString(); System.out.println("\t " + nextElement + " : " + props.getProperty(nextElement)); } File workspaceFile = new File(workspace); File targetHome = new File(workspaceFile, MIGRATION_FOLDER); if (targetHome.exists()) { try { FileUtils.deleteDirectory(targetHome); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } } final String versionInProjectName = getVersionInProjectName(classifier_base, version_base); String versionInProjectName2 = getVersionInProjectName(classifier_target, version_target); if (frameworkmodulesPath.contains(",")) { // this is a list of paths String[] split = frameworkmodulesPath.split(","); for (String string : split) { if (StringUtils.trimToNull(string) != null) { executeInpath(inplace, string, classifier_base, version_base, classifier_target, version_target, frameworkmodulesInplace, workspaceFile, versionInProjectName, versionInProjectName2); } } } else { executeInpath(inplace, frameworkmodulesPath, classifier_base, version_base, classifier_target, version_target, frameworkmodulesInplace, workspaceFile, versionInProjectName, versionInProjectName2); } System.out.println("Job's done !"); System.out.println("Please check " + MIGRATION_FOLDER); System.out.println( "If all is ok you can use commit.sh in a terminal do : cd " + MIGRATION_FOLDER + "; sh commit.sh"); System.out.println( "This script will create new svn projet and commit resources, add 'target' to svn:ignore ..."); }
From source file:io.fabric8.apiman.ApimanStarter.java
/** * Main entry point for the API Manager micro service. * @param args the arguments/*from w w w. j a v a2 s . co m*/ * @throws Exception when any unhandled exception occurs */ public static final void main(String[] args) throws Exception { Fabric8ManagerApiMicroService microService = new Fabric8ManagerApiMicroService(); boolean isTestMode = getSystemPropertyOrEnvVar(APIMAN_TESTMODE, false); if (isTestMode) log.info("Apiman running in TestMode"); boolean isSsl = getSystemPropertyOrEnvVar(APIMAN_SSL, false); log.info("Apiman running in SSL: " + isSsl); String protocol = "http"; if (isSsl) protocol = "https"; File apimanConfigFile = new File(APIMAN_PROPERTIES); String esUsername = null; String esPassword = null; if (apimanConfigFile.exists()) { PropertiesConfiguration config = new PropertiesConfiguration(apimanConfigFile); esUsername = config.getString("es.username"); esPassword = config.getString("es.password"); if (Utils.isNotNullOrEmpty(esPassword)) esPassword = new String(Base64.getDecoder().decode(esPassword), StandardCharsets.UTF_8).trim(); setConfigProp(APIMAN_ELASTICSEARCH_USERNAME, esUsername); setConfigProp(APIMAN_ELASTICSEARCH_PASSWORD, esPassword); } URL elasticEndpoint = null; // Require ElasticSearch and the Gateway Services to to be up before proceeding if (isTestMode) { URL url = new URL("https://localhost:9200"); elasticEndpoint = waitForDependency(url, "", "elasticsearch-v1", "status", "200", esUsername, esPassword); } else { String defaultEsUrl = protocol + "://elasticsearch-v1:9200"; String esURL = getSystemPropertyOrEnvVar(APIMAN_ELASTICSEARCH_URL, defaultEsUrl); URL url = new URL(esURL); elasticEndpoint = waitForDependency(url, "", "elasticsearch-v1", "status", "200", esUsername, esPassword); log.info("Found " + elasticEndpoint); String defaultGatewayUrl = protocol + "://apiman-gateway:7777"; gatewayUrl = getSystemPropertyOrEnvVar(APIMAN_GATEWAY_URL, defaultGatewayUrl); URL gatewayEndpoint = waitForDependency(new URL(gatewayUrl), "/api/system/status", "apiman-gateway", "up", "true", null, null); log.info("Found " + gatewayEndpoint); } setConfigProp("apiman.plugins.repositories", "http://repo1.maven.org/maven2/"); setConfigProp("apiman-manager.plugins.registries", "http://cdn.rawgit.com/apiman/apiman-plugin-registry/1.2.6.Final/registry.json"); setFabric8Props(elasticEndpoint); if (isSsl) { microService.startSsl(); microService.joinSsl(); } else { microService.start(); microService.join(); } }
From source file:com.act.analysis.similarity.SubstructureSearch.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());//from www .j a v a 2 s . c o m } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } if (cl.hasOption(OPTION_LICENSE_FILE)) { LicenseManager.setLicenseFile(cl.getOptionValue(OPTION_LICENSE_FILE)); } List<String> searchOpts = Collections.emptyList(); if (cl.hasOption(OPTION_SEARCH_OPTIONS)) { searchOpts = Arrays.asList(cl.getOptionValues(OPTION_SEARCH_OPTIONS)); } // Make sure we can initialize correctly before opening any file handles for writing. SubstructureSearch matcher = new SubstructureSearch(); try { matcher.init(cl.getOptionValue(OPTION_QUERY), searchOpts); } catch (IllegalArgumentException e) { System.err.format("Unable to initialize substructure search. %s\n", e.getMessage()); HELP_FORMATTER.printHelp(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } catch (MolFormatException e) { System.err.format("Invalid SMILES structure query. %s\n", e.getMessage()); HELP_FORMATTER.printHelp(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } Pair<List<String>, Iterator<Map<String, String>>> iterPair = null; if (cl.hasOption(OPTION_INPUT_FILE)) { File inFile = new File(cl.getOptionValue(OPTION_INPUT_FILE)); if (!inFile.exists()) { System.err.format("File at %s does not exist", inFile.getAbsolutePath()); HELP_FORMATTER.printHelp(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } iterPair = iterateOverTSV(inFile); } else if (cl.hasOption(OPTION_INPUT_DB)) { iterPair = iterateOverDB(cl.getOptionValue(OPTION_INPUT_DB_HOST, DEFAULT_HOST), Integer.parseInt(cl.getOptionValue(OPTION_INPUT_DB_HOST, DEFAULT_PORT)), cl.getOptionValue(OPTION_INPUT_DB)); } else { System.err.format("Must specify either input TSV file or input DB from which to read.\n"); HELP_FORMATTER.printHelp(SubstructureSearch.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } TSVWriter<String, String> writer = new TSVWriter<>(iterPair.getLeft()); writer.open(new File(cl.getOptionValue(OPTION_OUTPUT_FILE))); LOGGER.info("Seaching for substructure '%s'", cl.getOptionValue(OPTION_QUERY)); try { int rowNum = 0; while (iterPair.getRight().hasNext()) { Map<String, String> row = iterPair.getRight().next(); rowNum++; try { String inchi = row.get(FIELD_INCHI); Molecule target = null; try { target = MolImporter.importMol(inchi); } catch (Exception e) { LOGGER.warn("Skipping molecule %d due to exception: %s\n", rowNum, e.getMessage()); continue; } if (matcher.matchSubstructure(target)) { writer.append(row); writer.flush(); } else { // Don't output if not a match. LOGGER.debug("Found non-matching molecule: %s", inchi); } } catch (SearchException e) { LOGGER.error("Exception on input line %d: %s\n", rowNum, e.getMessage()); throw e; } } } finally { writer.close(); } LOGGER.info("Done with substructure search"); }
From source file:raymond.mockftpserver.S3CachedFtpServer.java
public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); String identityPath = (String) ctx.getBean("identityPath"); String charset = (String) ctx.getBean("charset"); String keyBase = (String) ctx.getBean("keyBase"); // String host = (String) ctx.getBean("s3Host"); String bucket = (String) ctx.getBean("s3Bucket"); String chave = (String) ctx.getBean("chave"); Region region = (Region) ctx.getBean("s3Region"); ctx.close();//from ww w . j a v a 2s. c o m // check if user wants to create credentials File _accessFile = new File(identityPath); S3CachedFtpServer s3FtpServer = new S3CachedFtpServer(); s3FtpServer.init(_accessFile, chave, charset, keyBase, bucket, region); if (!_accessFile.exists() && args.length != 2) { throw new RuntimeException("sem credenciais"); } else if (!_accessFile.exists()) { s3FtpServer.writeKeyFile(args[0], args[1].toCharArray()); } s3FtpServer.go(); }
From source file:de.micromata.tpsb.doc.StaticTestDocGenerator.java
public static void main(String[] args) { ParserConfig.Builder bCfg = new ParserConfig.Builder(); ParserConfig.Builder tCfg = new ParserConfig.Builder(); tCfg.generateIndividualFiles(true);// w w w. j av a 2 s. co m bCfg.generateIndividualFiles(true); List<String> la = Arrays.asList(args); Iterator<String> it = la.iterator(); boolean baseDirSet = false; boolean ignoreLocalSettings = false; List<String> addRepos = new ArrayList<String>(); StringResourceLoader.setRepository(StringResourceLoader.REPOSITORY_NAME_DEFAULT, new StringResourceRepositoryImpl()); try { while (it.hasNext()) { String arg = it.next(); String value = null; if ((value = getArgumentOption(it, arg, "--project-root", "-pr")) != null) { File f = new File(value); if (f.exists() == false) { System.err.print("project root doesn't exists: " + f.getAbsolutePath()); continue; } TpsbEnvironment.get().addProjectRoots(f); File ts = new File(f, "src/test"); if (ts.exists() == true) { tCfg.addSourceFileRespository(new FileSystemSourceFileRepository(ts.getAbsolutePath())); bCfg.addSourceFileRespository(new FileSystemSourceFileRepository(ts.getAbsolutePath())); } continue; } if ((value = getArgumentOption(it, arg, "--test-input", "-ti")) != null) { File f = new File(value); if (f.exists() == false) { System.err.print("test-input doesn't exists: " + f.getAbsolutePath()); } tCfg.addSourceFileRespository(new FileSystemSourceFileRepository(value)); bCfg.addSourceFileRespository(new FileSystemSourceFileRepository(value)); continue; } if ((value = getArgumentOption(it, arg, "--output-path", "-op")) != null) { if (baseDirSet == false) { tCfg.outputDir(value); bCfg.outputDir(value); TpsbEnvironment.setBaseDir(value); baseDirSet = true; } else { addRepos.add(value); } continue; } if ((value = getArgumentOption(it, arg, "--index-vmtemplate", "-ivt")) != null) { try { String content = FileUtils.readFileToString(new File(value), CharEncoding.UTF_8); StringResourceRepository repo = StringResourceLoader.getRepository(); repo.putStringResource("customIndexTemplate", content, CharEncoding.UTF_8); tCfg.indexTemplate("customIndexTemplate"); } catch (IOException ex) { throw new RuntimeException( "Cannot load file " + new File(value).getAbsolutePath() + ": " + ex.getMessage(), ex); } continue; } if ((value = getArgumentOption(it, arg, "--test-vmtemplate", "-tvt")) != null) { try { String content = FileUtils.readFileToString(new File(value), CharEncoding.UTF_8); StringResourceRepository repo = StringResourceLoader.getRepository(); repo.putStringResource("customTestTemplate", content, CharEncoding.UTF_8); tCfg.testTemplate("customTestTemplate"); } catch (IOException ex) { throw new RuntimeException( "Cannot load file " + new File(value).getAbsolutePath() + ": " + ex.getMessage(), ex); } continue; } if (arg.equals("--singlexml") == true) { tCfg.generateIndividualFiles(false); bCfg.generateIndividualFiles(false); } else if (arg.equals("--ignore-local-settings") == true) { ignoreLocalSettings = true; continue; } } } catch (RuntimeException ex) { System.err.print(ex.getMessage()); return; } if (ignoreLocalSettings == false) { readLocalSettings(bCfg, tCfg); } bCfg// .addSourceFileFilter(new MatcherSourceFileFilter("*Builder,*App,*builder")) // .addSourceFileFilter(new AnnotationSourceFileFilter(TpsbBuilder.class)) // .addSourceFileFilter(new AnnotationSourceFileFilter(TpsbApplication.class)) // ; tCfg// .addSourceFileFilter(new MatcherSourceFileFilter("*Test,*TestCase")) // .addSourceFileFilter(new AnnotationSourceFileFilter(TpsbTestSuite.class)) // ; StaticTestDocGenerator docGenerator = new StaticTestDocGenerator(bCfg.build(), tCfg.build()); TpsbEnvironment env = TpsbEnvironment.get(); if (addRepos.isEmpty() == false) { env.setIncludeRepos(addRepos); } docGenerator.parseTestBuilders(); docGenerator.parseTestCases(); }
From source file:de.prozesskraft.pkraft.Createmap.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try/* w w w . j a v a 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(Createmap.class) + "/" + "../etc/pkraft-createmap.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"); /*---------------------------- create argument options ----------------------------*/ Option ooutput = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory; default: process.dot] file for generated map.") // .isRequired() .create("output"); Option odefinition = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory] process definition file.") // .isRequired() .create("definition"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ooutput); options.addOption(odefinition); /*---------------------------- 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("createmap", options); System.out.println(""); System.out.println("author: " + author + " | version: " + version + " | 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 output = new java.io.File(commandline.getOptionValue("output")); if (output.exists()) { System.err.println("warn: already exists: " + output.getCanonicalPath()); exiter(); } p1.setInfilexml(commandline.getOptionValue("definition")); System.err.println("info: reading process definition " + commandline.getOptionValue("definition")); // dummy process Process p2 = null; try { p2 = p1.readXml(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); System.err.println("error"); exiter(); } // den wrapper process generieren ArrayList<String> dot = p2.getProcessAsDotGraph(); // dot file rausschreiben writeFile.writeFile(output, dot); }
From source file:com.act.lcms.v2.fullindex.Builder.java
public static void main(String[] args) throws Exception { CLIUtil cliUtil = new CLIUtil(Builder.class, HELP_MESSAGE, OPTION_BUILDERS); CommandLine cl = cliUtil.parseCommandLine(args); File inputFile = new File(cl.getOptionValue(OPTION_SCAN_FILE)); if (!inputFile.exists()) { cliUtil.failWithMessage("Cannot find input scan file at %s", inputFile.getAbsolutePath()); }// ww w .j a va 2 s .c o m File indexDir = new File(cl.getOptionValue(OPTION_INDEX_PATH)); if (indexDir.exists()) { cliUtil.failWithMessage("Index file at %s already exists--remove and retry", indexDir.getAbsolutePath()); } Builder indexBuilder = Factory.makeBuilder(indexDir); try { indexBuilder.processScan(indexBuilder.makeTargetMasses(), inputFile); } finally { if (indexBuilder != null) { indexBuilder.close(); } } LOGGER.info("Done"); }