List of usage examples for java.lang String String
String(byte[] value, byte coder)
From source file:mapas.Mapas.java
public static void main(String[] args) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setPassword("test"); factory.setUsername("test"); final Connection connection = factory.newConnection(); final Channel channel = connection.createChannel(); channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); channel.basicQos(1);/*from w w w . java 2 s . c om*/ final Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'"); try { doWork(message); } catch (Exception e) { System.out.println(e.getMessage()); } System.out.println(" [x] Done"); channel.basicAck(envelope.getDeliveryTag(), false); } }; channel.basicConsume(TASK_QUEUE_NAME, false, consumer); }
From source file:cn.xyz.lcg.rocketmq.quickstart.PullScheduleConsumer.java
public static void main(String[] args) throws MQClientException { final MQPullConsumerScheduleService scheduleService = new MQPullConsumerScheduleService( "schedulerPullConsumer"); scheduleService.setMessageModel(MessageModel.CLUSTERING); scheduleService.getDefaultMQPullConsumer().setNamesrvAddr("centOS1:9876"); scheduleService.registerPullTaskCallback("simpleTest", new PullTaskCallback() { @Override//from w w w .j a v a2s. c o m public void doPullTask(MessageQueue mq, PullTaskContext context) { MQPullConsumer consumer = context.getPullConsumer(); try { long offset = consumer.fetchConsumeOffset(mq, false); if (offset < 0) offset = 0; PullResult pullResult = consumer.pull(mq, "*", offset, 6); // System.out.println(offset + "\t" + mq + "\t" + pullResult); if (CollectionUtils.isNotEmpty(pullResult.getMsgFoundList())) { for (MessageExt msg : pullResult.getMsgFoundList()) { System.out.println( Thread.currentThread().getName() + " " + new String(msg.getBody(), "UTF-8")); } } switch (pullResult.getPullStatus()) { case FOUND: break; case NO_MATCHED_MSG: break; case NO_NEW_MSG: case OFFSET_ILLEGAL: break; default: break; } consumer.updateConsumeOffset(mq, pullResult.getNextBeginOffset()); context.setPullNextDelayTimeMillis(1000); } catch (Exception e) { e.printStackTrace(); } } }); scheduleService.start(); }
From source file:zz.pseas.ghost.login.taobao.MTaobaoLogin.java
public static void main(String[] args) throws UnsupportedEncodingException { String tbuserNmae = "TBname"; String tbpassWord = "TBpasssword"; GhostClient iPhone = new GhostClient("utf-8"); String ans = iPhone.get("https://login.m.taobao.com/login.htm"); Document doc = Jsoup.parse(ans); String url = doc.select("form#loginForm").first().attr("action"); String _tb_token = doc.select("input[name=_tb_token_]").first().attr("value"); String sid = doc.select("input[name=sid]").first().attr("value"); System.out.println(_tb_token); System.out.println(sid);//from w w w . j av a 2 s . c om System.out.println(url); HashMap<String, String> map = new HashMap<String, String>(); map.put("TPL_password", tbpassWord); map.put("TPL_username", tbuserNmae); map.put("_tb_token_", _tb_token); map.put("action", "LoginAction"); map.put("event_submit_do_login", "1"); map.put("loginFrom", "WAP_TAOBAO"); map.put("sid", sid); String location = null; while (true) { CommonsPage commonsPage = iPhone.postForPage(url, map); location = commonsPage.getHeader("Location"); String postAns = new String(commonsPage.getContents(), "utf-8"); if (StringUtil.isNotEmpty(location) && StringUtil.isEmpty(postAns)) { break; } String s = Jsoup.parse(postAns).select("img.checkcode-img").first().attr("src"); String imgUrl = "https:" + s; byte[] bytes = iPhone.getBytes(imgUrl); FileUtil.writeFile(bytes, "g:/tbCaptcha.jpg"); String wepCheckId = Jsoup.parse(postAns).select("input[name=wapCheckId]").val(); String captcha = null; map.put("TPL_checkcode", captcha); map.put("wapCheckId", wepCheckId); } iPhone.get(location); String tk = iPhone.getCookieValue("_m_h5_tk"); if (StringUtil.isNotEmpty(tk)) { tk = tk.split("_")[0]; } else { tk = "undefined"; } String url2 = genUrl(tk); String ans1 = iPhone.get(url2); System.out.println(url2); System.out.println(ans1); tk = iPhone.getCookieValue("_m_h5_tk").split("_")[0]; if (StringUtil.isEmpty(tk)) { tk = "undefined"; } System.out.println(tk); url2 = genUrl(tk); iPhone.showCookies(); RequestConfig requestConfig = RequestConfig.custom().setProxy(new HttpHost("127.0.0.1", 8888)).build(); HttpUriRequest get = RequestBuilder.get().setConfig(requestConfig) //.addHeader("User-Agent","Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16") .addHeader("Host", "api.m.taobao.com").setUri(url2).build(); ans1 = iPhone.execute(get); System.out.println(ans1); }
From source file:ch.algotrader.event.TopicEventDumper.java
public static void main(String... args) throws Exception { SingleConnectionFactory jmsActiveMQFactory = new SingleConnectionFactory( new ActiveMQConnectionFactory("tcp://localhost:61616")); jmsActiveMQFactory.afterPropertiesSet(); jmsActiveMQFactory.resetConnection(); ActiveMQTopic topic = new ActiveMQTopic(">"); DefaultMessageListenerContainer messageListenerContainer = new DefaultMessageListenerContainer(); messageListenerContainer.setDestination(topic); messageListenerContainer.setConnectionFactory(jmsActiveMQFactory); messageListenerContainer.setSubscriptionShared(false); messageListenerContainer.setCacheLevel(DefaultMessageListenerContainer.CACHE_CONSUMER); messageListenerContainer.setMessageListener((MessageListener) message -> { try {/*from w ww . j a v a2s .co m*/ Destination destination = message.getJMSDestination(); if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; System.out.println(destination + " -> " + textMessage.getText()); } else if (message instanceof BytesMessage) { BytesMessage bytesMessage = (BytesMessage) message; byte[] bytes = new byte[(int) bytesMessage.getBodyLength()]; bytesMessage.readBytes(bytes); System.out.println(destination + " -> " + new String(bytes, Charsets.UTF_8)); } } catch (JMSException ex) { throw new UnrecoverableCoreException(ex); } }); messageListenerContainer.initialize(); messageListenerContainer.start(); System.out.println("Dumping messages from all topics"); Runtime.getRuntime().addShutdownHook(new Thread(messageListenerContainer::stop)); Thread.sleep(Long.MAX_VALUE); }
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step3AddRawDocumentsFromClueWeb.java
public static void main(String[] args) throws IOException { // input dir - list of xml query containers // step2a-retrieved-results File inputDir = new File(args[0]); // warc.bz file containing all required documents according to ClueWeb IDs // ltr-50queries-100docs-clueweb-export.warc.gz File warc = new File(args[1]); // output dir File outputDir = new File(args[2]); if (!outputDir.exists()) { outputDir.mkdirs();/* ww w. j a va2s. co m*/ } // iterate over query containers for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) { QueryResultContainer queryResultContainer = QueryResultContainer .fromXML(FileUtils.readFileToString(f, "utf-8")); // iterate over warc for each query WARCFileReader reader = new WARCFileReader(new Configuration(), new Path(warc.getAbsolutePath())); try { while (true) { WARCRecord read = reader.read(); String trecId = read.getHeader().getField("WARC-TREC-ID"); // now iterate over retrieved results for the query and find matching IDs for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) { if (rankedResults.clueWebID.equals(trecId)) { // add the raw html content String fullHTTPResponse = new String(read.getContent(), "utf-8"); // TODO fix coding? String html = removeHTTPHeaders(fullHTTPResponse); rankedResults.originalHtml = sanitizeXmlChars(html.trim()); } } } } catch (EOFException e) { // end of file } // check if all results have filled html for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) { if (rankedResults.originalHtml == null) { System.err.println("Missing original html for\t" + rankedResults.clueWebID + ", setting relevance to false"); rankedResults.relevant = Boolean.FALSE.toString(); } } // and save the query to output dir File outputFile = new File(outputDir, queryResultContainer.qID + ".xml"); FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8"); System.out.println("Finished " + outputFile); } }
From source file:MeCabBench.java
public static void main(String[] args) { try {/* w ww . ja v a 2 s . c om*/ if (args.length == 0) { System.out.println("usage: java MeCabBench file [file ..]"); System.exit(2); } Tagger tagger = new Tagger(new String[] { "java", "-d", dicPath }); long processed = 0; long nbytes = 0; long nchars = 0; long start = System.currentTimeMillis(); for (int a = 0; a < args.length; a++) { String text = ""; try { RandomAccessFile raf = new RandomAccessFile(args[a], "r"); byte[] buf = new byte[(int) raf.length()]; raf.readFully(buf); raf.close(); text = new String(buf, encoding); nbytes += buf.length; nchars += text.length(); } catch (IOException ioe) { log.error(ioe); continue; } long s_start = System.currentTimeMillis(); for (int c = 0; c < repeat; c++) doWork(tagger, text); long s_end = System.currentTimeMillis(); processed += (s_end - s_start); } long end = System.currentTimeMillis(); System.out.println("number of files: " + args.length); System.out.println("number of repeat: " + repeat); System.out.println("number of bytes: " + nbytes); System.out.println("number of chars: " + nchars); System.out.println("total time elapsed: " + (end - start) + " msec."); System.out.println("analysis time: " + (processed) + " msec."); } catch (Exception e) { e.printStackTrace(System.err); System.exit(1); } }
From source file:cc.twittertools.index.ExtractTermStatisticsFromIndex.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("index").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("min").create(MIN_OPTION)); CommandLine cmdline = null;//from w w w . j a v a 2 s . c o m 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(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(ExtractTermStatisticsFromIndex.class.getName(), options); System.exit(-1); } String indexLocation = cmdline.getOptionValue(INDEX_OPTION); int min = cmdline.hasOption(MIN_OPTION) ? Integer.parseInt(cmdline.getOptionValue(MIN_OPTION)) : 1; PrintStream out = new PrintStream(System.out, true, "UTF-8"); IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(indexLocation))); Terms terms = SlowCompositeReaderWrapper.wrap(reader).terms(StatusField.TEXT.name); TermsEnum termsEnum = terms.iterator(TermsEnum.EMPTY); long missingCnt = 0; int skippedTerms = 0; BytesRef bytes = new BytesRef(); while ((bytes = termsEnum.next()) != null) { byte[] buf = new byte[bytes.length]; System.arraycopy(bytes.bytes, 0, buf, 0, bytes.length); String term = new String(buf, "UTF-8"); int df = termsEnum.docFreq(); long cf = termsEnum.totalTermFreq(); if (df < min) { skippedTerms++; missingCnt += cf; continue; } out.println(term + "\t" + df + "\t" + cf); } reader.close(); out.close(); System.err.println("skipped terms: " + skippedTerms + ", cnt: " + missingCnt); }
From source file:com.emc.ecs.s3.sample.ECSS3Factory.java
public static void main(String[] args) { try {// w w w . j a va2 s .co m KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA"); keyGenerator.initialize(1024, new SecureRandom()); KeyPair myKeyPair = keyGenerator.generateKeyPair(); // Serialize. byte[] pubKeyBytes = myKeyPair.getPublic().getEncoded(); byte[] privKeyBytes = myKeyPair.getPrivate().getEncoded(); String pubKeyStr = new String(Base64.encodeBase64(pubKeyBytes, false), "US-ASCII"); String privKeyStr = new String(Base64.encodeBase64(privKeyBytes, false), "US-ASCII"); System.out.println("Public Key: " + pubKeyStr); System.out.println("Private Key: " + privKeyStr); } catch (Exception e) { e.printStackTrace(); } }
From source file:dhtaccess.tools.Get.java
public static void main(String[] args) { boolean details = false; // parse properties Properties prop = System.getProperties(); String gateway = prop.getProperty("dhtaccess.gateway"); if (gateway == null || gateway.length() <= 0) { gateway = DEFAULT_GATEWAY;/* w ww . jav a 2s. c o m*/ } // parse options Options options = new Options(); options.addOption("h", "help", false, "print help"); options.addOption("g", "gateway", true, "gateway URI, list at http://opendht.org/servers.txt"); options.addOption("d", "details", false, "print secret hash and TTL"); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println("There is an invalid option."); e.printStackTrace(); System.exit(1); } String optVal; if (cmd.hasOption('h')) { usage(COMMAND); System.exit(1); } optVal = cmd.getOptionValue('g'); if (optVal != null) { gateway = optVal; } if (cmd.hasOption('d')) { details = true; } args = cmd.getArgs(); // parse arguments if (args.length < 1) { usage(COMMAND); System.exit(1); } // prepare for RPC DHTAccessor accessor = null; try { accessor = new DHTAccessor(gateway); } catch (MalformedURLException e) { e.printStackTrace(); System.exit(1); } for (int index = 0; index < args.length; index++) { byte[] key = null; try { key = args[index].getBytes(ENCODE); } catch (UnsupportedEncodingException e1) { // NOTREACHED } // RPC if (args.length > 1) { System.out.println(args[index] + ":"); } if (details) { Set<DetailedGetResult> results = accessor.getDetails(key); for (DetailedGetResult r : results) { String valString = null; try { valString = new String((byte[]) r.getValue(), ENCODE); } catch (UnsupportedEncodingException e) { // NOTREACHED } BigInteger hashedSecure = new BigInteger(1, (byte[]) r.getHashedSecret()); System.out.println(valString + " " + r.getTTL() + " " + r.getHashType() + " 0x" + ("0000000" + hashedSecure.toString(16)).substring(0, 8)); } } else { Set<byte[]> results = accessor.get(key); for (byte[] valBytes : results) { try { System.out.println(new String((byte[]) valBytes, ENCODE)); } catch (UnsupportedEncodingException e) { // NOTREACHED } } } } // for (int index = 0... }
From source file:de.serverfrog.pw.crypt.SerpentUtil.java
/** * Print all Security providers and their algos * * @param args args// w ww. ja v a2 s.com * @throws Exception Exception */ public static void main(String[] args) throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); SecretKeySpec keySpec = new SecretKeySpec("test".getBytes("UTF-8"), "AES"); try (CipherOutputStream outputStream = SerpentUtil.getOutputStream(byteArrayOutputStream, keySpec)) { IOUtils.write("TEST", outputStream); } System.out.println(Arrays.toString(byteArrayOutputStream.toByteArray())); System.out.println(byteArrayOutputStream.toString("UTF-8")); byte[] toByteArray = byteArrayOutputStream.toByteArray(); ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(toByteArray); CipherInputStream inputStream = SerpentUtil.getInputStream(arrayInputStream, new SecretKeySpec("test".getBytes("UTF-8"), "AES")); byte[] bytes = new byte[1048576]; IOUtils.read(inputStream, bytes); System.out.println(new String(bytes, "UTF-8").trim()); // // for (Provider provider : Security.getProviders()) { // System.out.println(""); // System.out.println(""); // System.out.println(""); // System.out.println("-------------------------------"); // System.out.println("Name: " + provider.getName()); // System.out.println("Info: " + provider.getInfo()); // for (Map.Entry<Object, Object> entry : provider.entrySet()) { // System.out.println("Key: Class:" + entry.getKey().getClass() + " String: " + entry.getKey()); // System.out.println("Value: Class:" + entry.getValue().getClass() + " String: " + entry.getValue()); // } // for (Provider.Service service : provider.getServices()) { // System.out.println("Service: Algorithm:" + service.getAlgorithm() // + " ClassName:" + service.getClassName() // + " Type:" + service.getType() + " toString:" + service.toString()); // } // for (Object object : provider.values()) { // System.out.println("Value: " + object.getClass() + " toString:" + object.toString()); // // } // System.out.println("-------------------------------"); // } }