Search in sources :

Example 11 with ObjectMarshallingStrategy

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

the class CaseFileInstanceMarshallingStrategy method marshal.

@Override
public byte[] marshal(Context context, ObjectOutputStream os, Object object) throws IOException {
    logger.debug("About to marshal {}", object);
    CaseFileInstanceImpl caseFile = (CaseFileInstanceImpl) object;
    Map<String, Object> caseFileContent = new HashMap<>();
    caseFileContent.put(CASE_ID_KEY, caseFile.getCaseId());
    caseFileContent.put(CASE_DEF_ID_KEY, caseFile.getDefinitionId());
    caseFileContent.put(CASE_START_KEY, caseFile.getCaseStartDate());
    caseFileContent.put(CASE_END_KEY, caseFile.getCaseEndDate());
    caseFileContent.put(CASE_REOPEN_KEY, caseFile.getCaseReopenDate());
    caseFileContent.put(CASE_ROLE_ASSIGNMENTS_KEY, new HashMap<>(caseFile.getRolesAssignments()));
    caseFileContent.put(CASE_COMMENTS_KEY, new ArrayList<>(caseFile.getComments()));
    logger.debug("CaseFileContent before case file data is {}", caseFileContent);
    List<SerializedContent> caseDataContent = new ArrayList<>();
    caseFileContent.put(CASE_DATA_KEY, caseDataContent);
    // transform with various strategies data that belong to a case
    for (Entry<String, Object> dataEntry : caseFile.getData().entrySet()) {
        byte[] content = null;
        String marshallerName = null;
        logger.debug("About to find marshaller for {}", dataEntry.getValue());
        for (ObjectMarshallingStrategy marshaller : marshallersByName.values()) {
            if (marshaller.accept(dataEntry.getValue())) {
                content = marshaller.marshal(context, os, dataEntry.getValue());
                marshallerName = marshaller.getClass().getName();
                logger.debug("Object {} marshalled by {}", dataEntry.getValue(), marshallerName);
                break;
            }
        }
        SerializedContent serializedContent = new SerializedContent(marshallerName, dataEntry.getKey(), content);
        caseDataContent.add(serializedContent);
        logger.debug("Serialized content for object {} is {}", dataEntry.getValue(), serializedContent);
    }
    caseFileContent.put(CASE_DATA_RESTRICTIONS_KEY, new HashMap<>(caseFile.getAccessRestrictions()));
    caseFileContent.put(CASE_PARENT_INSTANCE_ID_KEY, caseFile.getParentInstanceId());
    caseFileContent.put(CASE_PARENT_WORK_ITEM_ID_KEY, caseFile.getParentWorkItemId());
    byte[] caseFileBytes = caseFileMarshaller.marshal(context, os, caseFileContent);
    logger.debug("Content of the case file instance after marshaller is of length {}", (caseFileBytes == null ? 0 : caseFileBytes.length));
    return caseFileBytes;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) CaseFileInstanceImpl(org.jbpm.casemgmt.impl.model.instance.CaseFileInstanceImpl) ArrayList(java.util.ArrayList)

Example 12 with ObjectMarshallingStrategy

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

the class RuntimeEnvironmentBuilder method getDefault.

/**
 * Provides default configuration of <code>RuntimeEnvironmentBuilder</code> that is based on:
 * <ul>
 * 	<li>DefaultRuntimeEnvironment</li>
 * </ul>
 * This one is tailored to works smoothly with kjars as the notion of kbase and ksessions
 * @param releaseId <code>ReleaseId</code> that described the kjar
 * @param kbaseName name of the kbase defined in kmodule.xml stored in kjar
 * @param ksessionName name of the ksession define in kmodule.xml stored in kjar
 * @return new instance of <code>RuntimeEnvironmentBuilder</code> that is already preconfigured with defaults
 *
 * @see DefaultRuntimeEnvironment
 */
