Search in sources :

Example 31 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 32 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 33 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)

Example 34 with ObjectMarshallingStrategy

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

the class ContentMarshallerHelper method marshallContent.

@SuppressWarnings("unchecked")
public static byte[] marshallContent(Task task, Object o, Environment env) {
    ProcessMarshallerWriteContext context;
    try {
        MarshallingConfigurationImpl marshallingConfigurationImpl = null;
        if (env != null) {
            marshallingConfigurationImpl = new MarshallingConfigurationImpl((ObjectMarshallingStrategy[]) env.get(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES), false, false);
        } else {
            marshallingConfigurationImpl = new MarshallingConfigurationImpl(new ObjectMarshallingStrategy[] { new SerializablePlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT) }, false, false);
        }
        ObjectMarshallingStrategyStore objectMarshallingStrategyStore = marshallingConfigurationImpl.getObjectMarshallingStrategyStore();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        context = new ProcessMarshallerWriteContext(stream, null, null, null, objectMarshallingStrategyStore, env);
        if (task != null) {
            context.setTaskId(task.getId());
            context.setProcessInstanceId(task.getTaskData().getProcessInstanceId());
            context.setWorkItemId(task.getTaskData().getWorkItemId());
            // determine state of the task
            int taskState = ProcessMarshallerWriteContext.STATE_ACTIVE;
            if (task.getTaskData().getStatus() == Status.Completed || task.getTaskData().getStatus() == Status.Error || task.getTaskData().getStatus() == Status.Exited || task.getTaskData().getStatus() == Status.Failed || task.getTaskData().getStatus() == Status.Obsolete) {
                taskState = ProcessMarshallerWriteContext.STATE_COMPLETED;
            }
            context.setState(taskState);
        }
        Map<String, Object> input = null;
        if (o instanceof Map) {
            input = (Map<String, Object>) o;
        } else {
            // in case there is only single variable to be stored place it into a map under special key
            input = new HashMap<String, Object>();
            input.put(SINGLE_VAR_KEY, o);
        }
        Message marshallVariable = ProtobufProcessMarshaller.marshallVariablesContainer(context, input);
        PersisterHelper.writeToStreamWithHeader(context, marshallVariable);
        context.close();
        return stream.toByteArray();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return null;
}
Also used : SerializablePlaceholderResolverStrategy(org.drools.core.marshalling.impl.SerializablePlaceholderResolverStrategy) ObjectMarshallingStrategyStore(org.kie.api.marshalling.ObjectMarshallingStrategyStore) MarshallingConfigurationImpl(org.drools.core.marshalling.impl.MarshallingConfigurationImpl) Message(com.google.protobuf.Message) ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) ProcessMarshallerWriteContext(org.drools.core.marshalling.impl.ProcessMarshallerWriteContext)

Example 35 with ObjectMarshallingStrategy

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

the class KModuleDeploymentService method boostrapRuntimeEnvironmentBuilder.

/**
 * This creates and fills a {@link RuntimeEnvironmentBuilder} instance, which is later used when creating services.
 * </p>
 * A lot of the logic here is used to process the information in the {@link DeploymentDescriptor} instance, which is
 * part of the {@link DeploymentUnit}.
 *
 * @param deploymentUnit The {@link KModuleDeploymentUnit}, which is filled by the method
 * @param deployedUnit The {@link DeployedUnit}, which is also filled by the method
 * @param kieContainer The {@link KieContainer}, which contains information needed to fill the above two arguments
 * @param mode The {@link MergeMode} used to resolve conflicts in the {@link DeploymentDescriptor}.
 * @return A {@link RuntimeEnvironmentBuilder} instance ready for use
 */
