List of usage examples for java.io ByteArrayOutputStream write
public synchronized void write(byte b[], int off, int len)
From source file:com.weibo.wesync.client.NHttpClient2.java
public static void main(String[] args) throws Exception { RSAPublicKey publicKey = RSAEncrypt.loadPublicKey("D:\\weibo\\meyou_gw\\conf\\public.pem"); // //www .j a v a 2s . c o m byte[] cipher = RSAEncrypt.encrypt(publicKey, password.getBytes()); password = RSAEncrypt.toHexString(cipher); // HTTP parameters for the client HttpParams params = new SyncBasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); // Create HTTP protocol processing chain HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Use standard client-side protocol interceptors new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); // Create client-side HTTP protocol handler HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor(); // Create client-side I/O event dispatch final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, params); // Create client-side I/O reactor IOReactorConfig config = new IOReactorConfig(); config.setIoThreadCount(1); final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(config); // Create HTTP connection pool BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, params); // Limit total number of connections to just two pool.setDefaultMaxPerRoute(2); pool.setMaxTotal(1); // Run the I/O reactor in a separate thread Thread t = new Thread(new Runnable() { public void run() { try { // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); } }); // Start the client thread t.start(); // Create HTTP requester // HttpAsyncRequester requester = new HttpAsyncRequester( // httpproc, new DefaultConnectionReuseStrategy(), params); // Execute HTTP GETs to the following hosts and HttpHost[] targets = new HttpHost[] { // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), new HttpHost("123.125.106.28", 8082, "http") }; final CountDownLatch latch = new CountDownLatch(targets.length); int callbackId = 0; for (int i = 0; i < 1; i++) { for (final HttpHost target : targets) { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/wesync"); // String usrpwd = Base64.encodeBase64String((username + ":" + password).getBytes()); // request.setHeader("authorization", "Basic " + usrpwd); request.setHeader("uid", "2565640713"); Meyou.MeyouPacket packet = null; if (callbackId == 0) { packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++)) .setSort(MeyouSort.notice).build(); } else { packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++)) .setSort(MeyouSort.wesync).build(); } ByteArrayEntity entity = new ByteArrayEntity(packet.toByteArray()); request.setEntity(entity); // BasicHttpRequest request = new BasicHttpRequest("GET", "/test.html"); System.out.println("send ..."); HttpAsyncRequester requester = new HttpAsyncRequester(httpproc, new DefaultConnectionReuseStrategy(), params); requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), pool, new BasicHttpContext(), // Handle HTTP response from a callback new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { StatusLine status = response.getStatusLine(); int code = status.getStatusCode(); if (code == 200) { try { latch.countDown(); DataInputStream in; in = new DataInputStream(response.getEntity().getContent()); int packetLength = in.readInt(); int start = 0; while (packetLength > 0) { ByteArrayOutputStream outstream = new ByteArrayOutputStream( packetLength); byte[] buffer = new byte[1024]; int len = 0; while (start < packetLength && (len = in.read(buffer, start, packetLength)) > 0) { outstream.write(buffer, 0, len); start += len; } Meyou.MeyouPacket packet0 = Meyou.MeyouPacket .parseFrom(outstream.toByteArray()); System.out.println(target + "->" + packet0); if ((len = in.read(buffer, start, 4)) > 0) { packetLength = Util.readPacketLength(buffer); } else { break; } } } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { System.out.println("error code=" + code + "|" + status.getReasonPhrase()); } } public void failed(final Exception ex) { latch.countDown(); System.out.println(target + "->" + ex); } public void cancelled() { latch.countDown(); System.out.println(target + " cancelled"); } }); Thread.sleep((long) (Math.random() * 10000)); } } // latch.await(); // System.out.println("Shutting down I/O reactor"); // ioReactor.shutdown(); // System.out.println("Done"); }
From source file:Main.java
public static void main(String args[]) throws Exception { final ByteArrayOutputStream out = new ByteArrayOutputStream(); float sampleRate = 8000; int sampleSizeInBits = 8; int channels = 1; boolean signed = true; boolean bigEndian = true; final AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian); DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); final TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info); line.open(format);/*from w w w. jav a 2 s. com*/ line.start(); Runnable runner = new Runnable() { int bufferSize = (int) format.getSampleRate() * format.getFrameSize(); byte buffer[] = new byte[bufferSize]; public void run() { try { int count = line.read(buffer, 0, buffer.length); if (count > 0) { out.write(buffer, 0, count); } out.close(); } catch (IOException e) { System.err.println("I/O problems: " + e); System.exit(-1); } } }; Thread captureThread = new Thread(runner); captureThread.start(); byte audio[] = out.toByteArray(); InputStream input = new ByteArrayInputStream(audio); final SourceDataLine line1 = (SourceDataLine) AudioSystem.getLine(info); final AudioInputStream ais = new AudioInputStream(input, format, audio.length / format.getFrameSize()); line1.open(format); line1.start(); runner = new Runnable() { int bufferSize = (int) format.getSampleRate() * format.getFrameSize(); byte buffer[] = new byte[bufferSize]; public void run() { try { int count; while ((count = ais.read(buffer, 0, buffer.length)) != -1) { if (count > 0) { line1.write(buffer, 0, count); } } line1.drain(); line1.close(); } catch (IOException e) { System.err.println("I/O problems: " + e); System.exit(-3); } } }; Thread playThread = new Thread(runner); playThread.start(); }
From source file:de.mpg.escidoc.services.common.util.Util.java
/** * Command line transformation./*ww w . ja v a2s . co m*/ * * @param see usage * @throws Exception Any exception */ public static void main(String[] args) throws Exception { if (args.length < 7) { System.out.println("Usage: "); System.out.println( "Util <srcFile> <srcFormatName> <srcFormatType> <srcFormatEncoding> <trgFormatName> <trgFormatType> <trgFormatEncoding> [<trgFile> [<service>]]"); System.out.println("Example:"); System.out.println( "Util /tmp/source.xml eDoc application/xml UTF-8 eSciDoc application/xml UTF-8 /tmp/target.xml"); } else { // Init Transformation transformation = new TransformationBean(true); Format srcFormat = new Format(args[1], args[2], args[3]); Format trgFormat = new Format(args[4], args[5], args[6]); File srcFile = new File(args[0]); OutputStream trgStream; if (args.length > 7) { trgStream = new FileOutputStream(new File(args[7])); } else { trgStream = System.out; } String service = "eSciDoc"; if (args.length > 8) { service = args[8]; } // Get file content FileInputStream inputStream = new FileInputStream(srcFile); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int read; while ((read = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, read); } byte[] content = outputStream.toByteArray(); // Transform byte[] result = transformation.transform(content, srcFormat, trgFormat, service); // Stream back trgStream.write(result); trgStream.close(); } }
From source file:Base64.java
public static void main(String[] args) throws IOException { boolean decode = false; int mode = 0; for (String arg : args) { if (arg.equals("-e")) { decode = false;//from ww w .java 2 s. c o m } else if (arg.equals("-d")) { decode = true; } else if (arg.equals("-b64")) { mode = 0; } else if (arg.equals("-hqx")) { mode = 1; } else if (arg.equals("-a85")) { mode = 2; } else if (arg.equals("-l85")) { mode = 3; } else if (arg.equals("-k85")) { mode = 4; } else if (arg.equals("-uue")) { mode = 5; } else if (arg.equals("-xxe")) { mode = 6; } else if (arg.equals("--")) { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1048576]; int len = 0; while ((len = System.in.read(buf)) >= 0) { out.write(buf, 0, len); } out.close(); if (decode) { switch (mode) { case 0: System.out.println(new String(decodeBase64(out.toString()))); break; case 1: System.out.println(new String(decodeBinHex(out.toString()))); break; case 2: System.out.println(new String(decodeASCII85(out.toString()))); break; case 3: System.out.println(new String(decodeLegacy85(out.toString()))); break; case 4: System.out.println(new String(decodeKreative85(out.toString()))); break; case 5: System.out.println(new String(decodeUU(out.toString()))); break; case 6: System.out.println(new String(decodeXX(out.toString()))); break; } } else { switch (mode) { case 0: System.out.println(encodeBase64(out.toByteArray())); break; case 1: System.out.println(encodeBinHex(out.toByteArray())); break; case 2: System.out.println(encodeASCII85(out.toByteArray())); break; case 3: System.out.println(encodeLegacy85(out.toByteArray())); break; case 4: System.out.println(encodeKreative85(out.toByteArray())); break; case 5: System.out.println(encodeUU(out.toByteArray())); break; case 6: System.out.println(encodeXX(out.toByteArray())); break; } } } else if (decode) { switch (mode) { case 0: System.out.println(new String(decodeBase64(arg))); break; case 1: System.out.println(new String(decodeBinHex(arg))); break; case 2: System.out.println(new String(decodeASCII85(arg))); break; case 3: System.out.println(new String(decodeLegacy85(arg))); break; case 4: System.out.println(new String(decodeKreative85(arg))); break; case 5: System.out.println(new String(decodeUU(arg))); break; case 6: System.out.println(new String(decodeXX(arg))); break; } } else { switch (mode) { case 0: System.out.println(encodeBase64(arg.getBytes())); break; case 1: System.out.println(encodeBinHex(arg.getBytes())); break; case 2: System.out.println(encodeASCII85(arg.getBytes())); break; case 3: System.out.println(encodeLegacy85(arg.getBytes())); break; case 4: System.out.println(encodeKreative85(arg.getBytes())); break; case 5: System.out.println(encodeUU(arg.getBytes())); break; case 6: System.out.println(encodeXX(arg.getBytes())); break; } } } }
From source file:edu.umn.cs.spatialHadoop.indexing.RTree.java
/** * A main method that creates a single R-tree out of a single file. * @param args/* w ww.j a va2s. co m*/ * @throws IOException */ public static void main(String[] args) throws IOException { final OperationsParams params = new OperationsParams(new GenericOptionsParser(args)); if (!params.checkInputOutput()) throw new RuntimeException("Input-output combination not correct"); Path inPath = params.getInputPath(); Path outPath = params.getOutputPath(); Shape shape = params.getShape("shape"); // Read the whole input file as one byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 1024]; FileSystem inFS = inPath.getFileSystem(params); FSDataInputStream in = inFS.open(inPath); int bytesRead; while ((bytesRead = in.read(buffer)) >= 0) { baos.write(buffer, 0, bytesRead); } in.close(); baos.close(); // Create the R-tree and write to output byte[] inputData = baos.toByteArray(); FileSystem outFS = outPath.getFileSystem(params); FSDataOutputStream out = outFS.create(outPath); RTree.bulkLoadWrite(inputData, 0, inputData.length, 4, out, shape, true); out.close(); }
From source file:Main.java
public static byte[] readStream(InputStream is) throws Exception { byte[] bytes = new byte[1024]; int leng;//from w ww .j a v a 2 s . co m ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((leng = is.read(bytes)) != -1) { baos.write(bytes, 0, leng); } return baos.toByteArray(); }
From source file:Main.java
public static String inputStream2String(InputStream in) throws IOException { byte[] buf = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (int i; (i = in.read(buf)) != -1;) { baos.write(buf, 0, i); }//from w w w . jav a2 s .co m return baos.toString("UTF-8"); }
From source file:Main.java
public static byte[] toByte(InputStream input) throws IOException { byte[] buf = new byte[1024]; int len = -1; ByteArrayOutputStream output = new ByteArrayOutputStream(); while ((len = input.read(buf)) != -1) { output.write(buf, 0, len); }/* w w w . j av a 2 s. c om*/ byte[] data = output.toByteArray(); output.close(); input.close(); return data; }
From source file:Main.java
private static byte[] readFully(InputStream input) throws IOException { byte[] buffer = new byte[8192]; int bytesRead; ByteArrayOutputStream output = new ByteArrayOutputStream(); while ((bytesRead = input.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); }//from www. j av a2 s. c o m return output.toByteArray(); }
From source file:Main.java
public static void writeData(ByteArrayOutputStream baos, byte[] data) { writeLength(baos, data.length);/*from ww w .j a va2 s.com*/ baos.write(data, 0, data.length); }