Example usage for io.netty.buffer Unpooled wrappedBuffer

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

Introduction

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

Prototype

public static ByteBuf wrappedBuffer(ByteBuffer... buffers) 

Source Link

Document

Creates a new big-endian composite buffer which wraps the slices of the specified NIO buffers without copying them.

Usage

From source file:com.friz.audio.network.AudioSessionContext.java

License:Open Source License

/**
 * Processes the file requests./*w w w.j  a v a  2s  .  c  o  m*/
 * @throws IOException The exception thrown if an i/o error occurs.
 */
public void processFileQueue() {
    FileRequestEvent request;
    synchronized (fileQueue) {
        request = fileQueue.pop();
        if (fileQueue.isEmpty()) {
            idle = true;
        } else {
            service.addAudioContext(this);
            idle = false;
        }
    }
    if (request != null) {
        int type = request.getType();
        int file = request.getFile();
        int crc = request.getCrc();
        int version = request.getVersion();
        HttpVersion http = request.getHttp();

        ByteBuf buf = Unpooled.buffer();
        if (type == 255 && file == 255) {
            buf = Unpooled.wrappedBuffer(server.getCache().getChecksum());
        } else {
            if (server.getCache().getReferenceTable(type).getEntry(file).getCrc() != crc
                    || server.getCache().getReferenceTable(type).getEntry(file).getVersion() != version) {
                writeResponse(http, buf);
                return;
            }

            try {
                buf = Unpooled.wrappedBuffer(server.getCache().getStore().read(type, file));
                if (type != 255)
                    buf = buf.slice(0, buf.readableBytes() - 2);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        writeResponse(http, buf);
    }
}

From source file:com.friz.game.network.codec.LoginDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
    int type = buf.readUnsignedByte();
    int size = buf.readUnsignedShort();

    int major = buf.readInt();
    int minor = buf.readInt();
    boolean dropped = buf.readBoolean();

    int rsaSize = buf.readUnsignedShort();
    byte[] rsa = new byte[rsaSize];
    buf.readBytes(rsa);/*from w ww . j av a  2s . c  om*/

    ByteBuf rsaBuf = Unpooled.wrappedBuffer(
            new BigInteger(rsa).modPow(Constants.LOGIN_EXPONENT, Constants.LOGIN_MODULUS).toByteArray());
    int rsaMagic = rsaBuf.readUnsignedByte();

    int[] key = new int[4];
    for (int i = 0; i < key.length; i++)
        key[i] = rsaBuf.readInt();

    int block = rsaBuf.readUnsignedByte();

    if (block == 1 || block == 3) {
        int code = rsaBuf.readUnsignedMedium();
        rsaBuf.readerIndex(rsaBuf.readerIndex() + 1);
    } else if (block == 0) {
        int trusted = rsaBuf.readInt();
    } else if (block == 2) {
        rsaBuf.readerIndex(rsaBuf.readerIndex() + 4);
    }

    String password = BufferUtils.getString(rsaBuf);

    long serverKey = rsaBuf.readLong();
    long clientKey = rsaBuf.readLong();

    byte[] xtea = new byte[buf.readableBytes()];
    buf.readBytes(xtea);
    ByteBuf xteaBuf = Unpooled.wrappedBuffer(new XTEA(xtea).decrypt(key).toByteArray());

    String username = "";
    boolean asString = xteaBuf.readBoolean();
    if (asString)
        username = BufferUtils.getString(xteaBuf);
    else
        username = BufferUtils.getBase37(xteaBuf);

    int display = xteaBuf.readUnsignedByte();
    int width = xteaBuf.readUnsignedShort();
    int height = xteaBuf.readUnsignedShort();

    int multisample = xteaBuf.readByte();

    byte[] uid = new byte[24];
    for (int i = 0; i < uid.length; i++)
        uid[i] = xteaBuf.readByte();

    String token = BufferUtils.getString(xteaBuf);

    int prefSize = xteaBuf.readUnsignedByte();
    int prefVersion = xteaBuf.readUnsignedByte();
    int aPref = xteaBuf.readUnsignedByte();
    int antiAliasing = xteaBuf.readUnsignedByte();
    int aPref1 = xteaBuf.readUnsignedByte();
    int bloom = xteaBuf.readUnsignedByte();
    int brightness = xteaBuf.readUnsignedByte();
    int buildArea = xteaBuf.readUnsignedByte();
    int aPref2 = xteaBuf.readUnsignedByte();
    int flickeringEffects = xteaBuf.readUnsignedByte();
    int fog = xteaBuf.readUnsignedByte();
    int groundBlending = xteaBuf.readUnsignedByte();
    int groundDecoration = xteaBuf.readUnsignedByte();
    int idleAnimations = xteaBuf.readUnsignedByte();
    int lighting = xteaBuf.readUnsignedByte();
    int sceneryShadows = xteaBuf.readUnsignedByte();
    int aPref3 = xteaBuf.readUnsignedByte();
    int nullPref = xteaBuf.readUnsignedByte();
    int orthoMode = xteaBuf.readUnsignedByte();
    int particles = xteaBuf.readUnsignedByte();
    int removeRoofs = xteaBuf.readUnsignedByte();
    int maxScreenSize = xteaBuf.readUnsignedByte();
    int skyboxes = xteaBuf.readUnsignedByte();
    int mobShadows = xteaBuf.readUnsignedByte();
    int textures = xteaBuf.readUnsignedByte();
    int desiredToolkit = xteaBuf.readUnsignedByte();
    int nullPref1 = xteaBuf.readUnsignedByte();
    int water = xteaBuf.readUnsignedByte();
    int screenSize = xteaBuf.readUnsignedByte();
    int customCursors = xteaBuf.readUnsignedByte();
    int graphics = xteaBuf.readUnsignedByte();
    int cpu = xteaBuf.readUnsignedByte();
    int aPref4 = xteaBuf.readUnsignedByte();
    int safeMode = xteaBuf.readUnsignedByte();
    int aPref5 = xteaBuf.readUnsignedByte();
    int aPref6 = xteaBuf.readUnsignedByte();
    int aPref7 = xteaBuf.readUnsignedByte();
    int soundEffectsVolume = xteaBuf.readUnsignedByte();
    int areaSoundsVolume = xteaBuf.readUnsignedByte();
    int voiceOverVolume = xteaBuf.readUnsignedByte();
    int musicVolume = xteaBuf.readUnsignedByte();
    int themeMusicVolume = xteaBuf.readUnsignedByte();
    int steroSound = xteaBuf.readUnsignedByte();

    int infoVersion = xteaBuf.readUnsignedByte();
    int osType = xteaBuf.readUnsignedByte();
    boolean arch64 = xteaBuf.readBoolean();
    int versionType = xteaBuf.readUnsignedByte();
    int vendorType = xteaBuf.readUnsignedByte();
    int jMajor = xteaBuf.readUnsignedByte();
    int jMinor = xteaBuf.readUnsignedByte();
    int jPatch = xteaBuf.readUnsignedByte();
    boolean falseBool = xteaBuf.readBoolean();
    int heapSize = xteaBuf.readUnsignedShort();
    int pocessorCount = xteaBuf.readUnsignedByte();
    int cpuPhyscialMemory = xteaBuf.readUnsignedMedium();
    int cpuClock = xteaBuf.readUnsignedShort();
    String gpuName = BufferUtils.getJagString(xteaBuf);
    String aString = BufferUtils.getJagString(xteaBuf);
    String dxVersion = BufferUtils.getJagString(xteaBuf);
    String aString1 = BufferUtils.getJagString(xteaBuf);
    int gpuDriverMonth = xteaBuf.readUnsignedByte();
    int gpuDriverYear = xteaBuf.readUnsignedShort();
    String cpuType = BufferUtils.getJagString(xteaBuf);
    String cpuName = BufferUtils.getJagString(xteaBuf);
    int cpuThreads = xteaBuf.readUnsignedByte();
    int anInt = xteaBuf.readUnsignedByte();
    int anInt1 = xteaBuf.readInt();
    int anInt2 = xteaBuf.readInt();
    int anInt3 = xteaBuf.readInt();
    int anInt4 = xteaBuf.readInt();
    String aString2 = BufferUtils.getString(xteaBuf);

    int anInt5 = xteaBuf.readInt();
    int anInt6 = xteaBuf.readInt();
    int anInt7 = xteaBuf.readInt();
    String aString3 = BufferUtils.getString(xteaBuf);

    boolean hasAdditional = xteaBuf.readBoolean();
    String additionalInfo = "";
    if (hasAdditional)
        additionalInfo = BufferUtils.getString(xteaBuf);

    int anInt8 = xteaBuf.readUnsignedByte();
    int anInt9 = xteaBuf.readUnsignedByte();
    int anInt10 = xteaBuf.readUnsignedByte();
    int anInt11 = xteaBuf.readInt();
    String aString4 = BufferUtils.getString(xteaBuf);

    boolean newWorld = xteaBuf.readBoolean();
    int lobbyId = xteaBuf.readUnsignedShort();

    int[] checksums = new int[(xteaBuf.readableBytes() / 4) + 1];
    for (int i = 0; i < checksums.length; i++) {
        if (i == 32)
            checksums[i] = -1;
        else
            checksums[i] = xteaBuf.readInt();
    }
}

From source file:com.friz.lobby.network.codec.LoginDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
    if (!buf.isReadable())
        return;// w  ww . j a va2 s.c  om

    int type = buf.readUnsignedByte();
    int size = buf.readUnsignedShort();

    if (!buf.isReadable(size))
        return;

    int major = buf.readInt();
    int minor = buf.readInt();

    int rsaSize = buf.readUnsignedShort();
    byte[] rsa = new byte[rsaSize];
    buf.readBytes(rsa);

    ByteBuf rsaBuf = Unpooled.wrappedBuffer(
            new BigInteger(rsa).modPow(Constants.LOGIN_EXPONENT, Constants.LOGIN_MODULUS).toByteArray());
    int rsaMagic = rsaBuf.readUnsignedByte();

    int[] key = new int[4];
    for (int i = 0; i < key.length; i++)
        key[i] = rsaBuf.readInt();

    int block = rsaBuf.readUnsignedByte();

    if (block == 1 || block == 3) {
        int code = rsaBuf.readUnsignedMedium();
        rsaBuf.readerIndex(rsaBuf.readerIndex() + 1);
        System.out.println(new GoogleAuthenticator().authorize("OE2ZSYF6T7N2R5CG", code));
    } else if (block == 0) {
        int trusted = rsaBuf.readInt();
    } else if (block == 2) {
        rsaBuf.readerIndex(rsaBuf.readerIndex() + 4);
    }

    String password = BufferUtils.getString(rsaBuf);

    long serverKey = rsaBuf.readLong();
    long clientKey = rsaBuf.readLong();

    byte[] xtea = new byte[buf.readableBytes()];
    buf.readBytes(xtea);
    ByteBuf xteaBuf = Unpooled.wrappedBuffer(new XTEA(xtea).decrypt(key).toByteArray());

    String username = "";
    boolean asString = xteaBuf.readBoolean();
    if (asString)
        username = BufferUtils.getString(xteaBuf);
    else
        username = BufferUtils.getBase37(xteaBuf);

    int game = xteaBuf.readUnsignedByte();
    int lang = xteaBuf.readUnsignedByte();
    int display = xteaBuf.readUnsignedByte();
    int width = xteaBuf.readUnsignedShort();
    int height = xteaBuf.readUnsignedShort();

    int multisample = xteaBuf.readByte();

    byte[] uid = new byte[24];
    for (int i = 0; i < uid.length; i++)
        uid[i] = xteaBuf.readByte();

    String token = BufferUtils.getString(xteaBuf);

    int prefSize = xteaBuf.readUnsignedByte();
    int prefVersion = xteaBuf.readUnsignedByte();
    int aPref = xteaBuf.readUnsignedByte();
    int antiAliasing = xteaBuf.readUnsignedByte();
    int aPref1 = xteaBuf.readUnsignedByte();
    int bloom = xteaBuf.readUnsignedByte();
    int brightness = xteaBuf.readUnsignedByte();
    int buildArea = xteaBuf.readUnsignedByte();
    int aPref2 = xteaBuf.readUnsignedByte();
    int flickeringEffects = xteaBuf.readUnsignedByte();
    int fog = xteaBuf.readUnsignedByte();
    int groundBlending = xteaBuf.readUnsignedByte();
    int groundDecoration = xteaBuf.readUnsignedByte();
    int idleAnimations = xteaBuf.readUnsignedByte();
    int lighting = xteaBuf.readUnsignedByte();
    int sceneryShadows = xteaBuf.readUnsignedByte();
    int aPref3 = xteaBuf.readUnsignedByte();
    int nullPref = xteaBuf.readUnsignedByte();
    int orthoMode = xteaBuf.readUnsignedByte();
    int particles = xteaBuf.readUnsignedByte();
    int removeRoofs = xteaBuf.readUnsignedByte();
    int maxScreenSize = xteaBuf.readUnsignedByte();
    int skyboxes = xteaBuf.readUnsignedByte();
    int mobShadows = xteaBuf.readUnsignedByte();
    int textures = xteaBuf.readUnsignedByte();
    int desiredToolkit = xteaBuf.readUnsignedByte();
    int nullPref1 = xteaBuf.readUnsignedByte();
    int water = xteaBuf.readUnsignedByte();
    int screenSize = xteaBuf.readUnsignedByte();
    int customCursors = xteaBuf.readUnsignedByte();
    int graphics = xteaBuf.readUnsignedByte();
    int cpu = xteaBuf.readUnsignedByte();
    int aPref4 = xteaBuf.readUnsignedByte();
    int safeMode = xteaBuf.readUnsignedByte();
    int aPref5 = xteaBuf.readUnsignedByte();
    int aPref6 = xteaBuf.readUnsignedByte();
    int aPref7 = xteaBuf.readUnsignedByte();
    int soundEffectsVolume = xteaBuf.readUnsignedByte();
    int areaSoundsVolume = xteaBuf.readUnsignedByte();
    int voiceOverVolume = xteaBuf.readUnsignedByte();
    int musicVolume = xteaBuf.readUnsignedByte();
    int themeMusicVolume = xteaBuf.readUnsignedByte();
    int steroSound = xteaBuf.readUnsignedByte();

    int infoVersion = xteaBuf.readUnsignedByte();
    int osType = xteaBuf.readUnsignedByte();
    boolean arch64 = xteaBuf.readBoolean();
    int versionType = xteaBuf.readUnsignedByte();
    int vendorType = xteaBuf.readUnsignedByte();
    int jMajor = xteaBuf.readUnsignedByte();
    int jMinor = xteaBuf.readUnsignedByte();
    int jPatch = xteaBuf.readUnsignedByte();
    boolean falseBool = xteaBuf.readBoolean();
    int heapSize = xteaBuf.readUnsignedShort();
    int pocessorCount = xteaBuf.readUnsignedByte();
    int cpuPhyscialMemory = xteaBuf.readUnsignedMedium();
    int cpuClock = xteaBuf.readUnsignedShort();
    String gpuName = BufferUtils.getJagString(xteaBuf);
    String aString = BufferUtils.getJagString(xteaBuf);
    String dxVersion = BufferUtils.getJagString(xteaBuf);
    String aString1 = BufferUtils.getJagString(xteaBuf);
    int gpuDriverMonth = xteaBuf.readUnsignedByte();
    int gpuDriverYear = xteaBuf.readUnsignedShort();
    String cpuType = BufferUtils.getJagString(xteaBuf);
    String cpuName = BufferUtils.getJagString(xteaBuf);
    int cpuThreads = xteaBuf.readUnsignedByte();
    int anInt = xteaBuf.readUnsignedByte();
    int anInt1 = xteaBuf.readInt();
    int anInt2 = xteaBuf.readInt();
    int anInt3 = xteaBuf.readInt();
    int anInt4 = xteaBuf.readInt();
    String aString2 = BufferUtils.getJagString(xteaBuf);

    int anInt5 = xteaBuf.readInt();
    String aString3 = BufferUtils.getString(xteaBuf);
    int affiliate = xteaBuf.readInt();
    int anInt6 = xteaBuf.readInt();
    String aString4 = BufferUtils.getString(xteaBuf);
    int anInt7 = xteaBuf.readUnsignedByte();

    int[] checksums = new int[(xteaBuf.readableBytes() / 4) + 1];
    for (int i = 0; i < checksums.length; i++) {
        if (i == 32)
            checksums[i] = -1;
        else
            checksums[i] = xteaBuf.readInt();
    }

    final List<Module> modules = new ArrayList<>();
    modules.add(new ClientVersionModule(major, minor));
    modules.add(new ClientTypeModule(game, lang, display, width, height));
    out.add(new LoginRequestEvent(modules));
}

