Search in sources :

Example 46 with ObjectMarshallingStrategy

use of org.kie.api.marshalling.ObjectMarshallingStrategy in project jbpm by kiegroup.

the class CaseFileInstanceMarshallingStrategy method unmarshal.

@SuppressWarnings("unchecked")
@Override
public Object unmarshal(Context context, ObjectInputStream is, byte[] object, ClassLoader classloader) throws IOException, ClassNotFoundException {
    logger.debug("About to read {} bytes to unmarshal CaseFileInstance", (object == null ? 0 : object.length));
    Map<String, Object> caseFileContent = (Map<String, Object>) caseFileMarshaller.unmarshal(context, is, object, classloader);
    CaseFileInstanceImpl caseFileInstance = new CaseFileInstanceImpl();
    caseFileInstance.setCaseId((String) caseFileContent.get(CASE_ID_KEY));
    caseFileInstance.setDefinitionId((String) caseFileContent.get(CASE_DEF_ID_KEY));
    caseFileInstance.setCaseStartDate((Date) caseFileContent.get(CASE_START_KEY));
    caseFileInstance.setCaseEndDate((Date) caseFileContent.get(CASE_END_KEY));
    caseFileInstance.setCaseReopenDate((Date) caseFileContent.get(CASE_REOPEN_KEY));
    caseFileInstance.setRolesAssignments((Map<String, CaseRoleInstance>) caseFileContent.get(CASE_ROLE_ASSIGNMENTS_KEY));
    caseFileInstance.setComments((List<CommentInstance>) caseFileContent.get(CASE_COMMENTS_KEY));
    logger.debug("CaseFileInstance meta data unmarshalled properly into {}", caseFileInstance);
    List<SerializedContent> caseDataContent = (List<SerializedContent>) caseFileContent.get(CASE_DATA_KEY);
    logger.debug("About to read serialized content {}", caseDataContent);
    for (SerializedContent serializedContent : caseDataContent) {
        ObjectMarshallingStrategy marshaller = marshallersByName.get(serializedContent.getMarshaller());
        logger.debug("Marshaller for {} is of type {}", serializedContent, marshaller);
        Object value = marshaller.unmarshal(context, is, serializedContent.getContent(), classloader);
        caseFileInstance.add(serializedContent.getName(), value);
        logger.debug("Data unmarshalled into {} and put into case file under '{}' name", value, serializedContent.getName());
    }
    caseFileInstance.setAccessRestrictions((Map<String, List<String>>) caseFileContent.get(CASE_DATA_RESTRICTIONS_KEY));
    caseFileInstance.setParentInstanceId((Long) caseFileContent.get(CASE_PARENT_INSTANCE_ID_KEY));
    caseFileInstance.setParentWorkItemId((Long) caseFileContent.get(CASE_PARENT_WORK_ITEM_ID_KEY));
    logger.debug("Unmarshal of CaseFileInstance completed - result {}", caseFileInstance);
    return caseFileInstance;
}
Also used : CommentInstance(org.jbpm.casemgmt.api.model.instance.CommentInstance) ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) CaseFileInstanceImpl(org.jbpm.casemgmt.impl.model.instance.CaseFileInstanceImpl) ArrayList(java.util.ArrayList) List(java.util.List) CaseRoleInstance(org.jbpm.casemgmt.api.model.instance.CaseRoleInstance) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 47 with ObjectMarshallingStrategy

use of org.kie.api.marshalling.ObjectMarshallingStrategy in project jbpm by kiegroup.

the class MarshalVariablesProcessEventListener method afterProcessCompleted.

public void afterProcessCompleted(ProcessCompletedEvent event) {
    ObjectMarshallingStrategy[] strategies = (ObjectMarshallingStrategy[]) event.getKieRuntime().getEnvironment().get(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES);
    VariableScopeInstance variableScope = (VariableScopeInstance) ((WorkflowProcessInstance) event.getProcessInstance()).getContextInstance(VariableScope.VARIABLE_SCOPE);
    Map<String, Object> variables = variableScope.getVariables();
    for (Map.Entry<String, Object> variable : variables.entrySet()) {
        logger.debug("Searching for applicable strategy to handle variable name '{}' value '{}'", variable.getKey(), variable.getValue());
        for (ObjectMarshallingStrategy strategy : strategies) {
            // are removed together with process instance
            if (strategy instanceof SerializablePlaceholderResolverStrategy) {
                continue;
            }
            if (strategy.accept(variable.getValue())) {
                logger.debug("Strategy of type {} found to handle variable '{}'", strategy, variable.getKey());
                try {
                    ProcessMarshallerWriteContext context = new ProcessMarshallerWriteContext(new ByteArrayOutputStream(), null, null, null, null, event.getKieRuntime().getEnvironment());
                    context.setProcessInstanceId(event.getProcessInstance().getId());
                    context.setState(ProcessMarshallerWriteContext.STATE_COMPLETED);
                    strategy.marshal(null, context, variable.getValue());
                    logger.debug("Variable '{}' successfully persisted by strategy {}", variable.getKey(), strategy);
                    break;
                } catch (Exception e) {
                    logger.warn("Errer while storing process variable {} due to {}", variable.getKey(), e.getMessage());
                    logger.debug("Variable marshal error:", e);
                }
            }
        }
    }
}
Also used : SerializablePlaceholderResolverStrategy(org.drools.core.marshalling.impl.SerializablePlaceholderResolverStrategy) VariableScopeInstance(org.jbpm.process.instance.context.variable.VariableScopeInstance) ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Map(java.util.Map) ProcessMarshallerWriteContext(org.drools.core.marshalling.impl.ProcessMarshallerWriteContext)

