Search in sources :

Example 1 with SBase

use of org.bimserver.shared.meta.SBase in project BIMserver by opensourceBIM.

the class JsonConverter method fromJson.

public Object fromJson(SClass definedType, SClass genericType, Object object) throws ConvertException, IOException {
    try {
        if (object instanceof JsonObject) {
            JsonObject jsonObject = (JsonObject) object;
            if (jsonObject.has("__type")) {
                String type = jsonObject.get("__type").getAsString();
                SClass sClass = servicesMap.getType(type);
                if (sClass == null) {
                    throw new ConvertException("Unknown type: " + type);
                }
                SBase newObject = sClass.newInstance();
                for (SField field : newObject.getSClass().getAllFields()) {
                    if (jsonObject.has(field.getName())) {
                        newObject.sSet(field, fromJson(field.getType(), field.getGenericType(), jsonObject.get(field.getName())));
                    }
                }
                return newObject;
            } else {
                if (jsonObject.entrySet().size() != 0) {
                    throw new ConvertException("Missing __type field in " + jsonObject.toString());
                } else {
                    return null;
                }
            }
        } else if (object instanceof JsonArray) {
            JsonArray array = (JsonArray) object;
            if (definedType.isList()) {
                List<Object> list = new ArrayList<Object>();
                for (int i = 0; i < array.size(); i++) {
                    list.add(fromJson(definedType, genericType, array.get(i)));
                }
                return list;
            } else if (definedType.isSet()) {
                Set<Object> set = new HashSet<Object>();
                for (int i = 0; i < array.size(); i++) {
                    set.add(fromJson(definedType, genericType, array.get(i)));
                }
                return set;
            }
        } else if (object instanceof JsonNull) {
            return null;
        } else if (definedType.isByteArray()) {
            if (object instanceof JsonPrimitive) {
                JsonPrimitive jsonPrimitive = (JsonPrimitive) object;
                return Base64.decodeBase64(jsonPrimitive.getAsString().getBytes(Charsets.UTF_8));
            }
        } else if (definedType.isDataHandler()) {
            if (object instanceof JsonPrimitive) {
                JsonPrimitive jsonPrimitive = (JsonPrimitive) object;
                byte[] data = Base64.decodeBase64(jsonPrimitive.getAsString().getBytes(Charsets.UTF_8));
                return new DataHandler(new ByteArrayDataSource(null, data));
            }
        } else if (definedType.isInteger()) {
            if (object instanceof JsonPrimitive) {
                return ((JsonPrimitive) object).getAsInt();
            }
        } else if (definedType.isLong()) {
            if (object instanceof JsonPrimitive) {
                return ((JsonPrimitive) object).getAsLong();
            }
        } else if (definedType.isEnum()) {
            JsonPrimitive primitive = (JsonPrimitive) object;
            for (Object enumConstantObject : definedType.getInstanceClass().getEnumConstants()) {
                Enum<?> enumConstant = (Enum<?>) enumConstantObject;
                if (enumConstant.name().equals(primitive.getAsString())) {
                    return enumConstant;
                }
            }
        } else if (definedType.isDate()) {
            if (object instanceof JsonPrimitive) {
                return new Date(((JsonPrimitive) object).getAsLong());
            }
        } else if (definedType.isString()) {
            if (object instanceof JsonPrimitive) {
                return ((JsonPrimitive) object).getAsString();
            } else if (object instanceof JsonNull) {
                return null;
            }
        } else if (definedType.isBoolean()) {
            if (object instanceof JsonPrimitive) {
                return ((JsonPrimitive) object).getAsBoolean();
            }
        } else if (definedType.isList()) {
            if (genericType.isLong()) {
                if (object instanceof JsonPrimitive) {
                    return ((JsonPrimitive) object).getAsLong();
                }
            } else if (genericType.isInteger()) {
                if (object instanceof JsonPrimitive) {
                    return ((JsonPrimitive) object).getAsInt();
                }
            } else if (genericType.isString()) {
                if (object instanceof JsonPrimitive) {
                    return ((JsonPrimitive) object).getAsString();
                }
            } else if (genericType.isDouble()) {
                if (object instanceof JsonPrimitive) {
                    return ((JsonPrimitive) object).getAsDouble();
                }
            }
        } else if (definedType.isSet()) {
            if (genericType.isLong()) {
                if (object instanceof JsonPrimitive) {
                    return ((JsonPrimitive) object).getAsLong();
                }
            } else if (genericType.isInteger()) {
                if (object instanceof JsonPrimitive) {
                    return ((JsonPrimitive) object).getAsInt();
                }
            } else if (genericType.isString()) {
                if (object instanceof JsonPrimitive) {
                    return ((JsonPrimitive) object).getAsString();
                }
            }
        } else if (definedType.isDouble()) {
            if (object instanceof JsonPrimitive) {
                return ((JsonPrimitive) object).getAsDouble();
            }
        } else if (definedType.isFloat()) {
            if (object instanceof JsonPrimitive) {
                return ((JsonPrimitive) object).getAsFloat();
            }
        } else if (definedType.isVoid()) {
            return null;
        }
    } catch (NumberFormatException e) {
        throw new ConvertException(e);
    }
    throw new UnsupportedOperationException(object.toString());
}
Also used : SClass(org.bimserver.shared.meta.SClass) JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) SField(org.bimserver.shared.meta.SField) DataHandler(javax.activation.DataHandler) Date(java.util.Date) JsonNull(com.google.gson.JsonNull) JsonArray(com.google.gson.JsonArray) SBase(org.bimserver.shared.meta.SBase) ArrayList(java.util.ArrayList) List(java.util.List) JsonObject(com.google.gson.JsonObject) ByteArrayDataSource(org.bimserver.utils.ByteArrayDataSource) HashSet(java.util.HashSet)

