List of usage examples for java.lang String getBytes
public byte[] getBytes()
From source file:com.manning.blogapps.chapter10.examples.AuthPost.java
public static void main(String[] args) throws Exception { if (args.length < 4) { System.out.println("USAGE: authpost <username> <password> <filepath> <url>"); System.exit(-1);/*from ww w. j a v a2 s . c o m*/ } String credentials = args[0] + ":" + args[1]; String filepath = args[2]; String url = args[3]; HttpClient httpClient = new HttpClient(); EntityEnclosingMethod method = new PostMethod(url); method.setRequestHeader("Authorization", "Basic " + new String(Base64.encodeBase64(credentials.getBytes()))); File upload = new File(filepath); method.setRequestHeader("Title", upload.getName()); method.setRequestBody(new FileInputStream(upload)); String contentType = "application/atom+xml; charset=utf8"; if (filepath.endsWith(".gif")) contentType = "image/gif"; else if (filepath.endsWith(".jpg")) contentType = "image/jpg"; method.setRequestHeader("Content-type", contentType); httpClient.executeMethod(method); System.out.println(method.getResponseBodyAsString()); }
From source file:com.manning.blogapps.chapter10.examples.AuthPut.java
public static void main(String[] args) throws Exception { if (args.length < 4) { System.out.println("USAGE: authput <username> <password> <filepath> <url>"); System.exit(-1);/*w w w.j a va2 s. c o m*/ } String credentials = args[0] + ":" + args[1]; String filepath = args[2]; String url = args[3]; HttpClient httpClient = new HttpClient(); EntityEnclosingMethod method = new PutMethod(url); method.setRequestHeader("Authorization", "Basic " + new String(Base64.encodeBase64(credentials.getBytes()))); File upload = new File(filepath); method.setRequestHeader("name", upload.getName()); String contentType = "application/atom+xml; charset=utf8"; if (filepath.endsWith(".gif")) contentType = "image/gif"; else if (filepath.endsWith(".jpg")) contentType = "image/jpg"; method.setRequestHeader("Content-type", contentType); method.setRequestBody(new FileInputStream(filepath)); httpClient.executeMethod(method); System.out.println(method.getResponseBodyAsString()); }
From source file:com.manning.blogapps.chapter10.examples.AuthPostJava.java
public static void main(String[] args) throws Exception { if (args.length < 4) { System.out.println("USAGE: authpost <username> <password> <filepath> <url>"); System.exit(-1);//w ww. j av a2 s .c o m } String credentials = args[0] + ":" + args[1]; String filepath = args[2]; URL url = new URL(args[3]); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(credentials.getBytes()))); File upload = new File(filepath); conn.setRequestProperty("name", upload.getName()); String contentType = "application/atom+xml; charset=utf8"; if (filepath.endsWith(".gif")) contentType = "image/gif"; else if (filepath.endsWith(".jpg")) contentType = "image/jpg"; conn.setRequestProperty("Content-type", contentType); BufferedInputStream filein = new BufferedInputStream(new FileInputStream(upload)); BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream()); byte buffer[] = new byte[8192]; for (int count = 0; count != -1;) { count = filein.read(buffer, 0, 8192); if (count != -1) out.write(buffer, 0, count); } filein.close(); out.close(); String s = null; BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((s = in.readLine()) != null) { System.out.println(s); } }
From source file:com.camel.trainreserve.JDKHttpsClient.java
public static void main(String[] args) { JDKHttpsClient client = new JDKHttpsClient(); String url = "https://kyfw.12306.cn/otn/leftTicket/queryT?leftTicketDTO.train_date=2015-02-17&leftTicketDTO.from_station=SZQ&leftTicketDTO.to_station=SYQ&purpose_codes=ADULT"; try {/*from w ww . j av a 2 s . c o m*/ StopWatch stopWatch = new LoggingStopWatch("request 12306"); String rs = JDKHttpsClient.doGet(url); System.out.println(rs); System.out.println(MD5.GetMD5Code(rs.getBytes())); stopWatch.stop(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.metamx.datatypes.ExampleWriteNewLineJson.java
public static void main(String[] args) throws Exception { final MmxAuctionSummary sampleAuction1 = MmxAuctionSummary.builder() .timestamp(new DateTime("2014-01-01T00:00:00.000Z")).auctionType(2).build(); final MmxAuctionSummary sampleAuction2 = MmxAuctionSummary.builder() .timestamp(new DateTime("2014-01-01T01:00:00.000Z")).auctionType(1).build(); List<MmxAuctionSummary> auctionList = Arrays.asList(sampleAuction1, sampleAuction2); final String separator = "\n"; final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); final OutputStream outStream = new ByteArrayOutputStream(); for (MmxAuctionSummary auction : auctionList) { outStream.write(objectMapper.writeValueAsBytes(auction)); outStream.write(separator.getBytes()); }/*from w ww . j a v a 2 s. co m*/ System.out.println(outStream.toString()); }
From source file:io.druid.examples.rabbitmq.RabbitMQProducerMain.java
public static void main(String[] args) throws Exception { // We use a List to keep track of option insertion order. See below. final List<Option> optionList = new ArrayList<Option>(); optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h")); optionList.add(OptionBuilder.withLongOpt("hostname").hasArg() .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b")); optionList.add(OptionBuilder.withLongOpt("port").hasArg() .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n")); optionList.add(OptionBuilder.withLongOpt("username").hasArg() .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]") .create("u")); optionList.add(OptionBuilder.withLongOpt("password").hasArg() .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]") .create("p")); optionList.add(OptionBuilder.withLongOpt("vhost").hasArg() .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]") .create("v")); optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg() .withDescription("name of the AMQP exchange [required - no default]").create("e")); optionList.add(OptionBuilder.withLongOpt("key").hasArg() .withDescription("the routing key to use when sending messages [default: 'default.routing.key']") .create("k")); optionList.add(OptionBuilder.withLongOpt("type").hasArg() .withDescription("the type of exchange to create [default: 'topic']").create("t")); optionList.add(OptionBuilder.withLongOpt("durable") .withDescription("if set, a durable exchange will be declared [default: not set]").create("d")); optionList.add(OptionBuilder.withLongOpt("autodelete") .withDescription("if set, an auto-delete exchange will be declared [default: not set]") .create("a")); optionList.add(OptionBuilder.withLongOpt("single") .withDescription("if set, only a single message will be sent [default: not set]").create("s")); optionList.add(OptionBuilder.withLongOpt("start").hasArg() .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]") .create());//from ww w .j a v a 2 s. c o m optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription( "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]") .create()); optionList.add(OptionBuilder.withLongOpt("interval").hasArg() .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]") .create()); optionList.add(OptionBuilder.withLongOpt("delay").hasArg() .withDescription("the delay between sending messages in milliseconds [default: 100]").create()); // An extremely silly hack to maintain the above order in the help formatting. HelpFormatter formatter = new HelpFormatter(); // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order. formatter.setOptionComparator(new Comparator() { @Override public int compare(Object o1, Object o2) { // I know this isn't fast, but who cares! The list is short. return optionList.indexOf(o1) - optionList.indexOf(o2); } }); // Now we can add all the options to an Options instance. This is dumb! Options options = new Options(); for (Option option : optionList) { options.addOption(option); } CommandLine cmd = null; try { cmd = new BasicParser().parse(options, args); } catch (ParseException e) { formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null); System.exit(1); } if (cmd.hasOption("h")) { formatter.printHelp("RabbitMQProducerMain", options); System.exit(2); } ConnectionFactory factory = new ConnectionFactory(); if (cmd.hasOption("b")) { factory.setHost(cmd.getOptionValue("b")); } if (cmd.hasOption("u")) { factory.setUsername(cmd.getOptionValue("u")); } if (cmd.hasOption("p")) { factory.setPassword(cmd.getOptionValue("p")); } if (cmd.hasOption("v")) { factory.setVirtualHost(cmd.getOptionValue("v")); } if (cmd.hasOption("n")) { factory.setPort(Integer.parseInt(cmd.getOptionValue("n"))); } String exchange = cmd.getOptionValue("e"); String routingKey = "default.routing.key"; if (cmd.hasOption("k")) { routingKey = cmd.getOptionValue("k"); } boolean durable = cmd.hasOption("d"); boolean autoDelete = cmd.hasOption("a"); String type = cmd.getOptionValue("t", "topic"); boolean single = cmd.hasOption("single"); int interval = Integer.parseInt(cmd.getOptionValue("interval", "10")); int delay = Integer.parseInt(cmd.getOptionValue("delay", "100")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date()))); Random r = new Random(); Calendar timer = Calendar.getInstance(); timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00"))); String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}"; Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchange, type, durable, autoDelete, null); do { int wp = (10 + r.nextInt(90)) * 100; String gender = r.nextBoolean() ? "male" : "female"; int age = 20 + r.nextInt(70); String line = String.format(msg_template, sdf.format(timer.getTime()), wp, gender, age); channel.basicPublish(exchange, routingKey, null, line.getBytes()); System.out.println("Sent message: " + line); timer.add(Calendar.SECOND, interval); Thread.sleep(delay); } while ((!single && stop.after(timer.getTime()))); connection.close(); }
From source file:Main.java
public static void main(String[] args) { String data = "<root><row><column name='username' length='6'>admin</column>" + "<column name='password' length='1'>p</column></row><row>" + "<column name='username' length='6'>j</column>" + "<column name='password' length='8'>q</column></row></root>"; SAXBuilder builder = new SAXBuilder(); Document document = builder.build(new ByteArrayInputStream(data.getBytes())); Element root = document.getRootElement(); List rows = root.getChildren("row"); for (int i = 0; i < rows.size(); i++) { Element row = (Element) rows.get(i); List columns = row.getChildren("column"); for (int j = 0; j < columns.size(); j++) { Element column = (Element) columns.get(j); String name = column.getAttribute("name").getValue(); String value = column.getText(); int length = column.getAttribute("length").getIntValue(); System.out.println("name = " + name); System.out.println("value = " + value); System.out.println("length = " + length); }//from w ww . j a v a2s . c o m } }
From source file:com.mingsoft.util.Base64Util.java
public static void main(String[] args) { String str = "asfd"; System.out.println(Base64Util.getBASE64(str.getBytes())); }
From source file:com.clustercontrol.util.KeyCheck.java
/** * ????????/*from w w w .java 2 s . c om*/ * * @param args */ public static void main(String[] args) { PrivateKey privateKey = null; PublicKey publicKey = null; /// ??????? true /// ???????? false (?) boolean flag = false; if (flag) { try { // ? privateKey = getPrivateKey( "???????privateKey.txt??"); // ? publicKey = getPublicKey("???????"); // publicKey = getPublicKey(publicKeyStr); } catch (Exception e) { System.out.println("hoge" + e.getMessage()); } } else { KeyPairGenerator generator; try { generator = KeyPairGenerator.getInstance(ALGORITHM); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); // ?? 1024 generator.initialize(1024, random); KeyPair keyPair = generator.generateKeyPair(); privateKey = keyPair.getPrivate(); publicKey = keyPair.getPublic(); } catch (NoSuchAlgorithmException ex) { System.out.println(ex.getMessage()); } } // // ? System.out.println("?"); System.out.println(byte2String(privateKey.getEncoded())); System.out.println("?"); System.out.println(byte2String(publicKey.getEncoded())); // ??????? String string = "20140701_nttdata"; byte[] src = string.getBytes(); System.out.println("??String"); System.out.println(string); System.out.println("??byte"); System.out.println(byte2String(src)); // ? try { String encStr = encrypt(string, privateKey); System.out.println("?"); System.out.println(encStr); // ? String decStr = decrypt(encStr, publicKey); System.out.println("?"); System.out.println(decStr); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:com.openteach.diamond.repository.client.cache.FileLRUCache.java
public static void main(String[] args) { FileLRUCache cache = new FileLRUCache<String, String>("/tmp/filelrucache.cache"); cache.initialize();//from ww w. j a v a 2 s .c o m cache.register(new ValueConverter<String>() { @Override public byte[] toBytes(String v) { return v.getBytes(); } @Override public String fromBytes(byte[] bytes) { return new String(bytes); } }); for (int i = 0; i < 10240; i++) { cache.put(String.format("key:%d", i), String.format("value:%d", i)); } for (int i = 0; i < 1024; i++) { if (!String.format("value:%d", i).equals(cache.get(String.format("key:%d", i)))) { throw new RuntimeException("Wrong cache"); } } cache.stop(); }