Search in sources :

Example 21 with ServiceResponsesList

use of org.kie.server.api.model.ServiceResponsesList in project droolsjbpm-integration by kiegroup.

the class DMNKieContainerCommandServiceImpl method executeScript.

@Override
public ServiceResponsesList executeScript(CommandScript commands, MarshallingFormat marshallingFormat, String classType) {
    List<ServiceResponse<? extends Object>> responses = new ArrayList<ServiceResponse<? extends Object>>();
    for (KieServerCommand command : commands.getCommands()) {
        if (!(command instanceof DescriptorCommand)) {
            LOG.warn("Unsupported command '{}' given, will not process it", command.getClass().getName());
            continue;
        }
        try {
            ServiceResponse<?> result = null;
            Object handler = null;
            DescriptorCommand descriptorCommand = (DescriptorCommand) command;
            // find out the handler to call to process given command
            if ("DMNService".equals(descriptorCommand.getService())) {
                handler = modelEvaluatorServiceBase;
            } else {
                throw new IllegalStateException("Unable to find handler for " + descriptorCommand.getService() + " service");
            }
            List<Object> arguments = new ArrayList();
            // process and unwrap arguments
            for (Object arg : descriptorCommand.getArguments()) {
                LOG.debug("Before :: Argument with type {} and value {}", arg.getClass(), arg);
                if (arg instanceof Wrapped) {
                    arg = ((Wrapped) arg).unwrap();
                }
                LOG.debug("After :: Argument with type {} and value {}", arg.getClass(), arg);
                arguments.add(arg);
            }
            if (descriptorCommand.getPayload() != null && !descriptorCommand.getPayload().isEmpty()) {
                arguments.add(descriptorCommand.getPayload());
            }
            if (descriptorCommand.getMarshallerFormat() != null && !descriptorCommand.getMarshallerFormat().isEmpty()) {
                arguments.add(descriptorCommand.getMarshallerFormat());
            }
            LOG.debug("About to execute {} operation on {} with args {}", descriptorCommand.getMethod(), handler, arguments);
            // process command via reflection and handler
            result = (ServiceResponse<?>) MethodUtils.invokeMethod(handler, descriptorCommand.getMethod(), arguments.toArray());
            LOG.debug("Handler {} returned response {}", handler, result);
            // return successful result
            responses.add(result);
        } catch (InvocationTargetException e) {
            responses.add(new ServiceResponse(ServiceResponse.ResponseType.FAILURE, e.getTargetException().getMessage()));
        } catch (Throwable e) {
            LOG.error("Error while processing {} command", command, e);
            // return failure result
            responses.add(new ServiceResponse(ServiceResponse.ResponseType.FAILURE, e.getMessage()));
        }
    }
    LOG.debug("About to return responses '{}'", responses);
    return new ServiceResponsesList(responses);
}
Also used : DescriptorCommand(org.kie.server.api.commands.DescriptorCommand) ServiceResponsesList(org.kie.server.api.model.ServiceResponsesList) KieServerCommand(org.kie.server.api.model.KieServerCommand) ArrayList(java.util.ArrayList) InvocationTargetException(java.lang.reflect.InvocationTargetException) ServiceResponse(org.kie.server.api.model.ServiceResponse) Wrapped(org.kie.server.api.model.Wrapped)

Example 22 with ServiceResponsesList

use of org.kie.server.api.model.ServiceResponsesList in project droolsjbpm-integration by kiegroup.

the class JBPMKieContainerCommandServiceImpl method executeScript.

