Example usage for io.netty.buffer ByteBuf release

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

Introduction

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

Prototype

boolean release();

Source Link

Document

Decreases the reference count by 1 and deallocates this object if the reference count reaches at 0 .

Usage

From source file:com.github.spapageo.jannel.transcode.TranscoderHelperTest.java

License:Open Source License

@Test
public void testEncodeHeartBeatEncodesCorrectly() throws Exception {
    HeartBeat heartBeat = new HeartBeat();
    heartBeat.setLoad(1);/*from   w w  w . j  a v a2 s. c  o m*/
    ByteBuf byteBuf = Unpooled.buffer();
    transcoderHelper.encodeHeartBeat(heartBeat, byteBuf);

    assertEquals("HeartBeat load is incorrect", 1, byteBuf.readInt());
    byteBuf.release();
}

From source file:com.github.spapageo.jannel.transcode.TranscoderHelperTest.java

License:Open Source License

@Test
public void testEncodeAdminEncodesCorrectly() throws Exception {
    Admin admin = new Admin();
    admin.setAdminCommand(AdminCommand.IDENTIFY);
    admin.setBoxId("");
    ByteBuf byteBuf = Unpooled.buffer();
    transcoderHelper.encodeAdmin(admin, byteBuf);

    assertEquals("Type of admin command is incorrect", AdminCommand.IDENTIFY,
            AdminCommand.fromValue(byteBuf.readInt()));
    assertEquals("Box name is incorrect", "",
            ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8));
    byteBuf.release();
}

From source file:com.github.spapageo.jannel.transcode.TranscoderHelperTest.java

License:Open Source License

@Test
public void testEncodeSmsEncodesCorrectly() throws Exception {
    byte[] data = { 0x25 };
    ByteBuf udh = Unpooled.copiedBuffer(data);
    Sms sms = new Sms();
    sms.setSender("from");
    sms.setReceiver("to");
    sms.setUdhData(udh);/*from w w  w.  j ava2  s .  com*/
    sms.setMsgData("content");
    sms.setTime(0);
    sms.setSmscId("smsc");
    sms.setSmscNumber("smscNumber");
    sms.setForeignId("foreignId");
    sms.setService("service");
    sms.setAccount("account");
    sms.setId(UUID.randomUUID());
    sms.setSmsType(SmsType.MOBILE_TERMINATED_REPLY);
    sms.setMessageClass(MessageClass.MC_CLASS2);
    sms.setMwi(MessageWaitingIndicator.fromValue(3));
    sms.setCoding(DataCoding.fromValue(2));
    sms.setCompress(Compress.fromValue(1));
    sms.setValidity(6);
    sms.setDeferred(7);
    sms.setDlrMask(8);
    sms.setDlrUrl("dlrUrl");
    sms.setPid(9);
    sms.setAltDcs(10);
    sms.setRpi(ReturnPathIndicator.fromValue(1));
    sms.setCharset(Charsets.UTF_8);
    sms.setBoxId("box");
    sms.setBillingInfo("binfo");
    sms.setMsgLeft(12);
    sms.setPriority(13);
    sms.setResendTry(14);
    sms.setResendTime(15);
    sms.setMetaData("metadata");
    ByteBuf byteBuf = Unpooled.buffer();
    transcoderHelper.encodeSms(sms, byteBuf);

    assertEquals("The  from is incorrect", "from",
            ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8));
    assertEquals("The to is incorrect", "to",
            ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8));
    assertEquals("The udhdata is incorrect", udh.readerIndex(0),
            ChannelBufferUtils.readOctetStringToBytes(byteBuf));
    assertEquals("The message data is incorrect", "content",
            ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8));

    assertEquals("The time is incorrect", 0, byteBuf.readInt());
    assertEquals("The smsc is incorrect", "smsc",
            ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8));
    assertEquals("The smscNumber is incorrect", "smscNumber",
            ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8));
    assertEquals("The foreignId is incorrect", "foreignId",
            ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8));
    assertEquals("The service is incorrect", "service",
            ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8));
    assertEquals("The account is incorrect", "account",
            ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8));
    assertEquals("The id is incorrect", sms.getId(), ChannelBufferUtils.readUUID(byteBuf, Charsets.UTF_8));
    assertEquals("The sms type is incorrect", sms.getSmsType(), SmsType.fromValue(byteBuf.readInt()));
    assertEquals("The m class is incorrect", 2, byteBuf.readInt());
    assertEquals("The mwi is incorrect", 3, byteBuf.readInt());
    assertEquals("The coding is incorrect", 2, byteBuf.readInt());
    assertEquals("The compress is incorrect", 1, byteBuf.readInt());
    assertEquals("The validity is incorrect", 6, byteBuf.readInt());
    assertEquals("The deferred is incorrect", 7, byteBuf.readInt());
    assertEquals("The dlr mask is incorrect", 8, byteBuf.readInt());
    assertEquals("The dlr url is incorrect", "dlrUrl",
            ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8));

    assertEquals("The pid is incorrect", 9, byteBuf.readInt());
    assertEquals("The alt dcs is incorrect", 10, byteBuf.readInt());
    assertEquals("The rpi is incorrect", 1, byteBuf.readInt());
    assertEquals("The charset is incorrect", "UTF-8",
            ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8));
    assertEquals("The box id is incorrect", "box",
            ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8));
    assertEquals("The binfo is incorrect", "binfo",
            ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8));

    assertEquals("The msgLeft is incorrect", 12, byteBuf.readInt());
    assertEquals("The priority is incorrect", 13, byteBuf.readInt());
    assertEquals("The resend try is incorrect", 14, byteBuf.readInt());
    assertEquals("The resend time is incorrect", 15, byteBuf.readInt());
    assertEquals("The meta data is incorrect", "metadata",
            ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8));
    udh.release();
}

From source file:com.github.sparkfy.network.util.TransportFrameDecoder.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    for (ByteBuf b : buffers) {
        b.release();
    }/*  ww  w. j a va2 s  . co  m*/
    if (interceptor != null) {
        interceptor.channelInactive();
    }
    frameLenBuf.release();
    super.channelInactive(ctx);
}

From source file:com.github.subalakr.yasjl.AutoBenchRowPerf.java

License:Apache License

private void parseResults(String file, String path) throws Exception {
    String response = getResource(file);

    StringBuilder sb = new StringBuilder();
    sb.append("size: " + humanReadableByteCount(response.length(), true) + ",\t\t");
    sb.append("level-depth: " + path.split("/").length + ",\t\t");
    sb.append("time: ");

    JsonPointer[] jsonPointers = { new JsonPointer(path, new JsonPointerCB1() {
        public void call(ByteBuf buf) {
            buf.release();
        }//from  w  ww .  j ava2  s  .c o  m
    }) };
    ByteBuf buf = Unpooled.buffer();
    parser.initialize(buf, jsonPointers);
    buf.writeBytes(response.getBytes());
    long start = System.currentTimeMillis();
    parser.parse();
    long end = System.currentTimeMillis();
    sb.append((end - start) + "ms");
    System.out.println(sb.toString());
}

From source file:com.github.subalakr.yasjl.Bench.java

License:Apache License

public void run() throws Exception {
    for (int i = 0; i < iterations; i++) {
        ByteBuf inBuf = Unpooled.buffer();
        JsonPointer[] jsonPointers = { new JsonPointer("/metrics/resultCount", new JsonPointerCB1() {
            public void call(ByteBuf buf) {
                buf.release();
            }//from  w  w  w .  j  av  a 2s  .com
        }), new JsonPointer("/metrics/warningCount", new JsonPointerCB1() {
            public void call(ByteBuf buf) {
                buf.release();
            }
        }), new JsonPointer("/metrics/errorCount", new JsonPointerCB1() {
            public void call(ByteBuf buf) {
                buf.release();
            }
        }), new JsonPointer("/results/-", new JsonPointerCB1() {
            public void call(ByteBuf buf) {
                rowsEmitted.getAndIncrement();
                buf.release();
            }
        }), new JsonPointer("/errors/-", new JsonPointerCB1() {
            public void call(ByteBuf buf) {
                buf.release();
            }
        }), new JsonPointer("/warnings/-", new JsonPointerCB1() {
            public void call(ByteBuf buf) {
                buf.release();
            }
        }), };
        parser.initialize(inBuf, jsonPointers);
        inBuf.writeBytes(inJson.getBytes());
        long start = System.currentTimeMillis();
        parser.parse();
        long currentRun = System.currentTimeMillis() - start;
        totalDuration += currentRun;
        totalBytesRead += inJsonSz;
        inBuf.discardReadBytes();
        inBuf.release();
    }
}

From source file:com.heliosapm.streams.chronicle.MessageQueue.java

License:Apache License

public static void main(String[] args) {
    log("MessageQueue Test");
    //      System.setProperty("io.netty.leakDetection.level", "advanced");
    //      System.setProperty("Test.chronicle.rollcycle", RollCycles.MINUTELY.name());

    final ThreadLocalRandom tlr = ThreadLocalRandom.current();

    final MetricRegistry mr = new MetricRegistry();
    final Meter listenerEvents = mr.meter("listener.events");
    final Timer writerTime = mr.timer("writer.time");
    final Counter deserErrors = mr.counter("deser.errors");
    final ConsoleReporter cr = ConsoleReporter.forRegistry(mr).convertDurationsTo(TimeUnit.MICROSECONDS)
            .convertRatesTo(TimeUnit.SECONDS).outputTo(System.err).build();
    cr.start(5, TimeUnit.SECONDS);
    final MessageListener listener = new MessageListener() {
        @Override/* w  w w.  j av  a  2  s  . c om*/
        public int onMetric(final ByteBuf buf) {
            listenerEvents.mark();
            int cnt = 0;
            try {
                while (buf.isReadable(20)) {
                    StreamedMetric.read(buf);
                    listenerEvents.mark();
                    cnt++;
                }
            } catch (Exception ex) {
                deserErrors.inc();
            } finally {
                buf.release();
            }
            return cnt;
        }
    };
    final MessageQueue mq = MessageQueue.getInstance("Test", listener, System.getProperties());
    log("Acquired MessageQueue Instance:" + mq);
    final int batchSize = 100;
    final boolean compressed = mq.compression;
    final Thread producer = new Thread() {
        @Override
        public void run() {
            log("Producer Thread Started");
            try {
                for (int i = 0; i < Integer.MAX_VALUE; i++) {
                    final Context ctx = writerTime.time();
                    if (compressed) {
                        for (int x = 0; x < batchSize; x++) {
                            mq.writeEntry(new StreamedMetricValue(System.currentTimeMillis(), tlr.nextDouble(),
                                    "foo.bar", AgentName.getInstance().getGlobalTags()));
                        }
                    } else {
                        final ByteBuf buffer = BufferManager.getInstance().directBuffer(batchSize * 128);
                        for (int x = 0; x < batchSize; x++) {
                            new StreamedMetricValue(System.currentTimeMillis(), tlr.nextDouble(), "foo.bar",
                                    AgentName.getInstance().getGlobalTags()).intoByteBuf(buffer);
                        }
                        mq.writeEntry(buffer);
                    }
                    ctx.stop();
                }
            } catch (Exception ex) {
                if (ex instanceof InterruptedException) {
                    mq.log.info("Producer Thread is stopping");
                }
            }
        }
    };
    producer.setDaemon(true);
    producer.start();
    final AtomicBoolean closed = new AtomicBoolean(false);
    StdInCommandHandler.getInstance().registerCommand("shutdown", new Runnable() {
        @Override
        public void run() {
            if (closed.compareAndSet(false, true)) {
                mq.log.info(">>>>> Stopping MessageQueue...");
                producer.interrupt();
                try {
                    mq.close();
                } catch (Exception x) {
                    /* No Op */}
                mq.log.info("<<<<< MessageQueue Stopped");
                System.exit(1);
            }
        }
    }).shutdownHook("shutdown").run();
}

From source file:com.heliosapm.streams.json.JSONOps.java

License:Apache License

/**
 * Serializes the passed object to an off-heap buffer and returns an InputStream to read it back
 * @param obj The object to serialize//w w  w  .  ja va2  s .  co  m
 * @return an InputStream to read back the JSON serialized object 
 */
public static InputStream serializeOffHeapLoopBack(final Object obj) {
    if (obj == null)
        throw new IllegalArgumentException("The passed object was null");
    final ByteBuf cb = byteBufAllocator.buffer();
    final OutputStream os = new ByteBufOutputStream(cb);

    try {
        serialize(obj, os);
        os.flush();
        os.close();
    } catch (Exception ex) {
        throw new RuntimeException("Failed to write object to buffer", ex);
    }

    return new ByteBufInputStream(cb) {
        @Override
        public void close() throws IOException {
            super.close();
            try {
                cb.release();
            } catch (Exception x) {
                /* No Op */}
        }
    };
}

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

License:Apache License

/**
 * Unloads the UI content from a jar/*w w  w  . jav  a2 s  .co  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.streams.metrics.aggregation.StreamedMetricAggregation.java

License:Apache License

/**
 * Creates a new StreamedMetricAggregation from the passed bytes
 * @param bytes The bytes to read from/*w  w  w .ja  va  2 s  .c o m*/
 */
private StreamedMetricAggregation(final byte[] bytes) {
    size = bytes.length;
    final ByteBuf b = BufferManager.getInstance().buffer(size).writeBytes(bytes);
    try {
        sticky = b.getByte(STICKY) == 1;
        doubleType = b.getByte(DOUBLE_TYPE) == 1;
        createTime = b.getLong(CREATE_TIME);
        period = b.getLong(PERIOD);
        periodUnit = TUNITS[b.getByte(PERIOD_UNIT)];
        b.readerIndex(METRIC_VALUES);
        values.put(bytes, METRIC_VALUES, VALUE_SIZE);
        final byte tagCount = b.getByte(TAG_COUNT);
        b.readerIndex(METRIC_NAME);
        metricName = nextString(b);
        for (int i = 0; i < tagCount; i++) {
            tags.put(nextString(b), nextString(b));
            i++;
        }
    } finally {
        try {
            b.release();
        } catch (Exception x) {
            /* No Op */}
    }
}