List of usage examples for java.nio.channels WritableByteChannel write
public int write(ByteBuffer src) throws IOException;
From source file:org.wymiwyg.wrhapi.test.BaseTests.java
/** * test is the returned status code matches the one of the HandlerException * thrown, with a HandlerException thrown after a body is set * /*from w w w.j a v a 2 s .c o m*/ * @throws Exception * on failure */ /*public void testExceptionStatusCodeAfterBody() throws Exception { final int statusCode = 302; WebServer webServer = createServer().startNewWebServer(new Handler() { public void handle(Request request, Response response) throws HandlerException { log.info("handling testStatusCode"); response.setHeader(HeaderName.SERVER, "Ad-Hoc testing server"); response.setBody(new MessageBody2Write() { public void writeTo(WritableByteChannel out) throws IOException { out.write(ByteBuffer.wrap("my body\n\ncontent\n" .getBytes())); } }); throw new HandlerException(ResponseStatus.getInstanceByCode(statusCode)); } }, serverBinding); try { URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":" + serverBinding.getPort() + "/"); HttpClient client = new HttpClient(); HttpMethod method = new HeadMethod(serverURL.toString()); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); client.executeMethod(method); // for the handler to be invoked, something of the response has to // be asked assertEquals(statusCode, method.getStatusCode()); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { webServer.stop(); } }*/ @Test public void testRepeated() throws Exception { final String body = "This is the content of the body"; final boolean writeBody = false; WebServer webServer = createServer().startNewWebServer(new Handler() { public void handle(Request request, Response response) throws HandlerException { log.info("handling testSimpleBody"); if (writeBody) { response.setBody(new MessageBody2Write() { public void writeTo(WritableByteChannel out) throws IOException { out.write(ByteBuffer.wrap(body.getBytes())); } }); } else { response.setBody(new MessageBody2Read() { public ReadableByteChannel read() throws IOException { return Channels.newChannel(new ByteArrayInputStream(body.getBytes())); } }); } } }, serverBinding); TimeLogger tl = new TimeLogger(); for (int r = 0; r < 10000; r++) { tl.startSection("iteration"); URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":" + serverBinding.getPort() + "/"); Reader reader = new InputStreamReader(serverURL.openStream()); StringWriter stringWriter = new StringWriter(); for (int ch = reader.read(); ch != -1; ch = reader.read()) { stringWriter.write(ch); } assertEquals(body, stringWriter.toString()); tl.endSection(); } webServer.stop(); tl.writeReport(new PrintWriter(System.out)); System.out.println("Using SummaryReportWriter:"); tl.setReportWriter(new SummaryReportWriter()); tl.writeReport(new PrintWriter(System.out)); }
From source file:org.apache.hadoop.ipc.ServerRpcSSLEngineImpl.java
@Override public int write(WritableByteChannel channel, ByteBuffer buffer) throws IOException { serverAppBuffer.clear();// www . ja v a 2 s .c om if (serverAppBuffer.capacity() < buffer.capacity()) { LOG.debug("ServerAppBuffer capacity: " + serverAppBuffer.capacity() + " Buffer size: " + buffer.capacity()); serverAppBuffer = ByteBuffer.allocate(Math.min(buffer.capacity(), MAX_BUFFER_SIZE)); } serverAppBuffer.put(buffer); serverAppBuffer.flip(); int bytesWritten = 0; while (serverAppBuffer.hasRemaining()) { serverNetBuffer.clear(); SSLEngineResult result = sslEngine.wrap(serverAppBuffer, serverNetBuffer); switch (result.getStatus()) { case OK: serverNetBuffer.flip(); while (serverNetBuffer.hasRemaining()) { bytesWritten += channel.write(serverNetBuffer); } //return bytesWritten; break; case BUFFER_OVERFLOW: serverNetBuffer = enlargePacketBuffer(serverNetBuffer); break; case BUFFER_UNDERFLOW: throw new SSLException("Buffer underflow should not happen after wrap"); case CLOSED: sslEngine.closeOutbound(); doHandshake(); return -1; default: throw new IllegalStateException("Invalid SSL state: " + result.getStatus()); } } return bytesWritten; }
From source file:org.wymiwyg.wrhapi.test.BaseTests.java
@Test public void testEmptyBodyAnHeader() throws Exception { final String body = ""; WebServer webServer = createServer().startNewWebServer(new Handler() { public void handle(Request request, final Response response) throws HandlerException { log.info("handling testEmptyBody"); response.setResponseStatus(ResponseStatus.CREATED); response.setBody(new MessageBody2Write() { public void writeTo(WritableByteChannel out) throws IOException { try { response.setHeader(HeaderName.CONTENT_TYPE, "text/plain"); } catch (HandlerException ex) { throw new RuntimeException(ex); }//ww w. ja v a2s . com out.write(ByteBuffer.wrap(body.getBytes())); out.close(); } }); } }, serverBinding); try { URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":" + serverBinding.getPort() + "/"); HttpURLConnection connection = (HttpURLConnection) serverURL.openConnection(); assertEquals("text/plain", connection.getHeaderField("Content-Type")); assertEquals(ResponseStatus.CREATED.getCode(), connection.getResponseCode()); Reader reader = new InputStreamReader(connection.getInputStream()); StringWriter stringWriter = new StringWriter(); for (int ch = reader.read(); ch != -1; ch = reader.read()) { stringWriter.write(ch); } assertEquals(body, stringWriter.toString()); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { webServer.stop(); } }
From source file:org.bytesoft.openjtcc.supports.logger.DbTransactionLoggerImpl.java
private byte[] streamToByteArray(InputStream input) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ReadableByteChannel in = null; WritableByteChannel out = null; ByteBuffer buffer = ByteBuffer.allocate(1024); try {// w ww .j ava 2s .c om in = Channels.newChannel(input); out = Channels.newChannel(baos); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } } catch (IOException ex) { // ignore } finally { if (out != null) { try { out.close(); } catch (IOException e) { // ignore } } if (baos != null) { try { baos.close(); } catch (IOException e) { // ignore } } } return baos.toByteArray(); }
From source file:edu.usc.pgroup.floe.client.FloeClient.java
/** * Download the file from the Coordinator's scratch folder. * Note: Filename should not be an absolute path or contain ".." * * @param fileName name of the file to be downloaded from coordinator's * scratch./*from ww w.j av a2s . co m*/ * @param outFileName (local) output file name. */ public final void downloadFileSync(final String fileName, final String outFileName) { if (!Utils.checkValidFileName(fileName)) { throw new IllegalArgumentException( "Filename is valid. Should not" + " contain .. and should not be an absolute path."); } int rfid = 0; WritableByteChannel outChannel = null; try { rfid = getClient().beginFileDownload(fileName); File outFile = new File(outFileName); File parent = outFile.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } outChannel = Channels.newChannel(new FileOutputStream(outFileName)); } catch (TException e) { LOGGER.error(e.getMessage()); throw new RuntimeException(e); } catch (FileNotFoundException e) { LOGGER.error(e.getMessage()); throw new RuntimeException(e); } int written; try { do { ByteBuffer buffer = null; buffer = getClient().downloadChunk(rfid); written = outChannel.write(buffer); LOGGER.info(String.valueOf(written)); } while (written != 0); } catch (TException e) { LOGGER.error(e.getMessage()); throw new RuntimeException(e); } catch (IOException e) { LOGGER.error(e.getMessage()); throw new RuntimeException(e); } finally { if (outChannel != null) { try { outChannel.close(); } catch (IOException e) { LOGGER.error(e.getMessage()); throw new RuntimeException(e); } } } }
From source file:org.wymiwyg.wrhapi.test.BaseTests.java
@Test public void testHeaderAddedInMessageBody() throws Exception { final String serverHeaderValue = "Ad-Hoc testing server"; WebServer webServer = createServer().startNewWebServer(new Handler() { public void handle(Request request, final Response response) throws HandlerException { response.setBody(new MessageBody2Write() { public void writeTo(WritableByteChannel out) throws IOException { try { response.setHeader(HeaderName.SERVER, serverHeaderValue); } catch (HandlerException ex) { throw new RuntimeException(ex); }// w w w. j a va 2 s . co m ByteBuffer bb = ByteBuffer.wrap("this is the body".getBytes()); out.write(bb); } }); } }, serverBinding); try { URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":" + serverBinding.getPort() + "/"); URLConnection connection = serverURL.openConnection(); connection.connect(); // for the handler to be invoked, something of the response has to // be asked assertEquals(serverHeaderValue, connection.getHeaderField("server")); connection.getContentLength(); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { webServer.stop(); } }
From source file:org.wymiwyg.wrhapi.test.BaseTests.java
@Test public void testStatusCodeResetInMessageBody() throws Exception { final int newStatusCode = 302; WebServer webServer = createServer().startNewWebServer(new Handler() { public void handle(Request request, final Response response) throws HandlerException { log.info("handling testStatusCode"); response.setResponseStatus(ResponseStatus.CREATED); response.setHeader(HeaderName.SERVER, "Ad-Hoc testing server"); response.setHeader(HeaderName.LOCATION, "http://example.org"); response.setBody(new MessageBody2Write() { public void writeTo(WritableByteChannel out) throws IOException { try { response.setResponseStatus(ResponseStatus.getInstanceByCode(newStatusCode)); } catch (HandlerException ex) { throw new RuntimeException(ex); }/*from w w w . ja v a 2 s. c o m*/ ByteBuffer bb = ByteBuffer.wrap("this is the body".getBytes()); out.write(bb); } }); } }, serverBinding); try { URI serverURL = new URI("http://" + serverBinding.getInetAddress().getHostAddress() + ":" + serverBinding.getPort() + "/"); HttpHead method = new HttpHead(serverURL); DefaultHttpClient client = new DefaultHttpClient(); client.setHttpRequestRetryHandler(null); client.setRedirectHandler(nullRedirectHandler); HttpResponse response = client.execute(method); // for the handler to be invoked, something of the response has to // be asked assertEquals(newStatusCode, response.getStatusLine().getStatusCode()); } finally { webServer.stop(); } }
From source file:org.alfresco.contentstore.ChecksumTest.java
protected int applyPatch(ReadableByteChannel inChannel, WritableByteChannel outChannel, PatchDocument patchDocument) throws IOException { InChannel c = new InChannel(inChannel, patchDocument.getMatchedBlocks(), patchDocument.getBlockSize()); int totalWritten = 0; int blockIndex = c.nextBlock(); if (blockIndex > -1) { for (Patch patch : patchDocument.getPatches()) { int lastMatchingBlockIndex = patch.getLastMatchIndex(); while (blockIndex != -1 && blockIndex <= lastMatchingBlockIndex) { int bytesWritten = outChannel.write(c.currentBlock); totalWritten += bytesWritten; if (bytesWritten != c.blockSize) { throw new RuntimeException("Wrote too few bytes, " + c.blockSize + ", " + bytesWritten); }//from ww w .j a va 2 s. c o m blockIndex = c.nextBlock(); if (blockIndex == -1) { break; } } // apply patch int patchSize = patch.getSize(); ReadableByteChannel patchChannel = Channels.newChannel(patch.getStream()); ByteBuffer patchBB = ByteBuffer.allocate(patchSize); int bytesRead = patchChannel.read(patchBB); patchBB.flip(); int bytesWritten = outChannel.write(patchBB); totalWritten += bytesWritten; if (bytesWritten != bytesRead) { throw new RuntimeException( "Wrote too few bytes, expected " + bytesRead + ", got " + bytesWritten); } } // we're done with all the patches, add the remaining blocks while (blockIndex != -1) { int bytesWritten = outChannel.write(c.currentBlock); totalWritten += bytesWritten; if (bytesWritten != c.bytesRead) { throw new RuntimeException("Wrote too few bytes"); } blockIndex = c.nextBlock(); } } return totalWritten; }
From source file:com.github.hrpc.rpc.Server.java
/** * Helper for {@link #channelRead(ReadableByteChannel, ByteBuffer)} * and {@link #channelWrite(WritableByteChannel, ByteBuffer)}. Only * one of readCh or writeCh should be non-null. * * @see #channelRead(ReadableByteChannel, ByteBuffer) * @see #channelWrite(WritableByteChannel, ByteBuffer) */// w w w. ja va 2s . c om private static int channelIO(ReadableByteChannel readCh, WritableByteChannel writeCh, ByteBuffer buf) throws IOException { int originalLimit = buf.limit(); int initialRemaining = buf.remaining(); int ret = 0; while (buf.remaining() > 0) { try { int ioSize = Math.min(buf.remaining(), NIO_BUFFER_LIMIT); buf.limit(buf.position() + ioSize); ret = (readCh == null) ? writeCh.write(buf) : readCh.read(buf); if (ret < ioSize) { break; } } finally { buf.limit(originalLimit); } } int nBytes = initialRemaining - buf.remaining(); return (nBytes > 0) ? nBytes : ret; }