@Override
public ServiceResponsesList executeScript(CommandScript commands, MarshallingFormat marshallingFormat, String classType) {
    List<ServiceResponse<? extends Object>> responses = new ArrayList<ServiceResponse<? extends Object>>();
    for (KieServerCommand command : commands.getCommands()) {
        if (!(command instanceof DescriptorCommand)) {
            logger.warn("Unsupported command '{}' given, will not process it", command.getClass().getName());
            continue;
        }
        boolean wrapResults = false;
        try {
            Object result = null;
            Object handler = null;
            DescriptorCommand descriptorCommand = (DescriptorCommand) command;
            // find out the handler to call to process given command
            if ("DefinitionService".equals(descriptorCommand.getService())) {
                handler = definitionServiceBase;
            } else if ("ProcessService".equals(descriptorCommand.getService())) {
                handler = processServiceBase;
            } else if ("UserTaskService".equals(descriptorCommand.getService())) {
                handler = userTaskServiceBase;
            } else if ("QueryService".equals(descriptorCommand.getService())) {
                handler = runtimeDataServiceBase;
            } else if ("JobService".equals(descriptorCommand.getService())) {
                handler = executorServiceBase;
            } else if ("QueryDataService".equals(descriptorCommand.getService())) {
                handler = queryDataServiceBase;
                // enable wrapping as in case of embedded objects jaxb does not properly parse it due to possible unknown types (List<?> etc)
                if (marshallingFormat.equals(MarshallingFormat.JAXB)) {
                    wrapResults = true;
                }
            } else if ("DocumentService".equals(descriptorCommand.getService())) {
                handler = documentServiceBase;
            } else if ("ProcessAdminService".equals(descriptorCommand.getService())) {
                handler = processAdminServiceBase;
            } else if ("UserTaskAdminService".equals(descriptorCommand.getService())) {
                handler = userTaskAdminServiceBase;
            } else {
                throw new IllegalStateException("Unable to find handler for " + descriptorCommand.getService() + " service");
            }
            List<Object> arguments = new ArrayList();
            // process and unwrap arguments
            for (Object arg : descriptorCommand.getArguments()) {
                logger.debug("Before :: Argument with type {} and value {}", arg.getClass(), arg);
                if (arg instanceof Wrapped) {
                    arg = ((Wrapped) arg).unwrap();
                }
                logger.debug("After :: Argument with type {} and value {}", arg.getClass(), arg);
                arguments.add(arg);
            }
            if (descriptorCommand.getPayload() != null && !descriptorCommand.getPayload().isEmpty()) {
                arguments.add(descriptorCommand.getPayload());
            }
            if (descriptorCommand.getMarshallerFormat() != null && !descriptorCommand.getMarshallerFormat().isEmpty()) {
                arguments.add(descriptorCommand.getMarshallerFormat());
            }
            logger.debug("About to execute {} operation on {} with args {}", descriptorCommand.getMethod(), handler, arguments);
            // process command via reflection and handler
            result = MethodUtils.invokeMethod(handler, descriptorCommand.getMethod(), arguments.toArray());
            logger.debug("Handler {} returned response {}", handler, result);
            if (wrapResults) {
                result = ModelWrapper.wrap(result);
                logger.debug("Wrapped response is {}", result);
            }
            // return successful result
            responses.add(new ServiceResponse(ServiceResponse.ResponseType.SUCCESS, "", result));
        } catch (InvocationTargetException e) {
            logger.error("Error while processing {} command", command, e);
            responses.add(new ServiceResponse(ServiceResponse.ResponseType.FAILURE, e.getTargetException().getMessage()));
        } catch (Throwable e) {
            logger.error("Error while processing {} command", command, e);
            // return failure result
            responses.add(new ServiceResponse(ServiceResponse.ResponseType.FAILURE, e.getMessage()));
        }
    }
    logger.debug("About to return responses '{}'", responses);
    return new ServiceResponsesList(responses);
}
Also used : DescriptorCommand(org.kie.server.api.commands.DescriptorCommand) ServiceResponsesList(org.kie.server.api.model.ServiceResponsesList) KieServerCommand(org.kie.server.api.model.KieServerCommand) ArrayList(java.util.ArrayList) InvocationTargetException(java.lang.reflect.InvocationTargetException) ServiceResponse(org.kie.server.api.model.ServiceResponse) Wrapped(org.kie.server.api.model.Wrapped)

Example 23 with ServiceResponsesList

use of org.kie.server.api.model.ServiceResponsesList in project droolsjbpm-integration by kiegroup.

the class KieServerDroolsIntegrationTest method testCommandScript.

@Test
@Category(Smoke.class)
public void testCommandScript() throws Exception {
    Marshaller marshaller = MarshallerFactory.getMarshaller(new HashSet<Class<?>>(extraClasses.values()), configuration.getMarshallingFormat(), kjarClassLoader);
    Object message = createInstance(MESSAGE_CLASS_NAME);
    KieServerReflections.setValue(message, MESSAGE_TEXT_FIELD, MESSAGE_REQUEST);
    Command<?> insert = commandsFactory.newInsert(message, MESSAGE_OUT_IDENTIFIER);
    Command<?> fire = commandsFactory.newFireAllRules();
    BatchExecutionCommand batch = commandsFactory.newBatchExecution(Arrays.<Command<?>>asList(insert, fire), KIE_SESSION);
    String payload = marshaller.marshall(batch);
    String containerId = "command-script-container";
    KieServerCommand create = new CreateContainerCommand(new KieContainerResource(containerId, releaseIdScript, null));
    KieServerCommand call = new CallContainerCommand(containerId, payload);
    KieServerCommand dispose = new DisposeContainerCommand(containerId);
    List<KieServerCommand> cmds = Arrays.asList(create, call, dispose);
    CommandScript script = new CommandScript(cmds);
    ServiceResponsesList reply = client.executeScript(script);
    for (ServiceResponse<? extends Object> r : reply.getResponses()) {
        Assert.assertEquals(ServiceResponse.ResponseType.SUCCESS, r.getType());
    }
}
Also used : ServiceResponsesList(org.kie.server.api.model.ServiceResponsesList) Marshaller(org.kie.server.api.marshalling.Marshaller) CallContainerCommand(org.kie.server.api.commands.CallContainerCommand) KieServerCommand(org.kie.server.api.model.KieServerCommand) CommandScript(org.kie.server.api.commands.CommandScript) DisposeContainerCommand(org.kie.server.api.commands.DisposeContainerCommand) CreateContainerCommand(org.kie.server.api.commands.CreateContainerCommand) BatchExecutionCommand(org.kie.api.command.BatchExecutionCommand) BeforeClass(org.junit.BeforeClass) KieContainerResource(org.kie.server.api.model.KieContainerResource) Category(org.junit.experimental.categories.Category) Test(org.junit.Test)

Example 24 with ServiceResponsesList

use of org.kie.server.api.model.ServiceResponsesList in project droolsjbpm-integration by kiegroup.

the class KieServerMDB method onMessage.

