List of usage examples for java.lang StringBuffer append
@Override public synchronized StringBuffer append(double d)
From source file:Main.java
public static void main(String[] arguments) throws Exception { StringBuffer output = new StringBuffer(); FileReader file = new FileReader("a.htm"); BufferedReader buff = new BufferedReader(file); boolean eof = false; while (!eof) { String line = buff.readLine(); if (line == null) eof = true;//from w w w .j a va2 s . c o m else output.append(line + "\n"); } buff.close(); String page = output.toString(); Pattern pattern = Pattern.compile("<a.+href=\"(.+?)\""); Matcher matcher = pattern.matcher(page); while (matcher.find()) { System.out.println(matcher.group(1)); } }
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 {/*from ww w. j a v a 2 s . c om*/ 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:io.s4.util.AvroSchemaSupplementer.java
public static void main(String args[]) { if (args.length < 1) { System.err.println("No schema filename specified"); System.exit(1);/*ww w .jav a 2 s .c o m*/ } String filename = args[0]; FileReader fr = null; BufferedReader br = null; InputStreamReader isr = null; try { if (filename == "-") { isr = new InputStreamReader(System.in); br = new BufferedReader(isr); } else { fr = new FileReader(filename); br = new BufferedReader(fr); } String inputLine = ""; StringBuffer jsonBuffer = new StringBuffer(); while ((inputLine = br.readLine()) != null) { jsonBuffer.append(inputLine); } JSONObject jsonRecord = new JSONObject(jsonBuffer.toString()); JSONObject keyPathElementSchema = new JSONObject(); keyPathElementSchema.put("name", "KeyPathElement"); keyPathElementSchema.put("type", "record"); JSONArray fieldsArray = new JSONArray(); JSONObject fieldRecord = new JSONObject(); fieldRecord.put("name", "index"); JSONArray typeArray = new JSONArray("[\"int\", \"null\"]"); fieldRecord.put("type", typeArray); fieldsArray.put(fieldRecord); fieldRecord = new JSONObject(); fieldRecord.put("name", "keyName"); typeArray = new JSONArray("[\"string\", \"null\"]"); fieldRecord.put("type", typeArray); fieldsArray.put(fieldRecord); keyPathElementSchema.put("fields", fieldsArray); JSONObject keyInfoSchema = new JSONObject(); keyInfoSchema.put("name", "KeyInfo"); keyInfoSchema.put("type", "record"); fieldsArray = new JSONArray(); fieldRecord = new JSONObject(); fieldRecord.put("name", "keyPath"); typeArray = new JSONArray("[\"string\", \"null\"]"); fieldRecord.put("type", typeArray); fieldsArray.put(fieldRecord); fieldRecord = new JSONObject(); fieldRecord.put("name", "fullKeyPath"); typeArray = new JSONArray("[\"string\", \"null\"]"); fieldRecord.put("type", typeArray); fieldsArray.put(fieldRecord); fieldRecord = new JSONObject(); fieldRecord.put("name", "keyPathElementList"); JSONObject typeRecord = new JSONObject(); typeRecord.put("type", "array"); typeRecord.put("items", keyPathElementSchema); fieldRecord.put("type", typeRecord); fieldsArray.put(fieldRecord); keyInfoSchema.put("fields", fieldsArray); JSONObject partitionInfoSchema = new JSONObject(); partitionInfoSchema.put("name", "PartitionInfo"); partitionInfoSchema.put("type", "record"); fieldsArray = new JSONArray(); fieldRecord = new JSONObject(); fieldRecord.put("name", "partitionId"); typeArray = new JSONArray("[\"int\", \"null\"]"); fieldRecord.put("type", typeArray); fieldsArray.put(fieldRecord); fieldRecord = new JSONObject(); fieldRecord.put("name", "compoundKey"); typeArray = new JSONArray("[\"string\", \"null\"]"); fieldRecord.put("type", typeArray); fieldsArray.put(fieldRecord); fieldRecord = new JSONObject(); fieldRecord.put("name", "compoundValue"); typeArray = new JSONArray("[\"string\", \"null\"]"); fieldRecord.put("type", typeArray); fieldsArray.put(fieldRecord); fieldRecord = new JSONObject(); fieldRecord.put("name", "keyInfoList"); typeRecord = new JSONObject(); typeRecord.put("type", "array"); typeRecord.put("items", keyInfoSchema); fieldRecord.put("type", typeRecord); fieldsArray.put(fieldRecord); partitionInfoSchema.put("fields", fieldsArray); fieldRecord = new JSONObject(); fieldRecord.put("name", "S4__PartitionInfo"); typeRecord = new JSONObject(); typeRecord.put("type", "array"); typeRecord.put("items", partitionInfoSchema); fieldRecord.put("type", typeRecord); fieldsArray = jsonRecord.getJSONArray("fields"); fieldsArray.put(fieldRecord); System.out.println(jsonRecord.toString(3)); } catch (Exception ioe) { throw new RuntimeException(ioe); } finally { if (br != null) try { br.close(); } catch (Exception e) { } if (isr != null) try { isr.close(); } catch (Exception e) { } if (fr != null) try { fr.close(); } catch (Exception e) { } } }
From source file:de.micromata.genome.tpsb.executor.GroovyShellExecutor.java
public static void main(String[] args) { String methodName = null;/* w ww .j a v a 2 s. c o m*/ if (args.length > 0 && StringUtils.isNotBlank(args[0])) { methodName = args[0]; } GroovyShellExecutor exec = new GroovyShellExecutor(); //System.out.println("GroovyShellExecutor start"); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; StringBuffer code = new StringBuffer(); try { while ((line = in.readLine()) != null) { if (line.equals("--EOF--") == true) { break; } code.append(line); code.append("\n"); //System.out.flush(); } } catch (IOException ex) { throw new RuntimeException("Failure reading std in: " + ex.toString(), ex); } try { exec.executeCode(code.toString(), methodName); } catch (Throwable ex) { // NOSONAR "Illegal Catch" framework warn("GroovyShellExecutor failed with exception: " + ex.getClass().getName() + ": " + ex.getMessage() + "\n" + ExceptionUtils.getStackTrace(ex)); } System.out.println("--EOP--"); System.out.flush(); }
From source file:com.cyberway.issue.crawler.extractor.ExtractorTool.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option("h", "help", false, "Prints this message and exits.")); StringBuffer defaultExtractors = new StringBuffer(); for (int i = 0; i < DEFAULT_EXTRACTORS.length; i++) { if (i > 0) { defaultExtractors.append(", "); }/*from w w w . j av a2 s .co m*/ defaultExtractors.append(DEFAULT_EXTRACTORS[i]); } options.addOption(new Option("e", "extractor", true, "List of comma-separated extractor class names. " + "Run in order listed. " + "If no extractors listed, runs following: " + defaultExtractors.toString() + ".")); options.addOption( new Option("s", "scratch", true, "Directory to write scratch files to. Default: '/tmp'.")); PosixParser parser = new PosixParser(); CommandLine cmdline = parser.parse(options, args, false); List cmdlineArgs = cmdline.getArgList(); Option[] cmdlineOptions = cmdline.getOptions(); HelpFormatter formatter = new HelpFormatter(); // If no args, print help. if (cmdlineArgs.size() <= 0) { usage(formatter, options, 0); } // Now look at options passed. String[] extractors = DEFAULT_EXTRACTORS; String scratch = null; for (int i = 0; i < cmdlineOptions.length; i++) { switch (cmdlineOptions[i].getId()) { case 'h': usage(formatter, options, 0); break; case 'e': String value = cmdlineOptions[i].getValue(); if (value == null || value.length() <= 0) { // Allow saying NO extractors so we can see // how much it costs just reading through // ARCs. extractors = new String[0]; } else { extractors = value.split(","); } break; case 's': scratch = cmdlineOptions[i].getValue(); break; default: throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId()); } } ExtractorTool tool = new ExtractorTool(extractors, scratch); for (Iterator i = cmdlineArgs.iterator(); i.hasNext();) { tool.extract((String) i.next()); } }
From source file:edu.cmu.lti.oaqa.apps.Client.java
public static void main(String args[]) { BufferedReader inp = new BufferedReader(new InputStreamReader(System.in)); Options opt = new Options(); Option o = new Option(PORT_SHORT_PARAM, PORT_LONG_PARAM, true, PORT_DESC); o.setRequired(true);//from w w w. j av a 2s .c o m opt.addOption(o); o = new Option(HOST_SHORT_PARAM, HOST_LONG_PARAM, true, HOST_DESC); o.setRequired(true); opt.addOption(o); opt.addOption(K_SHORT_PARAM, K_LONG_PARAM, true, K_DESC); opt.addOption(R_SHORT_PARAM, R_LONG_PARAM, true, R_DESC); opt.addOption(QUERY_TIME_SHORT_PARAM, QUERY_TIME_LONG_PARAM, true, QUERY_TIME_DESC); opt.addOption(RET_OBJ_SHORT_PARAM, RET_OBJ_LONG_PARAM, false, RET_OBJ_DESC); opt.addOption(RET_EXTERN_ID_SHORT_PARAM, RET_EXTERN_ID_LONG_PARAM, false, RET_EXTERN_ID_DESC); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try { CommandLine cmd = parser.parse(opt, args); String host = cmd.getOptionValue(HOST_SHORT_PARAM); String tmp = null; tmp = cmd.getOptionValue(PORT_SHORT_PARAM); int port = -1; try { port = Integer.parseInt(tmp); } catch (NumberFormatException e) { Usage("Port should be integer!"); } boolean retObj = cmd.hasOption(RET_OBJ_SHORT_PARAM); boolean retExternId = cmd.hasOption(RET_EXTERN_ID_SHORT_PARAM); String queryTimeParams = cmd.getOptionValue(QUERY_TIME_SHORT_PARAM); if (null == queryTimeParams) queryTimeParams = ""; SearchType searchType = SearchType.kKNNSearch; int k = 0; double r = 0; if (cmd.hasOption(K_SHORT_PARAM)) { if (cmd.hasOption(R_SHORT_PARAM)) { Usage("Range search is not allowed if the KNN search is specified!"); } tmp = cmd.getOptionValue(K_SHORT_PARAM); try { k = Integer.parseInt(tmp); } catch (NumberFormatException e) { Usage("K should be integer!"); } searchType = SearchType.kKNNSearch; } else if (cmd.hasOption(R_SHORT_PARAM)) { if (cmd.hasOption(K_SHORT_PARAM)) { Usage("KNN search is not allowed if the range search is specified!"); } searchType = SearchType.kRangeSearch; tmp = cmd.getOptionValue(R_SHORT_PARAM); try { r = Double.parseDouble(tmp); } catch (NumberFormatException e) { Usage("The range value should be numeric!"); } } else { Usage("One has to specify either range or KNN-search parameter"); } String separator = System.getProperty("line.separator"); StringBuffer sb = new StringBuffer(); String s; while ((s = inp.readLine()) != null) { sb.append(s); sb.append(separator); } String queryObj = sb.toString(); try { TTransport transport = new TSocket(host, port); transport.open(); TProtocol protocol = new TBinaryProtocol(transport); QueryService.Client client = new QueryService.Client(protocol); if (!queryTimeParams.isEmpty()) client.setQueryTimeParams(queryTimeParams); List<ReplyEntry> res = null; long t1 = System.nanoTime(); if (searchType == SearchType.kKNNSearch) { System.out.println(String.format("Running a %d-NN search", k)); res = client.knnQuery(k, queryObj, retExternId, retObj); } else { System.out.println(String.format("Running a range search (r=%g)", r)); res = client.rangeQuery(r, queryObj, retExternId, retObj); } long t2 = System.nanoTime(); System.out.println(String.format("Finished in %g ms", (t2 - t1) / 1e6)); for (ReplyEntry e : res) { System.out.println(String.format("id=%d dist=%g %s", e.getId(), e.getDist(), retExternId ? "externId=" + e.getExternId() : "")); if (retObj) System.out.println(e.getObj()); } transport.close(); // Close transport/socket ! } catch (TException te) { System.err.println("Apache Thrift exception: " + te); te.printStackTrace(); } } catch (ParseException e) { Usage("Cannot parse arguments"); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
From source file:Main.java
public static void main(String[] args) throws Exception { XMLInputFactory xif = XMLInputFactory.newInstance(); XMLEventReader xmlr = xif.createXMLEventReader((new FileInputStream(new File("./file.xml")))); boolean inline = false; StringBuffer sb = new StringBuffer(); while (xmlr.hasNext()) { XMLEvent event = xmlr.nextEvent(); if (event.isStartElement()) { StartElement element = (StartElement) event; if ("data".equals(element.getName().toString().trim())) { inline = true;// ww w.j a va 2 s . c om } } if (inline) { sb.append(xmlr.peek()); } if (event.isEndElement()) { EndElement element = (EndElement) event; if ("data".equals(element.getName().toString().trim())) { inline = false; System.out.println(sb.toString()); sb.setLength(0); } } } }
From source file:com.hsbc.frc.SevenHero.ClientProxyAuthentication.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try {/*from w w w . ja v a2 s . c o m*/ httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080), new UsernamePasswordCredentials("43668069", "wf^O^2013")); HttpHost targetHost = new HttpHost("pt.3g.qq.com"); HttpHost proxy = new HttpHost("133.13.162.149", 8080); BasicClientCookie netscapeCookie = null; httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); // httpclient.getCookieStore().addCookie(netscapeCookie); httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); HttpGet httpget = new HttpGet("/"); httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"); System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("via proxy: " + proxy); System.out.println("to target: " + targetHost); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } InputStream is = entity.getContent(); StringBuffer sb = new StringBuffer(200); byte data[] = new byte[65536]; int n = 1; do { n = is.read(data); if (n > 0) { sb.append(new String(data)); } } while (n > 0); // System.out.println(sb); EntityUtils.consume(entity); System.out.println("----------------------------------------"); Header[] headerlist = response.getAllHeaders(); for (int i = 0; i < headerlist.length; i++) { Header header = headerlist[i]; if (header.getName().equals("Set-Cookie")) { String setCookie = header.getValue(); String cookies[] = setCookie.split(";"); for (int j = 0; j < cookies.length; j++) { String cookie[] = cookies[j].split("="); CookieManager.cookie.put(cookie[0], cookie[1]); } } System.out.println(header.getName() + ":" + header.getValue()); } String sid = getSid(sb.toString(), "&"); System.out.println("sid: " + sid); httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080), new UsernamePasswordCredentials("43668069", "wf^O^2013")); String url = Constant.openUrl + "&" + sid; targetHost = new HttpHost(url); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); httpget = new HttpGet("/"); httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"); Iterator it = CookieManager.cookie.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); Object key = entry.getKey(); Object value = entry.getValue(); netscapeCookie = new BasicClientCookie((String) (key), (String) (value)); netscapeCookie.setVersion(0); netscapeCookie.setDomain(".qq.com"); netscapeCookie.setPath("/"); // httpclient.getCookieStore().addCookie(netscapeCookie); } response = httpclient.execute(targetHost, httpget); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:com.curiousby.baoyou.cn.hadoop.HDFSUtils.java
public static void main(String[] args) throws IOException { String hdfsRoot = "/user/hadoop/storm"; // System.setProperty("hadoop.home.dir", "I:\\software\\hadoop-2.6.0"); HDFSUtils hdfs = new HDFSUtils(); hdfs.init();// ww w . ja v a 2 s . c o m System.out.println(hdfs.dir("/")); System.out.println("================1=============="); String terminalPath = hdfsRoot + "/" + "terminal_" + "108999000003"; boolean existsTerminalPath = hdfs.exists(terminalPath); if (!existsTerminalPath) { hdfs.createDir(terminalPath); hdfs.close(); hdfs.init(); } System.out.println("================2=============="); String terminalTodayPath = terminalPath + "/temialinfo." + DatetimeUtil.getYMD(new Date()) + ".log"; boolean existsTerminalTodayPath = hdfs.exists(terminalTodayPath); if (!existsTerminalTodayPath) { hdfs.create(terminalTodayPath); } System.out.println("================3==============="); StringBuffer sb = new StringBuffer(); sb.append( "108999000003,2016-12-27 17:20:05,863360028147399,0c3631303038393039393030303030303030333030,460010430511343,MI 3W,Xiaomi,MMSHANGCHENG,108999000003-Android,unknown,2.0,2,Android,Android,unknown,unknown,8,1920*1080,Wi-Fi,unknown,unknown,ARMv7 Processor rev 1 (v7l)"); System.out.println("================4==============="); hdfs.writeAppendFile(terminalTodayPath, sb.toString()); System.out.println("================5==============="); hdfs.close(); }
From source file:ASCII2NATIVE.java
public static void main(String[] args) { File f = new File("c:\\mydb.script"); File f2 = new File("c:\\mydb3.script"); if (f.exists() && f.isFile()) { // convert param-file BufferedReader br = null; StringBuffer sb = new StringBuffer(); String line;/*ww w .j a v a2s . c o m*/ try { br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "JISAutoDetect")); while ((line = br.readLine()) != null) { System.out.println(ascii2Native(line)); sb.append(ascii2Native(line)).append(";\n");//.append(";\n\r") } BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f2), "utf-8")); out.append(sb.toString()); out.flush(); out.close(); } catch (FileNotFoundException e) { System.err.println("file not found - " + f); } catch (IOException e) { System.err.println("read error - " + f); } finally { try { if (br != null) br.close(); } catch (Exception e) { } } } else { // // convert param-data // System.out.print(ascii2native(args[i])); // if (i + 1 < args.length) // System.out.print(' '); } }