public static RuntimeEnvironmentBuilder getDefault(ReleaseId releaseId, String kbaseName, String ksessionName) {
    KieMavenRepository repository = KieMavenRepository.getKieMavenRepository();
    repository.resolveArtifact(releaseId.toExternalForm());
    KieServices ks = KieServices.Factory.get();
    KieContainer kieContainer = ks.newKieContainer(releaseId);
    DeploymentDescriptorManager descriptorManager = new DeploymentDescriptorManager();
    List<DeploymentDescriptor> descriptorHierarchy = descriptorManager.getDeploymentDescriptorHierarchy(kieContainer);
    DeploymentDescriptorMerger merger = new DeploymentDescriptorMerger();
    DeploymentDescriptor descriptor = merger.merge(descriptorHierarchy, MergeMode.MERGE_COLLECTIONS);
    if (StringUtils.isEmpty(kbaseName)) {
        KieBaseModel defaultKBaseModel = ((KieContainerImpl) kieContainer).getKieProject().getDefaultKieBaseModel();
        if (defaultKBaseModel != null) {
            kbaseName = defaultKBaseModel.getName();
        } else {
            kbaseName = DEFAULT_KBASE_NAME;
        }
    }
    InternalKieModule module = (InternalKieModule) ((KieContainerImpl) kieContainer).getKieModuleForKBase(kbaseName);
    if (module == null) {
        throw new IllegalStateException("Cannot find kbase, either it does not exist or there are multiple default kbases in kmodule.xml");
    }
    KieBase kbase = kieContainer.getKieBase(kbaseName);
    RuntimeEnvironmentBuilder builder = null;
    if (descriptor.getPersistenceMode() == PersistenceMode.NONE) {
        builder = getDefaultInMemory();
    } else {
        builder = getDefault();
    }
    Map<String, Object> contaxtParams = new HashMap<String, Object>();
    contaxtParams.put("classLoader", kieContainer.getClassLoader());
    // populate various properties of the builder
    if (descriptor.getPersistenceUnit() != null) {
        EntityManagerFactory emf = EntityManagerFactoryManager.get().getOrCreate(descriptor.getPersistenceUnit());
        builder.entityManagerFactory(emf);
        contaxtParams.put("entityManagerFactory", emf);
    }
    // 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).knowledgeBase(kbase).classLoader(kieContainer.getClassLoader()).registerableItemsFactory(new KModuleRegisterableItemsFactory(kieContainer, ksessionName));
    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) DeploymentDescriptor(org.kie.internal.runtime.conf.DeploymentDescriptor) DeploymentDescriptorManager(org.jbpm.runtime.manager.impl.deploy.DeploymentDescriptorManager) KieServices(org.kie.api.KieServices) KieBaseModel(org.kie.api.builder.model.KieBaseModel) NamedObjectModel(org.kie.internal.runtime.conf.NamedObjectModel) KieBase(org.kie.api.KieBase) EntityManagerFactory(javax.persistence.EntityManagerFactory) KieMavenRepository(org.kie.scanner.KieMavenRepository) DeploymentDescriptorMerger(org.jbpm.runtime.manager.impl.deploy.DeploymentDescriptorMerger) KieContainer(org.kie.api.runtime.KieContainer) InternalKieModule(org.drools.compiler.kie.builder.impl.InternalKieModule)

Example 13 with ObjectMarshallingStrategy

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

the class SimpleRuntimeEnvironment method copyEnvironment.