Example 2 with SBase

use of org.bimserver.shared.meta.SBase in project BIMserver by opensourceBIM.

the class JsonConverter method toJson.

public JsonElement toJson(Object object) throws IOException {
    if (object instanceof SBase) {
        SBase base = (SBase) object;
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("__type", new JsonPrimitive(base.getSClass().getSimpleName()));
        for (SField field : base.getSClass().getOwnFields()) {
            jsonObject.add(field.getName(), toJson(base.sGet(field)));
        }
        return jsonObject;
    } else if (object instanceof Collection) {
        Collection<?> collection = (Collection<?>) object;
        JsonArray jsonArray = new JsonArray();
        for (Object value : collection) {
            jsonArray.add(toJson(value));
        }
        return jsonArray;
    } else if (object instanceof Date) {
        return new JsonPrimitive(((Date) object).getTime());
    } else if (object instanceof DataHandler) {
        DataHandler dataHandler = (DataHandler) object;
        InputStream inputStream = dataHandler.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IOUtils.copy(inputStream, out);
        return new JsonPrimitive(new String(Base64.encodeBase64(out.toByteArray()), Charsets.UTF_8));
    } else if (object instanceof Boolean) {
        return new JsonPrimitive((Boolean) object);
    } else if (object instanceof String) {
        return new JsonPrimitive((String) object);
    } else if (object instanceof Long) {
        return new JsonPrimitive((Long) object);
    } else if (object instanceof Integer) {
        return new JsonPrimitive((Integer) object);
    } else if (object instanceof Double) {
        return new JsonPrimitive((Double) object);
    } else if (object instanceof Enum) {
        return new JsonPrimitive(object.toString());
    } else if (object == null) {
        return JsonNull.INSTANCE;
    } else if (object instanceof byte[]) {
        byte[] data = (byte[]) object;
        return new JsonPrimitive(new String(Base64.encodeBase64(data), Charsets.UTF_8));
    }
    throw new UnsupportedOperationException(object.getClass().getName());
}
Also used : JsonPrimitive(com.google.gson.JsonPrimitive) InputStream(java.io.InputStream) JsonObject(com.google.gson.JsonObject) SField(org.bimserver.shared.meta.SField) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Date(java.util.Date) JsonArray(com.google.gson.JsonArray) SBase(org.bimserver.shared.meta.SBase) Collection(java.util.Collection) JsonObject(com.google.gson.JsonObject)

Example 3 with SBase

use of org.bimserver.shared.meta.SBase in project BIMserver by opensourceBIM.

the class JsonConverter method toJson.