Example 48 with ObjectMarshallingStrategy

use of org.kie.api.marshalling.ObjectMarshallingStrategy in project jbpm by kiegroup.

the class JbpmBpmn2TestCase method createEnvironment.

protected Environment createEnvironment(EntityManagerFactory emf) {
    Environment env = EnvironmentFactory.newEnvironment();
    env.set(ENTITY_MANAGER_FACTORY, emf);
    env.set(TRANSACTION_MANAGER, com.arjuna.ats.jta.TransactionManager.transactionManager());
    if (sessionPersistence) {
        ObjectMarshallingStrategy[] strategies = (ObjectMarshallingStrategy[]) env.get(OBJECT_MARSHALLING_STRATEGIES);
        List<ObjectMarshallingStrategy> listStrategies = new ArrayList<ObjectMarshallingStrategy>(Arrays.asList(strategies));
        listStrategies.add(0, new ProcessInstanceResolverStrategy());
        strategies = new ObjectMarshallingStrategy[listStrategies.size()];
        env.set(OBJECT_MARSHALLING_STRATEGIES, listStrategies.toArray(strategies));
    }
    return env;
}
Also used : ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) ProcessInstanceResolverStrategy(org.jbpm.marshalling.impl.ProcessInstanceResolverStrategy) ArrayList(java.util.ArrayList) Environment(org.kie.api.runtime.Environment)

Example 49 with ObjectMarshallingStrategy

use of org.kie.api.marshalling.ObjectMarshallingStrategy in project jbpm by kiegroup.

the class AbstractProcessInstanceMarshaller method readProcessInstance.

// Input methods
public ProcessInstance readProcessInstance(MarshallerReaderContext context) throws IOException {
    ObjectInputStream stream = context.stream;
    InternalKnowledgeBase kBase = context.kBase;
    InternalWorkingMemory wm = context.wm;
    WorkflowProcessInstanceImpl processInstance = createProcessInstance();
    processInstance.setId(stream.readLong());
    String processId = stream.readUTF();
    processInstance.setProcessId(processId);
    Process process = kBase.getProcess(processId);
    if (kBase != null) {
        processInstance.setProcess(process);
    }
    processInstance.setState(stream.readInt());
    long nodeInstanceCounter = stream.readLong();
    processInstance.setKnowledgeRuntime(wm.getKnowledgeRuntime());
    int nbSwimlanes = stream.readInt();
    if (nbSwimlanes > 0) {
        Context swimlaneContext = ((org.jbpm.process.core.Process) process).getDefaultContext(SwimlaneContext.SWIMLANE_SCOPE);
        SwimlaneContextInstance swimlaneContextInstance = (SwimlaneContextInstance) processInstance.getContextInstance(swimlaneContext);
        for (int i = 0; i < nbSwimlanes; i++) {
            String name = stream.readUTF();
            String value = stream.readUTF();
            swimlaneContextInstance.setActorId(name, value);
        }
    }
    while (stream.readShort() == PersisterEnums.NODE_INSTANCE) {
        readNodeInstance(context, processInstance, processInstance);
    }
    int exclusiveGroupInstances = stream.readInt();
    for (int i = 0; i < exclusiveGroupInstances; i++) {
        ExclusiveGroupInstance exclusiveGroupInstance = new ExclusiveGroupInstance();
        processInstance.addContextInstance(ExclusiveGroup.EXCLUSIVE_GROUP, exclusiveGroupInstance);
        int nodeInstances = stream.readInt();
        for (int j = 0; j < nodeInstances; j++) {
            long nodeInstanceId = stream.readLong();
            NodeInstance nodeInstance = processInstance.getNodeInstance(nodeInstanceId);
            if (nodeInstance == null) {
                throw new IllegalArgumentException("Could not find node instance when deserializing exclusive group instance: " + nodeInstanceId);
            }
            exclusiveGroupInstance.addNodeInstance(nodeInstance);
        }
    }
    // Process Variables
    // - Number of Variables = keys.size()
    // For Each Variable
    // - Variable Key
    // - Marshalling Strategy Index
    // - Marshalled Object
    int nbVariables = stream.readInt();
    if (nbVariables > 0) {
        Context variableScope = ((org.jbpm.process.core.Process) process).getDefaultContext(VariableScope.VARIABLE_SCOPE);
        VariableScopeInstance variableScopeInstance = (VariableScopeInstance) processInstance.getContextInstance(variableScope);
        for (int i = 0; i < nbVariables; i++) {
            String name = stream.readUTF();
            try {
                ObjectMarshallingStrategy strategy = null;
                int index = stream.readInt();
                // This is the old way of de/serializing strategy objects
                if (index >= 0) {
                    strategy = context.resolverStrategyFactory.getStrategy(index);
                } else // This is the new way
                if (index == -2) {
                    String strategyClassName = context.stream.readUTF();
                    if (!StringUtils.isEmpty(strategyClassName)) {
                        strategy = context.resolverStrategyFactory.getStrategyObject(strategyClassName);
                        if (strategy == null) {
                            throw new IllegalStateException("No strategy of type " + strategyClassName + " available.");
                        }
                    }
                }
                // If either way retrieves a strategy, use it
                Object value = null;
                if (strategy != null) {
                    value = strategy.read(stream);
                }
                variableScopeInstance.internalSetVariable(name, value);
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException("Could not reload variable " + name);
            }
        }
    }
    processInstance.internalSetNodeInstanceCounter(nodeInstanceCounter);
    if (wm != null) {
        processInstance.reconnect();
    }
    return processInstance;
}
Also used : SwimlaneContext(org.jbpm.process.core.context.swimlane.SwimlaneContext) MarshallerWriteContext(org.drools.core.marshalling.impl.MarshallerWriteContext) MarshallerReaderContext(org.drools.core.marshalling.impl.MarshallerReaderContext) Context(org.jbpm.process.core.Context) ExclusiveGroupInstance(org.jbpm.process.instance.context.exclusive.ExclusiveGroupInstance) SwimlaneContextInstance(org.jbpm.process.instance.context.swimlane.SwimlaneContextInstance) ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) WorkflowProcessInstanceImpl(org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl) Process(org.kie.api.definition.process.Process) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) VariableScopeInstance(org.jbpm.process.instance.context.variable.VariableScopeInstance) NodeInstance(org.kie.api.runtime.process.NodeInstance) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) ObjectInputStream(java.io.ObjectInputStream)

