Search in sources :

Example 11 with MarshallingFormat

use of org.kie.server.api.marshalling.MarshallingFormat in project droolsjbpm-integration by kiegroup.

the class ControllerUtils method marshal.

public static String marshal(String marshallingFormat, Object entity) {
    MarshallingFormat format = getFormat(marshallingFormat);
    if (format == null) {
        throw new IllegalArgumentException("Unknown marshalling format " + marshallingFormat);
    }
    Marshaller marshaller = null;
    switch(format) {
        case JAXB:
            {
                marshaller = jaxbMarshaller;
                break;
            }
        case JSON:
            {
                marshaller = jsonMarshaller;
                break;
            }
        default:
            {
                marshaller = jsonMarshaller;
                break;
            }
    }
    return marshaller.marshall(entity);
}
Also used : Marshaller(org.kie.server.api.marshalling.Marshaller) MarshallingFormat(org.kie.server.api.marshalling.MarshallingFormat)

Example 12 with MarshallingFormat

use of org.kie.server.api.marshalling.MarshallingFormat 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 13 with MarshallingFormat

use of org.kie.server.api.marshalling.MarshallingFormat in project droolsjbpm-integration by kiegroup.

the class CustomResource method insertFireReturn.

@POST
@Path("/{ksessionId}")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response insertFireReturn(@Context HttpHeaders headers, @PathParam("id") String id, @PathParam("ksessionId") String ksessionId, String cmdPayload) {
    Variant v = RestUtils.getVariant(headers);
    String contentType = RestUtils.getContentType(headers);
    MarshallingFormat format = MarshallingFormat.fromType(contentType);
    try {
        KieContainerInstance kci = registry.getContainer(id, ContainerLocatorProvider.get().getLocator());
        Marshaller marshaller = kci.getMarshaller(format);
        List<?> listOfFacts = marshaller.unmarshall(cmdPayload, List.class);
        List<Command<?>> commands = new ArrayList<Command<?>>();
        BatchExecutionCommand executionCommand = commandsFactory.newBatchExecution(commands, ksessionId);
        for (Object fact : listOfFacts) {
            commands.add(commandsFactory.newInsert(fact, fact.toString()));
        }
        commands.add(commandsFactory.newFireAllRules());
        commands.add(commandsFactory.newGetObjects());
        ExecutionResults results = rulesExecutionService.call(kci, executionCommand);
        String result = marshaller.marshall(results);
        logger.debug("Returning OK response with content '{}'", result);
        return RestUtils.createResponse(result, v, Response.Status.OK);
    } catch (Exception e) {
        // in case marshalling failed return the call container response to keep backward compatibility
        String response = "Execution failed with error : " + e.getMessage();
        logger.debug("Returning Failure response with content '{}'", response);
        return RestUtils.createResponse(response, v, Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : Marshaller(org.kie.server.api.marshalling.Marshaller) MarshallingFormat(org.kie.server.api.marshalling.MarshallingFormat) ExecutionResults(org.kie.api.runtime.ExecutionResults) ArrayList(java.util.ArrayList) KieContainerInstance(org.kie.server.services.api.KieContainerInstance) Variant(javax.ws.rs.core.Variant) Command(org.kie.api.command.Command) BatchExecutionCommand(org.kie.api.command.BatchExecutionCommand) BatchExecutionCommand(org.kie.api.command.BatchExecutionCommand) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 14 with MarshallingFormat

use of org.kie.server.api.marshalling.MarshallingFormat in project droolsjbpm-integration by kiegroup.

the class MarshallerHelper method unmarshal.

public <T> T unmarshal(String data, String marshallingFormat, Class<T> unmarshalType) {
    if (data == null || data.isEmpty()) {
        return null;
    }
    MarshallingFormat format = getFormat(marshallingFormat);
    Marshaller marshaller = serverMarshallers.get(format);
    if (marshaller == null) {
        marshaller = MarshallerFactory.getMarshaller(getExtraClasses(registry), format, this.getClass().getClassLoader());
        serverMarshallers.put(format, marshaller);
    }
    Object instance = marshaller.unmarshall(data, unmarshalType, MarshallingFormat.buildParameters(marshallingFormat));
    if (instance instanceof Wrapped) {
        return (T) ((Wrapped) instance).unwrap();
    }
    return (T) instance;
}
Also used : Marshaller(org.kie.server.api.marshalling.Marshaller) MarshallingFormat(org.kie.server.api.marshalling.MarshallingFormat) Wrapped(org.kie.server.api.model.Wrapped)

Example 15 with MarshallingFormat

use of org.kie.server.api.marshalling.MarshallingFormat in project businessautomation-cop by redhat-cop.

the class GetCasesWithDataResource method getCaseInstancesWithData.

@SuppressWarnings("unchecked")
@GET
@Path("/instancesWithData")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response getCaseInstancesWithData(@Context HttpHeaders headers, @QueryParam("dataItem") List<String> dataItems) {
    Variant v = getVariant(headers);
    String contentType = getContentType(headers);
    MarshallingFormat format = MarshallingFormat.fromType(contentType);
    if (format == null) {
        format = MarshallingFormat.valueOf(contentType);
    }
    MarshallerHelper marshallerHelper = new MarshallerHelper(registry);
    try {
        // Fetching all OPEN cases
        CaseInstanceList cases = this.caseManagementRuntimeDataService.getCaseInstancesAnyRole(Arrays.asList("open"), 0, 0, "", true);
        List<CaseInstance> finalList = new ArrayList<CaseInstance>();
        // for every case instance found, let's fetch the case data specified in the query parameter 'dateItems'
        for (CaseInstance caseInstance : cases.getItems()) {
            String caseFileData = caseManagementServiceBase.getCaseFileData(caseInstance.getContainerId(), caseInstance.getCaseId(), dataItems, format.toString());
            logger.debug("Following data were fetched :" + caseFileData + "\n for case instance id:" + caseInstance.getCaseId());
            Map<String, Object> caseFileDataUnmarshalled = marshallerHelper.unmarshal(caseInstance.getContainerId(), caseFileData, format.toString(), Map.class, new ByCaseIdContainerLocator(caseInstance.getCaseId()));
            caseInstance.setCaseFile(CaseFile.builder().data(caseFileDataUnmarshalled).build());
            finalList.add(caseInstance);
        }
        cases.setCaseInstances(finalList.toArray(new CaseInstance[finalList.size()]));
        String result = marshallerHelper.marshal(format.toString(), cases);
        logger.debug("Returning OK response with content '{}'", result);
        return createResponse(result, v, Response.Status.OK);
    } catch (Exception e) {
        // backward compatibility
        String response = "Execution failed with error : " + e.getMessage();
        logger.debug("Returning Failure response with content '{}'", response);
        return createResponse(response, v, Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : RESTUtils.getVariant(org.redhat.gss.extension.RESTUtils.getVariant) Variant(javax.ws.rs.core.Variant) CaseInstanceList(org.kie.server.api.model.cases.CaseInstanceList) CaseInstance(org.kie.server.api.model.cases.CaseInstance) MarshallingFormat(org.kie.server.api.marshalling.MarshallingFormat) MarshallerHelper(org.kie.server.services.impl.marshal.MarshallerHelper) ArrayList(java.util.ArrayList) ByCaseIdContainerLocator(org.kie.server.services.casemgmt.locator.ByCaseIdContainerLocator) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

MarshallingFormat (org.kie.server.api.marshalling.MarshallingFormat)17 Marshaller (org.kie.server.api.marshalling.Marshaller)9 Consumes (javax.ws.rs.Consumes)6 Produces (javax.ws.rs.Produces)6 Variant (javax.ws.rs.core.Variant)6 Path (javax.ws.rs.Path)5 KieContainerInstance (org.kie.server.services.api.KieContainerInstance)4 ArrayList (java.util.ArrayList)3 POST (javax.ws.rs.POST)3 Wrapped (org.kie.server.api.model.Wrapped)3 RestUtils.getVariant (org.kie.server.remote.rest.common.util.RestUtils.getVariant)3 MarshallerHelper (org.kie.server.services.impl.marshal.MarshallerHelper)3 HashSet (java.util.HashSet)2 GET (javax.ws.rs.GET)2 BatchExecutionCommand (org.kie.api.command.BatchExecutionCommand)2 ExecutionResults (org.kie.api.runtime.ExecutionResults)2 RuleServicesClient (org.kie.server.client.RuleServicesClient)2 RESTUtils.getVariant (org.redhat.gss.extension.RESTUtils.getVariant)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ApiOperation (io.swagger.annotations.ApiOperation)1