From source file:com.friz.lobby.network.codec.SocialDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
    if (!buf.isReadable())
        return;/*from w  ww .j  av  a2  s.co  m*/

    int type = buf.readUnsignedByte();
    int size = buf.readUnsignedShort();

    if (!buf.isReadable(size))
        return;

    byte[] xtea = new byte[size];
    buf.readBytes(xtea);
    ByteBuf xteaBuf = Unpooled.wrappedBuffer(new XTEA(xtea).decrypt(key).toByteArray());

    int game = xteaBuf.readUnsignedByte();
    int lang = xteaBuf.readUnsignedByte();
    int display = xteaBuf.readUnsignedByte();
    int width = xteaBuf.readUnsignedShort();
    int height = xteaBuf.readUnsignedShort();

    int multisample = xteaBuf.readByte();

    byte[] uid = new byte[24];
    for (int i = 0; i < uid.length; i++)
        uid[i] = xteaBuf.readByte();

    String gameToken = BufferUtils.getString(xteaBuf);

    int prefSize = xteaBuf.readUnsignedByte();
    int prefVersion = xteaBuf.readUnsignedByte();
    int aPref = xteaBuf.readUnsignedByte();
    int antiAliasing = xteaBuf.readUnsignedByte();
    int aPref1 = xteaBuf.readUnsignedByte();
    int bloom = xteaBuf.readUnsignedByte();
    int brightness = xteaBuf.readUnsignedByte();
    int buildArea = xteaBuf.readUnsignedByte();
    int aPref2 = xteaBuf.readUnsignedByte();
    int flickeringEffects = xteaBuf.readUnsignedByte();
    int fog = xteaBuf.readUnsignedByte();
    int groundBlending = xteaBuf.readUnsignedByte();
    int groundDecoration = xteaBuf.readUnsignedByte();
    int idleAnimations = xteaBuf.readUnsignedByte();
    int lighting = xteaBuf.readUnsignedByte();
    int sceneryShadows = xteaBuf.readUnsignedByte();
    int aPref3 = xteaBuf.readUnsignedByte();
    int nullPref = xteaBuf.readUnsignedByte();
    int orthoMode = xteaBuf.readUnsignedByte();
    int particles = xteaBuf.readUnsignedByte();
    int removeRoofs = xteaBuf.readUnsignedByte();
    int maxScreenSize = xteaBuf.readUnsignedByte();
    int skyboxes = xteaBuf.readUnsignedByte();
    int mobShadows = xteaBuf.readUnsignedByte();
    int textures = xteaBuf.readUnsignedByte();
    int desiredToolkit = xteaBuf.readUnsignedByte();
    int nullPref1 = xteaBuf.readUnsignedByte();
    int water = xteaBuf.readUnsignedByte();
    int screenSize = xteaBuf.readUnsignedByte();
    int customCursors = xteaBuf.readUnsignedByte();
    int graphics = xteaBuf.readUnsignedByte();
    int cpu = xteaBuf.readUnsignedByte();
    int aPref4 = xteaBuf.readUnsignedByte();
    int safeMode = xteaBuf.readUnsignedByte();
    int aPref5 = xteaBuf.readUnsignedByte();
    int aPref6 = xteaBuf.readUnsignedByte();
    int aPref7 = xteaBuf.readUnsignedByte();
    int soundEffectsVolume = xteaBuf.readUnsignedByte();
    int areaSoundsVolume = xteaBuf.readUnsignedByte();
    int voiceOverVolume = xteaBuf.readUnsignedByte();
    int musicVolume = xteaBuf.readUnsignedByte();
    int themeMusicVolume = xteaBuf.readUnsignedByte();
    int steroSound = xteaBuf.readUnsignedByte();
    xteaBuf.readMedium();
    xteaBuf.readMedium();

    int infoVersion = xteaBuf.readUnsignedByte();
    int osType = xteaBuf.readUnsignedByte();
    boolean arch64 = xteaBuf.readBoolean();
    int versionType = xteaBuf.readUnsignedByte();
    int vendorType = xteaBuf.readUnsignedByte();
    int jMajor = xteaBuf.readUnsignedByte();
    int jMinor = xteaBuf.readUnsignedByte();
    int jPatch = xteaBuf.readUnsignedByte();
    boolean falseBool = xteaBuf.readBoolean();
    int heapSize = xteaBuf.readUnsignedShort();
    int pocessorCount = xteaBuf.readUnsignedByte();
    int cpuPhyscialMemory = xteaBuf.readUnsignedMedium();
    int cpuClock = xteaBuf.readUnsignedShort();
    String gpuName = BufferUtils.getJagString(xteaBuf);
    String aString = BufferUtils.getJagString(xteaBuf);
    String dxVersion = BufferUtils.getJagString(xteaBuf);
    String aString1 = BufferUtils.getJagString(xteaBuf);
    int gpuDriverMonth = xteaBuf.readUnsignedByte();
    int gpuDriverYear = xteaBuf.readUnsignedShort();
    String cpuType = BufferUtils.getJagString(xteaBuf);
    String cpuName = BufferUtils.getJagString(xteaBuf);
    int cpuThreads = xteaBuf.readUnsignedByte();
    int anInt = xteaBuf.readUnsignedByte();
    int anInt1 = xteaBuf.readInt();
    int anInt2 = xteaBuf.readInt();
    int anInt3 = xteaBuf.readInt();
    int anInt4 = xteaBuf.readInt();
    String aString2 = BufferUtils.getJagString(xteaBuf);

    int anInt5 = xteaBuf.readInt();
    String seed = BufferUtils.getString(xteaBuf);
    int affiliate = xteaBuf.readInt();
    int anInt6 = xteaBuf.readInt();
    String updateToken = BufferUtils.getString(xteaBuf);
    int anInt7 = xteaBuf.readUnsignedByte();

    int[] checksums = new int[(xteaBuf.readableBytes() / 4) + 1];
    for (int i = 0; i < checksums.length; i++) {
        if (i == 32)
            checksums[i] = -1;
        else
            checksums[i] = xteaBuf.readInt();
    }

    System.out.println(seed);
}

