List of usage examples for java.io InputStreamReader InputStreamReader
public InputStreamReader(InputStream in)
From source file:com.renren.ntc.sg.util.wxpay.https.ClientCustomSSL.java
public final static void main(String[] args) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream( new File("/Users/allenz/Downloads/wx_cert/apiclient_cert.p12")); try {/*w w w. j ava 2s.c o m*/ keyStore.load(instream, Constants.mch_id.toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, Constants.mch_id.toCharArray()) .build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); try { HttpPost post = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"); System.out.println("executing request" + post.getRequestLine()); String openid = "oQfDLjmZD7Lgynv6vuoBlWXUY_ic"; String nonce_str = Sha1Util.getNonceStr(); String orderId = SUtils.getOrderId(); String re_user_name = "?"; String amount = "1"; String desc = ""; String spbill_create_ip = "123.56.102.224"; String txt = TXT.replace("{mch_appid}", Constants.mch_appid); txt = txt.replace("{mchid}", Constants.mch_id); txt = txt.replace("{openid}", openid); txt = txt.replace("{nonce_str}", nonce_str); txt = txt.replace("{partner_trade_no}", orderId); txt = txt.replace("{check_name}", "FORCE_CHECK"); txt = txt.replace("{re_user_name}", re_user_name); txt = txt.replace("{amount}", amount); txt = txt.replace("{desc}", desc); txt = txt.replace("{spbill_create_ip}", spbill_create_ip); SortedMap<String, String> map = new TreeMap<String, String>(); map.put("mch_appid", Constants.mch_appid); map.put("mchid", Constants.mch_id); map.put("openid", openid); map.put("nonce_str", nonce_str); map.put("partner_trade_no", orderId); //FORCE_CHECK| OPTION_CHECK | NO_CHECK map.put("check_name", "OPTION_CHECK"); map.put("re_user_name", re_user_name); map.put("amount", amount); map.put("desc", desc); map.put("spbill_create_ip", spbill_create_ip); String sign = SUtils.createSign(map).toUpperCase(); txt = txt.replace("{sign}", sign); post.setEntity(new StringEntity(txt, "utf-8")); CloseableHttpResponse response = httpclient.execute(post); try { HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent())); String text; StringBuffer sb = new StringBuffer(); while ((text = bufferedReader.readLine()) != null) { sb.append(text); } String resp = sb.toString(); LoggerUtils.getInstance().log(String.format("req %s rec %s", txt, resp)); if (isOk(resp)) { String payment_no = getValue(resp, "payment_no"); LoggerUtils.getInstance() .log(String.format("order %s pay OK payment_no %s", orderId, payment_no)); } } EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } }
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 a va 2 s . 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:com.github.brandtg.StlPlotter.java
public static void main(String[] args) throws Exception { List<Long> times = new ArrayList<>(); List<Number> series = new ArrayList<>(); try (InputStream is = new FileInputStream(args[1]); BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { String line = reader.readLine(); // header while ((line = reader.readLine()) != null) { String[] tokens = line.split(","); times.add(Long.valueOf(tokens[0])); series.add(Double.valueOf(tokens[1])); }/*from w w w. j a v a2 s. c o m*/ } StlConfig config = new StlConfig(); config.setNumberOfObservations(Integer.valueOf(args[0])); config.setNumberOfDataPoints(times.size()); config.setNumberOfRobustnessIterations(1); config.setPeriodic(true); StlResult result = new StlDecomposition(config).decompose(times, series); plot(result); }
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;// w w w. j av a 2s . com 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:cc.twittertools.index.IndexStatuses.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option(HELP_OPTION, "show help")); options.addOption(new Option(OPTIMIZE_OPTION, "merge indexes into a single segment")); options.addOption(new Option(STORE_TERM_VECTORS_OPTION, "store term vectors")); options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("source collection directory") .create(COLLECTION_OPTION)); options.addOption(//from w ww. j av a 2 s . c o m OptionBuilder.withArgName("dir").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("file with deleted tweetids") .create(DELETES_OPTION)); options.addOption(OptionBuilder.withArgName("id").hasArg().withDescription("max id").create(MAX_ID_OPTION)); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(COLLECTION_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(IndexStatuses.class.getName(), options); System.exit(-1); } String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION); String indexPath = cmdline.getOptionValue(INDEX_OPTION); final FieldType textOptions = new FieldType(); textOptions.setIndexed(true); textOptions.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); textOptions.setStored(true); textOptions.setTokenized(true); if (cmdline.hasOption(STORE_TERM_VECTORS_OPTION)) { textOptions.setStoreTermVectors(true); } LOG.info("collection: " + collectionPath); LOG.info("index: " + indexPath); LongOpenHashSet deletes = null; if (cmdline.hasOption(DELETES_OPTION)) { deletes = new LongOpenHashSet(); File deletesFile = new File(cmdline.getOptionValue(DELETES_OPTION)); if (!deletesFile.exists()) { System.err.println("Error: " + deletesFile + " does not exist!"); System.exit(-1); } LOG.info("Reading deletes from " + deletesFile); FileInputStream fin = new FileInputStream(deletesFile); byte[] ignoreBytes = new byte[2]; fin.read(ignoreBytes); // "B", "Z" bytes from commandline tools BufferedReader br = new BufferedReader(new InputStreamReader(new CBZip2InputStream(fin))); String s; while ((s = br.readLine()) != null) { if (s.contains("\t")) { deletes.add(Long.parseLong(s.split("\t")[0])); } else { deletes.add(Long.parseLong(s)); } } br.close(); fin.close(); LOG.info("Read " + deletes.size() + " tweetids from deletes file."); } long maxId = Long.MAX_VALUE; if (cmdline.hasOption(MAX_ID_OPTION)) { maxId = Long.parseLong(cmdline.getOptionValue(MAX_ID_OPTION)); LOG.info("index: " + maxId); } long startTime = System.currentTimeMillis(); File file = new File(collectionPath); if (!file.exists()) { System.err.println("Error: " + file + " does not exist!"); System.exit(-1); } StatusStream stream = new JsonStatusCorpusReader(file); Directory dir = FSDirectory.open(new File(indexPath)); IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_43, IndexStatuses.ANALYZER); config.setOpenMode(OpenMode.CREATE); IndexWriter writer = new IndexWriter(dir, config); int cnt = 0; Status status; try { while ((status = stream.next()) != null) { if (status.getText() == null) { continue; } // Skip deletes tweetids. if (deletes != null && deletes.contains(status.getId())) { continue; } if (status.getId() > maxId) { continue; } cnt++; Document doc = new Document(); doc.add(new LongField(StatusField.ID.name, status.getId(), Field.Store.YES)); doc.add(new LongField(StatusField.EPOCH.name, status.getEpoch(), Field.Store.YES)); doc.add(new TextField(StatusField.SCREEN_NAME.name, status.getScreenname(), Store.YES)); doc.add(new Field(StatusField.TEXT.name, status.getText(), textOptions)); doc.add(new IntField(StatusField.FRIENDS_COUNT.name, status.getFollowersCount(), Store.YES)); doc.add(new IntField(StatusField.FOLLOWERS_COUNT.name, status.getFriendsCount(), Store.YES)); doc.add(new IntField(StatusField.STATUSES_COUNT.name, status.getStatusesCount(), Store.YES)); long inReplyToStatusId = status.getInReplyToStatusId(); if (inReplyToStatusId > 0) { doc.add(new LongField(StatusField.IN_REPLY_TO_STATUS_ID.name, inReplyToStatusId, Field.Store.YES)); doc.add(new LongField(StatusField.IN_REPLY_TO_USER_ID.name, status.getInReplyToUserId(), Field.Store.YES)); } String lang = status.getLang(); if (!lang.equals("unknown")) { doc.add(new TextField(StatusField.LANG.name, status.getLang(), Store.YES)); } long retweetStatusId = status.getRetweetedStatusId(); if (retweetStatusId > 0) { doc.add(new LongField(StatusField.RETWEETED_STATUS_ID.name, retweetStatusId, Field.Store.YES)); doc.add(new LongField(StatusField.RETWEETED_USER_ID.name, status.getRetweetedUserId(), Field.Store.YES)); doc.add(new IntField(StatusField.RETWEET_COUNT.name, status.getRetweetCount(), Store.YES)); if (status.getRetweetCount() < 0 || status.getRetweetedStatusId() < 0) { LOG.warn("Error parsing retweet fields of " + status.getId()); } } writer.addDocument(doc); if (cnt % 100000 == 0) { LOG.info(cnt + " statuses indexed"); } } LOG.info(String.format("Total of %s statuses added", cnt)); if (cmdline.hasOption(OPTIMIZE_OPTION)) { LOG.info("Merging segments..."); writer.forceMerge(1); LOG.info("Done!"); } LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms"); } catch (Exception e) { e.printStackTrace(); } finally { writer.close(); dir.close(); stream.close(); } }
From source file:com.joliciel.csvLearner.CSVLearner.java
public static void main(String[] args) throws Exception { if (args.length == 0) { InputStream usageStream = CSVLearner.class.getResourceAsStream("/com/joliciel/csvLearner/usage.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(usageStream)); String strLine;/*from ww w . ja v a 2 s . c o m*/ while ((strLine = br.readLine()) != null) System.out.println(strLine); return; } CSVLearner learner = new CSVLearner(args); learner.run(); }
From source file:com.google.oacurl.Login.java
public static void main(String[] args) throws Exception { LoginOptions options = new LoginOptions(); try {/*from ww w.j a v a 2 s .c o 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:asl.seedscan.DQAWeb.java
public static void main(String args[]) { db = new MetricDatabase("", "", ""); findConsoleHandler();/*w w w .j a va 2 s . 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);//w ww . jav a 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:org.wso2.charon3.samples.user.sample01.CreateUserSample.java
public static void main(String[] args) { try {/*from w w w. j ava 2 s .c om*/ String url = "http://localhost:8080/scim/v2/Users"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // Setting basic post request con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/scim+json"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(createRequestBody); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in; if (responseCode == HttpURLConnection.HTTP_CREATED) { // success in = new BufferedReader(new InputStreamReader(con.getInputStream())); } else { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); } String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //printing result from response System.out.println("Response Code : " + responseCode); System.out.println("Response Message : " + con.getResponseMessage()); System.out.println("Response Content : " + response.toString()); } catch (ProtocolException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }