Example usage for io.netty.buffer ByteBufInputStream ByteBufInputStream

List of usage examples for io.netty.buffer ByteBufInputStream ByteBufInputStream

Introduction

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

Prototype

public ByteBufInputStream(ByteBuf buffer) 

Source Link

Document

Creates a new stream which reads data from the specified buffer starting at the current readerIndex and ending at the current writerIndex .

Usage

From source file:com.ibm.mqlight.api.security.PemFile.java

License:Apache License

/**
 * Obtains the list of certificates stored in the PEM file.
 * //w w w. jav  a 2 s.  com
 * @return The list of certificates stored in the PEM file.
 * @throws CertificateException If a parsing error occurs.
 * @throws IOException If the PEM file cannot be read for any reason.
 */
public List<Certificate> getCertificates() throws CertificateException, IOException {
    final String methodName = "getCertificates";
    logger.entry(this, methodName);

    final String fileData = getPemFileData();

    final List<ByteBuf> certDataList = new ArrayList<ByteBuf>();
    final Matcher m = CERTIFICATE_PATTERN.matcher(fileData);
    int start = 0;
    while (m.find(start)) {
        final ByteBuf base64CertData = Unpooled.copiedBuffer(m.group(1), Charset.forName("US-ASCII"));
        final ByteBuf certData = Base64.decode(base64CertData);
        base64CertData.release();
        certDataList.add(certData);
        start = m.end();
    }

    if (certDataList.isEmpty()) {
        final CertificateException exception = new CertificateException(
                "No certificates found in PEM file: " + pemFile);
        logger.throwing(this, methodName, exception);
        throw exception;
    }

    final CertificateFactory cf = CertificateFactory.getInstance("X.509");
    final List<Certificate> certificates = new ArrayList<Certificate>();

    try {
        for (ByteBuf certData : certDataList) {
            certificates.add(cf.generateCertificate(new ByteBufInputStream(certData)));
        }
    } finally {
        for (ByteBuf certData : certDataList)
            certData.release();
    }

    logger.exit(this, methodName, certificates);

    return certificates;
}

From source file:com.jfastnet.peers.netty.KryoNettyPeer.java

License:Apache License

public void receive(ChannelHandlerContext ctx, DatagramPacket packet) {
    ByteBuf content = packet.content();//from   w w w.j a v a  2  s .co  m
    Message message = config.serialiser.deserialiseWithStream(new ByteBufInputStream(content));
    if (message == null) {
        return;
    }
    // TODO set config and state
    message.payload = content;
    if (message.getFeatures() != null) {
        message.getFeatures().resolve();
    }

    if (config.debug && debugRandom.nextInt(100) < config.debugLostPackagePercentage) {
        // simulated N % loss rate
        log.warn("DEBUG: simulated loss of packet: {}", message);
        return;
    }

    message.socketAddressSender = packet.sender();
    message.socketAddressRecipient = packet.recipient();

    if (config.trackData) {
        int frame = 0;
        config.netStats.getData().add(new NetStats.Line(false, message.getSenderId(), frame,
                message.getTimestamp(), message.getClass(), ((ByteBuf) message.payload).writerIndex()));
    }

    // Let the controller receive the message.
    // Processors are called there.
    config.internalReceiver.receive(message);
}

From source file:com.kanbekotori.keycraft.network.RewriteNetwork.java

License:Open Source License

/**  */
@SubscribeEvent/*from   w  w  w.  j a v a2  s . com*/
public void onServerPacket(ServerCustomPacketEvent event) {
    EntityPlayerMP player = ((NetHandlerPlayServer) event.handler).playerEntity;

    ByteBufInputStream stream = new ByteBufInputStream(event.packet.payload());
    try {
        switch (stream.readInt()) {
        case LEARN_SKILL_CODE:
            RewriteHelper.learnSkill(player, stream.readInt());
            break;

        case USE_SKILL_CODE:
            RewriteHelper.useSkill(player);
            break;
        }

        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.kanbekotori.keycraft.network.RewriteNetwork.java

License:Open Source License

/**  */
@SubscribeEvent//from w w w.  ja va2  s. co  m
public void onClientPacket(ClientCustomPacketEvent event) {
    EntityPlayer player = MainHelper.getPlayerCl();

    ByteBufInputStream stream = new ByteBufInputStream(event.packet.payload());
    try {
        switch (stream.readInt()) {
        case SYNC_AURORA_POINT_CODE:
            RewriteHelper.setAuroraPoint(player, stream.readInt());
            break;

        case SYNC_SKILL_CODE:
            for (int i = 0; i < RewriteHelper.SKILLS.length; i++) {
                RewriteHelper.learnSkill(player, RewriteHelper.SKILLS[i].id, stream.readBoolean());
            }
            break;
        }

        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.kixeye.kixmpp.KixmppWebSocketCodec.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
    WebSocketFrame frame = (WebSocketFrame) msg;

    ByteBuf content = frame.retain().content();
    String frameString = content.toString(StandardCharsets.UTF_8);

    if (logger.isDebugEnabled()) {
        logger.debug("Received: [{}]", frameString);
    }/*from   ww  w.ja va 2  s  . c o  m*/

    if (frameString.startsWith("<?xml")) {
        frameString = frameString.replaceFirst("<\\?xml.*?\\?>", "");
    }

    if (frameString.startsWith("<stream:stream")) {
        out.add(new KixmppStreamStart(null, true));
    } else if (frameString.startsWith("</stream:stream")) {
        out.add(new KixmppStreamEnd());
    } else {

        SAXBuilder saxBuilder = new SAXBuilder(readerFactory);
        Document document = saxBuilder.build(new ByteBufInputStream(content));

        Element element = document.getRootElement();

        out.add(element);
    }

}

From source file:com.kixeye.kixmpp.p2p.serialization.ProtostuffDecoder.java

License:Apache License

/**
 * Expose deserializer for unit testing.
 *
 * @param registry// w w  w .  j  a v a  2  s.  c  o m
 * @param buf
 * @return
 * @throws IOException
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object deserializeFromByteBuf(MessageRegistry registry, ByteBuf buf) throws IOException {
    // get message class
    int typeIdx = buf.readInt();
    Class<?> clazz = registry.getClassFromId(typeIdx);

    // decode rest of array into object
    Schema schema = RuntimeSchema.getSchema(clazz);
    Object obj = schema.newMessage();
    ProtostuffIOUtil.mergeFrom(new ByteBufInputStream(buf), obj, schema);

    return obj;
}

From source file:com.linecorp.armeria.client.thrift.TByteBufInputTransport.java

License:Apache License

TByteBufInputTransport(ByteBuf inputByteBuf) {
    byteBufInputStream = new ByteBufInputStream(inputByteBuf);
}

From source file:com.linkedin.flashback.netty.builder.RecordedHttpMessageBuilder.java

License:Open Source License

/**
 * Build serializable {@Link RecordedHttpBody} using temporary byte buffers.
 * Based on Charset, we will build concrete Http body either binary or characters.
 * TODO: throw customized exception if failed to create http body
 *
 * *///from   ww w  . ja v  a  2s . c  o  m
protected RecordedHttpBody getBody() {
    try {
        InputStream byteBufInputStream = new ByteBufInputStream(_bodyByteBuf);
        return RecordedHttpBodyFactory.create(getContentType(), getContentEncoding(), byteBufInputStream,
                getCharset());
    } catch (IOException e) {
        throw new RuntimeException("Failed to create Httpbody");
    }
}

From source file:com.mastfrog.acteur.ContentConverter.java

License:Open Source License

public String toString(ByteBuf content, Charset encoding) throws IOException {
    String result;/*ww  w.j av  a 2 s  . com*/
    try (ByteBufInputStream in = new ByteBufInputStream(content)) {
        result = Streams.readString(in, encoding.toString());
    } finally {
        content.resetReaderIndex();
    }
    if (result.length() > 0 && result.charAt(0) == '"') {
        result = result.substring(1);
    }
    if (result.length() > 1 && result.charAt(result.length() - 1) == '"') {
        result = result.substring(0, result.length() - 2);
    }
    return result;
}

From source file:com.mastfrog.acteur.ContentConverter.java

License:Open Source License

@SuppressWarnings("unchecked")
public <T> T toObject(ByteBuf content, MediaType mimeType, Class<T> type) throws IOException {
    if (mimeType == null) {
        mimeType = MediaType.ANY_TYPE;//from ww w . j  a  va2 s . c  o m
    }
    // Special handling for strings
    if (type == String.class || type == CharSequence.class) {
        return type.cast(toString(content, findCharset(mimeType)));
    }

    if (type.isInterface()) {
        Map<String, Object> m;
        try (InputStream in = new ByteBufInputStream(content)) {
            m = codec.readValue(in, Map.class);
        }
        return toObject(m, type);
    }
    return readObject(content, mimeType, type);
}