From source file:com.friz.update.network.UpdateSessionContext.java

License:Open Source License

/**
 * Processes the file requests.//from  www.j a va2  s  .c o  m
 * @throws IOException The exception thrown if an i/o error occurs.
 */
public void processFileQueue() {
    FileRequestEvent request;
    synchronized (fileQueue) {
        request = fileQueue.pop();
        if (fileQueue.isEmpty()) {
            idle = true;
        } else {
            service.addUpdateContext(this);
            idle = false;
        }
    }
    if (request != null) {
        int type = request.getType();
        int file = request.getFile();
        ByteBuf buf;
        try {
            if (type == 255 && file == 255) {
                buf = Unpooled.wrappedBuffer(server.getCache().getChecksum());
            } else {
                buf = Unpooled.wrappedBuffer(server.getCache().getStore().read(type, file));
                if (type != 255)
                    buf = buf.slice(0, buf.readableBytes() - 2);
            }
            channel.writeAndFlush(new FileResponseEvent(request.isPriority(), type, file, buf));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.github.ambry.admin.AdminIntegrationTest.java

License:Open Source License

/**
 * Method to easily create a request.//  w  w w . jav a2 s . c  o m
 * @param httpMethod the {@link HttpMethod} desired.
 * @param uri string representation of the desired URI.
 * @param headers any associated headers as a {@link HttpHeaders} object. Can be null.
 * @param content the content that accompanies the request. Can be null.
 * @return A {@link FullHttpRequest} object that defines the request required by the input.
 */
private FullHttpRequest buildRequest(HttpMethod httpMethod, String uri, HttpHeaders headers,
        ByteBuffer content) {
    ByteBuf contentBuf;
    if (content != null) {
        contentBuf = Unpooled.wrappedBuffer(content);
    } else {
        contentBuf = Unpooled.buffer(0);
    }
    FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, uri, contentBuf);
    if (headers != null) {
        httpRequest.headers().set(headers);
    }
    return httpRequest;
}

From source file:com.github.ambry.frontend.FrontendIntegrationTest.java

License:Open Source License

/**
 * Creates a {@link HttpPostRequestEncoder} that encodes the given {@code request} and {@code blobContent}.
 * @param request the {@link HttpRequest} containing headers and other metadata about the request.
 * @param blobContent the {@link ByteBuffer} that represents the content of the blob.
 * @param usermetadata the {@link ByteBuffer} that represents user metadata
 * @return a {@link HttpPostRequestEncoder} that can encode the {@code request} and {@code blobContent}.
 * @throws HttpPostRequestEncoder.ErrorDataEncoderException
 * @throws IOException//ww w.j  av a  2s . c om
 */
private HttpPostRequestEncoder createEncoder(HttpRequest request, ByteBuffer blobContent,
        ByteBuffer usermetadata) throws HttpPostRequestEncoder.ErrorDataEncoderException, IOException {
    HttpDataFactory httpDataFactory = new DefaultHttpDataFactory(false);
    HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(httpDataFactory, request, true);
    FileUpload fileUpload = new MemoryFileUpload(RestUtils.MultipartPost.BLOB_PART,
            RestUtils.MultipartPost.BLOB_PART, "application/octet-stream", "", Charset.forName("UTF-8"),
            blobContent.remaining());
    fileUpload.setContent(Unpooled.wrappedBuffer(blobContent));
    encoder.addBodyHttpData(fileUpload);
    fileUpload = new MemoryFileUpload(RestUtils.MultipartPost.USER_METADATA_PART,
            RestUtils.MultipartPost.USER_METADATA_PART, "application/octet-stream", "",
            Charset.forName("UTF-8"), usermetadata.remaining());
    fileUpload.setContent(Unpooled.wrappedBuffer(usermetadata));
    encoder.addBodyHttpData(fileUpload);
    return encoder;
}

From source file:com.github.ambry.rest.EchoMethodHandler.java

License:Open Source License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject obj) throws Exception {
    logger.trace("Reading on channel {}", ctx.channel());
    if (obj instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) obj;
        logger.trace("Handling incoming request " + request);
        requestUri = request.getUri();//w w  w  .j a v  a2  s  . c o m
        byte[] methodBytes = request.getMethod().toString().getBytes();
        if (request.headers().get(IS_CHUNKED) == null || !request.headers().get(IS_CHUNKED).equals("true")) {
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                    Unpooled.wrappedBuffer(methodBytes));
            updateHeaders(response, request, methodBytes.length);
        } else {
            httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
            HttpHeaders.setTransferEncodingChunked(httpResponse);
            httpContentList = new ArrayList<HttpContent>();
            ByteBuf content = Unpooled.wrappedBuffer(methodBytes);
            HttpContent httpContent = new DefaultHttpContent(content);
            httpContentList.add(httpContent);
            httpContentList.add(httpContent);
            updateHeaders(httpResponse, request, methodBytes.length);
        }
    } else if (obj instanceof LastHttpContent) {
        if (requestUri.equals(DISCONNECT_URI)) {
            ctx.disconnect();
        } else if (requestUri.equals(CLOSE_URI)) {
            ctx.close();
        } else {
            if (response != null) {
                ctx.writeAndFlush(response);
            } else if (httpResponse != null) {
                ctx.writeAndFlush(httpResponse);
                for (HttpContent httpContent : httpContentList) {
                    ctx.writeAndFlush(httpContent);
                }
                ctx.writeAndFlush(new DefaultLastHttpContent());
            }
        }
    }
}

