Search in sources :

Example 11 with SMethod

use of org.bimserver.shared.meta.SMethod 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)

Example 12 with SMethod

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

the class JsonHandler method processSingleRequest.

private void processSingleRequest(ObjectNode request, String jsonToken, String oAuthCode, HttpServletRequest httpRequest, JsonGenerator 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").asText();
    if (!request.has("method")) {
        throw new UserException("No \"method\" parameter found in request");
    }
    String methodName = request.get("method").asText();
    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")) {
        ObjectNode parametersJson = (ObjectNode) request.get("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");
    }
    ServiceMap serviceMap = getServiceMap(httpRequest, bimServer, methodName, jsonToken, oAuthCode);
    PublicInterface service = getServiceInterface(httpRequest, bimServer, sService.getInterfaceClass(), methodName, jsonToken, serviceMap);
    String oldThreadName = Thread.currentThread().getName();
    Thread.currentThread().setName(interfaceName + "." + methodName);
    try {
        boolean isMonitor = serviceMap != null && serviceMap.getUser() != null && serviceMap.getUser().getUserType() == UserType.MONITOR;
        Recording recording = null;
        if (!isMonitor) {
            recording = bimServer.getMetricsRegistry().startRecording(sService, method);
        }
        Object result = method.invoke(sService.getInterfaceClass(), service, parameters);
        if (!isMonitor) {
            recording.finish();
        }
        // can start streaming
        if (writer != null) {
            if (result == null) {
                writer.writeStartObject();
                writer.writeFieldName("result");
                writer.writeStartObject();
                writer.writeEndObject();
                writer.writeEndObject();
            } else {
                writer.writeStartObject();
                writer.writeFieldName("result");
                JsonNode jsonResult = converter.toJson(result);
                OBJECT_MAPPER.writeValue(writer, jsonResult);
                writer.writeEndObject();
            }
        }
        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) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ServiceMap(org.bimserver.webservices.ServiceMap) JsonNode(com.fasterxml.jackson.databind.JsonNode) PublicInterface(org.bimserver.shared.interfaces.PublicInterface) SParameter(org.bimserver.shared.meta.SParameter) UserException(org.bimserver.shared.exceptions.UserException) SMethod(org.bimserver.shared.meta.SMethod) SService(org.bimserver.shared.meta.SService)

Example 13 with SMethod

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

the class ProtocolBuffersGenerator method generateProtoFile.

private void generateProtoFile(Class<?> serviceInterfaceClass, File protoFile, boolean createBaseMessages, SService service, List<String> imports) {
    PrintWriter out = null;
    try {
        out = new PrintWriter(protoFile);
        out.println("package org.bimserver.pb;\n");
        out.println(Licenser.getCommentedLicenseText(new File("license.txt")));
        for (String importFile : imports) {
            out.println("import \"" + importFile + ".proto\";");
        }
        out.println("option java_generic_services = true;\n");
        out.println("option java_outer_classname = \"" + service.getSimpleName() + "Impl\";\n");
        // or CODE_SIZE
        out.println("option optimize_for = SPEED;\n");
        StringBuilder serviceBuilder = new StringBuilder();
        StringBuilder messageBuilder = new StringBuilder();
        serviceBuilder.append("service " + service.getSimpleName() + " {\n");
        if (createBaseMessages) {
            createVoidResponseMessage(messageBuilder);
            generateVoidMessage(messageBuilder);
        }
        for (SMethod method : service.getMethods()) {
            String inputObjectName = StringUtils.firstUpperCase(method.getName()) + "Request";
            String outputObjectName = StringUtils.firstUpperCase(method.getName()) + "Response";
            createRequestMessage(messageBuilder, method, inputObjectName);
            if (method.returnsVoid()) {
                outputObjectName = "VoidResponse";
            } else {
                createResponseMessage(messageBuilder, method, outputObjectName);
            }
            serviceBuilder.append("\trpc " + method.getName() + " (" + inputObjectName + ") returns (" + outputObjectName + ");\n\n");
        }
        serviceBuilder.append("}\n\n");
        out.print(serviceBuilder.toString());
        out.print(messageBuilder.toString());
    } catch (FileNotFoundException e) {
        LOGGER.error("", e);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}
Also used : FileNotFoundException(java.io.FileNotFoundException) SMethod(org.bimserver.shared.meta.SMethod) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 14 with SMethod

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

the class NotificationsManager method handleIncoming.

public void handleIncoming(ObjectNode request) throws UserException, ConvertException, IOException {
    // TODO copied code from JsonHandler
    String interfaceName = request.get("interface").asText();
    String methodName = request.get("method").asText();
    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")) {
        ObjectNode parametersJson = (ObjectNode) request.get("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) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ServiceException(org.bimserver.shared.exceptions.ServiceException) SParameter(org.bimserver.shared.meta.SParameter) ReflectorException(org.bimserver.shared.reflector.ReflectorException) UserException(org.bimserver.shared.exceptions.UserException) SMethod(org.bimserver.shared.meta.SMethod) SService(org.bimserver.shared.meta.SService)

Example 15 with SMethod

use of org.bimserver.shared.meta.SMethod 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

SMethod (org.bimserver.shared.meta.SMethod)17 SParameter (org.bimserver.shared.meta.SParameter)11 UserException (org.bimserver.shared.exceptions.UserException)9 SService (org.bimserver.shared.meta.SService)8 KeyValuePair (org.bimserver.shared.reflector.KeyValuePair)6 ArrayList (java.util.ArrayList)4 CannotCompileException (javassist.CannotCompileException)4 CtClass (javassist.CtClass)4 CtConstructor (javassist.CtConstructor)4 CtField (javassist.CtField)4 CtMethod (javassist.CtMethod)4 NotFoundException (javassist.NotFoundException)4 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)3 DynamicMessage (com.google.protobuf.DynamicMessage)3 DataHandler (javax.activation.DataHandler)3 PublicInterface (org.bimserver.shared.interfaces.PublicInterface)3 ReflectorException (org.bimserver.shared.reflector.ReflectorException)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 JsonObject (com.google.gson.JsonObject)2 ByteString (com.google.protobuf.ByteString)2