public void toJson(Object object, JsonWriter out) throws IOException, SerializerException {
    if (object instanceof SBase) {
        SBase base = (SBase) object;
        out.beginObject();
        out.name("__type");
        out.value(base.getSClass().getSimpleName());
        for (SField field : base.getSClass().getAllFields()) {
            out.name(field.getName());
            toJson(base.sGet(field), out);
        }
        out.endObject();
    } else if (object instanceof Collection) {
        Collection<?> collection = (Collection<?>) object;
        out.beginArray();
        for (Object value : collection) {
            toJson(value, out);
        }
        out.endArray();
    } else if (object instanceof Date) {
        out.value(((Date) object).getTime());
    } else if (object instanceof DataHandler) {
        DataHandler dataHandler = (DataHandler) object;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (dataHandler.getDataSource() instanceof CacheStoringEmfSerializerDataSource) {
            CacheStoringEmfSerializerDataSource cacheStoringEmfSerializerDataSource = (CacheStoringEmfSerializerDataSource) dataHandler.getDataSource();
            cacheStoringEmfSerializerDataSource.writeToOutputStream(baos, null);
            out.value(new String(Base64.encodeBase64(baos.toByteArray()), Charsets.UTF_8));
        } else {
            InputStream inputStream = dataHandler.getInputStream();
            IOUtils.copy(inputStream, baos);
            out.value(new String(Base64.encodeBase64(baos.toByteArray()), Charsets.UTF_8));
        }
    } else if (object instanceof byte[]) {
        byte[] data = (byte[]) object;
        out.value(new String(Base64.encodeBase64(data), Charsets.UTF_8));
    } else if (object instanceof String) {
        out.value((String) object);
    } else if (object instanceof Number) {
        out.value((Number) object);
    } else if (object instanceof Enum) {
        out.value(object.toString());
    } else if (object instanceof Boolean) {
        out.value((Boolean) object);
    } else if (object == null) {
        out.nullValue();
    } else {
        throw new UnsupportedOperationException(object.toString());
    }
}
Also used : CacheStoringEmfSerializerDataSource(org.bimserver.plugins.serializers.CacheStoringEmfSerializerDataSource) InputStream(java.io.InputStream) SField(org.bimserver.shared.meta.SField) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Date(java.util.Date) SBase(org.bimserver.shared.meta.SBase) Collection(java.util.Collection) JsonObject(com.google.gson.JsonObject)

Example 4 with SBase

use of org.bimserver.shared.meta.SBase in project BIMserver by opensourceBIM.

the class ProtocolBuffersConverter method convertSObjectToProtocolBuffersObject.