From source file:com.github.ambry.rest.NettyMessageProcessorTest.java

License:Open Source License

/**
 * Tests the case where raw bytes are POSTed as chunks.
 * @throws InterruptedException//from ww w .jav  a2  s .  c  om
 */
@Test
public void rawBytesPostTest() throws InterruptedException {
    Random random = new Random();
    // request also contains content.
    ByteBuffer content = ByteBuffer.wrap(RestTestUtils.getRandomBytes(random.nextInt(128) + 128));
    HttpRequest postRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/",
            Unpooled.wrappedBuffer(content));
    HttpHeaders.setHeader(postRequest, RestUtils.Headers.SERVICE_ID, "rawBytesPostTest");
    HttpHeaders.setHeader(postRequest, RestUtils.Headers.BLOB_SIZE, content.remaining());
    postRequest = ReferenceCountUtil.retain(postRequest);
    ByteBuffer receivedContent = doPostTest(postRequest, null);
    compareContent(receivedContent, Collections.singletonList(content));

    // request and content separate.
    final int NUM_CONTENTS = 5;
    postRequest = RestTestUtils.createRequest(HttpMethod.POST, "/", null);
    List<ByteBuffer> contents = new ArrayList<ByteBuffer>(NUM_CONTENTS);
    int blobSize = 0;
    for (int i = 0; i < NUM_CONTENTS; i++) {
        ByteBuffer buffer = ByteBuffer.wrap(RestTestUtils.getRandomBytes(random.nextInt(128) + 128));
        blobSize += buffer.remaining();
        contents.add(i, buffer);
    }
    HttpHeaders.setHeader(postRequest, RestUtils.Headers.SERVICE_ID, "rawBytesPostTest");
    HttpHeaders.setHeader(postRequest, RestUtils.Headers.BLOB_SIZE, blobSize);
    receivedContent = doPostTest(postRequest, contents);
    compareContent(receivedContent, contents);
}

