Example usage for io.netty.buffer Unpooled directBuffer

List of usage examples for io.netty.buffer Unpooled directBuffer

Introduction

In this page you can find the example usage for io.netty.buffer Unpooled directBuffer.

Prototype

public static ByteBuf directBuffer(int initialCapacity) 

Source Link

Document

Creates a new big-endian direct buffer with the specified capacity , which expands its capacity boundlessly on demand.

Usage

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 ww  w. ja  v a2 s .c om
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.heliosapm.tsdblite.json.JSON.java

License:Apache License

/**
 * Serializes the passed object as JSON into the passed buffer
 * @param obj The object to serialize//from   w  w w  .j  a va  2  s  .  c o  m
 * @param buf The buffer to serialize into. If null, a new buffer is created
 * @return The buffer the object was written to
 */
public static ByteBuf serializeToBuf(final Object obj, final ByteBuf buf) {
    if (obj == null)
        throw new IllegalArgumentException("The passed object was null");
    final ByteBuf b = buf == null ? Unpooled.directBuffer(2048) : buf;
    OutputStream os = null;
    try {
        os = new ByteBufOutputStream(b);
        serialize(obj, os);
        os.flush();
        return b;
    } catch (Exception ex) {
        throw new RuntimeException("Failed to bufferize serialized object", ex);
    } finally {
        if (os != null)
            try {
                os.close();
            } catch (Exception x) {
                /* No Op */}
    }
}

From source file:com.kixeye.kixmpp.p2p.message.MessageWrapper.java

License:Apache License

public ByteBuf getSerialized(MessageRegistry messageRegistry) {
    if (buf == null) {
        try {/*from   ww  w .  j a v  a  2  s  . c om*/
            buf = ProtostuffEncoder.serializeToByteBuf(messageRegistry, Unpooled.directBuffer(256), message);
        } catch (IOException e) {
            logger.error("Exception serializing message", e);
        }
    }
    return buf;
}

From source file:io.atomix.cluster.messaging.impl.MessageDecoderTest.java

License:Apache License

@Test
public void testReadStringFromDirectBuffer() throws Exception {
    String payload = "huuhaa";
    ByteBuf byteBuf = Unpooled.directBuffer(payload.length())
            .writeBytes(payload.getBytes(StandardCharsets.UTF_8));
    try {/*  w  ww . j a va 2s .  co m*/
        assertEquals(payload, MessageDecoder.readString(byteBuf, payload.length(), StandardCharsets.UTF_8));
    } finally {
        byteBuf.release();
    }
}

From source file:io.grpc.alts.internal.ByteBufTestUtils.java

License:Apache License

public static ByteBuf getDirectBuffer(int len, RegisterRef ref) {
    return ref.register(Unpooled.directBuffer(len));
}

From source file:org.apache.hadoop.hbase.ipc.NettyRpcConnection.java

License:Apache License

NettyRpcConnection(NettyRpcClient rpcClient, ConnectionId remoteId) throws IOException {
    super(rpcClient.conf, AbstractRpcClient.WHEEL_TIMER, remoteId, rpcClient.clusterId,
            rpcClient.userProvider.isHBaseSecurityEnabled(), rpcClient.codec, rpcClient.compressor);
    this.rpcClient = rpcClient;
    byte[] connectionHeaderPreamble = getConnectionHeaderPreamble();
    this.connectionHeaderPreamble = Unpooled.directBuffer(connectionHeaderPreamble.length)
            .writeBytes(connectionHeaderPreamble);
    ConnectionHeader header = getConnectionHeader();
    this.connectionHeaderWithLength = Unpooled.directBuffer(4 + header.getSerializedSize());
    this.connectionHeaderWithLength.writeInt(header.getSerializedSize());
    header.writeTo(new ByteBufOutputStream(this.connectionHeaderWithLength));
}

From source file:org.lanternpowered.server.network.buffer.UnpooledByteBufferAllocator.java

License:MIT License

@Override
public ByteBuffer directBuffer(int initialCapacity) {
    return new LanternByteBuffer(Unpooled.directBuffer(initialCapacity));
}

From source file:org.nd4j.linalg.jcublas.buffer.CudaDoubleDataBuffer.java

License:Apache License

private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException {
    stream.defaultReadObject();/*  w w  w .j a  v  a 2  s.c  o m*/

    int n = stream.readInt();
    double[] arr = new double[n];

    for (int i = 0; i < n; i++) {
        arr[i] = stream.readDouble();
    }

    this.length = n;
    this.elementSize = Sizeof.DOUBLE;
    dataBuffer = Unpooled.directBuffer((int) length());
    dataBuffer.order(ByteOrder.nativeOrder());
    setData(arr);
}