protected RuntimeEnvironmentBuilder boostrapRuntimeEnvironmentBuilder(KModuleDeploymentUnit deploymentUnit, DeployedUnit deployedUnit, KieContainer kieContainer, MergeMode mode) {
    DeploymentDescriptor descriptor = deploymentUnit.getDeploymentDescriptor();
    if (descriptor == null || ((DeploymentDescriptorImpl) descriptor).isEmpty()) {
        // skip empty descriptors as its default can override settings
        DeploymentDescriptorManager descriptorManager = new DeploymentDescriptorManager("org.jbpm.domain");
        List<DeploymentDescriptor> descriptorHierarchy = descriptorManager.getDeploymentDescriptorHierarchy(kieContainer);
        descriptor = merger.merge(descriptorHierarchy, mode);
        deploymentUnit.setDeploymentDescriptor(descriptor);
    } else if (descriptor != null && !deploymentUnit.isDeployed()) {
        DeploymentDescriptorManager descriptorManager = new DeploymentDescriptorManager("org.jbpm.domain");
        List<DeploymentDescriptor> descriptorHierarchy = descriptorManager.getDeploymentDescriptorHierarchy(kieContainer);
        descriptorHierarchy.add(0, descriptor);
        descriptor = merger.merge(descriptorHierarchy, mode);
        deploymentUnit.setDeploymentDescriptor(descriptor);
    }
    // first set on unit the strategy
    deploymentUnit.setStrategy(descriptor.getRuntimeStrategy());
    // setting up runtime environment via builder
    RuntimeEnvironmentBuilder builder = null;
    if (descriptor.getPersistenceMode() == PersistenceMode.NONE) {
        builder = RuntimeEnvironmentBuilder.Factory.get().newDefaultInMemoryBuilder();
    } else {
        builder = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder();
    }
    // populate various properties of the builder
    EntityManagerFactory emf = EntityManagerFactoryManager.get().getOrCreate(descriptor.getPersistenceUnit());
    builder.entityManagerFactory(emf);
    Map<String, Object> contaxtParams = new HashMap<String, Object>();
    contaxtParams.put("entityManagerFactory", emf);
    contaxtParams.put("classLoader", kieContainer.getClassLoader());
    // process object models that are globally configured (environment entries, session configuration)
    for (NamedObjectModel model : descriptor.getEnvironmentEntries()) {
        Object entry = getInstanceFromModel(model, kieContainer, contaxtParams);
        builder.addEnvironmentEntry(model.getName(), entry);
    }
    for (NamedObjectModel model : descriptor.getConfiguration()) {
        Object entry = getInstanceFromModel(model, kieContainer, contaxtParams);
        builder.addConfiguration(model.getName(), (String) entry);
    }
    ObjectMarshallingStrategy[] mStrategies = new ObjectMarshallingStrategy[descriptor.getMarshallingStrategies().size() + 1];
    int index = 0;
    for (ObjectModel model : descriptor.getMarshallingStrategies()) {
        Object strategy = getInstanceFromModel(model, kieContainer, contaxtParams);
        mStrategies[index] = (ObjectMarshallingStrategy) strategy;
        index++;
    }
    // lastly add the main default strategy
    mStrategies[index] = new SerializablePlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT);
    builder.addEnvironmentEntry(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, mStrategies);
    builder.addEnvironmentEntry("KieDeploymentDescriptor", descriptor);
    builder.addEnvironmentEntry("KieContainer", kieContainer);
    if (executorService != null) {
        builder.addEnvironmentEntry("ExecutorService", executorService);
    }
    if (identityProvider != null) {
        builder.addEnvironmentEntry(EnvironmentName.IDENTITY_PROVIDER, identityProvider);
    }
    // populate all assets with roles for this deployment unit
    List<String> requiredRoles = descriptor.getRequiredRoles(DeploymentDescriptor.TYPE_VIEW);
    if (requiredRoles != null && !requiredRoles.isEmpty()) {
        for (DeployedAsset desc : deployedUnit.getDeployedAssets()) {
            if (desc instanceof ProcessAssetDesc) {
                ((ProcessAssetDesc) desc).setRoles(requiredRoles);
            }
        }
    }
    // Classes 3: classes added from descriptor
    List<String> remoteableClasses = descriptor.getClasses();
    if (remoteableClasses != null && !remoteableClasses.isEmpty()) {
        for (String className : remoteableClasses) {
            Class descriptorClass = null;
            try {
                descriptorClass = kieContainer.getClassLoader().loadClass(className);
                logger.debug("Loaded {} into the classpath from deployment descriptor {}", className, kieContainer.getReleaseId().toExternalForm());
            } catch (ClassNotFoundException cnfe) {
                throw new IllegalArgumentException("Class " + className + " not found in the project");
            } catch (NoClassDefFoundError e) {
                throw new IllegalArgumentException("Class " + className + " not found in the project");
            }
            addClassToDeployedUnit(descriptorClass, (DeployedUnitImpl) deployedUnit);
        }
    }
    return builder;
}
Also used : SerializablePlaceholderResolverStrategy(org.drools.core.marshalling.impl.SerializablePlaceholderResolverStrategy) ObjectModel(org.kie.internal.runtime.conf.ObjectModel) NamedObjectModel(org.kie.internal.runtime.conf.NamedObjectModel) HashMap(java.util.HashMap) ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) DeployedAsset(org.jbpm.services.api.model.DeployedAsset) DeploymentDescriptor(org.kie.internal.runtime.conf.DeploymentDescriptor) DeploymentDescriptorManager(org.jbpm.runtime.manager.impl.deploy.DeploymentDescriptorManager) RuntimeEnvironmentBuilder(org.kie.api.runtime.manager.RuntimeEnvironmentBuilder) NamedObjectModel(org.kie.internal.runtime.conf.NamedObjectModel) ProcessAssetDesc(org.jbpm.kie.services.impl.model.ProcessAssetDesc) EntityManagerFactory(javax.persistence.EntityManagerFactory) List(java.util.List)

Aggregations

ObjectMarshallingStrategy (org.kie.api.marshalling.ObjectMarshallingStrategy)35 ArrayList (java.util.ArrayList)8 HashMap (java.util.HashMap)7 IOException (java.io.IOException)6 SerializablePlaceholderResolverStrategy (org.drools.core.marshalling.impl.SerializablePlaceholderResolverStrategy)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 File (java.io.File)4 Map (java.util.Map)4 DefaultFactHandle (org.drools.core.common.DefaultFactHandle)4 EventFactHandle (org.drools.core.common.EventFactHandle)4 InternalFactHandle (org.drools.core.common.InternalFactHandle)4 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)4 Marshaller (org.kie.api.marshalling.Marshaller)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 ObjectInputStream (java.io.ObjectInputStream)3 QueryElementFactHandle (org.drools.core.common.QueryElementFactHandle)3 MarshallerReaderContext (org.drools.core.marshalling.impl.MarshallerReaderContext)3 MarshallingConfigurationImpl (org.drools.core.marshalling.impl.MarshallingConfigurationImpl)3 ObjectTypeConf (org.drools.core.reteoo.ObjectTypeConf)3 KieMarshallers (org.kie.api.marshalling.KieMarshallers)3