@SuppressWarnings({ "unchecked", "rawtypes" })
public Message convertSObjectToProtocolBuffersObject(SBase object, SClass definedType) throws ConvertException {
    Builder builder = null;
    MessageDescriptorContainer messageDescriptor = protocolBuffersMetaData.getMessageDescriptor(definedType.getSimpleName());
    if (messageDescriptor == null) {
        throw new ConvertException("No message descriptor found with name " + definedType.getSimpleName());
    }
    Descriptor definedDescriptor = messageDescriptor.getDescriptor();
    try {
        builder = DynamicMessage.getDefaultInstance(definedDescriptor).newBuilderForType();
    } catch (SecurityException e) {
        throw new ConvertException(e);
    } catch (IllegalArgumentException e) {
        throw new ConvertException(e);
    }
    SClass sClass = object.getSClass();
    SClass superClass = sClass;
    while (superClass.getSuperClass() != null && superClass.getSuperClass().getInstanceClass() != Object.class) {
        superClass = superClass.getSuperClass();
    }
    if (sClass != superClass && messageDescriptor.getField("__actual_type") != null) {
        builder.setField(messageDescriptor.getField("__actual_type"), sClass.getSimpleName());
        builder.setField(messageDescriptor.getField("__" + sClass.getSimpleName()), convertSObjectToProtocolBuffersObject(object, sClass));
    }
    for (SField field : definedType.getAllFields()) {
        try {
            Object value = object.sGet(field);
            FieldDescriptor fieldDescriptor = messageDescriptor.getField(field.getName());
            if (value != null) {
                if (value.getClass().isPrimitive() || value.getClass() == String.class || value.getClass() == Long.class || value.getClass() == Double.class || value.getClass() == Integer.class || value.getClass() == Boolean.class) {
                    builder.setField(fieldDescriptor, value);
                } else if (value.getClass().isEnum()) {
                    Enum eNum = (Enum) value;
                    int ordinal = eNum.ordinal();
                    EnumValueDescriptor findValueByNumber = fieldDescriptor.getEnumType().findValueByNumber(ordinal);
                    builder.setField(fieldDescriptor, findValueByNumber);
                } else if (value.getClass() == Date.class) {
                    builder.setField(fieldDescriptor, ((Date) value).getTime());
                } else if (value.getClass() == DataHandler.class) {
                    DataHandler dataHandler = (DataHandler) value;
                    InputStream inputStream = dataHandler.getInputStream();
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    IOUtils.copy(inputStream, byteArrayOutputStream);
                    ByteString byteString = ByteString.copyFrom(byteArrayOutputStream.toByteArray());
                    builder.setField(fieldDescriptor, byteString);
                } else if (List.class.isAssignableFrom(value.getClass())) {
                    List list = (List) value;
                    List newList = new ArrayList();
                    for (Object o : list) {
                        if (fieldDescriptor.getJavaType() == JavaType.MESSAGE) {
                            newList.add(convertSObjectToProtocolBuffersObject((SBase) o, field.getGenericType()));
                        } else {
                            newList.add(o);
                        }
                    }
                    builder.setField(fieldDescriptor, newList);
                } else {
                    LOGGER.error("Unimplemented: " + fieldDescriptor.getName() + ": " + value);
                }
            }
        } catch (SecurityException e) {
            LOGGER.error("", e);
        } catch (IllegalArgumentException e) {
            LOGGER.error("", e);
        } catch (IOException e) {
            LOGGER.error("", e);
        }
    }
    return builder.build();
}
Also used : SClass(org.bimserver.shared.meta.SClass) MessageDescriptorContainer(org.bimserver.shared.pb.ProtocolBuffersMetaData.MessageDescriptorContainer) InputStream(java.io.InputStream) ByteString(com.google.protobuf.ByteString) Builder(com.google.protobuf.Message.Builder) ArrayList(java.util.ArrayList) SField(org.bimserver.shared.meta.SField) ByteString(com.google.protobuf.ByteString) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) FieldDescriptor(com.google.protobuf.Descriptors.FieldDescriptor) SBase(org.bimserver.shared.meta.SBase) Descriptor(com.google.protobuf.Descriptors.Descriptor) FieldDescriptor(com.google.protobuf.Descriptors.FieldDescriptor) EnumValueDescriptor(com.google.protobuf.Descriptors.EnumValueDescriptor) ArrayList(java.util.ArrayList) List(java.util.List) EnumValueDescriptor(com.google.protobuf.Descriptors.EnumValueDescriptor)

Example 5 with SBase

use of org.bimserver.shared.meta.SBase in project BIMserver by opensourceBIM.

