Search in sources :

Example 1 with KeyValuePair

use of org.bimserver.shared.reflector.KeyValuePair in project BIMserver by opensourceBIM.

the class JsonReflector method callMethod.

@Override
public Object callMethod(String interfaceName, String methodName, Class<?> definedReturnType, KeyValuePair... args) throws ServerException, UserException, ReflectorException {
    try {
        JsonObject request = new JsonObject();
        request.add("interface", new JsonPrimitive(interfaceName));
        request.add("method", new JsonPrimitive(methodName));
        JsonObject parameters = new JsonObject();
        for (KeyValuePair arg : args) {
            parameters.add(arg.getFieldName(), converter.toJson(arg.getValue()));
        }
        request.add("parameters", parameters);
        JsonObject requestObject = new JsonObject();
        requestObject.add("request", request);
        JsonObject jsonResult = call(requestObject);
        if (!isOneWay()) {
            if (jsonResult == null) {
                return null;
            }
            JsonObject response = jsonResult.getAsJsonObject("response");
            if (response.has("exception")) {
                JsonObject exceptionJson = response.getAsJsonObject("exception");
                String exceptionType = exceptionJson.get("__type").getAsString();
                String message = exceptionJson.has("message") ? exceptionJson.get("message").getAsString() : "unknown";
                if (exceptionType.equals(UserException.class.getSimpleName())) {
                    if (exceptionJson.has("errorCode")) {
                        throw new UserException(message, ErrorCode.parse(exceptionJson.get("errorCode").getAsInt()));
                    } else {
                        throw new UserException(message);
                    }
                } else if (exceptionType.equals(ServerException.class.getSimpleName())) {
                    if (exceptionJson.has("errorCode")) {
                        throw new ServerException(message, ErrorCode.parse(exceptionJson.get("errorCode").getAsInt()));
                    } else {
                        throw new ServerException(message);
                    }
                } else {
                    if (exceptionJson.has("errorCode")) {
                        throw new ServerException(message, ErrorCode.parse(exceptionJson.get("errorCode").getAsInt()));
                    } else {
                        throw new ServerException(message);
                    }
                }
            } else if (response.has("result")) {
                Object result = response.get("result");
                SMethod method = servicesMap.getBySimpleName(interfaceName).getSMethod(methodName);
                return converter.fromJson(method.getReturnType(), method.getGenericReturnType(), result);
            } else {
                return null;
            }
        } else {
            return null;
        }
    } catch (ReflectorException e) {
        throw e;
    } catch (UserException e) {
        throw e;
    } catch (ServerException e) {
        throw e;
    } catch (Exception e) {
        throw new ReflectorException(e);
    }
}
Also used : ServerException(org.bimserver.shared.exceptions.ServerException) KeyValuePair(org.bimserver.shared.reflector.KeyValuePair) JsonPrimitive(com.google.gson.JsonPrimitive) ReflectorException(org.bimserver.shared.reflector.ReflectorException) JsonObject(com.google.gson.JsonObject) JsonObject(com.google.gson.JsonObject) UserException(org.bimserver.shared.exceptions.UserException) SMethod(org.bimserver.shared.meta.SMethod) ReflectorException(org.bimserver.shared.reflector.ReflectorException) UserException(org.bimserver.shared.exceptions.UserException) ServerException(org.bimserver.shared.exceptions.ServerException)

Example 2 with KeyValuePair

use of org.bimserver.shared.reflector.KeyValuePair in project BIMserver by opensourceBIM.

the class NotificationsManager method handleIncoming.

public void handleIncoming(JsonObject request) throws UserException, ConvertException, IOException {
    // TODO copied code from JsonHandler
    String interfaceName = request.get("interface").getAsString();
    String methodName = request.get("method").getAsString();
    SService sService = servicesMap.getByName(interfaceName);
    if (sService == null) {
        sService = servicesMap.getBySimpleName(interfaceName);
    }
    if (sService == null) {
        throw new UserException("No service found with name " + interfaceName);
    }
    SMethod method = sService.getSMethod(methodName);
    if (method == null) {
        SMethod alternative = servicesMap.findMethod(methodName);
        if (alternative == null) {
            throw new UserException("Method " + methodName + " not found on " + interfaceName);
        } else {
            throw new UserException("Method " + methodName + " not found on " + interfaceName + " (suggestion: " + alternative.getService().getSimpleName() + ")");
        }
    }
    KeyValuePair[] parameters = new KeyValuePair[method.getParameters().size()];
    if (request.has("parameters")) {
        JsonObject parametersJson = request.getAsJsonObject("parameters");
        for (int i = 0; i < method.getParameters().size(); i++) {
            SParameter parameter = method.getParameter(i);
            if (parametersJson.has(parameter.getName())) {
                parameters[i] = new KeyValuePair(parameter.getName(), converter.fromJson(parameter.getType(), parameter.getGenericType(), parametersJson.get(parameter.getName())));
            } else {
                LOGGER.error("Missing parameters: " + method.getName() + " -> " + parameter.getName());
            }
        }
    } else {
        throw new UserException("Missing 'parameters' field");
    }
    try {
        method.invoke(sService.getInterfaceClass(), service, parameters);
    } catch (ServiceException e) {
        LOGGER.error("", e);
    } catch (ReflectorException e) {
        LOGGER.error("", e);
    }
}
Also used : KeyValuePair(org.bimserver.shared.reflector.KeyValuePair) ServiceException(org.bimserver.shared.exceptions.ServiceException) SParameter(org.bimserver.shared.meta.SParameter) ReflectorException(org.bimserver.shared.reflector.ReflectorException) JsonObject(com.google.gson.JsonObject) UserException(org.bimserver.shared.exceptions.UserException) SMethod(org.bimserver.shared.meta.SMethod) SService(org.bimserver.shared.meta.SService)

