List of usage examples for java.io InputStreamReader InputStreamReader
public InputStreamReader(InputStream in)
From source file:com.act.biointerpretation.BiointerpretationDriver.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/*from ww w.ja va2 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(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(ReactionDesalter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } if (cl.hasOption(OPTION_CONFIGURATION_FILE)) { List<BiointerpretationStep> steps; File configFile = new File(cl.getOptionValue(OPTION_CONFIGURATION_FILE)); if (!configFile.exists()) { String msg = String.format("Cannot find configuration file at %s", configFile.getAbsolutePath()); LOGGER.error(msg); throw new RuntimeException(msg); } // Read the whole config file. try (InputStream is = new FileInputStream(configFile)) { steps = OBJECT_MAPPER.readValue(is, new TypeReference<List<BiointerpretationStep>>() { }); } catch (IOException e) { LOGGER.error("Caught IO exception when attempting to read configuration file: %s", e.getMessage()); throw e; // Crash after logging if the config file can't be read. } // Ask for explicit confirmation before dropping databases. LOGGER.info("Biointerpretation plan:"); for (BiointerpretationStep step : steps) { crashIfInvalidDBName(step.getReadDBName()); crashIfInvalidDBName(step.getWriteDBName()); LOGGER.info("%s: %s -> %s", step.getOperation(), step.getReadDBName(), step.getWriteDBName()); } LOGGER.warn("WARNING: each DB to be written will be dropped before the writing step commences"); LOGGER.info("Proceed? [y/n]"); String readLine; try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { readLine = reader.readLine(); } readLine.trim(); if ("y".equalsIgnoreCase(readLine) || "yes".equalsIgnoreCase(readLine)) { LOGGER.info("Biointerpretation plan confirmed, commencing"); for (BiointerpretationStep step : steps) { performOperation(step, true); } LOGGER.info("Biointerpretation plan completed"); } else { LOGGER.info("Biointerpretation plan not confirmed, exiting"); } } else if (cl.hasOption(OPTION_SINGLE_OPERATION)) { if (!cl.hasOption(OPTION_SINGLE_READ_DB) || !cl.hasOption(OPTION_SINGLE_WRITE_DB)) { String msg = "Must specify read and write DB names when performing a single operation"; LOGGER.error(msg); throw new RuntimeException(msg); } BiointerpretationOperation operation; try { operation = BiointerpretationOperation.valueOf(cl.getOptionValue(OPTION_SINGLE_OPERATION)); } catch (IllegalArgumentException e) { LOGGER.error("Caught IllegalArgumentException when trying to parse operation '%s': %s", cl.getOptionValue(OPTION_SINGLE_OPERATION), e.getMessage()); throw e; // Crash if we can't interpret the operation. } String readDB = crashIfInvalidDBName(cl.getOptionValue(OPTION_SINGLE_READ_DB)); String writeDB = crashIfInvalidDBName(cl.getOptionValue(OPTION_SINGLE_WRITE_DB)); performOperation(new BiointerpretationStep(operation, readDB, writeDB), false); } else { String msg = "Must specify either a config file or a single operation to perform."; LOGGER.error(msg); throw new RuntimeException(msg); } }
From source file:com.aestel.chemistry.openEye.fp.Fingerprinter.java
public static void main(String... args) throws IOException { long start = System.currentTimeMillis(); long iCounter = 0; // create command line Options object Options options = new Options(); Option opt = new Option("in", true, "input file [.ism,.sdf,...]"); opt.setRequired(true);// w w w .j ava 2s.c o m options.addOption(opt); opt = new Option("out", true, "output file .tsv or oe-supported"); opt.setRequired(true); options.addOption(opt); opt = new Option("idTag", true, "field with ID (default title)"); opt.setRequired(false); options.addOption(opt); opt = new Option("fpType", true, "fingerPrintType: maccs|linear7|linear7*4|HashLinear7*4\n" + " maccs: generate maccs keys\n" + " linear7 generate 7 bonds long linear fingerprints (210k known rest hashed)\n" + " linear7*4 linear 7 bonds if more than 4 atoms code atoms as * (5.1k known rest hashed)\n" + " HashLinear7*4: as linear7*4 but hashed to 16k"); opt.setRequired(true); options.addOption(opt); opt = new Option("format", true, "folded512|folded2048|bitList|fragList|none\n" + " folded512/2048: hex encoded 512/2048 bits\n" + " bitList: list of bitpositions\n" + " none: no fp output for use with writeCodeMap"); opt.setRequired(true); options.addOption(opt); opt = new Option("writeCodeMap", false, "Overwrite the codeMap file at the end of processing"); 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 (cmd.hasOption("d")) { System.err.println("Start debugger and press return:"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } String idTag = null; if (cmd.hasOption("idTag")) idTag = cmd.getOptionValue("idTag"); String outformat = cmd.getOptionValue("format").toLowerCase().intern(); if (args.length != 0) { exitWithHelp(options); } String type = cmd.getOptionValue("fpType"); boolean updateDictionaryFile = cmd.hasOption("writeCodeMap"); boolean hashUnknownFrag = true; if (type.equals("HashLinear7*4")) hashUnknownFrag = false; if (type.equals("maccs")) hashUnknownFrag = false; if (updateDictionaryFile) hashUnknownFrag = false; Fingerprinter fprinter = createFingerprinter(type, updateDictionaryFile, hashUnknownFrag); OEMolBase mol = new OEGraphMol(); String inFile = cmd.getOptionValue("in"); String outFile = cmd.getOptionValue("out"); oemolistream ifs = new oemolistream(inFile); Runtime rt = Runtime.getRuntime(); Outputter out; if (outFile.endsWith(".txt") || outFile.endsWith(".tab")) out = new TabOutputter(fprinter.getMapper(), outFile, outformat); else out = new OEOutputter(fprinter.getMapper(), outFile, type, outformat); while (oechem.OEReadMolecule(ifs, mol)) { iCounter++; Fingerprint fp = fprinter.getFingerprint(mol); String id; if (idTag == null) id = mol.GetTitle(); else id = oechem.OEGetSDData(mol, idTag); if (iCounter % 100 == 0) System.err.print("."); if (iCounter % 4000 == 0) { System.err.printf(" %d %dsec\tt=%d f=%d u=%d m=%d tf=%d\n", iCounter, (System.currentTimeMillis() - start) / 1000, rt.totalMemory() / 1024, rt.freeMemory() / 1024, (rt.totalMemory() - rt.freeMemory()) / 1024, rt.maxMemory() / 1024, (rt.freeMemory() + (rt.maxMemory() - rt.totalMemory())) / 1024); } out.output(id, mol, fp); } System.err.printf("Fingerprinter: Read %d structures in %d sec\n", iCounter, (System.currentTimeMillis() - start) / 1000); if (updateDictionaryFile) fprinter.writeDictionary(); out.close(); fprinter.close(); }
From source file:com.splout.db.dnode.TCPStreamer.java
/** * This main method can be used for testing the TCP interface directly to a * local DNode. Will ask for protocol input from Stdin and print output to * Stdout//from w w w. ja v a 2s . c om */ public static void main(String[] args) throws UnknownHostException, IOException, SerializationException { SploutConfiguration config = SploutConfiguration.get(); Socket clientSocket = new Socket("localhost", config.getInt(DNodeProperties.STREAMING_PORT)); DataInputStream inFromServer = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream())); DataOutputStream outToServer = new DataOutputStream( new BufferedOutputStream(clientSocket.getOutputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter tablespace: "); String tablespace = reader.readLine(); System.out.println("Enter version number: "); long versionNumber = Long.parseLong(reader.readLine()); System.out.println("Enter partition: "); int partition = Integer.parseInt(reader.readLine()); System.out.println("Enter query: "); String query = reader.readLine(); outToServer.writeUTF(tablespace); outToServer.writeLong(versionNumber); outToServer.writeInt(partition); outToServer.writeUTF(query); outToServer.flush(); byte[] buffer = new byte[0]; boolean read; do { read = false; int nBytes = inFromServer.readInt(); if (nBytes > 0) { buffer = new byte[nBytes]; int inRead = inFromServer.read(buffer); if (inRead > 0) { Object[] res = ResultSerializer.deserialize(ByteBuffer.wrap(buffer), Object[].class); read = true; System.out.println(Arrays.toString(res)); } } } while (read); clientSocket.close(); }
From source file:edu.cmu.lti.oaqa.knn4qa.apps.ExtractDataAndQueryAsSparseVectors.java
public static void main(String[] args) { String optKeys[] = { CommonParams.MAX_NUM_QUERY_PARAM, MAX_NUM_DATA_PARAM, CommonParams.MEMINDEX_PARAM, IN_QUERIES_PARAM, OUT_QUERIES_PARAM, OUT_DATA_PARAM, TEXT_FIELD_PARAM, TEST_QTY_PARAM, }; String optDescs[] = { CommonParams.MAX_NUM_QUERY_DESC, MAX_NUM_DATA_DESC, CommonParams.MEMINDEX_DESC, IN_QUERIES_DESC, OUT_QUERIES_DESC, OUT_DATA_DESC, TEXT_FIELD_DESC, TEST_QTY_DESC }; boolean hasArg[] = { true, true, true, true, true, true, true, true }; ParamHelper prmHlp = null;/*from w w w . j av a 2 s . com*/ try { prmHlp = new ParamHelper(args, optKeys, optDescs, hasArg); CommandLine cmd = prmHlp.getCommandLine(); Options opt = prmHlp.getOptions(); int maxNumQuery = Integer.MAX_VALUE; String tmpn = cmd.getOptionValue(CommonParams.MAX_NUM_QUERY_PARAM); if (tmpn != null) { try { maxNumQuery = Integer.parseInt(tmpn); } catch (NumberFormatException e) { UsageSpecify(CommonParams.MAX_NUM_QUERY_PARAM, opt); } } int maxNumData = Integer.MAX_VALUE; tmpn = cmd.getOptionValue(MAX_NUM_DATA_PARAM); if (tmpn != null) { try { maxNumData = Integer.parseInt(tmpn); } catch (NumberFormatException e) { UsageSpecify(MAX_NUM_DATA_PARAM, opt); } } String memIndexPref = cmd.getOptionValue(CommonParams.MEMINDEX_PARAM); if (null == memIndexPref) { UsageSpecify(CommonParams.MEMINDEX_PARAM, opt); } String textField = cmd.getOptionValue(TEXT_FIELD_PARAM); if (null == textField) { UsageSpecify(TEXT_FIELD_PARAM, opt); } textField = textField.toLowerCase(); int fieldId = -1; for (int i = 0; i < FeatureExtractor.mFieldNames.length; ++i) if (FeatureExtractor.mFieldNames[i].compareToIgnoreCase(textField) == 0) { fieldId = i; break; } if (-1 == fieldId) { Usage("Wrong field index, should be one of the following: " + String.join(",", FeatureExtractor.mFieldNames), opt); } InMemForwardIndex indx = new InMemForwardIndex( FeatureExtractor.indexFileName(memIndexPref, FeatureExtractor.mFieldNames[fieldId])); BM25SimilarityLucene bm25simil = new BM25SimilarityLucene(FeatureExtractor.BM25_K1, FeatureExtractor.BM25_B, indx); String inQueryFile = cmd.getOptionValue(IN_QUERIES_PARAM); String outQueryFile = cmd.getOptionValue(OUT_QUERIES_PARAM); if ((inQueryFile == null) != (outQueryFile == null)) { Usage("You should either specify both " + IN_QUERIES_PARAM + " and " + OUT_QUERIES_PARAM + " or none of them", opt); } String outDataFile = cmd.getOptionValue(OUT_DATA_PARAM); tmpn = cmd.getOptionValue(TEST_QTY_PARAM); int testQty = 0; if (tmpn != null) { try { testQty = Integer.parseInt(tmpn); } catch (NumberFormatException e) { UsageSpecify(TEST_QTY_PARAM, opt); } } ArrayList<DocEntry> testDocEntries = new ArrayList<DocEntry>(); ArrayList<DocEntry> testQueryEntries = new ArrayList<DocEntry>(); ArrayList<TrulySparseVector> testDocVectors = new ArrayList<TrulySparseVector>(); ArrayList<TrulySparseVector> testQueryVectors = new ArrayList<TrulySparseVector>(); if (outDataFile != null) { BufferedWriter out = new BufferedWriter( new OutputStreamWriter(CompressUtils.createOutputStream(outDataFile))); ArrayList<DocEntryExt> docEntries = indx.getDocEntries(); for (int id = 0; id < Math.min(maxNumData, docEntries.size()); ++id) { DocEntry e = docEntries.get(id).mDocEntry; TrulySparseVector v = bm25simil.getDocSparseVector(e, false); if (id < testQty) { testDocEntries.add(e); testDocVectors.add(v); } outputVector(out, v); } out.close(); } Splitter splitOnSpace = Splitter.on(' ').trimResults().omitEmptyStrings(); if (outQueryFile != null) { BufferedReader inpText = new BufferedReader( new InputStreamReader(CompressUtils.createInputStream(inQueryFile))); BufferedWriter out = new BufferedWriter( new OutputStreamWriter(CompressUtils.createOutputStream(outQueryFile))); String queryText = XmlHelper.readNextXMLIndexEntry(inpText); for (int queryQty = 0; queryText != null && queryQty < maxNumQuery; queryText = XmlHelper .readNextXMLIndexEntry(inpText), queryQty++) { Map<String, String> queryFields = null; // 1. Parse a query try { queryFields = XmlHelper.parseXMLIndexEntry(queryText); } catch (Exception e) { System.err.println("Parsing error, offending QUERY:\n" + queryText); throw new Exception("Parsing error."); } String fieldText = queryFields.get(FeatureExtractor.mFieldsSOLR[fieldId]); if (fieldText == null) { fieldText = ""; } ArrayList<String> tmpa = new ArrayList<String>(); for (String s : splitOnSpace.split(fieldText)) tmpa.add(s); DocEntry e = indx.createDocEntry(tmpa.toArray(new String[tmpa.size()])); TrulySparseVector v = bm25simil.getDocSparseVector(e, true); if (queryQty < testQty) { testQueryEntries.add(e); testQueryVectors.add(v); } outputVector(out, v); } out.close(); } int testedQty = 0, diffQty = 0; // Now let's do some testing for (int iq = 0; iq < testQueryEntries.size(); ++iq) { DocEntry queryEntry = testQueryEntries.get(iq); TrulySparseVector queryVector = testQueryVectors.get(iq); for (int id = 0; id < testDocEntries.size(); ++id) { DocEntry docEntry = testDocEntries.get(id); TrulySparseVector docVector = testDocVectors.get(id); float val1 = bm25simil.compute(queryEntry, docEntry); float val2 = TrulySparseVector.scalarProduct(queryVector, docVector); ++testedQty; if (Math.abs(val1 - val2) > 1e5) { System.err.println( String.format("Potential mismatch BM25=%f <-> scalar product=%f", val1, val2)); ++diffQty; } } } if (testedQty > 0) System.out.println(String.format("Tested %d Mismatched %d", testedQty, diffQty)); } catch (ParseException e) { Usage("Cannot parse arguments: " + e, prmHlp != null ? prmHlp.getOptions() : null); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); System.err.println("Terminating due to an exception: " + e); System.exit(1); } }
From source file:licenseUtil.LicenseUtil.java
public static void main(String[] args) throws IOException, IncompleteLicenseObjectException { if (args.length == 0) { logger.error("Missing parameters. Use --help to get a list of the possible options."); } else if (args[0].equals("--addPomToTsv")) { if (args.length < 4) logger.error(//from ww w .j ava 2 s. co m "Missing arguments for option --addPomToTsv. Please specify <pomFileName> <licenses.stub.tsv> <currentVersion> or use the option --help for further information."); String pomFN = args[1]; String spreadSheetFN = args[2]; String currentVersion = args[3]; MavenProject project = null; try { project = Utils.readPom(new File(pomFN)); } catch (XmlPullParserException e) { logger.error("Could not parse pom file: \"" + pomFN + "\""); } LicensingList licensingList = new LicensingList(); File f = new File(spreadSheetFN); if (f.exists() && !f.isDirectory()) { licensingList.readFromSpreadsheet(spreadSheetFN); } licensingList.addMavenProject(project, currentVersion); licensingList.writeToSpreadsheet(spreadSheetFN); } else if (args[0].equals("--writeLicense3rdParty")) { if (args.length < 4) logger.error( "Missing arguments for option --writeLicense3rdParty. Please provide <licenses.enhanced.tsv> <processModule> <currentVersion> [and <targetDir>] or use the option --help for further information."); String spreadSheetFN = args[1]; String processModule = args[2]; String currentVersion = args[3]; HashMap<String, String> targetDirs = new HashMap<>(); if (args.length > 4) { File targetDir = new File(args[4]); logger.info("scan pom files in direct subdirectories of \"" + targetDir.getPath() + "\" to obtain target locations for 3rd party license files..."); File[] subdirs = targetDir.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY); for (File subdir : subdirs) { File pomFile = new File(subdir.getPath() + File.separator + POM_FN); if (!pomFile.exists()) continue; MavenProject mavenProject; try { mavenProject = Utils.readPom(pomFile); } catch (Exception e) { logger.warn("Could not read from pom file: \"" + pomFile.getPath() + "\" because of " + e.getMessage()); continue; } targetDirs.put(mavenProject.getModel().getArtifactId(), subdir.getAbsolutePath()); } } LicensingList licensingList = new LicensingList(); licensingList.readFromSpreadsheet(spreadSheetFN); if (processModule.toUpperCase().equals("ALL")) { for (String module : licensingList.getNonFixedHeaders()) { try { writeLicense3rdPartyFile(module, licensingList, currentVersion, targetDirs.get(module)); } catch (NoLicenseTemplateSetException e) { logger.error("Could not write file for module \"" + module + "\". There is no template specified for \"" + e.getLicensingObject() + "\". Please add an existing template filename to the column \"" + LicensingObject.ColumnHeader.LICENSE_TEMPLATE.value() + "\" of \"" + spreadSheetFN + "\"."); } } } else { try { writeLicense3rdPartyFile(processModule, licensingList, currentVersion, targetDirs.get(processModule)); } catch (NoLicenseTemplateSetException e) { logger.error("Could not write file for module \"" + processModule + "\". There is no template specified for \"" + e.getLicensingObject() + "\". Please add an existing template filename to the column \"" + LicensingObject.ColumnHeader.LICENSE_TEMPLATE.value() + "\" of \"" + spreadSheetFN + "\"."); } } } else if (args[0].equals("--buildEffectivePom")) { Utils.writeEffectivePom(new File(args[1]), (new File(EFFECTIVE_POM_FN)).getAbsolutePath()); } else if (args[0].equals("--updateTsvWithProjectsInFolder")) { if (args.length < 4) logger.error( "Missing arguments for option --processProjectsInFolder. Please provide <superDirectory> <licenses.stub.tsv> and <currentVersion> or use the option --help for further information."); File directory = new File(args[1]); String spreadSheetFN = args[2]; String currentVersion = args[3]; LicensingList licensingList = new LicensingList(); File f = new File(spreadSheetFN); if (f.exists() && !f.isDirectory()) { licensingList.readFromSpreadsheet(spreadSheetFN); } licensingList.addAll(processProjectsInFolder(directory, currentVersion, false)); licensingList.writeToSpreadsheet(spreadSheetFN); } else if (args[0].equals("--purgeTsv")) { if (args.length < 3) logger.error( "Missing arguments for option --purgeTsv. Please provide <spreadSheetIN.tsv>, <spreadSheetOUT.tsv> and <currentVersion> or use the option --help for further information."); String spreadSheetIN = args[1]; String spreadSheetOUT = args[2]; String currentVersion = args[3]; LicensingList licensingList = new LicensingList(); licensingList.readFromSpreadsheet(spreadSheetIN); licensingList.purge(currentVersion); licensingList.writeToSpreadsheet(spreadSheetOUT); } else if (args[0].equals("--help")) { InputStream in = LicenseUtil.class.getClassLoader().getResourceAsStream(README_PATH); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } else { logger.error("Unknown parameter: " + args[0] + ". Use --help to get a list of the possible options."); } }
From source file:com.genentech.chemistry.tool.mm.SDFMMMinimize.java
/** * Main function for running on the command line * @param args//from w ww .jav a 2 s.co m */ public static void main(String... args) throws IOException { // Get the available options from the programs Map<String, List<String>> allowedProgramsAndForceFields = getAllowedProgramsAndForceFields(); Map<String, List<String>> allowedProgramsAndSolvents = getAllowedProgramsAndSolvents(); // create command line Options object Options options = new Options(); Option opt = new Option(OPT_INFILE, true, "input file oe-supported Use .sdf|.smi to specify the file type."); opt.setRequired(true); options.addOption(opt); opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type."); opt.setRequired(true); options.addOption(opt); StringBuilder programOptions = new StringBuilder("Program to use for minimization. Choices are\n"); for (String program : allowedProgramsAndForceFields.keySet()) { programOptions.append("\n*** -program " + program + " ***\n"); String forcefields = ""; for (String option : allowedProgramsAndForceFields.get(program)) { forcefields += option + " "; } programOptions.append("-forcefield " + forcefields + "\n"); String solvents = ""; for (String option : allowedProgramsAndSolvents.get(program)) { solvents += option + " "; } programOptions.append("-solvent " + solvents + "\n"); } opt = new Option(OPT_PROGRAM, true, programOptions.toString()); opt.setRequired(true); options.addOption(opt); opt = new Option(OPT_FORCEFIELD, true, "Forcefield options. See -program for choices"); opt.setRequired(false); options.addOption(opt); opt = new Option(OPT_SOLVENT, true, "Solvent options. See -program for choices"); opt.setRequired(false); options.addOption(opt); opt = new Option(OPT_FIXED_ATOM_TAG, true, "SD tag name which contains the atom numbers to be held fixed."); opt.setRequired(false); options.addOption(opt); opt = new Option(OPT_FIX_TORSION, true, "true/false. if true, the atoms in fixedAtomTag contains 4 indices of atoms defining a torsion angle to be held fixed"); opt.setRequired(false); options.addOption(opt); opt = new Option(OPT_WORKING_DIR, true, "Working directory to put files."); 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) { System.err.println("Unknown arguments" + args); exitWithHelp(options); } if (cmd.hasOption("d")) { System.err.println("Start debugger and press return:"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } String inFile = cmd.getOptionValue(OPT_INFILE); String outFile = cmd.getOptionValue(OPT_OUTFILE); String fixedAtomTag = cmd.getOptionValue(OPT_FIXED_ATOM_TAG); boolean fixTorsion = (cmd.getOptionValue(OPT_FIX_TORSION) != null && cmd.getOptionValue(OPT_FIX_TORSION).equalsIgnoreCase("true")); String programName = cmd.getOptionValue(OPT_PROGRAM); String forcefield = cmd.getOptionValue(OPT_FORCEFIELD); String solvent = cmd.getOptionValue(OPT_SOLVENT); String workDir = cmd.getOptionValue(OPT_WORKING_DIR); if (workDir == null || workDir.trim().length() == 0) workDir = "."; // Create a minimizer SDFMMMinimize minimizer = new SDFMMMinimize(); minimizer.setMethod(programName, forcefield, solvent); minimizer.run(inFile, outFile, fixedAtomTag, fixTorsion, workDir); minimizer.close(); System.err.println("Minimization complete."); }
From source file:eu.scape_project.tb.chutney.ChutneyDriver.java
/** * This main runs only on the local machine when the job is initiated * //from w w w . j ava 2s.c om * @param args command line arguments * @throws ParseException command line parse issue */ @SuppressWarnings("unused") public static void main(String[] args) throws ParseException { System.out.println(Settings.JOB_NAME + "v" + Settings.VERSION); //warning code if (true) { String yes = "YeS"; System.out.println( "WARNING: this code has not been fully tested and it may delete/modify/alter your systems"); System.out.println("You run this development code at your own risk, no liability is assumed"); System.out.print("To continue, type \"" + yes + "\": "); try { String input = new BufferedReader(new InputStreamReader(System.in)).readLine(); if (!input.equals(yes)) { return; } } catch (IOException e1) { return; } } //end of warning code try { ToolRunner.run(new Configuration(), new ChutneyDriver(), args); } catch (Exception e) { e.printStackTrace(); } }
From source file:io.tempra.AppServer.java
public static void main(String[] args) throws Exception { try {/*w ww . j av a 2 s.c o m*/ // String dir = getProperty("storageLocal");// // System.getProperty("user.home"); String arch = "Win" + System.getProperty("sun.arch.data.model"); System.out.println("sun.arch.data.model " + arch); // Sample to force java load dll or so on a filesystem // InputStream in = AppServer.class.getResourceAsStream("/dll/" + // arch + "/RechargeRPC.dll"); // // File jCliSiTefI = new File(dir + "/" + "RechargeRPC.dll"); // System.out.println("Writing dll to: " + // jCliSiTefI.getAbsolutePath()); // OutputStream os = new FileOutputStream(jCliSiTefI); // byte[] buffer = new byte[4096]; // int length; // while ((length = in.read(buffer)) > 0) { // os.write(buffer, 0, length); // } // os.close(); // in.close(); // System.load(jCliSiTefI.toString()); // addLibraryPath(dir); } catch (Exception e) { e.printStackTrace(); } ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); Server jettyServer = new Server(Integer.parseInt(getProperty("localport"))); // security configuration // FilterHolder holder = new FilterHolder(CrossOriginFilter.class); // holder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, // "*"); // holder.setInitParameter("allowCredentials", "true"); // holder.setInitParameter( // CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*"); // holder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, // "GET,POST,HEAD"); // holder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, // "X-Requested-With,Content-Type,Accept,Origin"); // holder.setName("cross-origin"); // context.addFilter(holder, fm); ResourceHandler resource_handler = new ResourceHandler(); // add application on embedded server boolean servApp = true; boolean quioskMode = false; // if (System.getProperty("noServApp") != null ) // if (System.getProperty("noServApp").equalsIgnoreCase("true")) // servApp = false; if (servApp) { // ProtectionDomain domain = AppServer.class.getProtectionDomain(); String webDir = AppServer.class.getResource("/webapp").toExternalForm(); System.out.println("Jetty WEB DIR >>>>" + webDir); resource_handler.setDirectoriesListed(true); resource_handler.setWelcomeFiles(new String[] { "index.html" }); resource_handler.setResourceBase(webDir); // // "C:/git/tsAgenciaVirtual/www/"); // resource_handler.setResourceBase("C:/git/tsAgenciaVirtual/www/"); // copyJarResourceToFolder((JarURLConnection) AppServer.class // .getResource("/app").openConnection(), createTempDir("app")); // resource_handler.setResourceBase(System // .getProperty("java.io.tmpdir") + "/app"); } // sample to add rest services on container context.addServlet(FileUploadServlet.class, "/upload"); ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/services/*"); jerseyServlet.setInitOrder(0); jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", RestServices.class.getCanonicalName() + "," + RestServices.class.getCanonicalName()); HandlerList handlers = new HandlerList(); // context.addFilter(holder, "/*", EnumSet.of(DispatcherType.REQUEST)); handlers.setHandlers(new Handler[] { resource_handler, context, // wscontext, new DefaultHandler() }); jettyServer.setHandler(handlers); try { // Initialize javax.websocket layer ServerContainer wscontainer = WebSocketServerContainerInitializer.configureContext(context); wscontainer.setDefaultMaxSessionIdleTimeout(TimeUnit.HOURS.toMillis(1000)); // Add WebSocket endpoint to javax.websocket layer wscontainer.addEndpoint(FileUpload.class); } catch (Throwable t) { t.printStackTrace(System.err); } // try { jettyServer.start(); jettyServer.dump(System.err); if (servApp && quioskMode) { try { Process process = new ProcessBuilder( "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", "--kiosk", "--kiosk-printing", "--auto", "--disable-pinch", "--incognito", "--disable-session-crashed-bubble", "--overscroll-history-navigation=0", "http://localhost:" + getProperty("localport")).start(); // Process process = // Runtime.getRuntime().exec(" -kiosk http://localhost:8080"); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; System.out.printf("Output of running %s is:", Arrays.toString(args)); while ((line = br.readLine()) != null) { System.out.println(line); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } // } finally { // jettyServer.destroy(); // }//} jettyServer.join(); }
From source file:com.bluemarsh.jswat.console.Main.java
/** * Kicks off the application./*from w w w . ja v a 2s . co m*/ * * @param args the command line arguments. */ public static void main(String[] args) { // // An attempt was made early on to use the Console class in java.io, // but that is not designed to handle asynchronous output from // multiple threads, so we just use the usual System.out for output // and System.in for input. Note that automatic flushing is used to // ensure output is shown in a timely fashion. // // // Where console mode seems to work: // - bash // - emacs // // Where console mode does not seem to work: // - NetBeans: output from event listeners is never shown and the // cursor sometimes lags behind the output // // Turn on flushing so printing the prompt will flush // all buffered output generated from other threads. PrintWriter output = new PrintWriter(System.out, true); // Make sure we have the JPDA classes. try { Bootstrap.virtualMachineManager(); } catch (NoClassDefFoundError ncdfe) { output.println(NbBundle.getMessage(Main.class, "MSG_Main_NoJPDA")); System.exit(1); } // Ensure we can create the user directory by requesting the // platform service. Simply asking for it has the desired effect. PlatformProvider.getPlatformService(); // Define the logging configuration. LogManager manager = LogManager.getLogManager(); InputStream is = Main.class.getResourceAsStream("logging.properties"); try { manager.readConfiguration(is); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(1); } // Print out some useful debugging information. logSystemDetails(); // Add a shutdown hook to make sure we exit cleanly. Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { // Save the command aliases. CommandParser parser = CommandProvider.getCommandParser(); parser.saveSettings(); // Save the runtimes to persistent storage. RuntimeManager rm = RuntimeProvider.getRuntimeManager(); rm.saveRuntimes(); // Save the sessions to persistent storage and have them // close down in preparation to exit. SessionManager sm = SessionProvider.getSessionManager(); sm.saveSessions(true); } })); // Initialize the command parser and load the aliases. CommandParser parser = CommandProvider.getCommandParser(); parser.loadSettings(); parser.setOutput(output); // Create an OutputAdapter to display debuggee output. OutputAdapter adapter = new OutputAdapter(output); SessionManager sessionMgr = SessionProvider.getSessionManager(); sessionMgr.addSessionManagerListener(adapter); // Create a SessionWatcher to monitor the session status. SessionWatcher swatcher = new SessionWatcher(); sessionMgr.addSessionManagerListener(swatcher); // Create a BreakpointWatcher to monitor the breakpoints. BreakpointWatcher bwatcher = new BreakpointWatcher(); sessionMgr.addSessionManagerListener(bwatcher); // Add the watchers and adapters to the open sessions. Iterator<Session> iter = sessionMgr.iterateSessions(); while (iter.hasNext()) { Session s = iter.next(); s.addSessionListener(adapter); s.addSessionListener(swatcher); } // Find and run the RC file. try { runStartupFile(parser, output); } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); } // Process command line arguments. try { processArguments(args); } catch (ParseException pe) { // Report the problem and keep going. System.err.println("Option parsing failed: " + pe.getMessage()); logger.log(Level.SEVERE, null, pe); } // Display a helpful greeting. output.println(NbBundle.getMessage(Main.class, "MSG_Main_Welcome")); if (jdbEmulationMode) { output.println(NbBundle.getMessage(Main.class, "MSG_Main_Jdb_Emulation")); } // Enter the main loop of processing user input. BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); while (true) { // Keep the prompt format identical to jdb for compatibility // with emacs and other possible wrappers. output.print("> "); output.flush(); try { String command = input.readLine(); // A null value indicates end of stream. if (command != null) { performCommand(output, parser, command); } // Sleep briefly to give the event processing threads, // and the automatic output flushing, a chance to catch // up before printing the input prompt again. Thread.sleep(250); } catch (InterruptedException ie) { logger.log(Level.WARNING, null, ie); } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); output.println(NbBundle.getMessage(Main.class, "ERR_Main_IOError", ioe)); } catch (Exception x) { // Don't ever let an internal bug (e.g. in the command parser) // hork the console, as it really irritates people. logger.log(Level.SEVERE, null, x); output.println(NbBundle.getMessage(Main.class, "ERR_Main_Exception", x)); } } }
From source file:com.vmware.photon.controller.core.Main.java
public static void main(String[] args) throws Throwable { try {//from w ww. j a v a 2 s .co m LoggingFactory.bootstrap(); logger.info("args: " + Arrays.toString(args)); ArgumentParser parser = ArgumentParsers.newArgumentParser("PhotonControllerCore").defaultHelp(true) .description("Photon Controller Core"); parser.addArgument("config-file").help("photon controller configuration file"); parser.addArgument("--manual").type(Boolean.class).setDefault(false) .help("If true, create default deployment."); Namespace namespace = parser.parseArgsOrFail(args); PhotonControllerConfig photonControllerConfig = getPhotonControllerConfig(namespace); DeployerConfig deployerConfig = photonControllerConfig.getDeployerConfig(); new LoggingFactory(photonControllerConfig.getLogging(), "photon-controller-core").configure(); SSLContext sslContext; if (deployerConfig.getDeployerContext().isAuthEnabled()) { sslContext = SSLContext.getInstance(KeyStoreUtils.THRIFT_PROTOCOL); TrustManagerFactory tmf = null; tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance("JKS"); InputStream in = FileUtils .openInputStream(new File(deployerConfig.getDeployerContext().getKeyStorePath())); keyStore.load(in, deployerConfig.getDeployerContext().getKeyStorePassword().toCharArray()); tmf.init(keyStore); sslContext.init(null, tmf.getTrustManagers(), null); } else { KeyStoreUtils.generateKeys("/thrift/"); sslContext = KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL); } ThriftModule thriftModule = new ThriftModule(sslContext); PhotonControllerXenonHost xenonHost = startXenonHost(photonControllerConfig, thriftModule, deployerConfig, sslContext); if ((Boolean) namespace.get("manual")) { DefaultDeployment.createDefaultDeployment(photonControllerConfig.getXenonConfig().getPeerNodes(), deployerConfig, xenonHost); } // Creating a temp configuration file for apife with modification to some named sections in photon-controller-config // so that it can match the Configuration class of dropwizard. File apiFeTempConfig = File.createTempFile("apiFeTempConfig", ".tmp"); File source = new File(args[0]); FileInputStream fis = new FileInputStream(source); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); FileWriter fstream = new FileWriter(apiFeTempConfig, true); BufferedWriter out = new BufferedWriter(fstream); String aLine = null; while ((aLine = in.readLine()) != null) { if (aLine.equals("apife:")) { aLine = aLine.replace("apife:", "server:"); } out.write(aLine); out.newLine(); } in.close(); out.close(); // This approach can be simplified once the apife container is gone, but for the time being // it expects the first arg to be the string "server". String[] apiFeArgs = new String[2]; apiFeArgs[0] = "server"; apiFeArgs[1] = apiFeTempConfig.getAbsolutePath(); ApiFeService.setupApiFeConfigurationForServerCommand(apiFeArgs); ApiFeService.addServiceHost(xenonHost); ApiFeService.setSSLContext(sslContext); ApiFeService apiFeService = new ApiFeService(); apiFeService.run(apiFeArgs); apiFeTempConfig.deleteOnExit(); LocalApiClient localApiClient = apiFeService.getInjector().getInstance(LocalApiClient.class); xenonHost.setApiClient(localApiClient); // in the non-auth enabled scenario we need to be able to accept any self-signed certificate if (!deployerConfig.getDeployerContext().isAuthEnabled()) { KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { logger.info("Shutting down"); xenonHost.stop(); logger.info("Done"); LoggingFactory.detachAndStop(); } }); } catch (Exception e) { logger.error("Failed to start photon controller ", e); throw e; } }