Example usage for io.netty.buffer ByteBuf readBytes

List of usage examples for io.netty.buffer ByteBuf readBytes

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf readBytes.

Prototype

public abstract int readBytes(GatheringByteChannel out, int length) throws IOException;

Source Link

Document

Transfers this buffer's data to the specified stream starting at the current readerIndex .

Usage

From source file:com.comphenix.protocol.events.PacketContainer.java

License:Open Source License

private void writeObject(ObjectOutputStream output) throws IOException {
    // Default serialization
    output.defaultWriteObject();// ww w.j  a v a  2 s.  c  o  m

    // We'll take care of NULL packets as well
    output.writeBoolean(handle != null);

    try {
        if (MinecraftReflection.isUsingNetty()) {
            ByteBuf buffer = createPacketBuffer();
            MinecraftMethods.getPacketWriteByteBufMethod().invoke(handle, buffer);

            output.writeInt(buffer.readableBytes());
            buffer.readBytes(output, buffer.readableBytes());
        } else {
            // Call the write-method
            output.writeInt(-1);
            getMethodLazily(writeMethods, handle.getClass(), "write", DataOutput.class).invoke(handle,
                    new DataOutputStream(output));
        }

    } catch (IllegalArgumentException e) {
        throw new IOException("Minecraft packet doesn't support DataOutputStream", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Insufficient security privileges.", e);
    } catch (InvocationTargetException e) {
        throw new IOException("Could not serialize Minecraft packet.", e);
    }
}

From source file:com.github.jrialland.ajpclient.impl.ForwardImpl.java

License:Apache License

@Override
public void handleSendBodyChunkMessage(final ByteBuf data) throws Exception {
    data.readBytes(response.getOutputStream(), data.readableBytes());
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpDownloadHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (!msg.decoderResult().isSuccess()) {
        failAndClose(new IOException("Failed to parse the HTTP response."), ctx);
        return;//from  w ww  . j  a  v a 2  s .  c  om
    }
    if (!(msg instanceof HttpResponse) && !(msg instanceof HttpContent)) {
        failAndClose(
                new IllegalArgumentException("Unsupported message type: " + StringUtil.simpleClassName(msg)),
                ctx);
        return;
    }
    checkState(userPromise != null, "response before request");

    if (msg instanceof HttpResponse) {
        response = (HttpResponse) msg;
        if (!response.protocolVersion().equals(HttpVersion.HTTP_1_1)) {
            HttpException error = new HttpException(response,
                    "HTTP version 1.1 is required, was: " + response.protocolVersion(), null);
            failAndClose(error, ctx);
            return;
        }
        if (!HttpUtil.isContentLengthSet(response) && !HttpUtil.isTransferEncodingChunked(response)) {
            HttpException error = new HttpException(response,
                    "Missing 'Content-Length' or 'Transfer-Encoding: chunked' header", null);
            failAndClose(error, ctx);
            return;
        }
        downloadSucceeded = response.status().equals(HttpResponseStatus.OK);
        if (!downloadSucceeded) {
            out = new ByteArrayOutputStream();
        }
        keepAlive = HttpUtil.isKeepAlive((HttpResponse) msg);
    }

    if (msg instanceof HttpContent) {
        checkState(response != null, "content before headers");

        ByteBuf content = ((HttpContent) msg).content();
        content.readBytes(out, content.readableBytes());
        if (msg instanceof LastHttpContent) {
            if (downloadSucceeded) {
                succeedAndReset(ctx);
            } else {
                String errorMsg = response.status() + "\n";
                errorMsg += new String(((ByteArrayOutputStream) out).toByteArray(),
                        HttpUtil.getCharset(response));
                out.close();
                HttpException error = new HttpException(response, errorMsg, null);
                failAndReset(error, ctx);
            }
        }
    }
}

From source file:com.heliosapm.streams.metrichub.tsdbplugin.MetricsAPIHttpPlugin.java

License:Apache License

/**
 * Unloads the UI content from a jar//from   w  w w. j  av a  2  s.c o m
 * @param file The jar file
 */
protected void unloadFromJar(final File file) {
    log.info("Loading MetricsAPI UI Content from JAR: [{}]", file);
    final long startTime = System.currentTimeMillis();
    int filesLoaded = 0;
    int fileFailures = 0;
    int fileNewer = 0;
    long bytesLoaded = 0;

    JarFile jar = null;
    final ByteBuf contentBuffer = BufferManager.getInstance().directBuffer(30000);
    try {
        jar = new JarFile(file);
        final Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            final String name = entry.getName();
            if (name.startsWith(CONTENT_BASE + "/")) {
                final int contentSize = (int) entry.getSize();
                final long contentTime = entry.getTime();
                if (entry.isDirectory()) {
                    new File(metricUiContentDir, name).mkdirs();
                    continue;
                }
                File contentFile = new File(metricUiContentDir, name.replace(CONTENT_BASE + "/", ""));
                if (!contentFile.getParentFile().exists()) {
                    contentFile.getParentFile().mkdirs();
                }
                if (contentFile.exists()) {
                    if (contentFile.lastModified() >= contentTime) {
                        log.debug("File in directory was newer [{}]", name);
                        fileNewer++;
                        continue;
                    }
                    contentFile.delete();
                }
                log.debug("Writing content file [{}]", contentFile);
                contentFile.createNewFile();
                if (!contentFile.canWrite()) {
                    log.warn("Content file [{}] not writable", contentFile);
                    fileFailures++;
                    continue;
                }
                FileOutputStream fos = null;
                InputStream jis = null;
                try {
                    fos = new FileOutputStream(contentFile);
                    jis = jar.getInputStream(entry);
                    contentBuffer.writeBytes(jis, contentSize);
                    contentBuffer.readBytes(fos, contentSize);
                    fos.flush();
                    jis.close();
                    jis = null;
                    fos.close();
                    fos = null;
                    filesLoaded++;
                    bytesLoaded += contentSize;
                    log.debug("Wrote content file [{}] + with size [{}]", contentFile, contentSize);
                } finally {
                    if (jis != null)
                        try {
                            jis.close();
                        } catch (Exception ex) {
                        }
                    if (fos != null)
                        try {
                            fos.close();
                        } catch (Exception ex) {
                        }
                    contentBuffer.clear();
                }
            } // not content
        } // end of while loop
        final long elapsed = System.currentTimeMillis() - startTime;
        StringBuilder b = new StringBuilder(
                "\n\n\t===================================================\n\tMetricsAPI Content Directory:[")
                        .append(metricUiContentDir).append("]");
        b.append("\n\tTotal Files Written:").append(filesLoaded);
        b.append("\n\tTotal Bytes Written:").append(bytesLoaded);
        b.append("\n\tFile Write Failures:").append(fileFailures);
        b.append("\n\tExisting File Newer Than Content:").append(fileNewer);
        b.append("\n\tElapsed (ms):").append(elapsed);
        b.append("\n\t===================================================\n");
        log.info(b.toString());
    } catch (Exception ex) {
        log.error("Failed to export MetricsAPI content", ex);
    } finally {
        if (jar != null)
            try {
                jar.close();
            } catch (Exception x) {
                /* No Op */}
        try {
            contentBuffer.release();
        } catch (Exception x) {
            /* No Op */}
    }
}

