All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.tenio.common.data.msgpack.MsgPackUtility Maven / Gradle / Ivy

Go to download

TenIO is a java NIO (Non-blocking I/O) based server specifically designed for multiplayer games. It supports UDP and TCP transports which are handled by Netty for high-speed network transmission. This is the common module for multipurpose use of the framework.

There is a newer version: 0.6.0
Show newest version
/*
The MIT License

Copyright (c) 2016-2022 kong 

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package com.tenio.common.data.msgpack;

import static org.msgpack.template.Templates.TString;
import static org.msgpack.template.Templates.TValue;
import static org.msgpack.template.Templates.tMap;

import com.tenio.common.data.msgpack.element.MsgPackArray;
import com.tenio.common.data.msgpack.element.MsgPackMap;
import java.io.IOException;
import java.util.Map;
import org.msgpack.MessagePack;
import org.msgpack.template.Templates;
import org.msgpack.type.Value;
import org.msgpack.unpacker.Converter;

/**
 * MessagePack is an efficient
 * binary serialization format. It lets you exchange data among multiple
 * languages like JSON. But it's faster and smaller. Small integers are encoded
 * into a single byte, and typical short strings require only one extra byte in
 * addition to the strings themselves. This class helps you convert one system
 * object ({@link Map}) to MsgPack data and vice versa.
 */
public final class MsgPackUtility {

  /**
   * Serialize an object to an array of bytes data
   *
   * @param object a {@link Map} type object
   * @return an array of bytes data
   */
  public static byte[] serialize(Map object) {
    return MsgPackConverter.pack(object);
  }

  /**
   * Un-serialize an array of bytes data to a {@link Map}
   *
   * @param msgPackMap     the message container which is using in the system
   * @param byteArrayInput the object for converting raw bytes data to msgpack
   *                       using one
   * @param binaries       an array of bytes data
   * @return an message object in {@link MsgPackMap} type
   */
  public static MsgPackMap unserialize(MsgPackMap msgPackMap, ByteArrayInputStream byteArrayInput,
                                       byte[] binaries) {
    var dstMap = MsgPackConverter.unpack(byteArrayInput, binaries);
    if (dstMap == null || dstMap.isEmpty()) {
      return null;
    }
    dstMap.forEach((key, value) -> {
      try {
        msgPackMap.put(key, MsgPackConverter.valueToObject(value));
      } catch (IOException e) {
        e.printStackTrace();
      }
    });
    return msgPackMap;
  }

  /**
   * Un-serialize an array of bytes data to a {@link Map}
   *
   * @param binaries an array of bytes data
   * @return an message object in {@link MsgPackMap} type
   */
  public static MsgPackMap unserialize(byte[] binaries) {
    var msgObject = MsgPackMap.newInstance();
    var byteArrayInput = ByteArrayInputStream.newInstance();
    var dstMap = MsgPackConverter.unpack(byteArrayInput, binaries);
    if (dstMap == null || dstMap.isEmpty()) {
      return null;
    }
    dstMap.forEach((key, value) -> {
      try {
        msgObject.put(key, MsgPackConverter.valueToObject(value));
      } catch (IOException e) {
        e.printStackTrace();
      }
    });
    return msgObject;
  }
}

class MsgPackConverter {

  /**
   * A MsgPack instance
   */
  private static final MessagePack PACKER = new MessagePack();

  /**
   * Converting an object ({@link Map}) to array of bytes data
   *
   * @param map an object in {@link Map} type
   * @return an array of bytes data
   */
  public static byte[] pack(Map map) {
    try {
      return PACKER.write(map);
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
  }

  /**
   * Converting an array of bytes data to a {@link Map} object
   *
   * @param byteArrayInput object for handling byte array
   * @param binaries       an array of bytes
   * @return a object in map type
   */
  public static Map unpack(ByteArrayInputStream byteArrayInput, byte[] binaries) {
    var mapTmpl = tMap(TString, TValue);
    try {
      byteArrayInput.reset(binaries);
      var unpacker = PACKER.createUnpacker(byteArrayInput);
      return unpacker.read(mapTmpl);
    } catch (IOException | IllegalArgumentException e) {
      e.printStackTrace();
      return null;
    }
  }

  /**
   * Converting value in MsgPack type to its corresponding in Java type
   *
   * @param value the value in {@link Value} type
   * @return an object in Java type
   */
  public static Object valueToObject(Value value) throws IOException {
    if (value.isNilValue()) {
      return null;
    } else if (value.isRawValue()) {
      // String only
      return value.asRawValue().getString();
    } else if (value.isBooleanValue()) {
      return value.asBooleanValue().getBoolean();
    } else if (value.isFloatValue()) {
      // Float only (4 bytes)
      return value.asFloatValue().getFloat();
    } else if (value.isIntegerValue()) {
      // Integer only (4 bytes)
      return value.asIntegerValue().getInt();
    } else if (value.isArrayValue()) {
      // Convert value to list of objects (MsgPackArray)
      var arrayValue = value.asArrayValue();
      var array = MsgPackArray.newInstance();
      arrayValue.forEach(element -> {
        try {
          array.add(valueToObject(element));
        } catch (IOException e) {
          e.printStackTrace();
        }
      });
      return array;
    } else if (value.isMapValue()) {
      var mapValue = value.asMapValue();
      var map = MsgPackMap.newInstance();
      for (Value key : mapValue.keySet()) {
        map.put(new Converter(key).read(Templates.TString), valueToObject(mapValue.get(key)));
      }
      return map;
    } else {
      throw new UnsupportedOperationException();
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy