List of usage examples for java.util Arrays copyOfRange
public static boolean[] copyOfRange(boolean[] original, int from, int to)
From source file:com.act.lcms.CompareTwoNetCDFAroundMass.java
public static void main(String[] args) throws Exception { if (args.length < 5 || !areNCFiles(Arrays.copyOfRange(args, 3, args.length))) { throw new RuntimeException("Needs: \n" + "(1) mass value, e.g., 132.0772 for debugging, \n" + "(2) how many timepoints to process (-1 for all), \n" + "(3) prefix for .data and rendered .pdf \n" + "(4,5..) 2 or more NetCDF .nc files"); }/*from w ww .j a v a2 s.com*/ String fmt = "pdf"; Double mz = Double.parseDouble(args[0]); Integer numSpectraToProcess = Integer.parseInt(args[1]); String outPrefix = args[2]; String outImg = outPrefix.equals("-") ? null : outPrefix + "." + fmt; String outData = outPrefix.equals("-") ? null : outPrefix + ".data"; CompareTwoNetCDFAroundMass c = new CompareTwoNetCDFAroundMass(); String[] netCDF_fnames = Arrays.copyOfRange(args, 3, args.length); List<List<Pair<Double, Double>>> spectra = c.getSpectraForMass(mz, netCDF_fnames, numSpectraToProcess); // Write data output to outfile PrintStream out = outData == null ? System.out : new PrintStream(new FileOutputStream(outData)); // print out the spectra to outData for (List<Pair<Double, Double>> spectraInFile : spectra) { for (Pair<Double, Double> xy : spectraInFile) { out.format("%.4f\t%.4f\n", xy.getLeft(), xy.getRight()); out.flush(); } // delimit this dataset from the rest out.print("\n\n"); } // find the ymax across all spectra, so that we can have a uniform y scale Double yrange = 0.0; for (List<Pair<Double, Double>> spectraInFile : spectra) { Double ymax = 0.0; for (Pair<Double, Double> xy : spectraInFile) { Double intensity = xy.getRight(); if (ymax < intensity) ymax = intensity; } if (yrange < ymax) yrange = ymax; } if (outData != null) { // if outData is != null, then we have written to .data file // now render the .data to the corresponding .pdf file // first close the .data out.close(); // render outData to outFILE using gnuplo Gnuplotter plotter = new Gnuplotter(); plotter.plot2D(outData, outImg, netCDF_fnames, "time in seconds", yrange, "intensity", fmt); } }
From source file:grakn.core.console.GraknConsole.java
/** * Invocation from bash script './grakn console' *//*from w ww .j ava 2 s.c o m*/ public static void main(String[] args) { try { GraknConsole console = new GraknConsole(Arrays.copyOfRange(args, 1, args.length), System.out, System.err); console.run(); System.exit(0); } catch (GraknConsoleException e) { System.err.println(e.getMessage()); System.err.println("Cause: " + e.getCause().getClass().getName()); System.err.println(e.getCause().getMessage()); System.exit(1); } catch (GraknException e) { // TODO: don't do if-checks. Use different catch-clauses by class if (e.getMessage().startsWith(Status.Code.UNAVAILABLE.name())) { System.err.println(ErrorMessage.COULD_NOT_CONNECT.getMessage()); } else { e.printStackTrace(System.err); } System.exit(1); } catch (Exception e) { e.printStackTrace(System.err); System.exit(1); } }
From source file:at.treedb.util.Compress.java
/** * /* w w w .j av a 2 s. c o m*/ * @param args * @throws IOException */ public static void main(String[] args) throws IOException { StringBuffer buf = new StringBuffer(); buf.append("7z-compression with following parameters: "); for (String s : args) { buf.append(s); buf.append(' '); } System.out.println(buf.toString()); Compress c = new Compress(args[0], args[1], args[2], Arrays.copyOfRange(args, 3, args.length)); c.compress(); }
From source file:com.github.brandtg.switchboard.MysqlReplicator.java
/** Main. */ public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("u", "user", true, "MySQL user"); options.addOption("p", "password", true, "MySQL password"); options.addOption("h", "host", true, "MySQL host"); options.addOption("P", "port", true, "MySQL port"); options.addOption("s", "sinkPort", true, "Local sink port"); options.addOption("l", "lastIndex", true, "Last transaction ID"); options.addOption("h", "help", false, "Prints help message"); CommandLine commandLine = new GnuParser().parse(options, args); if (commandLine.getArgs().length < 2 || commandLine.hasOption("help")) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("usage: [opts] switchboardHost:port db1 [db2 ...]", options); System.exit(1);//w w w . j ava 2s . c o m } // Switchboard host String[] hostPort = commandLine.getArgs()[0].split(":"); InetSocketAddress source = new InetSocketAddress(hostPort[0], Integer.valueOf(hostPort[1])); InetSocketAddress sink = new InetSocketAddress( Integer.valueOf(commandLine.getOptionValue("sinkPort", "9090"))); // Databases to replicate String[] databases = Arrays.copyOfRange(commandLine.getArgs(), 1, commandLine.getArgs().length); // JDBC params for local copy String user = commandLine.getOptionValue("user", "root"); String password = commandLine.getOptionValue("password", ""); String jdbcString = String.format("jdbc:mysql://%s:%d", commandLine.getOptionValue("host", "localhost"), Integer.valueOf(commandLine.getOptionValue("port", "3306"))); Long lastIndex = Long.valueOf(commandLine.getOptionValue("lastIndex", "-1")); // Create replicators final List<MysqlReplicator> replicators = new ArrayList<>(); for (String database : databases) { MysqlReplicator replicator = new MysqlReplicator(database, source, sink, jdbcString, user, password, lastIndex); replicators.add(replicator); } // Shutdown hook Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { for (MysqlReplicator replicator : replicators) { try { replicator.shutdown(); } catch (Exception e) { LOG.error("Could not shut down {}", replicator, e); } } } }); for (MysqlReplicator replicator : replicators) { replicator.start(); LOG.info("Started {}", replicator); } }
From source file:com.yahoo.pulsar.client.cli.PulsarClientTool.java
public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("Usage: pulsar-client CONF_FILE_PATH [options] [command] [command options]"); System.exit(-1);//from www . ja va 2s. co m } String configFile = args[0]; Properties properties = new Properties(); if (configFile != null) { FileInputStream fis = null; try { fis = new FileInputStream(configFile); properties.load(fis); } finally { if (fis != null) { fis.close(); } } } PulsarClientTool clientTool = new PulsarClientTool(properties); int exit_code = clientTool.run(Arrays.copyOfRange(args, 1, args.length)); System.exit(exit_code); }
From source file:net.sfr.tv.mom.mgt.HornetqConsole.java
/** * @param args the command line arguments *///w w w. j a va2 s. co m public static void main(String[] args) { try { String jmxHost = "127.0.0.1"; String jmxPort = "6001"; // Process command line arguments String arg; for (int i = 0; i < args.length; i++) { arg = args[i]; switch (arg) { case "-h": jmxHost = args[++i]; break; case "-p": jmxPort = args[++i]; break; default: break; } } // Check for arguments consistency if (StringUtils.isEmpty(jmxHost) || !NumberUtils.isNumber(jmxPort)) { LOGGER.info("Usage : "); LOGGER.info("hq-console.jar <-h host(127.0.0.1)> <-p port(6001)>\n"); System.exit(1); } System.out.println( SystemUtils.LINE_SEPARATOR.concat(Ansi.format("HornetQ Console ".concat(VERSION), Color.CYAN))); final StringBuilder _url = new StringBuilder("service:jmx:rmi://").append(jmxHost).append(':') .append(jmxPort).append("/jndi/rmi://").append(jmxHost).append(':').append(jmxPort) .append("/jmxrmi"); final String jmxServiceUrl = _url.toString(); JMXConnector jmxc = null; final CommandRouter router = new CommandRouter(); try { jmxc = JMXConnectorFactory.connect(new JMXServiceURL(jmxServiceUrl), null); assert jmxc != null; // jmxc must be not null } catch (final MalformedURLException e) { System.out.println(SystemUtils.LINE_SEPARATOR .concat(Ansi.format(jmxServiceUrl + " :" + e.getMessage(), Color.RED))); } catch (Throwable t) { System.out.println(SystemUtils.LINE_SEPARATOR.concat( Ansi.format("Unable to connect to JMX service URL : ".concat(jmxServiceUrl), Color.RED))); System.out.print(SystemUtils.LINE_SEPARATOR.concat( Ansi.format("Did you add jmx-staticport-agent.jar to your classpath ?", Color.MAGENTA))); System.out.println(SystemUtils.LINE_SEPARATOR.concat(Ansi.format( "Or did you set the com.sun.management.jmxremote.port option in the hornetq server startup script ?", Color.MAGENTA))); System.exit(-1); } System.out.println("\n".concat(Ansi .format("Successfully connected to JMX service URL : ".concat(jmxServiceUrl), Color.YELLOW))); final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection(); // PRINT SERVER STATUS REPORT System.out.print((String) router.get(Command.STATUS, Option.VM).execute(mbsc, null)); System.out.print((String) router.get(Command.STATUS, Option.SERVER).execute(mbsc, null)); System.out.print((String) router.get(Command.STATUS, Option.CLUSTER).execute(mbsc, null)); printHelp(router); // START COMMAND LINE Scanner scanner = new Scanner(System.in); System.out.print("> "); String input; while (!(input = scanner.nextLine().concat(" ")).equals("exit ")) { String[] cliArgs = input.split("\\ "); CommandHandler handler; if (cliArgs.length < 1) { System.out.print("> "); continue; } Command cmd = Command.fromString(cliArgs[0]); if (cmd == null) { System.out.print(Ansi.format("Syntax error !", Color.RED).concat("\n")); cmd = Command.HELP; } switch (cmd) { case STATUS: case LIST: case DROP: Set<Option> options = router.get(cmd); for (Option opt : options) { if (cliArgs[1].equals(opt.toString())) { handler = router.get(cmd, opt); String[] cmdOpts = null; if (cliArgs.length > 2) { cmdOpts = new String[cliArgs.length - 2]; for (int i = 0; i < cmdOpts.length; i++) { cmdOpts[i] = cliArgs[2 + i]; } } Object result = handler.execute(mbsc, cmdOpts); if (result != null && String.class.isAssignableFrom(result.getClass())) { System.out.print((String) result); } System.out.print("> "); } } break; case FORK: // EXECUTE SYSTEM COMMAND ProcessBuilder pb = new ProcessBuilder(Arrays.copyOfRange(cliArgs, 1, cliArgs.length)); pb.inheritIO(); pb.start(); break; case HELP: printHelp(router); break; } } } catch (MalformedURLException ex) { LOGGER.log(Level.SEVERE, null, ex); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } echo(SystemUtils.LINE_SEPARATOR.concat(Ansi.format("Bye!", Color.CYAN))); }
From source file:edu.msu.cme.rdp.readseq.utils.QualityTrimmer.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("f", "fastq-out", false, "Write fastq instead of fasta file"); options.addOption("l", "less-than", false, "Trim at <= instead of strictly ="); options.addOption("i", "illumina", false, "Illumina trimming mode"); FastqWriter fastqOut = null;//from w w w. j a va 2s . c o m FastaWriter fastaOut = null; byte qualTrim = -1; boolean writeFasta = true; boolean trimle = false; boolean illumina = false; List<SeqReader> readers = new ArrayList(); List<File> seqFiles = new ArrayList(); try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("fastq-out")) { writeFasta = false; } if (line.hasOption("less-than")) { trimle = true; } if (line.hasOption("illumina")) { illumina = true; } args = line.getArgs(); if (args.length < 2) { throw new Exception("Unexpected number of arguments"); } if (args[0].length() != 1) { throw new Exception("Expected single character quality score"); } qualTrim = FastqCore.Phred33QualFunction.translate(args[0].charAt(0)); for (int index = 1; index < args.length; index++) { File seqFile = new File(args[index]); SeqReader reader; if (SeqUtils.guessFileFormat(seqFile) == SequenceFormat.FASTA) { if (index + 1 == args.length) { throw new Exception("Fasta files must be immediately followed by their quality file"); } File qualFile = new File(args[index + 1]); if (SeqUtils.guessFileFormat(qualFile) != SequenceFormat.FASTA) { throw new Exception(seqFile + " was not followed by a fasta quality file"); } reader = new QSeqReader(seqFile, qualFile); index++; } else { if (seqFile.getName().endsWith(".gz")) { reader = new SequenceReader(new GZIPInputStream(new FileInputStream(seqFile))); } else { reader = new SequenceReader(seqFile); } } readers.add(reader); seqFiles.add(seqFile); } } catch (Exception e) { new HelpFormatter().printHelp("USAGE: QualityTrimmer [options] <ascii_score> <seq_file> [qual_file]", options, true); System.err.println("Error: " + e.getMessage()); System.exit(1); } for (int readerIndex = 0; readerIndex < readers.size(); readerIndex++) { File seqFile = seqFiles.get(readerIndex); String outStem = "trimmed_" + seqFile.getName().substring(0, seqFile.getName().lastIndexOf(".")); if (writeFasta) { fastaOut = new FastaWriter(outStem + ".fasta"); } else { fastqOut = new FastqWriter(outStem + ".fastq", FastqCore.Phred33QualFunction); } int[] lengthHisto = new int[200]; SeqReader reader = readers.get(readerIndex); QSequence qseq; long totalLength = 0; int totalSeqs = 0; long trimmedLength = 0; int trimmedSeqs = 0; int zeroLengthAfterTrimming = 0; long startTime = System.currentTimeMillis(); while ((qseq = (QSequence) reader.readNextSequence()) != null) { char[] bases = qseq.getSeqString().toCharArray(); byte[] qual = qseq.getQuality(); if (bases.length != qual.length) { System.err.println(qseq.getSeqName() + ": Quality length doesn't match seq length for seq"); continue; } totalSeqs++; totalLength += bases.length; int trimIndex = -1; if (illumina && qual[bases.length - 1] == qualTrim) { trimIndex = bases.length - 1; while (trimIndex >= 0 && qual[trimIndex] == qualTrim) { trimIndex--; } trimIndex++; //Technically we're positioned over the first good base, move back to the last bad base } else if (!illumina) { for (int index = 0; index < bases.length; index++) { if (qual[index] == qualTrim || (trimle && qual[index] < qualTrim)) { trimIndex = index; break; } } } String outSeq; byte[] outQual; if (trimIndex == -1) { outSeq = qseq.getSeqString(); outQual = qseq.getQuality(); } else { outSeq = new String(bases, 0, trimIndex); outQual = Arrays.copyOfRange(qual, 0, trimIndex); trimmedSeqs++; } int len = outSeq.length(); trimmedLength += len; if (len >= lengthHisto.length) { lengthHisto = Arrays.copyOf(lengthHisto, len + 1); } lengthHisto[len]++; if (outSeq.length() == 0) { //System.err.println(qseq.getSeqName() + ": length 0 after trimming"); zeroLengthAfterTrimming++; continue; } if (writeFasta) { fastaOut.writeSeq(qseq.getSeqName(), qseq.getDesc(), outSeq); } else { fastqOut.writeSeq(qseq.getSeqName(), qseq.getDesc(), outSeq, outQual); } } reader.close(); if (writeFasta) { fastaOut.close(); } else { fastqOut.close(); } System.out.println( "Processed " + seqFile + " in " + (System.currentTimeMillis() - startTime) / 1000.0 + "s"); System.out.println("Before trimming:"); System.out.println("Total Sequences: " + totalSeqs); System.out.println("Total Sequence Data: " + totalLength); System.out.println("Average sequence length: " + ((float) totalLength / totalSeqs)); System.out.println(); System.out.println("After trimming:"); System.out.println("Total Sequences: " + (totalSeqs - zeroLengthAfterTrimming)); System.out.println("Sequences Trimmed: " + trimmedSeqs); System.out.println("Total Sequence Data: " + trimmedLength); System.out.println("Average sequence length: " + ((float) trimmedLength / (totalSeqs - zeroLengthAfterTrimming))); System.out.println(); System.out.println("Length\tCount"); for (int index = 0; index < lengthHisto.length; index++) { if (lengthHisto[index] == 0) { continue; } System.out.println(index + "\t" + lengthHisto[index]); } System.out.println(); System.out.println(); System.out.println(); } }
From source file:com.genentech.chemistry.openEye.apps.enumerate.SDFEnumerator.java
public static void main(String... args) throws IOException { Options options = new Options(); Option opt = new Option("out", true, "output file oe-supported"); opt.setRequired(true);//ww w . ja v a 2s. c o m options.addOption(opt); opt = new Option("hydrogenExplicit", false, "Use explicit hydrogens"); options.addOption(opt); opt = new Option("correctValences", false, "Correct valences after the enumeration"); options.addOption(opt); opt = new Option("regenerate2D", false, "Regenerate 2D coordinates for the products"); options.addOption(opt); opt = new Option("reactAllSites", false, "Generate a product for each match in a reagent."); options.addOption(opt); opt = new Option("randomFraction", true, "Only output a fraction of the products."); options.addOption(opt); opt = new Option("maxAtoms", true, "Only output products with <= maxAtoms."); options.addOption(opt); opt = new Option("notReacted", true, "Output file for reagents that didn't produce at leaste one output molecule, useful for debugging SMIRKS."); 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 < 2) { exitWithHelp("Transformation and/or reagentFiles missing", options); } String smirks = args[0]; if (new File(smirks).canRead()) smirks = IOUtil.fileToString(smirks).trim(); if (!smirks.contains(">>")) smirks = scaffoldToSmirks(smirks); String[] reagentSmiOrFiles = Arrays.copyOfRange(args, 1, args.length); if (cmd.hasOption("d")) { System.err.println("Start debugger and press return:"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } String outFile = cmd.getOptionValue("out"); OELibraryGen lg = new OELibraryGen(); lg.Init(smirks); if (!lg.IsValid()) exitWithHelp("Invalid Transform: " + smirks, options); lg.SetExplicitHydrogens(cmd.hasOption("hydrogenExplicit")); lg.SetValenceCorrection(cmd.hasOption("correctValences")); lg.SetRemoveUnmappedFragments(true); boolean regenerate2D = cmd.hasOption("regenerate2D"); boolean reactAllSites = cmd.hasOption("reactAllSites"); String unreactedFile = null; if (cmd.hasOption("notReacted")) { unreactedFile = cmd.getOptionValue("notReacted"); } double randomFract = 2; if (cmd.hasOption("randomFraction")) randomFract = Double.parseDouble(cmd.getOptionValue("randomFraction")); int maxAtoms = 0; if (cmd.hasOption("maxAtoms")) maxAtoms = Integer.parseInt(cmd.getOptionValue("maxAtoms")); SDFEnumerator en = new SDFEnumerator(lg, reactAllSites, reagentSmiOrFiles); en.generateLibrary(outFile, maxAtoms, randomFract, regenerate2D, unreactedFile); en.delete(); }
From source file:com.act.lcms.AnimateNetCDFAroundMass.java
public static void main(String[] args) throws Exception { if (args.length < 7 || !areNCFiles(Arrays.copyOfRange(args, 5, args.length))) { throw new RuntimeException( "Needs: \n" + "(1) mass value, e.g., 132.0772 \n" + "(2) time value, e.g., 39.2, (seconds), \n" + "(3) minimum Mz Precision, 0.04 \n" + "(4) max z axis, e.g., 20000 \n" + "(5) prefix for .data and rendered .pdf \n" + "(6..) 2 or more NetCDF .nc files"); }/*from w ww.j av a 2 s.c om*/ Double mz = Double.parseDouble(args[0]); Double time = Double.parseDouble(args[1]); Double minMzPrecision = Double.parseDouble(args[2]); Double maxZAxis = Double.parseDouble(args[3]); String outPrefix = args[4]; // the mz values go from 50-950, we start with a big window and exponentially narrow down double mzWin = 100; // time values go from 0-450, we start with a big window and exponentially narrow down double timeWin = 50; // the factor by which to zoom in every step (has to be >1, a value of 2 is good) double factor = 1.2; // the animation frame count int frame = 1; AnimateNetCDFAroundMass c = new AnimateNetCDFAroundMass(); String[] netCDFFnames = Arrays.copyOfRange(args, 5, args.length); List<List<XYZ>> spectra = c.getSpectra(netCDFFnames, time, timeWin, mz, mzWin); for (List<XYZ> s : spectra) { System.out.format("%d xyz datapoints in (initial narrowed) spectra\n", s.size()); } String[] labels = new String[netCDFFnames.length]; for (int i = 0; i < labels.length; i++) labels[i] = "Dataset: " + i; // you could set labels to netCDFFnames to get precise labels on the graphs Gnuplotter plotter = new Gnuplotter(); String fmt = "png"; List<String> outImgFiles = new ArrayList<>(), outDataFiles = new ArrayList<>(); while (mzWin > minMzPrecision) { // exponentially narrow windows down mzWin /= factor; timeWin /= factor; List<List<XYZ>> windowedSpectra = c.getSpectraInWindowAll(spectra, time, timeWin, mz, mzWin); String frameid = String.format("%03d", frame); String outPDF = outPrefix + frameid + "." + fmt; String outDATA = outPrefix + frameid + ".data"; outImgFiles.add(outPDF); outDataFiles.add(outDATA); frame++; // Write data output to outfile PrintStream out = new PrintStream(new FileOutputStream(outDATA)); // print out the spectra to outDATA for (List<XYZ> windowOfSpectra : windowedSpectra) { for (XYZ xyz : windowOfSpectra) { out.format("%.4f\t%.4f\t%.4f\n", xyz.time, xyz.mz, xyz.intensity); out.flush(); } // delimit this dataset from the rest out.print("\n\n"); } // close the .data out.close(); // render outDATA to outPDF using gnuplot plotter.plotMulti3D(outDATA, outPDF, fmt, labels, maxZAxis); } String outImgs = outPrefix + "*." + fmt; plotter.makeAnimatedGIF(outImgs, outPrefix + ".gif"); // all the frames are now in the animated gif, remove the intermediate files for (String f : outDataFiles) new File(f).delete(); for (String f : outImgFiles) new File(f).delete(); }
From source file:net.orzo.App.java
/** * *//*from w ww. j a v a 2 s . co m*/ public static void main(final String[] args) { final App app = new App(); Logger log = null; CommandLine cmd; try { cmd = app.init(args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "orzo [options] user_script [user_arg1 [user_arg2 [...]]]\n(to generate a template: orzo -t [file path])", app.cliOptions); } else if (cmd.hasOption("v")) { System.out.printf("Orzo.js version %s\n", app.props.get("orzo.version")); } else if (cmd.hasOption("t")) { String templateSrc = new ResourceLoader().getResourceAsString("net/orzo/template1.js"); File tplFile = new File(cmd.getOptionValue("t")); FileWriter tplWriter = new FileWriter(tplFile); tplWriter.write(templateSrc); tplWriter.close(); File dtsFile = new File( String.format("%s/orzojs.d.ts", new File(tplFile.getAbsolutePath()).getParent())); FileWriter dtsWriter = new FileWriter(dtsFile); String dtsSrc = new ResourceLoader().getResourceAsString("net/orzo/orzojs.d.ts"); dtsWriter.write(dtsSrc); dtsWriter.close(); } else if (cmd.hasOption("T")) { String templateSrc = new ResourceLoader().getResourceAsString("net/orzo/template1.js"); System.out.println(templateSrc); } else { // Logger initialization if (cmd.hasOption("g")) { System.setProperty("logback.configurationFile", cmd.getOptionValue("g")); } else { System.setProperty("logback.configurationFile", "./logback.xml"); } log = LoggerFactory.getLogger(App.class); if (cmd.hasOption("s")) { // Orzo.js as a REST and AMQP service FullServiceConfig conf = new Gson().fromJson(new FileReader(cmd.getOptionValue("s")), FullServiceConfig.class); Injector injector = Guice.createInjector(new CoreModule(conf), new RestServletModule()); HttpServer httpServer = new HttpServer(conf, new JerseyGuiceServletConfig(injector)); app.services.add(httpServer); if (conf.getAmqpResponseConfig() != null) { // response AMQP service must be initialized before receiving one app.services.add(injector.getInstance(AmqpResponseConnection.class)); } if (conf.getAmqpConfig() != null) { app.services.add(injector.getInstance(AmqpConnection.class)); app.services.add(injector.getInstance(AmqpService.class)); } if (conf.getRedisConf() != null) { app.services.add(injector.getInstance(RedisStorage.class)); } Runtime.getRuntime().addShutdownHook(new ShutdownHook(app)); app.startServices(); } else if (cmd.hasOption("d")) { // Demo mode final String scriptId = "demo"; final SourceCode demoScript = SourceCode.fromResource(DEMO_SCRIPT); System.err.printf("Running demo script %s.", demoScript.getName()); CmdConfig conf = new CmdConfig(scriptId, demoScript, null, cmd.getOptionValue("p", null)); TaskManager tm = new TaskManager(conf); tm.startTaskSync(tm.registerTask(scriptId, new String[0])); } else if (cmd.getArgs().length > 0) { // Command line mode File userScriptFile = new File(cmd.getArgs()[0]); String optionalModulesPath = null; String[] inputValues; SourceCode userScript; // custom CommonJS modules path if (cmd.hasOption("m")) { optionalModulesPath = cmd.getOptionValue("m"); } if (cmd.getArgs().length > 0) { inputValues = Arrays.copyOfRange(cmd.getArgs(), 1, cmd.getArgs().length); } else { inputValues = new String[0]; } userScript = SourceCode.fromFile(userScriptFile); CmdConfig conf = new CmdConfig(userScript.getName(), userScript, optionalModulesPath, cmd.getOptionValue("p", null)); TaskManager tm = new TaskManager(conf); String taskId = tm.registerTask(userScript.getName(), inputValues); tm.startTaskSync(taskId); if (tm.getTask(taskId).getStatus() == TaskStatus.ERROR) { tm.getTask(taskId).getFirstError().getErrors().stream().forEach(System.err::println); } } else { System.err.println("Invalid parameters. Try -h for more information."); System.exit(1); } } } catch (Exception ex) { System.err.printf("Orzo.js crashed with error: %s\nSee the log for details.\n", ex.getMessage()); if (log != null) { log.error(ex.getMessage(), ex); } else { ex.printStackTrace(); } } }