Search in sources :

Example 16 with DynamicMessage

use of com.google.protobuf.DynamicMessage 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)

Example 17 with DynamicMessage

use of com.google.protobuf.DynamicMessage in project BIMserver by opensourceBIM.

the class ReflectiveRpcChannel method callBlockingMethod.

@SuppressWarnings({ "unchecked", "rawtypes" })
public Message callBlockingMethod(MethodDescriptorContainer methodDescriptor, Message request) {
    FieldDescriptor errorMessageField = methodDescriptor.getOutputField("errorMessage");
    DynamicMessage response = DynamicMessage.getDefaultInstance(methodDescriptor.getOutputDescriptor());
    Descriptor inputType = methodDescriptor.getInputDescriptor();
    SMethod sMethod = servicesMap.getBySimpleName(methodDescriptor.getServiceDescriptorContainer().getName()).getSMethod(methodDescriptor.getName());
    if (sMethod == null) {
        LOGGER.info("Method " + methodDescriptor.getName() + " not found");
        return null;
    } else {
        try {
            KeyValuePair[] arguments = new KeyValuePair[inputType.getFields().size()];
            int i = 0;
            for (FieldDescriptor fieldDescriptor : inputType.getFields()) {
                SParameter sParameter = sMethod.getParameter(i);
                Object value = request.getField(fieldDescriptor);
                if (value instanceof EnumValueDescriptor) {
                    EnumValueDescriptor enumValueDescriptor = (EnumValueDescriptor) value;
                    Class en = getJavaType(fieldDescriptor);
                    arguments[i] = new KeyValuePair(fieldDescriptor.getName(), en.getEnumConstants()[enumValueDescriptor.getIndex()]);
                } else if (value instanceof ByteString) {
                    ByteString byteString = (ByteString) value;
                    DataSource dataSource = new org.bimserver.utils.ByteArrayDataSource("bytes", byteString.toByteArray());
                    DataHandler dataHandler = new DataHandler(dataSource);
                    arguments[i] = new KeyValuePair(fieldDescriptor.getName(), dataHandler);
                } else if (value instanceof DynamicMessage) {
                    arguments[i] = new KeyValuePair(fieldDescriptor.getName(), convertProtocolBuffersMessageToSObject((DynamicMessage) value, null, sParameter.getType()));
                } else if (value instanceof Collection) {
                    Collection col = (Collection) value;
                    if (sParameter.getType().isList()) {
                        List list = new ArrayList(col);
                        arguments[i] = new KeyValuePair(fieldDescriptor.getName(), list);
                    } else if (sParameter.getType().isSet()) {
                        Set set = new HashSet(col);
                        arguments[i] = new KeyValuePair(fieldDescriptor.getName(), set);
                    }
                } else {
                    arguments[i] = new KeyValuePair(fieldDescriptor.getName(), value);
                }
                i++;
            }
            Object result = sMethod.invoke(publicInterface, service, arguments);
            Builder builder = response.newBuilderForType();
            if (methodDescriptor.getOutputDescriptor().getName().equals("VoidResponse")) {
                builder.setField(errorMessageField, "OKE");
            } else {
                FieldDescriptor valueField = protocolBuffersMetaData.getMessageDescriptor(response.getDescriptorForType().getName()).getField("value");
                if (result != null) {
                    if (valueField.getType().getJavaType() == JavaType.ENUM) {
                        builder.setField(valueField, valueField.getEnumType().findValueByName(result.toString()));
                    } else if (valueField.getType().getJavaType() != JavaType.MESSAGE) {
                        if (result instanceof Date) {
                            builder.setField(valueField, ((Date) result).getTime());
                        } else {
                            if (valueField.isRepeated()) {
                                builder.setField(valueField, new ArrayList());
                            } else {
                                builder.setField(valueField, result);
                            }
                        }
                    } else if (result instanceof List) {
                        List list = new ArrayList();
                        List originalList = (List) result;
                        for (Object object : originalList) {
                            list.add(convertSObjectToProtocolBuffersObject((SBase) object, sMethod.getBestReturnType()));
                        }
                        builder.setField(valueField, list);
                    } else if (result instanceof Set) {
                        List list = new ArrayList();
                        Set originalSet = (Set) result;
                        for (Object object : originalSet) {
                            list.add(convertSObjectToProtocolBuffersObject((SBase) object, sMethod.getBestReturnType()));
                        }
                        builder.setField(valueField, list);
                    } else {
                        builder.setField(valueField, convertSObjectToProtocolBuffersObject((SBase) result, sMethod.getBestReturnType()));
                    }
                }
                builder.setField(errorMessageField, "OKE");
            }
            return builder.build();
        // } catch (InvocationTargetException e) {
        // Builder errorMessage = response.newBuilderForType();
        // if (e.getTargetException() != null && e.getTargetException().getMessage() != null) {
        // errorMessage.setField(errorMessageField, e.getTargetException().getMessage());
        // } else {
        // if (e.getMessage() != null) {
        // errorMessage.setField(errorMessageField, e.getMessage());
        // } else {
        // errorMessage.setField(errorMessageField, "Unknown error");
        // }
        // }
        // return errorMessage.build();
        } catch (Exception e) {
            if (!(e instanceof org.bimserver.shared.exceptions.ServiceException)) {
                LOGGER.error("", e);
            }
            Builder errorMessage = response.newBuilderForType();
            if (e.getMessage() != null) {
                errorMessage.setField(errorMessageField, e.getMessage());
            } else {
                LOGGER.error("", e);
                errorMessage.setField(errorMessageField, "Unknown error");
            }
            return errorMessage.build();
        }
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) ByteString(com.google.protobuf.ByteString) Builder(com.google.protobuf.Message.Builder) ArrayList(java.util.ArrayList) DynamicMessage(com.google.protobuf.DynamicMessage) DataHandler(javax.activation.DataHandler) FieldDescriptor(com.google.protobuf.Descriptors.FieldDescriptor) SParameter(org.bimserver.shared.meta.SParameter) ArrayList(java.util.ArrayList) List(java.util.List) SMethod(org.bimserver.shared.meta.SMethod) EnumValueDescriptor(com.google.protobuf.Descriptors.EnumValueDescriptor) HashSet(java.util.HashSet) KeyValuePair(org.bimserver.shared.reflector.KeyValuePair) Date(java.util.Date) DataSource(javax.activation.DataSource) SBase(org.bimserver.shared.meta.SBase) Descriptor(com.google.protobuf.Descriptors.Descriptor) FieldDescriptor(com.google.protobuf.Descriptors.FieldDescriptor) EnumValueDescriptor(com.google.protobuf.Descriptors.EnumValueDescriptor) Collection(java.util.Collection)

Example 18 with DynamicMessage

use of com.google.protobuf.DynamicMessage in project BIMserver by opensourceBIM.

the class SocketProtocolBuffersChannel method callBlockingMethod.

public Message callBlockingMethod(MethodDescriptorContainer methodDescriptor, Message request) throws ServiceException {
    try {
        dataOutputStream.writeUTF(methodDescriptor.getServiceDescriptorContainer().getName());
        dataOutputStream.writeUTF(methodDescriptor.getName());
        dataOutputStream.writeUTF(tokenHolder.getToken() == null ? "" : tokenHolder.getToken());
        request.writeDelimitedTo(dataOutputStream);
        dataOutputStream.flush();
        DynamicMessage response = DynamicMessage.getDefaultInstance(methodDescriptor.getOutputDescriptor());
        Builder responseBuilder = response.newBuilderForType();
        responseBuilder.mergeDelimitedFrom(inputStream);
        return responseBuilder.build();
    } catch (IOException e) {
        LOGGER.error("", e);
    }
    return null;
}
Also used : Builder(com.google.protobuf.DynamicMessage.Builder) DynamicMessage(com.google.protobuf.DynamicMessage) IOException(java.io.IOException)

Example 19 with DynamicMessage

use of com.google.protobuf.DynamicMessage in project eat by nhnent.

the class ProtoBufPacket method jsonToPacket.

@Override
public byte[] jsonToPacket(String packetType, String packageName, String packetName, String jsonContents) {
    byte[] packet = null;
    Message.Builder msg;
    DynamicMessage message;
    String serviceID;
    try {
        msg = ProtobufDescPool.obj().JsonToMessage(packageName + "." + packetName, jsonContents);
        message = (DynamicMessage) msg.build();
        serviceID = ProtobufConfig.obj().getProtobuf().getServiceId();
        packet = Packet.generateTransferPacket(serviceID, packetType, "", message);
    } catch (Exception e) {
        logger.error(ExceptionUtils.getStackTrace(e));
    }
    return packet;
}
Also used : DynamicMessage(com.google.protobuf.DynamicMessage) Message(com.google.protobuf.Message) DynamicMessage(com.google.protobuf.DynamicMessage) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException)