From source file:com.github.ambry.rest.NettyMessageProcessorTest.java

License:Open Source License

/**
 * Tests for error handling flow when bad input streams are provided to the {@link NettyMessageProcessor}.
 */// w  w  w  .  j a v  a 2 s.co m
@Test
public void requestHandleWithBadInputTest() throws IOException {
    String content = "@@randomContent@@@";
    // content without request.
    EmbeddedChannel channel = createChannel();
    channel.writeInbound(new DefaultLastHttpContent(Unpooled.wrappedBuffer(content.getBytes())));
    HttpResponse response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.BAD_REQUEST, response.getStatus());

    // content without request on a channel that was kept alive
    channel = createChannel();
    // send and receive response for a good request and keep the channel alive
    channel.writeInbound(
            RestTestUtils.createRequest(HttpMethod.GET, MockBlobStorageService.ECHO_REST_METHOD, null));
    channel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
    response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus());
    // drain the content
    while (channel.readOutbound() != null) {
        ;
    }
    assertTrue("Channel is not active", channel.isActive());
    // send content without request
    channel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
    response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.BAD_REQUEST, response.getStatus());

    // content when no content is expected.
    channel = createChannel();
    channel.writeInbound(RestTestUtils.createRequest(HttpMethod.GET, "/", null));
    channel.writeInbound(new DefaultLastHttpContent(Unpooled.wrappedBuffer(content.getBytes())));
    response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.BAD_REQUEST, response.getStatus());

    // wrong HTTPObject.
    channel = createChannel();
    channel.writeInbound(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK));
    response = (HttpResponse) channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.BAD_REQUEST, response.getStatus());
}