From source file:com.heliosapm.tsdblite.handlers.http.HttpStaticFileServerHandler.java

License:Open Source License

/**
 * Loads the Static UI content files from the classpath JAR to the configured static root directory
 * @param the name of the content directory to write the content to
 *///from  w  ww. ja  va  2  s. co  m
private void loadContent(String contentDirectory) {
    File gpDir = new File(contentDirectory);
    final long startTime = System.currentTimeMillis();
    int filesLoaded = 0;
    int fileFailures = 0;
    int fileNewer = 0;
    long bytesLoaded = 0;
    String codeSourcePath = HttpStaticFileServerHandler.class.getProtectionDomain().getCodeSource()
            .getLocation().getPath();
    File file = new File(codeSourcePath);
    if (codeSourcePath.endsWith(".jar") && file.exists() && file.canRead()) {
        JarFile jar = null;
        ByteBuf contentBuffer = Unpooled.directBuffer(300000);
        try {
            jar = new JarFile(file);
            final Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                final String name = entry.getName();
                if (name.startsWith(CONTENT_PREFIX + "/")) {
                    final int contentSize = (int) entry.getSize();
                    final long contentTime = entry.getTime();
                    if (entry.isDirectory()) {
                        new File(gpDir, name).mkdirs();
                        continue;
                    }
                    File contentFile = new File(gpDir, name.replace(CONTENT_PREFIX + "/", ""));
                    if (!contentFile.getParentFile().exists()) {
                        contentFile.getParentFile().mkdirs();
                    }
                    if (contentFile.exists()) {
                        if (contentFile.lastModified() >= contentTime) {
                            log.debug("File in directory was newer [{}]", name);
                            fileNewer++;
                            continue;
                        }
                        contentFile.delete();
                    }
                    log.debug("Writing content file [{}]", contentFile);
                    contentFile.createNewFile();
                    if (!contentFile.canWrite()) {
                        log.warn("Content file [{}] not writable", contentFile);
                        fileFailures++;
                        continue;
                    }
                    FileOutputStream fos = null;
                    InputStream jis = null;
                    try {
                        fos = new FileOutputStream(contentFile);
                        jis = jar.getInputStream(entry);
                        contentBuffer.writeBytes(jis, contentSize);
                        contentBuffer.readBytes(fos, contentSize);
                        fos.flush();
                        jis.close();
                        jis = null;
                        fos.close();
                        fos = null;
                        filesLoaded++;
                        bytesLoaded += contentSize;
                        log.debug("Wrote content file [{}] + with size [{}]", contentFile, contentSize);
                    } finally {
                        if (jis != null)
                            try {
                                jis.close();
                            } catch (Exception ex) {
                            }
                        if (fos != null)
                            try {
                                fos.close();
                            } catch (Exception ex) {
                            }
                    }
                } // not content
            } // end of while loop
            final long elapsed = System.currentTimeMillis() - startTime;
            StringBuilder b = new StringBuilder(
                    "\n\n\t===================================================\n\tStatic Root Directory:[")
                            .append(contentDirectory).append("]");
            b.append("\n\tTotal Files Written:").append(filesLoaded);
            b.append("\n\tTotal Bytes Written:").append(bytesLoaded);
            b.append("\n\tFile Write Failures:").append(fileFailures);
            b.append("\n\tExisting File Newer Than Content:").append(fileNewer);
            b.append("\n\tElapsed (ms):").append(elapsed);
            b.append("\n\t===================================================\n");
            log.info(b.toString());
        } catch (Exception ex) {
            log.error("Failed to export ui content", ex);
        } finally {
            if (jar != null)
                try {
                    jar.close();
                } catch (Exception x) {
                    /* No Op */}
        }
    } else { // end of was-not-a-jar
        log.warn(
                "\n\tThe TSDBLite classpath is not a jar file, so there is no content to unload.\n\tBuild the OpenTSDB jar and run 'java -jar <jar> --d <target>'.");
    }
}

