List of usage examples for java.nio.channels WritableByteChannel write
public int write(ByteBuffer src) throws IOException;
From source file:com.cloud.maint.UpgradeManagerImpl.java
public String deployNewAgent(String url) { s_logger.info("Updating agent with binary from " + url); final HttpClient client = new HttpClient(s_httpClientManager); final GetMethod method = new GetMethod(url); int response; File file = null;//from ww w . j av a2s. co m try { response = client.executeMethod(method); if (response != HttpURLConnection.HTTP_OK) { s_logger.warn("Retrieving the agent gives response code: " + response); return "Retrieving the file from " + url + " got response code: " + response; } final InputStream is = method.getResponseBodyAsStream(); file = File.createTempFile("agent-", "-" + Long.toString(new Date().getTime())); file.deleteOnExit(); s_logger.debug("Retrieving new agent into " + file.getAbsolutePath()); final FileOutputStream fos = new FileOutputStream(file); final ByteBuffer buffer = ByteBuffer.allocate(2048); final ReadableByteChannel in = Channels.newChannel(is); final WritableByteChannel out = fos.getChannel(); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } in.close(); out.close(); s_logger.debug("New Agent zip file is now retrieved"); } catch (final HttpException e) { return "Unable to retrieve the file from " + url; } catch (final IOException e) { return "Unable to retrieve the file from " + url; } finally { method.releaseConnection(); } file.delete(); return "File will be deployed."; }
From source file:SelfClassLoader.java
private byte[] loadClassBytes(String className) throws ClassNotFoundException { try {/*from w ww .j a va2s . c o m*/ String classFile = getClassFile(className); FileInputStream fis = new FileInputStream(classFile); FileChannel fileC = fis.getChannel(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel outC = Channels.newChannel(baos); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int i = fileC.read(buffer); if (i == 0 || i == -1) { break; } buffer.flip(); outC.write(buffer); buffer.clear(); } fis.close(); return baos.toByteArray(); } catch (IOException fnfe) { throw new ClassNotFoundException(className); } }
From source file:org.eclipse.packagedrone.utils.rpm.build.PayloadRecorder.java
public Result addFile(final String targetPath, final ByteBuffer data, final Consumer<CpioArchiveEntry> customizer) throws IOException { final long size = data.remaining(); final CpioArchiveEntry entry = new CpioArchiveEntry(targetPath); entry.setSize(size);/*from w w w . java 2 s . c o m*/ if (customizer != null) { customizer.accept(entry); } this.archiveStream.putArchiveEntry(entry); // record digest MessageDigest digest; try { digest = createDigest(); digest.update(data.slice()); } catch (final NoSuchAlgorithmException e) { throw new IOException(e); } // write data final WritableByteChannel channel = Channels.newChannel(this.archiveStream); while (data.hasRemaining()) { channel.write(data); } // close archive entry this.archiveStream.closeArchiveEntry(); return new Result(size, digest.digest()); }
From source file:com.bittorrent.mpetazzoni.tracker.TrackerService.java
/** * Process the announce request.// ww w .j a va 2 s. c o m * * <p> * This method attemps to read and parse the incoming announce request into * an announce request message, then creates the appropriate announce * response message and sends it back to the client. * </p> * * @param request The incoming announce request. * @param response The response object. * @param body The validated response body output stream. */ private void process(Request request, Response response, OutputStream body) throws IOException { // Prepare the response headers. response.set("Content-Type", "text/plain"); response.set("Server", this.version); response.setDate("Date", System.currentTimeMillis()); /** * Parse the query parameters into an announce request message. * * We need to rely on our own query parsing function because * SimpleHTTP's Query map will contain UTF-8 decoded parameters, which * doesn't work well for the byte-encoded strings we expect. */ HTTPAnnounceRequestMessage announceRequest = null; try { announceRequest = this.parseQuery(request); } catch (MessageValidationException mve) { this.serveError(response, body, Status.BAD_REQUEST, mve.getMessage()); return; } // The requested torrent must be announced by the tracker. TrackedTorrent torrent = this.torrents.get(announceRequest.getHexInfoHash()); if (torrent == null) { logger.warn("Requested torrent hash was: {}", announceRequest.getHexInfoHash()); this.serveError(response, body, Status.BAD_REQUEST, ErrorMessage.FailureReason.UNKNOWN_TORRENT); return; } AnnounceRequestMessage.RequestEvent event = announceRequest.getEvent(); String peerId = announceRequest.getHexPeerId(); // When no event is specified, it's a periodic update while the client // is operating. If we don't have a peer for this announce, it means // the tracker restarted while the client was running. Consider this // announce request as a 'started' event. if ((event == null || AnnounceRequestMessage.RequestEvent.NONE.equals(event)) && torrent.getPeer(peerId) == null) { event = AnnounceRequestMessage.RequestEvent.STARTED; } // If an event other than 'started' is specified and we also haven't // seen the peer on this torrent before, something went wrong. A // previous 'started' announce request should have been made by the // client that would have had us register that peer on the torrent this // request refers to. if (event != null && torrent.getPeer(peerId) == null && !AnnounceRequestMessage.RequestEvent.STARTED.equals(event)) { this.serveError(response, body, Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT); return; } // Update the torrent according to the announce event TrackedPeer peer = null; try { peer = torrent.update(event, ByteBuffer.wrap(announceRequest.getPeerId()), announceRequest.getHexPeerId(), announceRequest.getIp(), announceRequest.getPort(), announceRequest.getUploaded(), announceRequest.getDownloaded(), announceRequest.getLeft()); } catch (IllegalArgumentException iae) { this.serveError(response, body, Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT); return; } // Craft and output the answer HTTPAnnounceResponseMessage announceResponse = null; try { announceResponse = HTTPAnnounceResponseMessage.craft(torrent.getAnnounceInterval(), TrackedTorrent.MIN_ANNOUNCE_INTERVAL_SECONDS, this.version, torrent.seeders(), torrent.leechers(), torrent.getSomePeers(peer)); WritableByteChannel channel = Channels.newChannel(body); channel.write(announceResponse.getData()); } catch (Exception e) { this.serveError(response, body, Status.INTERNAL_SERVER_ERROR, e.getMessage()); } }
From source file:com.p2p.peercds.tracker.TrackerService.java
/** * Process the announce request./*from w ww . j ava 2 s . co m*/ * * <p> * This method attemps to read and parse the incoming announce request into * an announce request message, then creates the appropriate announce * response message and sends it back to the client. * </p> * * @param request The incoming announce request. * @param response The response object. * @param body The validated response body output stream. */ private void process(Request request, Response response, OutputStream body) throws IOException { // Prepare the response headers. response.set("Content-Type", "text/plain"); response.set("Server", this.version); response.setDate("Date", System.currentTimeMillis()); /** * Parse the query parameters into an announce request message. * * We need to rely on our own query parsing function because * SimpleHTTP's Query map will contain UTF-8 decoded parameters, which * doesn't work well for the byte-encoded strings we expect. */ HTTPAnnounceRequestMessage announceRequest = null; try { announceRequest = this.parseQuery(request); } catch (MessageValidationException mve) { this.serveError(response, body, Status.BAD_REQUEST, mve.getMessage()); return; } // first check for existing torrent, if not present add a new torrent TrackerTorrent torrent = this.torrents.get(announceRequest.getHexInfoHash()); if (torrent == null) { logger.info("New Torrent announce request received. Veriyfing the event-type:"); if ((announceRequest.getEvent() == null || !AnnounceRequestMessage.RequestEvent.STARTED.equals(announceRequest.getEvent()))) { logger.warn("New torrent must be registered with started event"); this.serveError(response, body, Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT); return; } else { logger.info("Lock grabbed to register a new torrent"); lock.lock(); if (this.torrents.get(announceRequest.getHexInfoHash()) == null) { logger.info("Event type verified, registering newly announced torrent."); torrent = new UntrackedTorrent("NewTorrent", announceRequest.getHexInfoHash()); torrents.put(announceRequest.getHexInfoHash(), torrent); logger.info("new torrent registration complete."); } else logger.info("Torrent already registered by someone. Skipping the registration."); lock.unlock(); logger.info("torrent registration lock released"); } } AnnounceRequestMessage.RequestEvent event = announceRequest.getEvent(); String peerId = announceRequest.getHexPeerId(); // When no event is specified, it's a periodic update while the client // is operating. If we don't have a peer for this announce, it means // the tracker restarted while the client was running. Consider this // announce request as a 'started' event. if ((event == null || AnnounceRequestMessage.RequestEvent.NONE.equals(event)) && torrent.getPeer(peerId) == null) { event = AnnounceRequestMessage.RequestEvent.STARTED; } // If an event other than 'started' is specified and we also haven't // seen the peer on this torrent before, something went wrong. A // previous 'started' announce request should have been made by the // client that would have had us register that peer on the torrent this // request refers to. if (event != null && torrent.getPeer(peerId) == null && !AnnounceRequestMessage.RequestEvent.STARTED.equals(event)) { this.serveError(response, body, Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT); return; } // Update the torrent according to the announce event TrackedPeer peer = null; try { peer = torrent.update(event, ByteBuffer.wrap(announceRequest.getPeerId()), announceRequest.getHexPeerId(), announceRequest.getIp(), announceRequest.getPort(), announceRequest.getUploaded(), announceRequest.getDownloaded(), announceRequest.getLeft()); } catch (IllegalArgumentException iae) { this.serveError(response, body, Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT); return; } catch (Exception e) { this.serveError(response, body, Status.INTERNAL_SERVER_ERROR, e.getMessage()); } // Craft and output the answer HTTPAnnounceResponseMessage announceResponse = null; try { announceResponse = HTTPAnnounceResponseMessage.craft(torrent.getAnnounceInterval(), TrackedTorrent.MIN_ANNOUNCE_INTERVAL_SECONDS, this.version, torrent.seeders(), torrent.leechers(), torrent.getSomePeers(peer)); WritableByteChannel channel = Channels.newChannel(body); channel.write(announceResponse.getData()); } catch (Exception e) { this.serveError(response, body, Status.INTERNAL_SERVER_ERROR, e.getMessage()); } }
From source file:org.alfresco.cacheserver.dropwizard.resources.CacheServerResource.java
private void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException { final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024); while (src.read(buffer) != -1) { // prepare the buffer to be drained buffer.flip();//from www. j a v a 2 s . c o m // write to the channel, may block dest.write(buffer); // If partial transfer, shift remainder down // If buffer is empty, same as doing clear() buffer.compact(); } // EOF will leave buffer in fill state buffer.flip(); // make sure the buffer is fully drained. while (buffer.hasRemaining()) { dest.write(buffer); } }
From source file:org.openhab.io.transport.cul.internal.network.CULNetworkHandlerImpl.java
private void processWrite(SelectionKey key) throws IOException { WritableByteChannel ch = (WritableByteChannel) key.channel(); synchronized (writeBuf) { writeBuf.flip();//from w ww . j a va 2s.co m int bytesOp = 0, bytesTotal = 0; while (writeBuf.hasRemaining() && (bytesOp = ch.write(writeBuf)) > 0) { bytesTotal += bytesOp; } logger.debug("Written {} bytes to the network", bytesTotal); if (writeBuf.remaining() == 0) { key.interestOps(key.interestOps() ^ SelectionKey.OP_WRITE); } if (bytesTotal > 0) { writeBuf.notify(); } else if (bytesOp == -1) { logger.info("peer closed write channel"); ch.close(); } writeBuf.compact(); } }
From source file:org.red5.server.net.proxy.DebugProxyHandler.java
/** {@inheritDoc} */ @Override//from w w w . j ava 2 s .c om public void sessionCreated(IoSession session) throws Exception { boolean isClient = session.getRemoteAddress().equals(forward); //session.getConfig(); if (log.isDebugEnabled()) { log.debug("Is downstream: " + isClient); session.setAttribute(ProtocolState.SESSION_KEY, new RTMP(isClient)); session.getFilterChain().addFirst("protocol", new ProtocolCodecFilter(codecFactory)); } session.getFilterChain().addFirst("proxy", new ProxyFilter(isClient ? "client" : "server")); if (true) { String fileName = System.currentTimeMillis() + '_' + forward.getHostName() + '_' + forward.getPort() + '_' + (isClient ? "DOWNSTREAM" : "UPSTREAM"); File headersFile = loader.getResource(dumpTo + fileName + ".cap").getFile(); headersFile.createNewFile(); File rawFile = loader.getResource(dumpTo + fileName + ".raw").getFile(); rawFile.createNewFile(); FileOutputStream headersFos = new FileOutputStream(headersFile); WritableByteChannel headers = headersFos.getChannel(); FileOutputStream rawFos = new FileOutputStream(rawFile); WritableByteChannel raw = rawFos.getChannel(); ByteBuffer header = ByteBuffer.allocate(1); header.put((byte) (isClient ? 0x00 : 0x01)); header.flip(); headers.write(header.buf()); session.getFilterChain().addFirst("dump", new NetworkDumpFilter(headers, raw)); } //session.getFilterChain().addLast( // "logger", new LoggingFilter() ); if (!isClient) { log.debug("Connecting.."); SocketConnector connector = new SocketConnector(); ConnectFuture future = connector.connect(forward, this); future.join(); // wait for connect, or timeout if (future.isConnected()) { if (log.isDebugEnabled()) { log.debug("Connected: " + forward); } IoSession client = future.getSession(); client.setAttribute(ProxyFilter.FORWARD_KEY, session); session.setAttribute(ProxyFilter.FORWARD_KEY, client); } } super.sessionCreated(session); }
From source file:org.apache.beam.sdk.io.FileBasedSinkTest.java
private File writeValuesWithWritableByteChannelFactory(final WritableByteChannelFactory factory, String... values) throws IOException { final File file = tmpFolder.newFile("test.gz"); final WritableByteChannel channel = factory.create(Channels.newChannel(new FileOutputStream(file))); for (String value : values) { channel.write(ByteBuffer.wrap((value + "\n").getBytes(StandardCharsets.UTF_8))); }// w ww . j a v a 2s . c o m channel.close(); return file; }
From source file:com.streamsets.pipeline.lib.generator.wholefile.WholeFileDataGenerator.java
@Override public void write(Record record) throws IOException, DataGeneratorException { validateRecord(record);/*from w w w .ja v a2s . c om*/ FileRef fileRef = record.get(FileRefUtil.FILE_REF_FIELD_PATH).getValueAsFileRef(); int bufferSize = fileRef.getBufferSize(); boolean canUseDirectByteBuffer = fileRef.getSupportedStreamClasses().contains(ReadableByteChannel.class); if (canUseDirectByteBuffer) { //Don't have to close this here, because generate.close will call output stream close WritableByteChannel writableByteChannel = Channels.newChannel(outputStream); //NOSONAR try (ReadableByteChannel readableByteChannel = getReadableStream(fileRef, ReadableByteChannel.class)) { ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize); while ((readableByteChannel.read(buffer)) > 0) { //Flip to use the buffer from 0 to position. buffer.flip(); while (buffer.hasRemaining()) { writableByteChannel.write(buffer); } //Compact the buffer for reuse. buffer.clear(); } } } else { byte[] b = new byte[bufferSize]; try (InputStream stream = getReadableStream(fileRef, InputStream.class)) { IOUtils.copyLarge(stream, outputStream, b); } } }