protected Environment copyEnvironment() {
    Environment copy = EnvironmentFactory.newEnvironment();
    addIfPresent(EnvironmentName.ENTITY_MANAGER_FACTORY, copy);
    addIfPresent(EnvironmentName.CALENDARS, copy);
    addIfPresent(EnvironmentName.DATE_FORMATS, copy);
    addIfPresent(EnvironmentName.GLOBALS, copy);
    addIfPresent(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, copy);
    addIfPresent(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER, copy);
    addIfPresent(EnvironmentName.TASK_PERSISTENCE_CONTEXT_MANAGER, copy);
    addIfPresent(EnvironmentName.TRANSACTION_MANAGER, copy);
    addIfPresent(EnvironmentName.TRANSACTION_SYNCHRONIZATION_REGISTRY, copy);
    addIfPresent(EnvironmentName.TRANSACTION, copy);
    addIfPresent(EnvironmentName.USE_LOCAL_TRANSACTIONS, copy);
    addIfPresent(EnvironmentName.USE_PESSIMISTIC_LOCKING, copy);
    addIfPresent(EnvironmentName.EXEC_ERROR_MANAGER, copy);
    addIfPresent(EnvironmentName.DEPLOYMENT_ID, copy);
    if (usePersistence()) {
        ObjectMarshallingStrategy[] strategies = (ObjectMarshallingStrategy[]) copy.get(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES);
        List<ObjectMarshallingStrategy> listStrategies = new ArrayList<ObjectMarshallingStrategy>(Arrays.asList(strategies));
        listStrategies.add(0, new ProcessInstanceResolverStrategy());
        strategies = new ObjectMarshallingStrategy[listStrategies.size()];
        copy.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, listStrategies.toArray(strategies));
    }
    // copy if present in environment template which in general should not be used
    // unless with some framework support to make EM thread safe - like spring
    addIfPresent(EnvironmentName.APP_SCOPED_ENTITY_MANAGER, copy);
    addIfPresent(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER, copy);
    addIfPresent("IS_JTA_TRANSACTION", copy);
    addIfPresent("IS_TIMER_CMT", copy);
    addIfPresent("IS_SHARED_ENTITY_MANAGER", copy);
    addIfPresent("TRANSACTION_LOCK_ENABLED", copy);
    addIfPresent("IdentityProvider", copy);
    addIfPresent("jbpm.business.calendar", copy);
    // handle for custom environment entries that might be required by non engine use cases
    if (!environmentEntries.isEmpty()) {
        for (Entry<String, Object> entry : environmentEntries.entrySet()) {
            // don't override
            if (copy.get(entry.getKey()) != null) {
                continue;
            }
            copy.set(entry.getKey(), entry.getValue());
        }
    }
    return copy;
}
Also used : ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) ProcessInstanceResolverStrategy(org.jbpm.marshalling.impl.ProcessInstanceResolverStrategy) ArrayList(java.util.ArrayList) RuntimeEnvironment(org.kie.internal.runtime.manager.RuntimeEnvironment) Environment(org.kie.api.runtime.Environment)

Example 14 with ObjectMarshallingStrategy

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

the class ContentMarshallerHelper method unmarshall.

public static Object unmarshall(byte[] content, Environment env, ClassLoader classloader) {
    MarshallerReaderContext context = null;
    try {
        ByteArrayInputStream stream = new ByteArrayInputStream(content);
        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();
        context = new MarshallerReaderContext(stream, null, null, objectMarshallingStrategyStore, null, env);
        if (classloader != null) {
            context.classLoader = classloader;
        } else {
            context.classLoader = ContentMarshallerHelper.class.getClassLoader();
        }
        ExtensionRegistry registry = PersisterHelper.buildRegistry(context, null);
        Header _header = PersisterHelper.readFromStreamWithHeaderPreloaded(context, registry);
        try {
            VariableContainer parseFrom = JBPMMessages.VariableContainer.parseFrom(_header.getPayload(), registry);
            Map<String, Object> value = ProtobufProcessMarshaller.unmarshallVariableContainerValue(context, parseFrom);
            // in case there was single variable stored return only that variable and not map
            if (value.containsKey(SINGLE_VAR_KEY) && value.size() == 1) {
                return value.get(SINGLE_VAR_KEY);
            }
            return value;
        } catch (Exception e) {
            // backward compatible fallback mechanism to ensure existing data can be read properly
            return fallbackParse(context, _header, registry);
        }
    } catch (Exception ex) {
        logger.warn("Exception while unmarshaling content", ex);
    }
    return null;
}
Also used : SerializablePlaceholderResolverStrategy(org.drools.core.marshalling.impl.SerializablePlaceholderResolverStrategy) ObjectMarshallingStrategyStore(org.kie.api.marshalling.ObjectMarshallingStrategyStore) MarshallingConfigurationImpl(org.drools.core.marshalling.impl.MarshallingConfigurationImpl) ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) IOException(java.io.IOException) ExtensionRegistry(com.google.protobuf.ExtensionRegistry) Header(org.drools.core.marshalling.impl.ProtobufMessages.Header) VariableContainer(org.jbpm.marshalling.impl.JBPMMessages.VariableContainer) ByteArrayInputStream(java.io.ByteArrayInputStream) MarshallerReaderContext(org.drools.core.marshalling.impl.MarshallerReaderContext)

Example 15 with ObjectMarshallingStrategy

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

the class AbstractProcessInstanceMarshaller method writeProcessInstance.

