List of usage examples for java.lang System in
InputStream in
To view the source code for java.lang System in.
Click Source Link
From source file:jena.RuleMap.java
/** * General command line utility to process one RDF file into another * by application of a set of forward chaining rules. * <pre>//from w w w .j a v a 2 s.c o m * Usage: RuleMap [-il inlang] [-ol outlang] -d infile rulefile * </pre> */ public static void main(String[] args) { try { // Parse the command line String usage = "Usage: RuleMap [-il inlang] [-ol outlang] [-d] rulefile infile (- for stdin)"; final CommandLineParser parser = new DefaultParser(); Options options = new Options().addOption("il", "inputLang", true, "input language") .addOption("ol", "outputLang", true, "output language").addOption("d", "Deductions only?"); CommandLine cl = parser.parse(options, args); final List<String> filenameArgs = cl.getArgList(); if (filenameArgs.size() != 2) { System.err.println(usage); System.exit(1); } String inLang = cl.getOptionValue("inputLang"); String fname = filenameArgs.get(1); Model inModel = null; if (fname.equals("-")) { inModel = ModelFactory.createDefaultModel(); inModel.read(System.in, null, inLang); } else { inModel = FileManager.get().loadModel(fname, inLang); } String outLang = cl.hasOption("outputLang") ? cl.getOptionValue("outputLang") : "N3"; boolean deductionsOnly = cl.hasOption('d'); // Fetch the rule set and create the reasoner BuiltinRegistry.theRegistry.register(new Deduce()); Map<String, String> prefixes = new HashMap<>(); List<Rule> rules = loadRules(filenameArgs.get(0), prefixes); Reasoner reasoner = new GenericRuleReasoner(rules); // Process InfModel infModel = ModelFactory.createInfModel(reasoner, inModel); infModel.prepare(); infModel.setNsPrefixes(prefixes); // Output try (PrintWriter writer = new PrintWriter(System.out)) { if (deductionsOnly) { Model deductions = infModel.getDeductionsModel(); deductions.setNsPrefixes(prefixes); deductions.setNsPrefixes(inModel); deductions.write(writer, outLang); } else { infModel.write(writer, outLang); } } } catch (Throwable t) { System.err.println("An error occured: \n" + t); t.printStackTrace(); } }
From source file:de.huberlin.cuneiform.main.Main.java
public static void main(String[] args) throws ParseException, IOException, NotDerivableException, InterruptedException, JSONException { GnuParser gnuParser;// w w w .j ava 2s . c o m CommandLine cmdline; Options opt; String value; int platform; File outputDir; String[] fileList; StringBuffer buf; String line; String dagid; File logFile; opt = new Options(); opt.addOption("p", "platform", true, "The platform to perform the Cuneiform script's interpretation. " + "Possible platforms are: 'dot', 'local', and 'debug'. Default is 'local'."); opt.addOption("d", "directory", true, "The output directory, to put the interpretation intermediate and output result as well as the default location to store the log."); opt.addOption("c", "clean", false, "If set, the execution engine ignores all cached results and starts a clean workflow run."); opt.addOption("r", "runid", true, "If set, a custom id is set for this workflow run. By default a UUID string is used."); opt.addOption("f", "file", true, "Override the default location of the log file and use the specified filename instead. If the platform is 'dot', this option sets the name of the output dot-file."); opt.addOption("h", "help", false, "Print help text."); gnuParser = new GnuParser(); cmdline = gnuParser.parse(opt, args); if (cmdline.hasOption("help")) { System.out.println("CUNEIFORM - A Functional Workflow Language\n" + LABEL_VERSION); new HelpFormatter().printHelp("java -jar cuneiform.jar [OPTION]*", opt); return; } if (cmdline.hasOption("platform")) { value = cmdline.getOptionValue("platform"); if (value.equals("dot")) platform = PLATFORM_DOT; else if (value.equals("local")) platform = PLATFORM_LOCAL; else if (value.equals("debug")) platform = PLATFORM_DEBUG; else throw new RuntimeException("Specified platform '" + value + "' not recognized."); } else platform = PLATFORM_LOCAL; if (cmdline.hasOption('d')) { value = cmdline.getOptionValue('d'); } else value = "build"; outputDir = new File(value); if (outputDir.exists()) { if (!outputDir.isDirectory()) throw new IOException( "Output directory '" + outputDir.getAbsolutePath() + "' exists but is not a directory."); else if (cmdline.hasOption('c')) { FileUtils.deleteDirectory(outputDir); if (!outputDir.mkdirs()) throw new IOException( "Could not create output directory '" + outputDir.getAbsolutePath() + "'"); } } else if (!outputDir.mkdirs()) throw new IOException("Could not create output directory '" + outputDir.getAbsolutePath() + "'"); if (cmdline.hasOption('r')) dagid = cmdline.getOptionValue('r'); else dagid = UUID.randomUUID().toString(); if (cmdline.hasOption('f')) logFile = new File(cmdline.getOptionValue('f')); else logFile = null; fileList = cmdline.getArgs(); buf = new StringBuffer(); if (fileList.length == 0) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { while ((line = reader.readLine()) != null) buf.append(line).append('\n'); } switch (platform) { case PLATFORM_DOT: createDot(buf.toString(), outputDir, logFile); break; case PLATFORM_LOCAL: runLocal(buf.toString(), outputDir, logFile, dagid); break; case PLATFORM_DEBUG: runDebug(buf.toString(), outputDir, logFile, dagid); break; default: throw new RuntimeException("Platform not recognized."); } } else switch (platform) { case PLATFORM_DOT: createDot(fileList, outputDir, logFile); break; case PLATFORM_LOCAL: runLocal(fileList, outputDir, logFile, dagid); break; case PLATFORM_DEBUG: runDebug(fileList, outputDir, logFile, dagid); break; default: throw new RuntimeException("Platform not recognized."); } }
From source file:cf.service.TestBroker.java
public static void main(String[] args) throws Exception { final CfTokens cfTokens = new CfTokens(); final CfTokens.CfToken target = cfTokens.getCurrentTargetToken(); if (target == null) { System.err.println("It appears you haven't logged into a Cloud Foundry instance with cf."); return;//w w w . ja v a 2 s . c o m } if (target.getVersion() == null || target.getVersion() != 2) { System.err.println("You must target a v2 Cloud Controller using cf."); return; } if (target.getSpaceGuid() == null) { System.err.println("You must select a space to use using cf."); return; } LOGGER.info("Using Cloud Controller at: {}", target.getTarget()); final int serverPort = 8000; final String label = "testbroker"; final String provider = "Tester"; final String url = "http://" + localIp(target.getTarget()) + ":" + serverPort; final String description = "A service used for testing the service framework."; final String version = "0.1"; final String servicePlan = "ServicePlan"; final String servicePlanDescription = "Finest service... ever."; final String authToken = "SsshhhThisIsASecret"; final CloudController cloudController = new DefaultCloudController(new DefaultHttpClient(), target.getTarget()); final UUID serviceGuid = UUID.randomUUID(); // We need to keep track of the services GUID. // final String serviceGuid = cloudControllerClient.createService(new CreateServiceRequest( // label, provider, url, description, version // )); // LOGGER.debug("Created service with guid: {}", serviceGuid); // try (final SimpleHttpServer server = new SimpleHttpServer(new InetSocketAddress(serverPort))) { new NettyBrokerServer(server, new Provisioner() { private final AtomicInteger id = new AtomicInteger(); @Override public ServiceInstance create(CreateRequest request) { LOGGER.info("Creating service"); final Integer i = id.getAndIncrement(); final ServiceInstance serviceInstance = new ServiceInstance(i.toString()); serviceInstance.addGatewayDataField("key", "value"); serviceInstance.addCredential("user", "test"); return serviceInstance; } @Override public void delete(String instanceId) { } @Override public ServiceBinding bind(BindRequest request) { LOGGER.info("Binding service"); final Integer i = id.getAndIncrement(); final ServiceBinding serviceBinding = new ServiceBinding(request.getServiceInstanceId(), i.toString()); serviceBinding.addGatewayDataField("bindkey", "bind value"); serviceBinding.addCredential("binduser", "test"); return serviceBinding; } @Override public void unbind(String instanceId, String handleId) { } @Override public Iterable<String> serviceInstanceIds() { return null; } @Override public Iterable<String> bindingIds(String instanceId) { return null; } @Override public void removeOrphanedBinding(String instanceId, String bindingId) { } @Override public void removeOrphanedServiceInstance(String instanceId) { } }, authToken); // final String serviceGuid = cloudControllerClient.createService(new CreateServiceRequest( // label, provider, url, description, version // )); // LOGGER.debug("Created service with guid: {}", serviceGuid); // // final String servicePlanGuid = cloudControllerClient.createServicePlan(new CreateServicePlanRequest(servicePlan, servicePlanDescription, serviceGuid)); // LOGGER.debug("Created service plan with guid: {}", serviceGuid); // // final String authTokenGuid = cloudControllerClient.createAuthToken(new CreateAuthTokenRequest(label, provider, authToken)); // LOGGER.debug("Created service token with guid: {}", authTokenGuid); // // final String instanceName = "testservice"; // final String serviceInstaceGuid = cloudControllerClient.createServiceInstance(instanceName, servicePlanGuid, target.getSpaceGuid()); System.in.read(); } }
From source file:com.genentech.chemistry.openEye.apps.SDFMCSSNNFinder.java
public static void main(String... args) throws IOException { CommandLineParser parser = new PosixParser(); CommandLine cmd = null;//from w ww . ja v a 2s .c o m try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(e.getMessage()); exitWithHelp(); } args = cmd.getArgs(); if (args.length > 0) { exitWithHelp("Unknown param: " + args[0]); } if (cmd.hasOption("d")) { System.err.println("Start debugger and press return:"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } int nCpu = 1; int maxNeighbors = 1; double minSim = 0D; String idTag = cmd.getOptionValue("idTag"); boolean printAll = cmd.hasOption("printAll"); String d = cmd.getOptionValue("nCpu"); if (d != null) nCpu = Integer.parseInt(d); d = cmd.getOptionValue("maxNeighbors"); if (d != null) maxNeighbors = Integer.parseInt(d); d = cmd.getOptionValue("minSimilarity"); if (d != null) minSim = Double.parseDouble(d); String countAboveSimilarityStr = cmd.getOptionValue("countSimilarAbove"); String inFile = cmd.getOptionValue("in"); String outFile = cmd.getOptionValue("out"); String refFile = cmd.getOptionValue("ref"); String tabOutput = cmd.getOptionValue("tabOutput"); boolean outputDuplicates = cmd.hasOption("outputDuplicates"); if (outputDuplicates && tabOutput != null) exitWithHelp("-outputDuplicates will not work with outputVTab"); if (outputDuplicates && refFile == null) exitWithHelp("-outputDuplicates requires -ref "); if ("tab".equalsIgnoreCase(tabOutput) && refFile != null) exitWithHelp("-tabOutput tab: does not work with reference file"); if ("tab".equalsIgnoreCase(tabOutput) && maxNeighbors == 1) exitWithHelp("-tabOutput tab: does not make sense with -maxNeighbors = 1"); if (cmd.hasOption("countSimilarAbove") && tabOutput != null) exitWithHelp("-countSimilarAbove not supported for tab or vTab output"); if (printAll && !(maxNeighbors > 1 || minSim > 0)) exitWithHelp("printAll only supported if: maxNeighbors > 1 or minSim > 0"); if (printAll && tabOutput != null) System.err.println("WARNING: printAll ignored for tab output!\n"); SimComparatorFactory<OEMolBase, OEMolBase, SimComparator<OEMolBase>> compFact; compFact = getComparatorFactory(cmd); if (refFile == null) { // no reference file; run all by all comparison performMatrixNNSearch(inFile, outFile, tabOutput, compFact, minSim, maxNeighbors, idTag, nCpu, countAboveSimilarityStr, printAll); } else { // refrence file; compare inFile to refFile performReferenceSearch(inFile, refFile, outFile, tabOutput, compFact, minSim, maxNeighbors, idTag, nCpu, countAboveSimilarityStr, outputDuplicates, printAll); } }
From source file:com.momab.dstool.DSTool.java
public static void main(String[] args) throws ParseException, IOException, ClassNotFoundException { final CommandLineParser parser = new BasicParser(); final Options options = commandLineOptions(); final CommandLine line = parser.parse(options, args); if (args.length == 0) { printUsage(options, System.out); System.exit(0);/*from ww w .j av a 2s . c o m*/ } if (args.length == 1 && line.hasOption("h")) { printHelp(options, System.out); System.exit(0); } if (!line.hasOption("r") && !line.hasOption("w") && !line.hasOption("d")) { printErrorMessage("One of the options -r -w or -d must be specified.", System.err); System.exit(-1); } if (line.getArgs().length != 2) { printErrorMessage("To few arguments.", System.err); System.exit(-1); } DSOperation op = null; // Required operands/arguments DSOperationBuilder opBuilder = new DSOperationBuilder(line.getArgs()[0], line.getArgs()[1]); // Username and password if (line.hasOption("u") || line.hasOption("p")) { if (!line.hasOption("u") || !line.hasOption("p")) { printErrorMessage("Missing username or password", System.err); System.exit(-1); } opBuilder.asUser(line.getOptionValue("u"), line.getOptionValue("p")); } // Port if (line.hasOption("P")) { opBuilder = opBuilder.usingPort(Integer.valueOf(line.getOptionValue("P"))); } // File File file = null; OutputStream out = null; InputStream in = null; if (line.hasOption("f")) { if (line.hasOption("d")) { printErrorMessage("Option -f is invalid for a -d delete operation", System.err); System.exit(-1); } file = new File(line.getOptionValue("f")); } // Read (download) operation if (line.hasOption("r")) { if (file != null) { out = new FileOutputStream(file); } else { out = System.out; } opBuilder = opBuilder.writeTo(out); op = opBuilder.buildDownload(); } // Write (upload) operation if (line.hasOption("w")) { if (file != null) { in = new FileInputStream(file); } else { in = System.in; } opBuilder = opBuilder.readFrom(in); op = opBuilder.buildUpload(); } // Delete (upload) operation if (line.hasOption("d")) { op = opBuilder.buildDelete(); } if (file != null || line.hasOption("d")) { boolean result = op.Run(new ProgressPrinter() { }); if (in != null) in.close(); if (out != null) out.close(); System.exit(result ? 0 : -1); } else { System.exit(op.Run(null) ? 0 : -1); } }
From source file:com.google.oacurl.Login.java
public static void main(String[] args) throws Exception { LoginOptions options = new LoginOptions(); try {// ww w . j a v a2s. co m options.parse(args); } catch (ParseException e) { System.err.println(e.getMessage()); System.exit(-1); } if (options.isHelp()) { new HelpFormatter().printHelp(" ", options.getOptions()); System.exit(0); } if (options.isInsecure()) { SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier()); } LoggingConfig.init(options.isVerbose()); if (options.isWirelogVerbose()) { LoggingConfig.enableWireLog(); } ServiceProviderDao serviceProviderDao = new ServiceProviderDao(); ConsumerDao consumerDao = new ConsumerDao(options); AccessorDao accessorDao = new AccessorDao(); String serviceProviderFileName = options.getServiceProviderFileName(); if (serviceProviderFileName == null) { if (options.isBuzz()) { // Buzz has its own provider because it has a custom authorization URL serviceProviderFileName = "BUZZ"; } else if (options.getVersion() == OAuthVersion.V2) { serviceProviderFileName = "GOOGLE_V2"; } else { serviceProviderFileName = "GOOGLE"; } } // We have a wee library of service provider properties files bundled into // the resources, so we set up the PropertiesProvider to search for them // if the file cannot be found. OAuthServiceProvider serviceProvider = serviceProviderDao.loadServiceProvider( new PropertiesProvider(serviceProviderFileName, ServiceProviderDao.class, "services/").get()); OAuthConsumer consumer = consumerDao .loadConsumer(new PropertiesProvider(options.getConsumerFileName()).get(), serviceProvider); OAuthAccessor accessor = accessorDao.newAccessor(consumer); OAuthClient client = new OAuthClient(new HttpClient4()); LoginCallbackServer callbackServer = null; boolean launchedBrowser = false; try { if (!options.isNoServer()) { callbackServer = new LoginCallbackServer(options); callbackServer.start(); } String callbackUrl; if (options.getCallback() != null) { callbackUrl = options.getCallback(); } else if (callbackServer != null) { callbackUrl = callbackServer.getCallbackUrl(); } else { callbackUrl = null; } OAuthEngine engine; switch (options.getVersion()) { case V1: engine = new V1OAuthEngine(); break; case V2: engine = new V2OAuthEngine(); break; case WRAP: engine = new WrapOAuthEngine(); break; default: throw new IllegalArgumentException("Unknown version: " + options.getVersion()); } do { String authorizationUrl = engine.getAuthorizationUrl(client, accessor, options, callbackUrl); if (!options.isNoServer()) { callbackServer.setAuthorizationUrl(authorizationUrl); } if (!launchedBrowser) { String url = options.isDemo() ? callbackServer.getDemoUrl() : authorizationUrl; if (options.isNoBrowser()) { System.out.println(url); System.out.flush(); } else { launchBrowser(options, url); } launchedBrowser = true; } accessor.accessToken = null; logger.log(Level.INFO, "Waiting for verification token..."); String verifier; if (options.isNoServer()) { System.out.print("Verification token: "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); verifier = ""; while (verifier.isEmpty()) { String line = reader.readLine(); if (line == null) { System.exit(-1); } verifier = line.trim(); } } else { verifier = callbackServer.waitForVerifier(accessor, -1); if (verifier == null) { System.err.println("Wait for verifier interrupted"); System.exit(-1); } } logger.log(Level.INFO, "Verification token received: " + verifier); boolean success = engine.getAccessToken(accessor, client, callbackUrl, verifier); if (success) { if (callbackServer != null) { callbackServer.setTokenStatus(TokenStatus.VALID); } Properties loginProperties = new Properties(); accessorDao.saveAccessor(accessor, loginProperties); consumerDao.saveConsumer(consumer, loginProperties); loginProperties.put("oauthVersion", options.getVersion().toString()); new PropertiesProvider(options.getLoginFileName()).overwrite(loginProperties); } else { if (callbackServer != null) { callbackServer.setTokenStatus(TokenStatus.INVALID); } } } while (options.isDemo()); } catch (OAuthProblemException e) { OAuthUtil.printOAuthProblemException(e); } finally { if (callbackServer != null) { callbackServer.stop(); } } }
From source file:com.github.horrorho.inflatabledonkey.Main.java
/** * @param args the command line arguments * @throws IOException/*w ww . j av a 2 s .c om*/ */ public static void main(String[] args) throws IOException { try { if (!PropertyLoader.instance().test(args)) { return; } } catch (IllegalArgumentException ex) { System.out.println("Argument error: " + ex.getMessage()); System.out.println("Try '" + Property.APP_NAME.value() + " --help' for more information."); System.exit(-1); } // SystemDefault HttpClient. // TODO concurrent CloseableHttpClient httpClient = HttpClients.custom().setUserAgent("CloudKit/479 (13A404)") .useSystemProperties().build(); // Auth // TODO rework when we have UncheckedIOException for Authenticator Auth auth = Property.AUTHENTICATION_TOKEN.value().map(Auth::new).orElse(null); if (auth == null) { auth = Authenticator.authenticate(httpClient, Property.AUTHENTICATION_APPLEID.value().get(), Property.AUTHENTICATION_PASSWORD.value().get()); } logger.debug("-- main() - auth: {}", auth); logger.info("-- main() - dsPrsID:mmeAuthToken: {}:{}", auth.dsPrsID(), auth.mmeAuthToken()); if (Property.ARGS_TOKEN.booleanValue().orElse(false)) { System.out.println("DsPrsID:mmeAuthToken " + auth.dsPrsID() + ":" + auth.mmeAuthToken()); return; } logger.info("-- main() - Apple ID: {}", Property.AUTHENTICATION_APPLEID.value()); logger.info("-- main() - password: {}", Property.AUTHENTICATION_PASSWORD.value()); logger.info("-- main() - token: {}", Property.AUTHENTICATION_TOKEN.value()); // Account Account account = Accounts.account(httpClient, auth); // Backup Backup backup = Backup.create(httpClient, account); // BackupAccount BackupAccount backupAccount = backup.backupAccount(httpClient); logger.debug("-- main() - backup account: {}", backupAccount); // Devices List<Device> devices = backup.devices(httpClient, backupAccount.devices()); logger.debug("-- main() - device count: {}", devices.size()); // Snapshots List<SnapshotID> snapshotIDs = devices.stream().map(Device::snapshots).flatMap(Collection::stream) .collect(Collectors.toList()); logger.info("-- main() - total snapshot count: {}", snapshotIDs.size()); Map<String, Snapshot> snapshots = backup.snapshot(httpClient, snapshotIDs).stream().collect( Collectors.toMap(s -> s.record().getRecordIdentifier().getValue().getName(), Function.identity())); boolean repeat = false; do { for (int i = 0; i < devices.size(); i++) { Device device = devices.get(i); List<SnapshotID> deviceSnapshotIDs = device.snapshots(); System.out.println(i + " " + device.info()); for (int j = 0; j < deviceSnapshotIDs.size(); j++) { SnapshotID sid = deviceSnapshotIDs.get(j); System.out.println("\t" + j + snapshots.get(sid.id()).info() + " " + sid.timestamp()); } } if (Property.PRINT_SNAPSHOTS.booleanValue().orElse(false)) { return; } // Selection Scanner input = new Scanner(System.in); int deviceIndex; int snapshotIndex = Property.SELECT_SNAPSHOT_INDEX.intValue().get(); if (devices.size() > 1) { System.out.printf("Select a device [0 - %d]: ", devices.size() - 1); deviceIndex = input.nextInt(); } else deviceIndex = Property.SELECT_DEVICE_INDEX.intValue().get(); if (deviceIndex >= devices.size() || deviceIndex < 0) { System.out.println("No such device: " + deviceIndex); System.exit(-1); } Device device = devices.get(deviceIndex); System.out.println("Selected device: " + deviceIndex + ", " + device.info()); if (device.snapshots().size() > 1) { System.out.printf("Select a snapshot [0 - %d]: ", device.snapshots().size() - 1); snapshotIndex = input.nextInt(); } else snapshotIndex = Property.SELECT_SNAPSHOT_INDEX.intValue().get(); if (snapshotIndex >= devices.get(deviceIndex).snapshots().size() || snapshotIndex < 0) { System.out.println("No such snapshot for selected device: " + snapshotIndex); System.exit(-1); } logger.info("-- main() - arg device index: {}", deviceIndex); logger.info("-- main() - arg snapshot index: {}", snapshotIndex); String selected = devices.get(deviceIndex).snapshots().get(snapshotIndex).id(); Snapshot snapshot = snapshots.get(selected); System.out.println("Selected snapshot: " + snapshotIndex + ", " + snapshot.info()); // Asset list. List<Assets> assetsList = backup.assetsList(httpClient, snapshot); logger.info("-- main() - assets count: {}", assetsList.size()); // Domains filter --domain option String chosenDomain = Property.FILTER_DOMAIN.value().orElse("").toLowerCase(Locale.US); logger.info("-- main() - arg domain substring filter: {}", Property.FILTER_DOMAIN.value()); // Output domains --domains option if (Property.PRINT_DOMAIN_LIST.booleanValue().orElse(false)) { System.out.println("Domains / file count:"); assetsList.stream().filter(a -> a.domain().isPresent()) .map(a -> a.domain().get() + " / " + a.files().size()).sorted() .forEach(System.out::println); System.out.print("Type a domain ('null' to exit): "); chosenDomain = input.next().toLowerCase(Locale.US); if (chosenDomain.equals("null")) return; // TODO check Assets without domain information. } String domainSubstring = chosenDomain; Predicate<Optional<String>> domainFilter = domain -> domain.map(d -> d.toLowerCase(Locale.US)) .map(d -> d.contains(domainSubstring)).orElse(false); List<String> files = Assets.files(assetsList, domainFilter); logger.info("-- main() - domain filtered file count: {}", files.size()); // Output folders. Path outputFolder = Paths.get(Property.OUTPUT_FOLDER.value().orElse("output")); Path assetOutputFolder = outputFolder.resolve("assets"); // TODO assets value injection Path chunkOutputFolder = outputFolder.resolve("chunks"); // TODO chunks value injection logger.info("-- main() - output folder chunks: {}", chunkOutputFolder); logger.info("-- main() - output folder assets: {}", assetOutputFolder); // Download tools. AuthorizeAssets authorizeAssets = AuthorizeAssets.backupd(); DiskChunkStore chunkStore = new DiskChunkStore(chunkOutputFolder); StandardChunkEngine chunkEngine = new StandardChunkEngine(chunkStore); AssetDownloader assetDownloader = new AssetDownloader(chunkEngine); KeyBagManager keyBagManager = backup.newKeyBagManager(); // Mystery Moo. Moo moo = new Moo(authorizeAssets, assetDownloader, keyBagManager); // Filename extension filter. String filenameExtension = Property.FILTER_EXTENSION.value().orElse("").toLowerCase(Locale.US); logger.info("-- main() - arg filename extension filter: {}", Property.FILTER_EXTENSION.value()); Predicate<Asset> assetFilter = asset -> asset.relativePath().map(d -> d.toLowerCase(Locale.US)) .map(d -> d.endsWith(filenameExtension)).orElse(false); // Batch process files in groups of 100. // TODO group files into batches based on file size. List<List<String>> batches = ListUtils.partition(files, 100); for (List<String> batch : batches) { List<Asset> assets = backup.assets(httpClient, batch).stream().filter(assetFilter::test) .collect(Collectors.toList()); logger.info("-- main() - filtered asset count: {}", assets.size()); moo.download(httpClient, assets, assetOutputFolder); } System.out.print("Download other snapshot (Y/N)? "); repeat = input.next().toLowerCase(Locale.US).charAt(0) == 'y'; } while (repeat == true); }
From source file:asl.seedscan.DQAWeb.java
public static void main(String args[]) { db = new MetricDatabase("", "", ""); findConsoleHandler();/*from www . j a v a 2s . c om*/ consoleHandler.setLevel(Level.ALL); Logger.getLogger("").setLevel(Level.CONFIG); // Default locations of config and schema files File configFile = new File("dqaweb-config.xml"); File schemaFile = new File("schemas/DQAWebConfig.xsd"); boolean parseConfig = true; boolean testMode = false; ArrayList<File> schemaFiles = new ArrayList<File>(); schemaFiles.add(schemaFile); // ==== Command Line Parsing ==== Options options = new Options(); Option opConfigFile = new Option("c", "config-file", true, "The config file to use for seedscan. XML format according to SeedScanConfig.xsd."); Option opSchemaFile = new Option("s", "schema-file", true, "The schame file which should be used to verify the config file format. "); Option opTest = new Option("t", "test", false, "Run in test console mode rather than as a servlet."); OptionGroup ogConfig = new OptionGroup(); ogConfig.addOption(opConfigFile); OptionGroup ogSchema = new OptionGroup(); ogConfig.addOption(opSchemaFile); OptionGroup ogTest = new OptionGroup(); ogTest.addOption(opTest); options.addOptionGroup(ogConfig); options.addOptionGroup(ogSchema); options.addOptionGroup(ogTest); PosixParser optParser = new PosixParser(); CommandLine cmdLine = null; try { cmdLine = optParser.parse(options, args, true); } catch (org.apache.commons.cli.ParseException e) { logger.severe("Error while parsing command-line arguments."); System.exit(1); } Option opt; Iterator iter = cmdLine.iterator(); while (iter.hasNext()) { opt = (Option) iter.next(); if (opt.getOpt().equals("c")) { configFile = new File(opt.getValue()); } else if (opt.getOpt().equals("s")) { schemaFile = new File(opt.getValue()); } else if (opt.getOpt().equals("t")) { testMode = true; } } String query = ""; System.out.println("Entering Test Mode"); System.out.println("Enter a query string to view results or type \"help\" for example query strings"); InputStreamReader input = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(input); String result = ""; while (testMode == true) { try { System.out.printf("Query: "); query = reader.readLine(); if (query.equals("exit")) { testMode = false; } else if (query.equals("help")) { System.out.println("Need to add some help for people"); //TODO } else { result = processCommand(query); } System.out.println(result); } catch (IOException err) { System.err.println("Error reading line, in DQAWeb.java"); } } System.err.printf("DONE.\n"); }
From source file:com.genentech.chemistry.openEye.apps.SDFMDLSSSMatcher.java
public static void main(String... args) throws IOException, InterruptedException { oechem.OEUseJavaHeap(false);/*from w ww .j a va 2 s . c om*/ // create command line Options object Options options = new Options(); Option opt = new Option("in", true, "input file [.sdf,...]"); opt.setRequired(true); options.addOption(opt); opt = new Option("out", true, "output file oe-supported"); opt.setRequired(false); options.addOption(opt); opt = new Option("ref", true, "refrence file with MDL query molecules"); opt.setRequired(true); options.addOption(opt); opt = new Option("anyMatch", false, "if set all matches are reported not just the first."); opt.setRequired(false); options.addOption(opt); opt = new Option("printAll", false, "if set even compounds that do not macht are outputted."); opt.setRequired(false); options.addOption(opt); opt = new Option("nCpu", true, "number of CPU's used in parallel, dafault 1"); opt.setRequired(false); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(e.getMessage()); exitWithHelp(options); } args = cmd.getArgs(); if (args.length > 0) { exitWithHelp("Unknown param: " + args[0], options); } if (cmd.hasOption("d")) { System.err.println("Start debugger and press return:"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } int nCpu = 1; boolean firstMatch = !cmd.hasOption("anyMatch"); boolean printAll = cmd.hasOption("printAll"); String d = cmd.getOptionValue("nCpu"); if (d != null) nCpu = Integer.parseInt(d); String inFile = cmd.getOptionValue("in"); String outFile = cmd.getOptionValue("out"); String refFile = cmd.getOptionValue("ref"); SDFMDLSSSMatcher matcher = new SDFMDLSSSMatcher(refFile, outFile, firstMatch, printAll, nCpu); matcher.run(inFile); matcher.close(); }
From source file:com.github.brandtg.stl.StlPlotter.java
public static void main(String[] args) throws Exception { List<Double> times = new ArrayList<Double>(); List<Double> series = new ArrayList<Double>(); List<Double> trend = new ArrayList<Double>(); List<Double> seasonal = new ArrayList<Double>(); List<Double> remainder = new ArrayList<Double>(); // Read from STDIN String line;/*w ww . java2 s. co m*/ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while ((line = reader.readLine()) != null) { String[] tokens = line.split(","); times.add(Double.valueOf(tokens[0])); series.add(Double.valueOf(tokens[1])); trend.add(Double.valueOf(tokens[2])); seasonal.add(Double.valueOf(tokens[3])); remainder.add(Double.valueOf(tokens[4])); } StlResult res = new StlResult(convert(times), convert(series), convert(trend), convert(seasonal), convert(remainder)); if (args.length == 1) { plot(res, new File(args[0])); } else { plotOnScreen(res, "Seasonal Decomposition"); } }