public void onMessage(Message message) {
    JMSConnection connect = null;
    try {
        String username = null;
        String password = null;
        try {
            username = message.getStringProperty(USER_PROPERTY_NAME);
            password = message.getStringProperty(PASSWRD_PROPERTY_NAME);
        } catch (JMSException jmse) {
            logger.warn("Unable to retrieve user name and/or password, from message");
        }
        if (username != null && password != null) {
            JMSSecurityAdapter.login(username, password);
        } else {
            logger.warn("Unable to login to JMSSecurityAdapter, user name and/or password missing");
        }
        KieContainerCommandService executor = null;
        // 0. Get msg correlation id (for response)
        String msgCorrId = null;
        try {
            msgCorrId = message.getJMSCorrelationID();
        } catch (JMSException jmse) {
            String errMsg = "Unable to retrieve JMS correlation id from message! " + ID_NECESSARY;
            throw new JMSRuntimeException(errMsg, jmse);
        }
        // for backward compatibility default to KieServer
        String targetCapability = getStringProperty(message, TARGET_CAPABILITY_PROPERTY_NAME, "KieServer");
        String containerId = getStringProperty(message, CONTAINER_ID_PROPERTY_NAME, null);
        String conversationId = getStringProperty(message, CONVERSATION_ID_PROPERTY_NAME, null);
        int interactionPattern = getIntProperty(message, INTERACTION_PATTERN_PROPERTY_NAME, REQUEST_REPLY_PATTERN);
        // 1. get marshalling info
        MarshallingFormat format = null;
        String classType = null;
        try {
            classType = message.getStringProperty(CLASS_TYPE_PROPERTY_NAME);
            if (!message.propertyExists(SERIALIZATION_FORMAT_PROPERTY_NAME)) {
                format = MarshallingFormat.JAXB;
            } else {
                int intFormat = message.getIntProperty(SERIALIZATION_FORMAT_PROPERTY_NAME);
                logger.debug("Serialization format (int) is {}", intFormat);
                format = MarshallingFormat.fromId(intFormat);
                logger.debug("Serialization format is {}", format);
                if (format == null) {
                    String errMsg = "Unsupported marshalling format '" + intFormat + "' from message " + msgCorrId + ".";
                    throw new JMSRuntimeException(errMsg);
                }
            }
        } catch (JMSException jmse) {
            String errMsg = "Unable to retrieve property '" + SERIALIZATION_FORMAT_PROPERTY_NAME + "' from message " + msgCorrId + ".";
            throw new JMSRuntimeException(errMsg, jmse);
        }
        // 2. get marshaller
        Marshaller marshaller = getMarshaller(containerId, format);
        logger.debug("Selected marshaller is {}", marshaller);
        // 3. deserialize request
        CommandScript script = unmarshallRequest(message, msgCorrId, marshaller, format);
        logger.debug("Target capability is {}", targetCapability);
        for (KieServerExtension extension : kieServer.getServerExtensions()) {
            KieContainerCommandService tmp = extension.getAppComponents(KieContainerCommandService.class);
            if (tmp != null && extension.getImplementedCapability().equalsIgnoreCase(targetCapability)) {
                executor = tmp;
                logger.debug("Extension {} returned command executor {} with capability {}", extension, executor, extension.getImplementedCapability());
                break;
            }
        }
        if (executor == null) {
            throw new IllegalStateException("No executor found for script execution");
        }
        // 4. process request
        ServiceResponsesList response = executor.executeScript(script, format, classType);
        if (interactionPattern < UPPER_LIMIT_REPLY_INTERACTION_PATTERNS) {
            connect = startConnectionAndSession();
            logger.debug("Response message is about to be sent according to selected interaction pattern {}", interactionPattern);
            // 5. serialize response
            Message msg = marshallResponse(connect.getSession(), msgCorrId, format, marshaller, response);
            // set conversation id for routing
            if (containerId != null && (conversationId == null || conversationId.trim().isEmpty())) {
                try {
                    KieContainerInstance containerInstance = kieServer.getServerRegistry().getContainer(containerId);
                    if (containerInstance != null) {
                        ReleaseId releaseId = containerInstance.getResource().getResolvedReleaseId();
                        if (releaseId == null) {
                            releaseId = containerInstance.getResource().getReleaseId();
                        }
                        conversationId = ConversationId.from(KieServerEnvironment.getServerId(), containerId, releaseId).toString();
                    }
                } catch (Exception e) {
                    logger.warn("Unable to build conversation id due to {}", e.getMessage(), e);
                }
            }
            try {
                if (conversationId != null) {
                    msg.setStringProperty(CONVERSATION_ID_PROPERTY_NAME, conversationId);
                }
            } catch (JMSException e) {
                logger.debug("Unable to set conversation id on response message due to {}", e.getMessage());
            }
            // 6. send response
            sendResponse(connect.getSession(), msgCorrId, format, msg);
        } else {
            logger.debug("Response message is skipped according to selected interaction pattern {}", FIRE_AND_FORGET_PATTERN);
        }
    } finally {
        if (connect != null) {
            // Only attempt to close the connection/session if they were actually created
            try {
                closeConnectionAndSession(connect);
            } catch (JMSRuntimeException runtimeException) {
                logger.error("Error while attempting to close connection/session", runtimeException);
            } finally {
                JMSSecurityAdapter.logout();
            }
        } else {
            JMSSecurityAdapter.logout();
        }
    }
}
Also used : ServiceResponsesList(org.kie.server.api.model.ServiceResponsesList) Marshaller(org.kie.server.api.marshalling.Marshaller) Message(javax.jms.Message) TextMessage(javax.jms.TextMessage) MarshallingFormat(org.kie.server.api.marshalling.MarshallingFormat) KieServerExtension(org.kie.server.services.api.KieServerExtension) CommandScript(org.kie.server.api.commands.CommandScript) JMSException(javax.jms.JMSException) KieContainerCommandService(org.kie.server.services.api.KieContainerCommandService) ReleaseId(org.kie.server.api.model.ReleaseId) NamingException(javax.naming.NamingException) JMSException(javax.jms.JMSException) KieContainerInstance(org.kie.server.services.api.KieContainerInstance)