// Output methods
public Object writeProcessInstance(MarshallerWriteContext context, ProcessInstance processInstance) throws IOException {
    WorkflowProcessInstanceImpl workFlow = (WorkflowProcessInstanceImpl) processInstance;
    ObjectOutputStream stream = context.stream;
    stream.writeLong(workFlow.getId());
    stream.writeUTF(workFlow.getProcessId());
    stream.writeInt(workFlow.getState());
    stream.writeLong(workFlow.getNodeInstanceCounter());
    SwimlaneContextInstance swimlaneContextInstance = (SwimlaneContextInstance) workFlow.getContextInstance(SwimlaneContext.SWIMLANE_SCOPE);
    if (swimlaneContextInstance != null) {
        Map<String, String> swimlaneActors = swimlaneContextInstance.getSwimlaneActors();
        stream.writeInt(swimlaneActors.size());
        for (Map.Entry<String, String> entry : swimlaneActors.entrySet()) {
            stream.writeUTF(entry.getKey());
            stream.writeUTF(entry.getValue());
        }
    } else {
        stream.writeInt(0);
    }
    List<NodeInstance> nodeInstances = new ArrayList<NodeInstance>(workFlow.getNodeInstances());
    Collections.sort(nodeInstances, new Comparator<NodeInstance>() {

        public int compare(NodeInstance o1, NodeInstance o2) {
            return (int) (o1.getId() - o2.getId());
        }
    });
    for (NodeInstance nodeInstance : nodeInstances) {
        stream.writeShort(PersisterEnums.NODE_INSTANCE);
        writeNodeInstance(context, nodeInstance);
    }
    stream.writeShort(PersisterEnums.END);
    List<ContextInstance> exclusiveGroupInstances = workFlow.getContextInstances(ExclusiveGroup.EXCLUSIVE_GROUP);
    if (exclusiveGroupInstances == null) {
        stream.writeInt(0);
    } else {
        stream.writeInt(exclusiveGroupInstances.size());
        for (ContextInstance contextInstance : exclusiveGroupInstances) {
            ExclusiveGroupInstance exclusiveGroupInstance = (ExclusiveGroupInstance) contextInstance;
            Collection<NodeInstance> groupNodeInstances = exclusiveGroupInstance.getNodeInstances();
            stream.writeInt(groupNodeInstances.size());
            for (NodeInstance nodeInstance : groupNodeInstances) {
                stream.writeLong(nodeInstance.getId());
            }
        }
    }
    VariableScopeInstance variableScopeInstance = (VariableScopeInstance) workFlow.getContextInstance(VariableScope.VARIABLE_SCOPE);
    Map<String, Object> variables = variableScopeInstance.getVariables();
    List<String> keys = new ArrayList<String>(variables.keySet());
    Collection<Object> values = variables.values();
    Collections.sort(keys, new Comparator<String>() {

        public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }
    });
    // Process Variables
    // - Number of non null Variables = nonnullvariables.size()
    // For Each Variable
    // - Variable Key
    // - Marshalling Strategy Index
    // - Marshalled Object
    Collection<Object> notNullValues = new ArrayList<Object>();
    for (Object value : values) {
        if (value != null) {
            notNullValues.add(value);
        }
    }
    stream.writeInt(notNullValues.size());
    for (String key : keys) {
        Object object = variables.get(key);
        if (object != null) {
            stream.writeUTF(key);
            // New marshalling algorithm when using strategies
            int useNewMarshallingStrategyAlgorithm = -2;
            stream.writeInt(useNewMarshallingStrategyAlgorithm);
            // Choose first strategy that accepts the object (what was always done)
            ObjectMarshallingStrategy strategy = context.objectMarshallingStrategyStore.getStrategyObject(object);
            stream.writeUTF(strategy.getClass().getName());
            strategy.write(stream, object);
        }
    }
    return null;
}
Also used : 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) ArrayList(java.util.ArrayList) ObjectOutputStream(java.io.ObjectOutputStream) VariableScopeInstance(org.jbpm.process.instance.context.variable.VariableScopeInstance) ContextInstance(org.jbpm.process.instance.ContextInstance) SwimlaneContextInstance(org.jbpm.process.instance.context.swimlane.SwimlaneContextInstance) HashMap(java.util.HashMap) Map(java.util.Map) NodeInstance(org.kie.api.runtime.process.NodeInstance)

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