From source file:com.mastfrog.acteur.server.EventImpl.java

License:Open Source License

public OutputStream getContentAsStream() throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream(40);
    getChannel().read();/*from  w w  w . j av a2  s . c o m*/
    ByteBuf inbound = getContent();
    int count;
    do {
        count = inbound.readableBytes();
        if (count > 0) {
            inbound.readBytes(out, count);
        }
    } while (count > 0);
    return out;
}

From source file:com.mobius.software.android.iotbroker.mqtt.net.MQDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
    ByteBuf nextHeader = null;/*www  .  j  a  v  a2  s.  co  m*/
    do {
        if (buf.readableBytes() > 1)
            nextHeader = MQParser.next(buf);

        if (nextHeader != null) {
            buf.readBytes(nextHeader, nextHeader.capacity());
            try {
                MQMessage header = MQParser.decode(nextHeader);
                out.add(header);
            } catch (Exception e) {
                buf.resetReaderIndex();
                ctx.channel().pipeline().remove(this);
                throw e;
            } finally {
                nextHeader.release();
            }
        }
    } while (buf.readableBytes() > 1 && nextHeader != null);
}

From source file:com.mobius.software.mqtt.performance.controller.net.Decoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) {
    ByteBuf nextHeader = null;//  w  w w .j  a v a  2s . c o  m
    do {
        if (buf.readableBytes() > 1) {
            try {
                nextHeader = MQParser.next(buf);
            } catch (MalformedMessageException | IndexOutOfBoundsException ex) {
                buf.resetReaderIndex();
                if (nextHeader != null)
                    nextHeader = null;
            }
        }

        if (nextHeader != null) {
            buf.readBytes(nextHeader, nextHeader.capacity());
            try {
                MQMessage header = MQParser.decode(nextHeader);
                out.add(header);
            } catch (Exception e) {
                buf.resetReaderIndex();
                ctx.channel().pipeline().remove(this);
                throw e;
            } finally {
                nextHeader.release();
            }
        }
    } while (buf.readableBytes() > 1 && nextHeader != null);
}

From source file:com.myftpserver.handler.ReceiveFileHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (bos == null) {
        User user = fs.getUser();/*from   ww w  .ja  v  a2  s .c o m*/
        if (user.getUploadSpeedLitmit() == 0L)
            logger.info("File upload speed is limited by connection speed");
        else {
            ctx.channel().pipeline().addFirst("TrafficShapingHandler",
                    new ChannelTrafficShapingHandler(0L, user.getUploadSpeedLitmit() * 1024));
            logger.info("File upload speed limit:" + user.getUploadSpeedLitmit() + " kB/s");
        }
        ctx.channel().closeFuture().addListener(this);
        tempFile = File.createTempFile("temp-file-name", ".tmp");
        fs.setUploadTempFile(tempFile);
        bos = new BufferedOutputStream(new FileOutputStream(tempFile));
    }
    ByteBuf in = (ByteBuf) msg;
    //logger.debug("ReceiveFileHandler channelRead buffer capacity="+in.capacity()+",readable byte count="+in.readableBytes());
    try {
        while (in.isReadable()) {
            in.readBytes(bos, in.readableBytes());
        }
        bos.flush();
    } finally {
        in.release();
    }
}

From source file:com.ReceiveFileHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;

    try {/*from w w  w . j  a  v  a 2 s  . c o  m*/
        while (in.isReadable()) {
            in.readBytes(bos, in.readableBytes());
        }
        bos.flush();
    } finally {
        in.release();
    }
}