Example 25 with ServiceResponsesList

use of org.kie.server.api.model.ServiceResponsesList in project droolsjbpm-integration by kiegroup.

the class BlockingResponseCallback method get.

@Override
public <T> T get(Class<T> type) {
    if (marshaller == null) {
        throw new IllegalStateException("No marshaller given, can't use get(Class) to return response");
    }
    ServiceResponsesList responsesList = get();
    if (responsesList.getResponses() == null || responsesList.getResponses().isEmpty()) {
        logger.debug("No data found in the response, returning null");
        return null;
    }
    ServiceResponse response = responsesList.getResponses().get(0);
    if (response.getType().equals(ServiceResponse.ResponseType.SUCCESS)) {
        Object result = response.getResult();
        if (result instanceof String) {
            logger.debug("Response '{}' of type string, unmarshalling it...", result);
            result = marshaller.unmarshall((String) result, type);
            logger.debug("Result after unmarshall operation {}", result);
        }
        // handle wrapped objects
        if (result instanceof Wrapped) {
            result = ((Wrapped) result).unwrap();
        }
        return (T) result;
    } else {
        logger.debug("Non successful response '{}', returning null", response.getMsg());
        return null;
    }
}
Also used : ServiceResponsesList(org.kie.server.api.model.ServiceResponsesList) ServiceResponse(org.kie.server.api.model.ServiceResponse) Wrapped(org.kie.server.api.model.Wrapped)

Aggregations

ServiceResponsesList (org.kie.server.api.model.ServiceResponsesList)30 ServiceResponse (org.kie.server.api.model.ServiceResponse)23 KieServerCommand (org.kie.server.api.model.KieServerCommand)18 CommandScript (org.kie.server.api.commands.CommandScript)17 WebSocketServiceResponse (org.kie.server.controller.websocket.common.handlers.WebSocketServiceResponse)13 ArrayList (java.util.ArrayList)9 DescriptorCommand (org.kie.server.api.commands.DescriptorCommand)5 KieContainerResource (org.kie.server.api.model.KieContainerResource)5 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 JMSException (javax.jms.JMSException)4 CreateContainerCommand (org.kie.server.api.commands.CreateContainerCommand)4 DisposeContainerCommand (org.kie.server.api.commands.DisposeContainerCommand)4 Wrapped (org.kie.server.api.model.Wrapped)4 TextMessage (javax.jms.TextMessage)3 Test (org.junit.Test)3 UpdateReleaseIdCommand (org.kie.server.api.commands.UpdateReleaseIdCommand)3 UpdateScannerCommand (org.kie.server.api.commands.UpdateScannerCommand)3 KieServicesException (org.kie.server.api.exception.KieServicesException)3 ReleaseId (org.kie.server.api.model.ReleaseId)3 IOException (java.io.IOException)2