the class ProtocolBuffersReflector method callMethod.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Object callMethod(String interfaceName, String methodName, Class<?> definedReturnType, KeyValuePair... args) throws ServerException, UserException {
    try {
        MethodDescriptorContainer methodDescriptorContainer;
        try {
            methodDescriptorContainer = protocolBuffersMetaData.getMethod(interfaceName, methodName);
            SMethod sMethod = servicesMap.getBySimpleName(interfaceName).getSMethod(methodName);
            Descriptor inputDescriptor = methodDescriptorContainer.getInputDescriptor();
            Builder builder = DynamicMessage.newBuilder(methodDescriptorContainer.getInputDescriptor());
            int i = 0;
            for (FieldDescriptor field : inputDescriptor.getFields()) {
                Object arg = args[i].getValue();
                if (field.getJavaType() == JavaType.ENUM) {
                    EnumDescriptor enumType = field.getEnumType();
                    builder.setField(field, enumType.findValueByName(arg.toString()));
                } else {
                    if (arg instanceof SBase) {
                        builder.setField(field, convertSObjectToProtocolBuffersObject((SBase) arg, sMethod.getParameter(i).getType()));
                    } else if (arg instanceof DataHandler) {
                        DataHandler dataHandler = (DataHandler) arg;
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        try {
                            IOUtils.copy(dataHandler.getInputStream(), baos);
                        } catch (IOException e) {
                            LOGGER.error("", e);
                        }
                        builder.setField(field, ByteString.copyFrom(baos.toByteArray()));
                    } else {
                        if (arg != null) {
                            if (arg instanceof Collection) {
                                Collection col = (Collection) arg;
                                Iterator iterator = col.iterator();
                                while (iterator.hasNext()) {
                                    Object o = iterator.next();
                                    builder.addRepeatedField(field, o);
                                }
                            } else {
                                builder.setField(field, arg);
                            }
                        }
                    }
                }
                i++;
            }
            DynamicMessage message = builder.build();
            Message result = channel.callBlockingMethod(methodDescriptorContainer, message);
            FieldDescriptor errorMessageField = methodDescriptorContainer.getOutputField("errorMessage");
            String errorMessage = (String) result.getField(errorMessageField);
            if (errorMessage.equals("OKE")) {
                if (result.getDescriptorForType().getName().equals("VoidResponse")) {
                    return null;
                } else {
                    FieldDescriptor outputField = methodDescriptorContainer.getOutputField("value");
                    Object value = result.getField(outputField);
                    if (outputField.isRepeated()) {
                        if (value instanceof Collection) {
                            Collection collection = (Collection) value;
                            Collection x = null;
                            if (definedReturnType == List.class) {
                                x = new ArrayList();
                            } else if (definedReturnType == Set.class) {
                                x = new HashSet();
                            }
                            for (Object v : collection) {
                                if (v instanceof DynamicMessage) {
                                    x.add(convertProtocolBuffersMessageToSObject((DynamicMessage) v, null, sMethod.getBestReturnType()));
                                } else {
                                    x.add(v);
                                }
                            }
                            return x;
                        } else {
                            return new ArrayList();
                        }
                    } else if (outputField.getJavaType() == JavaType.ENUM) {
                        EnumDescriptor enumType = outputField.getEnumType();
                        return enumType.findValueByName(value.toString());
                    } else if (value instanceof DynamicMessage) {
                        return convertProtocolBuffersMessageToSObject((DynamicMessage) value, null, sMethod.getBestReturnType());
                    } else {
                        if (definedReturnType == Date.class) {
                            return new Date((Long) value);
                        }
                        return value;
                    }
                }
            } else {
                throw new UserException(errorMessage);
            }
        } catch (ConvertException e) {
            throw new ServerException(e);
        } catch (ServiceException e) {
            throw new ServerException(e.getMessage());
        }
    } catch (ServiceNotFoundException e) {
        throw new ServerException(e);
    } catch (ServiceMethodNotFoundException e) {
        throw new ServerException(e);
    }
}
Also used : MethodDescriptorContainer(org.bimserver.shared.pb.ProtocolBuffersMetaData.MethodDescriptorContainer) HashSet(java.util.HashSet) Set(java.util.Set) DynamicMessage(com.google.protobuf.DynamicMessage) Message(com.google.protobuf.Message) Builder(com.google.protobuf.DynamicMessage.Builder) ArrayList(java.util.ArrayList) DataHandler(javax.activation.DataHandler) DynamicMessage(com.google.protobuf.DynamicMessage) ByteString(com.google.protobuf.ByteString) FieldDescriptor(com.google.protobuf.Descriptors.FieldDescriptor) Iterator(java.util.Iterator) SMethod(org.bimserver.shared.meta.SMethod) UserException(org.bimserver.shared.exceptions.UserException) HashSet(java.util.HashSet) ServerException(org.bimserver.shared.exceptions.ServerException) EnumDescriptor(com.google.protobuf.Descriptors.EnumDescriptor) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Date(java.util.Date) ServiceException(com.google.protobuf.ServiceException) SBase(org.bimserver.shared.meta.SBase) Descriptor(com.google.protobuf.Descriptors.Descriptor) FieldDescriptor(com.google.protobuf.Descriptors.FieldDescriptor) EnumDescriptor(com.google.protobuf.Descriptors.EnumDescriptor) Collection(java.util.Collection)

Aggregations

DataHandler (javax.activation.DataHandler)6 SBase (org.bimserver.shared.meta.SBase)6 Date (java.util.Date)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 ArrayList (java.util.ArrayList)4 Collection (java.util.Collection)4 SField (org.bimserver.shared.meta.SField)4 JsonObject (com.google.gson.JsonObject)3 ByteString (com.google.protobuf.ByteString)3 Descriptor (com.google.protobuf.Descriptors.Descriptor)3 FieldDescriptor (com.google.protobuf.Descriptors.FieldDescriptor)3 InputStream (java.io.InputStream)3 HashSet (java.util.HashSet)3 List (java.util.List)3 JsonArray (com.google.gson.JsonArray)2 JsonPrimitive (com.google.gson.JsonPrimitive)2 EnumValueDescriptor (com.google.protobuf.Descriptors.EnumValueDescriptor)2 DynamicMessage (com.google.protobuf.DynamicMessage)2 Builder (com.google.protobuf.Message.Builder)2 IOException (java.io.IOException)2