/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vut.msa.utilities;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import org.apache.log4j.Logger;

/**
 *
 * @author starosta
 */
public class StringToByteBuffer {

    private final static Logger log = Logger.getLogger(StringToByteBuffer.class);
    public static Charset charset = Charset.forName("UTF-8");
    public final static CharsetEncoder encoder = charset.newEncoder();
    public final static CharsetDecoder decoder = charset.newDecoder();

    public static ByteBuffer stringToByteBuffer(String msg) {
        try {
            return encoder.encode(CharBuffer.wrap(msg));
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
        return null;
    }

    public static String byteBufferToString (ByteBuffer buffer) {

        String data = "";
        try {
            int old_position = buffer.position();
            data = decoder.decode(buffer).toString();
            buffer.position(old_position);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            return "";
        }
        return data;
    }
}