Example 50 with ObjectMarshallingStrategy

use of org.kie.api.marshalling.ObjectMarshallingStrategy in project jbpm by kiegroup.

the class ProtobufProcessMarshaller method marshallVariablesMap.

public static Variable marshallVariablesMap(MarshallerWriteContext context, Map<String, Object> variables) throws IOException {
    Map<String, Variable> marshalledVariables = new HashMap<String, Variable>();
    for (String key : variables.keySet()) {
        JBPMMessages.Variable.Builder builder = JBPMMessages.Variable.newBuilder().setName(key);
        if (variables.get(key) != null) {
            ObjectMarshallingStrategy strategy = context.objectMarshallingStrategyStore.getStrategyObject(variables.get(key));
            Integer index = context.getStrategyIndex(strategy);
            builder.setStrategyIndex(index).setValue(ByteString.copyFrom(strategy.marshal(context.strategyContext.get(strategy), context, variables.get(key))));
        }
        marshalledVariables.put(key, builder.build());
    }
    return marshallVariable(context, "variablesMap", marshalledVariables);
}
Also used : Variable(org.jbpm.marshalling.impl.JBPMMessages.Variable) HashMap(java.util.HashMap) ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) ByteString(com.google.protobuf.ByteString)

Aggregations

ObjectMarshallingStrategy (org.kie.api.marshalling.ObjectMarshallingStrategy)52 ArrayList (java.util.ArrayList)11 InternalFactHandle (org.drools.core.common.InternalFactHandle)9 DefaultFactHandle (org.drools.core.common.DefaultFactHandle)8 EventFactHandle (org.drools.core.common.EventFactHandle)8 IOException (java.io.IOException)7 ObjectInputStream (java.io.ObjectInputStream)7 HashMap (java.util.HashMap)7 ObjectMarshallingStrategyAcceptor (org.kie.api.marshalling.ObjectMarshallingStrategyAcceptor)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 QueryElementFactHandle (org.drools.core.common.QueryElementFactHandle)6 ObjectTypeConf (org.drools.core.reteoo.ObjectTypeConf)6 Marshaller (org.kie.api.marshalling.Marshaller)6 SerializablePlaceholderResolverStrategy (org.drools.core.marshalling.impl.SerializablePlaceholderResolverStrategy)5 Test (org.junit.Test)5 Environment (org.kie.api.runtime.Environment)5 KieSession (org.kie.api.runtime.KieSession)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 File (java.io.File)4 Collection (java.util.Collection)4