Example 20 with DynamicMessage

use of com.google.protobuf.DynamicMessage in project druid by druid-io.

the class ProtobufInputRowParser method parseBatch.

@Override
public List<InputRow> parseBatch(ByteBuffer input) {
    if (parser == null) {
        parser = parseSpec.makeParser();
    }
    Map<String, Object> record;
    DateTime timestamp;
    if (isFlatSpec) {
        try {
            DynamicMessage message = protobufBytesDecoder.parse(input);
            record = CollectionUtils.mapKeys(message.getAllFields(), k -> k.getJsonName());
            timestamp = this.timestampSpec.extractTimestamp(record);
        } catch (Exception ex) {
            throw new ParseException(null, ex, "Protobuf message could not be parsed");
        }
    } else {
        try {
            DynamicMessage message = protobufBytesDecoder.parse(input);
            String json = JsonFormat.printer().print(message);
            record = parser.parseToMap(json);
            timestamp = this.timestampSpec.extractTimestamp(record);
        } catch (InvalidProtocolBufferException e) {
            throw new ParseException(null, e, "Protobuf message could not be parsed");
        }
    }
    final List<String> dimensions;
    if (!this.dimensions.isEmpty()) {
        dimensions = this.dimensions;
    } else {
        dimensions = Lists.newArrayList(Sets.difference(record.keySet(), parseSpec.getDimensionsSpec().getDimensionExclusions()));
    }
    return ImmutableList.of(new MapBasedInputRow(timestamp, dimensions, record));
}
Also used : ParseSpec(org.apache.druid.data.input.impl.ParseSpec) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) ByteBufferInputRowParser(org.apache.druid.data.input.ByteBufferInputRowParser) DynamicMessage(com.google.protobuf.DynamicMessage) Parser(org.apache.druid.java.util.common.parsers.Parser) ParseException(org.apache.druid.java.util.common.parsers.ParseException) DateTime(org.joda.time.DateTime) MapBasedInputRow(org.apache.druid.data.input.MapBasedInputRow) JSONParseSpec(org.apache.druid.data.input.impl.JSONParseSpec) CollectionUtils(org.apache.druid.utils.CollectionUtils) TimestampSpec(org.apache.druid.data.input.impl.TimestampSpec) Sets(com.google.common.collect.Sets) ByteBuffer(java.nio.ByteBuffer) InputRow(org.apache.druid.data.input.InputRow) List(java.util.List) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) JsonFormat(com.google.protobuf.util.JsonFormat) Map(java.util.Map) JsonCreator(com.fasterxml.jackson.annotation.JsonCreator) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) DynamicMessage(com.google.protobuf.DynamicMessage) ParseException(org.apache.druid.java.util.common.parsers.ParseException) MapBasedInputRow(org.apache.druid.data.input.MapBasedInputRow) DateTime(org.joda.time.DateTime) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) ParseException(org.apache.druid.java.util.common.parsers.ParseException)

Aggregations

DynamicMessage (com.google.protobuf.DynamicMessage)29 Test (org.junit.Test)12 ByteString (com.google.protobuf.ByteString)11 FieldDescriptor (com.google.protobuf.Descriptors.FieldDescriptor)11 Descriptor (com.google.protobuf.Descriptors.Descriptor)9 IOException (java.io.IOException)6 List (java.util.List)6 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)5 Message (com.google.protobuf.Message)5 Map (java.util.Map)4 TableRow (com.google.api.services.bigquery.model.TableRow)3 EnumValueDescriptor (com.google.protobuf.Descriptors.EnumValueDescriptor)3 Builder (com.google.protobuf.DynamicMessage.Builder)3 ByteBuffer (java.nio.ByteBuffer)3 ArrayList (java.util.ArrayList)3 Date (java.util.Date)3 DataHandler (javax.activation.DataHandler)3 Nullable (javax.annotation.Nullable)3 Descriptors (com.google.protobuf.Descriptors)2 JsonFormat (com.google.protobuf.util.JsonFormat)2