Example 3 with KeyValuePair

use of org.bimserver.shared.reflector.KeyValuePair 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 4 with KeyValuePair

use of org.bimserver.shared.reflector.KeyValuePair in project BIMserver by opensourceBIM.

the class JsonHandler method processSingleRequest.

private void processSingleRequest(JsonObject request, String jsonToken, String oAuthCode, HttpServletRequest httpRequest, JsonWriter writer) throws Exception {
    long s = System.nanoTime();
    if (!request.has("interface")) {
        throw new UserException("No \"interface\" parameter found in request");
    }
    String interfaceName = request.get("interface").getAsString();
    if (!request.has("method")) {
        throw new UserException("No \"method\" parameter found in request");
    }
    String methodName = request.get("method").getAsString();
    SService sService = bimServer.getServicesMap().getByName(interfaceName);
    if (sService == null) {
        sService = bimServer.getServicesMap().getBySimpleName(interfaceName);
    }
    if (sService == null) {
        throw new UserException("No service found with name " + interfaceName);
    }
    SMethod method = sService.getSMethod(methodName);
    if (method == null) {
        SMethod alternative = bimServer.getServicesMap().findMethod(methodName);
        if (alternative == null) {
            throw new UserException("Method " + methodName + " not found on " + interfaceName);
        } else {
            throw new UserException("Method " + methodName + " not found on " + interfaceName + " (suggestion: " + alternative.getService().getSimpleName() + ")");
        }
    }
    KeyValuePair[] parameters = new KeyValuePair[method.getParameters().size()];
    if (request.has("parameters")) {
        JsonObject parametersJson = request.getAsJsonObject("parameters");
        for (int i = 0; i < method.getParameters().size(); i++) {
            SParameter parameter = method.getParameter(i);
            if (parametersJson.has(parameter.getName())) {
                parameters[i] = new KeyValuePair(parameter.getName(), converter.fromJson(parameter.getType(), parameter.getGenericType(), parametersJson.get(parameter.getName())));
            } else {
                LOGGER.error("Missing parameter: " + method.getName() + " -> " + parameter.getName());
                throw new UserException("Missing parameter: " + method.getName() + " -> " + parameter.getName());
            }
        }
    } else if (parameters.length > 0) {
        throw new UserException("Missing 'parameters' field, expected " + parameters.length + " parameters");
    }
    PublicInterface service = getServiceInterface(httpRequest, bimServer, sService.getInterfaceClass(), methodName, jsonToken, oAuthCode);
    String oldThreadName = Thread.currentThread().getName();
    Thread.currentThread().setName(interfaceName + "." + methodName);
    try {
        Recording recording = bimServer.getMetricsRegistry().startRecording(sService, method);
        Object result = method.invoke(sService.getInterfaceClass(), service, parameters);
        recording.finish();
        // can start streaming
        if (writer != null) {
            if (result == null) {
                writer.beginObject();
                writer.name("result");
                writer.beginObject();
                writer.endObject();
                writer.endObject();
            } else {
                writer.beginObject();
                writer.name("result");
                converter.toJson(result, writer);
                writer.endObject();
            }
        }
        long e = System.nanoTime();
        LOGGER.debug(interfaceName + "." + methodName + " " + ((e - s) / 1000000) + "ms");
    } finally {
        Thread.currentThread().setName(oldThreadName);
    }
}
Also used : KeyValuePair(org.bimserver.shared.reflector.KeyValuePair) JsonObject(com.google.gson.JsonObject) PublicInterface(org.bimserver.shared.interfaces.PublicInterface) SParameter(org.bimserver.shared.meta.SParameter) JsonObject(com.google.gson.JsonObject) UserException(org.bimserver.shared.exceptions.UserException) SMethod(org.bimserver.shared.meta.SMethod) SService(org.bimserver.shared.meta.SService)

Aggregations

SMethod (org.bimserver.shared.meta.SMethod)4 KeyValuePair (org.bimserver.shared.reflector.KeyValuePair)4 JsonObject (com.google.gson.JsonObject)3 UserException (org.bimserver.shared.exceptions.UserException)3 SParameter (org.bimserver.shared.meta.SParameter)3 SService (org.bimserver.shared.meta.SService)2 ReflectorException (org.bimserver.shared.reflector.ReflectorException)2 JsonPrimitive (com.google.gson.JsonPrimitive)1 ByteString (com.google.protobuf.ByteString)1 Descriptor (com.google.protobuf.Descriptors.Descriptor)1 EnumValueDescriptor (com.google.protobuf.Descriptors.EnumValueDescriptor)1 FieldDescriptor (com.google.protobuf.Descriptors.FieldDescriptor)1 DynamicMessage (com.google.protobuf.DynamicMessage)1 Builder (com.google.protobuf.Message.Builder)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 Date (java.util.Date)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Set (java.util.Set)1