inti.core.codec.direct.DirectByteCodec.java Source code

Java tutorial

Introduction

Here is the source code for inti.core.codec.direct.DirectByteCodec.java

Source

/**
 * Copyright 2012 the project-owners
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package inti.core.codec.direct;

import inti.core.codec.Codec;

import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.output.ByteArrayOutputStream;

public class DirectByteCodec implements Codec<byte[], byte[]> {

    protected ThreadLocal<ByteArrayOutputStream> outputs = new ThreadLocal<ByteArrayOutputStream>() {

        @Override
        protected ByteArrayOutputStream initialValue() {
            return new ByteArrayOutputStream(8192);
        }

    };
    protected ThreadLocal<byte[]> transferBuffers = new ThreadLocal<byte[]>() {

        @Override
        protected byte[] initialValue() {
            return new byte[8192];
        }

    };

    @Override
    public byte[] decode(InputStream input) throws Exception {
        ByteArrayOutputStream output = outputs.get();
        byte[] transferBuffer = transferBuffers.get();
        int read;

        output.reset();
        while (input.available() > 0 && (read = input.read(transferBuffer)) != -1) {
            output.write(transferBuffer, 0, read);
        }

        return output.toByteArray();
    }

    @Override
    public void encode(byte[] message, OutputStream stream) throws Exception {
        stream.write(message);
    }

}