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

com.alachisoft.ncache.serialization.JSON.JsonBinaryFormatter Maven / Gradle / Ivy

There is a newer version: 5.3.3
Show newest version
package com.alachisoft.ncache.serialization.JSON;

import com.alachisoft.ncache.runtime.JSON.JsonArray;
import com.alachisoft.ncache.runtime.JSON.JsonObject;
import com.alachisoft.ncache.runtime.JSON.JsonValue;
import com.alachisoft.ncache.runtime.JSON.JsonValueBase;
import com.alachisoft.ncache.runtime.exceptions.OperationFailedException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.exc.InvalidTypeIdException;

import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;


public class JsonBinaryFormatter
{
    public static final Charset SERIALIZATION_CHARSET = StandardCharsets.UTF_8;

    private static DefaultNCacheMapper _defaultTypedMapper;
    private static DefaultNCacheMapper _defaultNonTypedMapper;
    private static DataTypeNCacheMapper _dataTypeMapper;

    static {
        _defaultTypedMapper = new DefaultNCacheMapper(true);
        _defaultNonTypedMapper = new DefaultNCacheMapper(false);
        _dataTypeMapper = new DataTypeNCacheMapper();
    }

    public static byte[] toByteArray(Object serializableObject) throws OperationFailedException {
        return serializeObject(serializableObject).getBytes(SERIALIZATION_CHARSET);
    }

    public static String serializeObject(Object value) throws OperationFailedException {
        return serializeObject(value, false);
    }

    public static String serializeObject(Object value, boolean isCustomAtributeBaseSerialized) throws OperationFailedException {
        if(value == null)
            throw new IllegalArgumentException("Value cannot be null."+System.lineSeparator()+"Parameter name: value");
        try {
            if(isCustomAtributeBaseSerialized && anyFieldHasAnnotation(value.getClass()))
                return _dataTypeMapper.writeValueAsString(value);
            else if(JsonValueBase.class.isAssignableFrom(value.getClass()))
                return ((JsonValueBase) value).toJson();
            else
                return _defaultTypedMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new OperationFailedException("Failed to deserialize data", e);
        }
    }

    public static  T fromByteBuffer(byte[] buffer, Class cls) throws OperationFailedException {
        if(buffer == null)
            throw new IllegalArgumentException("Value cannot be null."+System.lineSeparator()+"Parameter name: buffer");
        String json = new String(buffer, SERIALIZATION_CHARSET);
        try {
            return deserializeObject(json, cls);
        } catch (JsonProcessingException e) {
            throw new OperationFailedException(e);
        }
    }

    public static  T deserializeObject(String value, Class cls) throws OperationFailedException, JsonProcessingException {
        if(value == null)
            throw new IllegalArgumentException("Value cannot be null."+System.lineSeparator()+"Parameter name: value");
        if(cls == null )
            cls = Object.class;

        JsonValueBase valuebase;
        try {
            if(JsonValueBase.class.isAssignableFrom(cls)) // if user has asked to deserialize in Json Type
            {
                valuebase = JsonValueBase.parse(value);
                //if we have JsonObject after deserialization and user has asked for JsonValue or any other json type
                //then we will throw class cast exception..
                if(cls.isAssignableFrom(valuebase.getClass()))
                {
                    return (T)valuebase;
                }
                else
                    throw new ClassCastException(valuebase.getClass()+" cannot be cast to "+cls);
            }
            else { // if user has passed custom object type in cls
                try {
                    return (T) _defaultTypedMapper.readValue(value, cls); // return if object can be serialized in cls, else it will throw InvalidTypeIdException
                } catch (InvalidTypeIdException ex)
                {
                    //here we will try to verify that either object was added as JsonType or Custom object.
                    // if it was added as custom object, it can be serialized in Object type
                    Object object= _defaultTypedMapper.readValue(value,Object.class);
                    //if the above call throws exception it will be InvalidTypeIdException that will be caught down in JsonProcessingException and then default instance of given Cls is returned
                    // if this call doesn't throw exception it means it was added as custom object, not as jsonobject
                    //so we will throw casting exception
                    //that will be given to the user

                    //this is all being done to match dotnet process
                    throw new ClassCastException("class "+object.getClass().getName()+" cannot be cast to "+cls);
                }
            }
        }
        catch (JsonProcessingException e) {}

        // if JsonProcessingException occurs, it might be that the type attribute is not available. In that case, deserialize into the type given by user.
        // configuration [configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)] is added so that while deserializing object with
        // properties assigned null jackson doesn't throw exception
        return (T) _defaultNonTypedMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).readValue(value, cls);
    }

    public static String decodeString(byte[] buffer) {
        return new String(buffer);
    }

    private static boolean anyFieldHasAnnotation(Class c) {
        for(Field f : c.getFields())
            if(f.isAnnotationPresent(PrimaryField.class))
                return true;
        return false;
    }

    private static void addTypeToJson(JsonValueBase json) {
        if(json.getClass().isAssignableFrom(JsonObject.class)) {

        }
        if(json.getClass().isAssignableFrom(JsonArray.class)) {

        }
        if(json.getClass().isAssignableFrom(JsonValue.class)) {

        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy