All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.bonitasoft.engine.service.ModelConvertor Maven / Gradle / Ivy

The newest version!
/**
 * Copyright (C) 2019 Bonitasoft S.A.
 * Bonitasoft, 32 rue Gustave Eiffel - 38000 Grenoble
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GNU Lesser General Public License as published by the Free Software Foundation
 * version 2.1 of the License.
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License along with this
 * program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
 * Floor, Boston, MA 02110-1301, USA.
 **/
package org.bonitasoft.engine.service;

import java.io.Serializable;
import java.util.*;
import java.util.Map.Entry;

import lombok.extern.slf4j.Slf4j;
import org.bonitasoft.engine.actor.mapping.model.SActor;
import org.bonitasoft.engine.actor.mapping.model.SActorMember;
import org.bonitasoft.engine.api.impl.SessionInfos;
import org.bonitasoft.engine.bpm.actor.ActorInstance;
import org.bonitasoft.engine.bpm.actor.ActorMember;
import org.bonitasoft.engine.bpm.actor.impl.ActorInstanceImpl;
import org.bonitasoft.engine.bpm.actor.impl.ActorMemberImpl;
import org.bonitasoft.engine.bpm.category.Category;
import org.bonitasoft.engine.bpm.category.impl.CategoryImpl;
import org.bonitasoft.engine.bpm.comment.ArchivedComment;
import org.bonitasoft.engine.bpm.comment.Comment;
import org.bonitasoft.engine.bpm.comment.impl.ArchivedCommentImpl;
import org.bonitasoft.engine.bpm.comment.impl.CommentImpl;
import org.bonitasoft.engine.bpm.connector.*;
import org.bonitasoft.engine.bpm.connector.impl.ArchivedConnectorInstanceImpl;
import org.bonitasoft.engine.bpm.connector.impl.ConnectorInstanceImpl;
import org.bonitasoft.engine.bpm.connector.impl.ConnectorInstanceWithFailureInfoImpl;
import org.bonitasoft.engine.bpm.contract.ContractDefinition;
import org.bonitasoft.engine.bpm.contract.InputDefinition;
import org.bonitasoft.engine.bpm.contract.Type;
import org.bonitasoft.engine.bpm.contract.impl.ConstraintDefinitionImpl;
import org.bonitasoft.engine.bpm.contract.impl.ContractDefinitionImpl;
import org.bonitasoft.engine.bpm.contract.impl.InputDefinitionImpl;
import org.bonitasoft.engine.bpm.data.ArchivedDataInstance;
import org.bonitasoft.engine.bpm.data.DataDefinition;
import org.bonitasoft.engine.bpm.data.DataInstance;
import org.bonitasoft.engine.bpm.data.impl.*;
import org.bonitasoft.engine.bpm.document.ArchivedDocument;
import org.bonitasoft.engine.bpm.document.Document;
import org.bonitasoft.engine.bpm.document.impl.ArchivedDocumentImpl;
import org.bonitasoft.engine.bpm.document.impl.DocumentImpl;
import org.bonitasoft.engine.bpm.flownode.*;
import org.bonitasoft.engine.bpm.flownode.impl.internal.*;
import org.bonitasoft.engine.bpm.process.*;
import org.bonitasoft.engine.bpm.process.impl.ProcessInstanceBuilder;
import org.bonitasoft.engine.bpm.process.impl.internal.ArchivedProcessInstanceImpl;
import org.bonitasoft.engine.bpm.process.impl.internal.ProcessDefinitionImpl;
import org.bonitasoft.engine.bpm.process.impl.internal.ProcessDeploymentInfoImpl;
import org.bonitasoft.engine.bpm.supervisor.ProcessSupervisor;
import org.bonitasoft.engine.bpm.supervisor.impl.ProcessSupervisorImpl;
import org.bonitasoft.engine.builder.BuilderFactory;
import org.bonitasoft.engine.business.data.BusinessDataReference;
import org.bonitasoft.engine.business.data.impl.MultipleBusinessDataReferenceImpl;
import org.bonitasoft.engine.business.data.impl.SimpleBusinessDataReferenceImpl;
import org.bonitasoft.engine.command.CommandDescriptor;
import org.bonitasoft.engine.command.CommandDescriptorImpl;
import org.bonitasoft.engine.command.model.SCommand;
import org.bonitasoft.engine.commons.exceptions.SBonitaRuntimeException;
import org.bonitasoft.engine.core.category.model.SCategory;
import org.bonitasoft.engine.core.connector.parser.SConnectorImplementationDescriptor;
import org.bonitasoft.engine.core.document.api.DocumentService;
import org.bonitasoft.engine.core.document.model.AbstractSMappedDocument;
import org.bonitasoft.engine.core.document.model.archive.SAMappedDocument;
import org.bonitasoft.engine.core.form.SFormMapping;
import org.bonitasoft.engine.core.operation.model.SLeftOperand;
import org.bonitasoft.engine.core.operation.model.SOperation;
import org.bonitasoft.engine.core.operation.model.SOperatorType;
import org.bonitasoft.engine.core.operation.model.builder.SLeftOperandBuilderFactory;
import org.bonitasoft.engine.core.operation.model.builder.SOperationBuilderFactory;
import org.bonitasoft.engine.core.process.comment.model.SComment;
import org.bonitasoft.engine.core.process.comment.model.archive.SAComment;
import org.bonitasoft.engine.core.process.definition.ProcessDefinitionService;
import org.bonitasoft.engine.core.process.definition.exception.SProcessDefinitionNotFoundException;
import org.bonitasoft.engine.core.process.definition.model.*;
import org.bonitasoft.engine.core.process.instance.model.*;
import org.bonitasoft.engine.core.process.instance.model.archive.*;
import org.bonitasoft.engine.core.process.instance.model.business.data.SProcessMultiRefBusinessDataInstance;
import org.bonitasoft.engine.core.process.instance.model.business.data.SRefBusinessDataInstance;
import org.bonitasoft.engine.core.process.instance.model.business.data.SSimpleRefBusinessDataInstance;
import org.bonitasoft.engine.core.process.instance.model.event.SBoundaryEventInstance;
import org.bonitasoft.engine.core.process.instance.model.event.SEventInstance;
import org.bonitasoft.engine.core.process.instance.model.event.handling.SWaitingErrorEvent;
import org.bonitasoft.engine.core.process.instance.model.event.handling.SWaitingEvent;
import org.bonitasoft.engine.core.process.instance.model.event.handling.SWaitingMessageEvent;
import org.bonitasoft.engine.core.process.instance.model.event.handling.SWaitingSignalEvent;
import org.bonitasoft.engine.core.process.instance.model.event.trigger.STimerEventTriggerInstance;
import org.bonitasoft.engine.data.definition.model.SDataDefinition;
import org.bonitasoft.engine.data.instance.model.SDataInstance;
import org.bonitasoft.engine.data.instance.model.archive.SADataInstance;
import org.bonitasoft.engine.exception.UnknownElementType;
import org.bonitasoft.engine.execution.state.FlowNodeStateManager;
import org.bonitasoft.engine.expression.Expression;
import org.bonitasoft.engine.expression.exception.SInvalidExpressionException;
import org.bonitasoft.engine.expression.impl.ExpressionImpl;
import org.bonitasoft.engine.expression.model.SExpression;
import org.bonitasoft.engine.expression.model.builder.SExpressionBuilder;
import org.bonitasoft.engine.expression.model.builder.SExpressionBuilderFactory;
import org.bonitasoft.engine.form.FormMapping;
import org.bonitasoft.engine.form.FormMappingTarget;
import org.bonitasoft.engine.form.FormMappingType;
import org.bonitasoft.engine.identity.*;
import org.bonitasoft.engine.identity.ContactDataCreator.ContactDataField;
import org.bonitasoft.engine.identity.GroupCreator.GroupField;
import org.bonitasoft.engine.identity.RoleCreator.RoleField;
import org.bonitasoft.engine.identity.UserCreator.UserField;
import org.bonitasoft.engine.identity.impl.*;
import org.bonitasoft.engine.identity.model.*;
import org.bonitasoft.engine.identity.xml.*;
import org.bonitasoft.engine.job.FailedJob;
import org.bonitasoft.engine.job.impl.FailedJobImpl;
import org.bonitasoft.engine.operation.Operation;
import org.bonitasoft.engine.operation.OperatorType;
import org.bonitasoft.engine.operation.impl.LeftOperandImpl;
import org.bonitasoft.engine.operation.impl.OperationImpl;
import org.bonitasoft.engine.page.PageURL;
import org.bonitasoft.engine.page.SPageMapping;
import org.bonitasoft.engine.page.SPageURL;
import org.bonitasoft.engine.persistence.SBonitaReadException;
import org.bonitasoft.engine.platform.Platform;
import org.bonitasoft.engine.platform.command.model.SPlatformCommand;
import org.bonitasoft.engine.platform.impl.PlatformImpl;
import org.bonitasoft.engine.platform.model.SPlatform;
import org.bonitasoft.engine.platform.model.SPlatformProperties;
import org.bonitasoft.engine.profile.Profile;
import org.bonitasoft.engine.profile.ProfileMember;
import org.bonitasoft.engine.profile.ProfileMemberCreator;
import org.bonitasoft.engine.profile.ProfileMemberCreator.ProfileMemberField;
import org.bonitasoft.engine.profile.impl.ProfileImpl;
import org.bonitasoft.engine.profile.impl.ProfileMemberImpl;
import org.bonitasoft.engine.profile.model.SProfile;
import org.bonitasoft.engine.profile.model.SProfileMember;
import org.bonitasoft.engine.resources.STenantResourceLight;
import org.bonitasoft.engine.scheduler.model.SFailedJob;
import org.bonitasoft.engine.session.APISession;
import org.bonitasoft.engine.session.impl.APISessionImpl;
import org.bonitasoft.engine.session.model.SSession;
import org.bonitasoft.engine.supervisor.mapping.model.SProcessSupervisor;
import org.bonitasoft.engine.tenant.TenantResource;
import org.bonitasoft.engine.tenant.TenantResourceState;

/**
 * @author Matthieu Chaffotte
 * @author Yanyan Liu
 * @author Celine Souchet
 */
@Slf4j
public class ModelConvertor {

    protected ModelConvertor() {
        // private constructor
    }

    public static APISession toAPISession(final SSession session, final String tenant) {
        final long tenantId = session.getTenantId();
        final long id = session.getId();
        final long userId = session.getUserId();
        final String userName = session.getUserName();
        final Date creationDate = session.getCreationDate();
        final long duration = session.getDuration();
        final boolean technicalUser = session.isTechnicalUser();
        final APISessionImpl apiSession = new APISessionImpl(id, creationDate, duration, userName, userId, tenant,
                tenantId);
        apiSession.setTechnicalUser(technicalUser);
        apiSession.setProfiles(session.getProfiles());
        return apiSession;
    }

    public static Platform toPlatform(final SPlatform sPlatform, SPlatformProperties sPlatformProperties) {
        return new PlatformImpl(sPlatformProperties.getPlatformVersion(), sPlatform.getInitialBonitaVersion(),
                sPlatform.getCreatedBy(),
                sPlatform.getCreated());
    }

    public static List toActivityInstances(final List sActivities,
            final FlowNodeStateManager flowNodeStateManager) {
        final List activityInstances = new ArrayList<>();
        for (final SActivityInstance sActivity : sActivities) {
            final ActivityInstance activityInstance = toActivityInstance(sActivity, flowNodeStateManager);
            activityInstances.add(activityInstance);
        }
        return activityInstances;
    }

    public static List toFlowNodeInstances(final List sFlowNodes,
            final FlowNodeStateManager flowNodeStateManager) {
        final List flowNodeInstances = new ArrayList<>();
        for (final SFlowNodeInstance sFlowNode : sFlowNodes) {
            final FlowNodeInstance flowNodeInstance = toFlowNodeInstance(sFlowNode, flowNodeStateManager);
            flowNodeInstances.add(flowNodeInstance);
        }
        return flowNodeInstances;
    }

    private static void updateFlowNode(final FlowNodeInstanceImpl flowNode, final SFlowNodeInstance sflowNode,
            final String state) {
        flowNode.setId(sflowNode.getId());
        flowNode.setState(state);
        flowNode.setParentContainerId(sflowNode.getParentContainerId());
        flowNode.setRootContainerId(sflowNode.getRootContainerId());
        flowNode.setProcessDefinitionId(sflowNode.getLogicalGroup(0));
        flowNode.setParentProcessInstanceId(sflowNode.getLogicalGroup(3));
        flowNode.setDisplayName(sflowNode.getDisplayName());
        flowNode.setDisplayDescription(sflowNode.getDisplayDescription());
        flowNode.setDescription(sflowNode.getDescription());
        flowNode.setExecutedBy(sflowNode.getExecutedBy());
        flowNode.setExecutedBySubstitute(sflowNode.getExecutedBySubstitute());
        flowNode.setStateCategory(StateCategory.valueOf(sflowNode.getStateCategory().name()));
        flowNode.setReachedSateDate(new Date(sflowNode.getReachedStateDate()));
        flowNode.setLastUpdateDate(new Date(sflowNode.getLastUpdateDate()));
    }

    public static ActivityInstance toActivityInstance(final SActivityInstance sActivity,
            final FlowNodeStateManager flowNodeStateManager) {
        switch (sActivity.getType()) {
            case AUTOMATIC_TASK:
                return toAutomaticTask((SAutomaticTaskInstance) sActivity, flowNodeStateManager);
            case MANUAL_TASK:
                return toManualTask((SManualTaskInstance) sActivity, flowNodeStateManager);
            case USER_TASK:
                return toUserTaskInstance((SUserTaskInstance) sActivity, flowNodeStateManager);
            case RECEIVE_TASK:
                return toReceiveTaskInstance((SReceiveTaskInstance) sActivity, flowNodeStateManager);
            case SEND_TASK:
                return toSendTaskInstance((SSendTaskInstance) sActivity, flowNodeStateManager);
            case CALL_ACTIVITY:
                return toCallActivityInstance((SCallActivityInstance) sActivity, flowNodeStateManager);
            case SUB_PROCESS:
                return toSubProcessActivityInstance((SSubProcessActivityInstance) sActivity, flowNodeStateManager);
            case LOOP_ACTIVITY:
                return toLoopActivityInstance((SLoopActivityInstance) sActivity, flowNodeStateManager);
            case MULTI_INSTANCE_ACTIVITY:
                return toMultiInstanceActivityInstance((SMultiInstanceActivityInstance) sActivity,
                        flowNodeStateManager);
            default:
                throw new UnknownElementType(sActivity.getType().name());
        }
    }

    public static FlowNodeInstance toFlowNodeInstance(final SFlowNodeInstance sFlowNode,
            final FlowNodeStateManager flowNodeStateManager) {
        switch (sFlowNode.getType()) {
            case START_EVENT:
            case INTERMEDIATE_CATCH_EVENT:
            case BOUNDARY_EVENT:
            case INTERMEDIATE_THROW_EVENT:
            case END_EVENT:
                return toEventInstance((SEventInstance) sFlowNode, flowNodeStateManager);
            case GATEWAY:
                return toGatewayInstance((SGatewayInstance) sFlowNode, flowNodeStateManager);
            default:
                if (sFlowNode instanceof SActivityInstance) {
                    return toActivityInstance((SActivityInstance) sFlowNode, flowNodeStateManager);
                }
                throw new UnknownElementType(sFlowNode.getType().name());
        }
    }

    public static ActivityInstance toAutomaticTask(final SAutomaticTaskInstance sActivity,
            final FlowNodeStateManager flowNodeStateManager) {
        final AutomaticTaskInstanceImpl automaticTaskInstance = new AutomaticTaskInstanceImpl(sActivity.getName(),
                sActivity.getFlowNodeDefinitionId());
        updateActivityInstance(sActivity, flowNodeStateManager, automaticTaskInstance);
        return automaticTaskInstance;
    }

    public static ActivityInstance toCallActivityInstance(final SCallActivityInstance sActivity,
            final FlowNodeStateManager flowNodeStateManager) {
        final CallActivityInstanceImpl callActivityInstance = new CallActivityInstanceImpl(sActivity.getName(),
                sActivity.getFlowNodeDefinitionId());
        updateActivityInstance(sActivity, flowNodeStateManager, callActivityInstance);
        return callActivityInstance;
    }

    public static ActivityInstance toCallActivityInstance(final SSubProcessActivityInstance sActivity,
            final FlowNodeStateManager flowNodeStateManager) {
        final SubProcessActivityInstanceImpl subProcActivityInstance = new SubProcessActivityInstanceImpl(
                sActivity.getName(),
                sActivity.getFlowNodeDefinitionId(), sActivity.isTriggeredByEvent());
        updateActivityInstance(sActivity, flowNodeStateManager, subProcActivityInstance);
        return subProcActivityInstance;
    }

    public static ActivityInstance toSubProcessActivityInstance(final SSubProcessActivityInstance sActivity,
            final FlowNodeStateManager flowNodeStateManager) {
        final SubProcessActivityInstanceImpl subProcessActivityInstance = new SubProcessActivityInstanceImpl(
                sActivity.getName(),
                sActivity.getFlowNodeDefinitionId(), sActivity.isTriggeredByEvent());
        updateActivityInstance(sActivity, flowNodeStateManager, subProcessActivityInstance);
        return subProcessActivityInstance;
    }

    public static ActivityInstance toLoopActivityInstance(final SLoopActivityInstance sActivity,
            final FlowNodeStateManager flowNodeStateManager) {
        final LoopActivityInstanceImpl loopActivityInstance = new LoopActivityInstanceImpl(sActivity.getName(),
                sActivity.getFlowNodeDefinitionId(),
                sActivity.getLoopCounter());
        updateActivityInstance(sActivity, flowNodeStateManager, loopActivityInstance);
        return loopActivityInstance;
    }

    public static ActivityInstance toMultiInstanceActivityInstance(final SMultiInstanceActivityInstance sActivity,
            final FlowNodeStateManager flowNodeStateManager) {
        final MultiInstanceActivityInstanceImpl loopActivityInstance = new MultiInstanceActivityInstanceImpl(
                sActivity.getName(),
                sActivity.getFlowNodeDefinitionId(), sActivity.isSequential(), sActivity.getLoopDataInputRef(),
                sActivity.getLoopDataOutputRef(),
                sActivity.getDataInputItemRef(), sActivity.getDataOutputItemRef(),
                sActivity.getNumberOfActiveInstances(),
                sActivity.getNumberOfCompletedInstances(), sActivity.getNumberOfTerminatedInstances(),
                sActivity.getLoopCardinality());
        updateActivityInstance(sActivity, flowNodeStateManager, loopActivityInstance);
        return loopActivityInstance;
    }

    public static GatewayInstance toGatewayInstance(final SGatewayInstance sGatewayInstance,
            final FlowNodeStateManager flowNodeStateManager) {
        final GatewayInstanceImpl gatewayInstance = new GatewayInstanceImpl(sGatewayInstance.getName(),
                sGatewayInstance.getFlowNodeDefinitionId());
        final String state = flowNodeStateManager.getState(sGatewayInstance.getStateId()).getName();
        updateFlowNode(gatewayInstance, sGatewayInstance, state);
        return gatewayInstance;
    }

    public static ArchivedGatewayInstance toArchivedGatewayInstance(final SAGatewayInstance saGatewayInstance,
            final FlowNodeStateManager flowNodeStateManager) {
        final String name = saGatewayInstance.getName();
        final ArchivedGatewayInstanceImpl aGatewayInstance = new ArchivedGatewayInstanceImpl(name);
        updateArchivedFlowNodeInstance(aGatewayInstance, saGatewayInstance,
                flowNodeStateManager.getState(saGatewayInstance.getStateId()).getName());
        return aGatewayInstance;
    }

    private static void updateActivityInstance(final SActivityInstance sActivity,
            final FlowNodeStateManager flowNodeStateManager,
            final ActivityInstanceImpl activity) {
        final String state = flowNodeStateManager.getState(sActivity.getStateId()).getName();
        updateFlowNode(activity, sActivity, state);
    }

    public static List toUserTaskInstances(final List sUserTasks,
            final FlowNodeStateManager flowNodeStateManager) {
        final List userTaskInstances = new ArrayList<>();
        for (final SUserTaskInstance sUserTask : sUserTasks) {
            final UserTaskInstance userTask = toUserTaskInstance(sUserTask, flowNodeStateManager);
            userTaskInstances.add(userTask);
        }
        return userTaskInstances;
    }

    public static UserTaskInstance toUserTaskInstance(final SUserTaskInstance sUserTask,
            final FlowNodeStateManager flowNodeStateManager) {
        final UserTaskInstanceImpl userTaskInstance = new UserTaskInstanceImpl(sUserTask.getName(),
                sUserTask.getFlowNodeDefinitionId(),
                sUserTask.getActorId());
        updateHumanTaskInstance(sUserTask, flowNodeStateManager, userTaskInstance);
        return userTaskInstance;
    }

    public static ActivityInstance toReceiveTaskInstance(final SReceiveTaskInstance sReceiveTask,
            final FlowNodeStateManager flowNodeStateManager) {
        final ReceiveTaskInstanceImpl receiveTaskInstance = new ReceiveTaskInstanceImpl(sReceiveTask.getName(),
                sReceiveTask.getFlowNodeDefinitionId());
        updateActivityInstance(sReceiveTask, flowNodeStateManager, receiveTaskInstance);
        return receiveTaskInstance;
    }

    public static ActivityInstance toSendTaskInstance(final SSendTaskInstance sSendTask,
            final FlowNodeStateManager flowNodeStateManager) {
        final SendTaskInstanceImpl sendTask = new SendTaskInstanceImpl(sSendTask.getName(),
                sSendTask.getFlowNodeDefinitionId());
        updateActivityInstance(sSendTask, flowNodeStateManager, sendTask);
        return sendTask;
    }

    private static void updateHumanTaskInstance(final SHumanTaskInstance sHumanTask,
            final FlowNodeStateManager flowNodeStateManager,
            final HumanTaskInstanceImpl humanTaskInstance) {
        updateActivityInstance(sHumanTask, flowNodeStateManager, humanTaskInstance);
        humanTaskInstance.setAssigneeId(sHumanTask.getAssigneeId());
        final long claimedDate = sHumanTask.getClaimedDate();
        if (claimedDate > 0) {
            humanTaskInstance.setClaimedDate(new Date(claimedDate));
        }
        humanTaskInstance.setPriority(TaskPriority.valueOf(sHumanTask.getPriority().name()));
        final Long expectedEndDate = sHumanTask.getExpectedEndDate();
        if (expectedEndDate != null) {
            humanTaskInstance.setExpectedEndDate(new Date(expectedEndDate));
        }
    }

    public static List toHumanTaskInstances(final List sHumanTasks,
            final FlowNodeStateManager flowNodeStateManager) {
        final List humanTaskInstances = new ArrayList<>(sHumanTasks.size());
        for (final SHumanTaskInstance sUserTask : sHumanTasks) {
            final HumanTaskInstance userTask = toHumanTaskInstance(sUserTask, flowNodeStateManager);
            humanTaskInstances.add(userTask);
        }
        return humanTaskInstances;
    }

    public static HumanTaskInstance toHumanTaskInstance(final SHumanTaskInstance sHumanTask,
            final FlowNodeStateManager flowNodeStateManager) {
        switch (sHumanTask.getType()) {
            case USER_TASK:
                return toUserTaskInstance((SUserTaskInstance) sHumanTask, flowNodeStateManager);
            case MANUAL_TASK:
                return toManualTask((SManualTaskInstance) sHumanTask, flowNodeStateManager);
            default:
                throw new UnknownElementType(sHumanTask.getType().name());
        }
    }

    public static ManualTaskInstance toManualTask(final SManualTaskInstance sHumanTask,
            final FlowNodeStateManager flowNodeStateManager) {
        final ManualTaskInstanceImpl manualTaskInstance = new ManualTaskInstanceImpl(sHumanTask.getName(),
                sHumanTask.getFlowNodeDefinitionId(),
                sHumanTask.getActorId());
        updateHumanTaskInstance(sHumanTask, flowNodeStateManager, manualTaskInstance);
        return manualTaskInstance;
    }

    public static ProcessDefinition toProcessDefinition(final SProcessDefinition sDefinition) {
        final ProcessDefinitionImpl processDefinitionImpl = new ProcessDefinitionImpl(sDefinition.getName(),
                sDefinition.getVersion());
        processDefinitionImpl.setId(sDefinition.getId());
        processDefinitionImpl.setDescription(sDefinition.getDescription());
        return processDefinitionImpl;
    }

    public static List toProcessInstances(final List sProcessInstances,
            final ProcessDefinitionService processDefinitionService) {
        final List clientProcessInstances = new ArrayList<>();
        if (sProcessInstances != null) {
            final Map processDefinitions = new HashMap<>();
            for (final SProcessInstance sProcessInstance : sProcessInstances) {
                SProcessDefinition sProcessDefinition = processDefinitions.computeIfAbsent(
                        sProcessInstance.getProcessDefinitionId(),
                        processDefinitionId -> getProcessDefinition(processDefinitionService, processDefinitionId));
                clientProcessInstances.add(toProcessInstance(sProcessDefinition, sProcessInstance));
            }
        }
        return Collections.unmodifiableList(clientProcessInstances);
    }

    /**
     * @param processDefinitionService the {@link ProcessDefinitionService}
     * @param processDefinitionId the process definition id
     * @return the {@link SProcessDefinition} for the processDefinitionId or null if no {@link SProcessDefinition} is
     *         found.
     */
    private static SProcessDefinition getProcessDefinition(final ProcessDefinitionService processDefinitionService,
            final long processDefinitionId) {
        try {
            return processDefinitionService.getProcessDefinition(processDefinitionId);
        } catch (SProcessDefinitionNotFoundException pdnfe) {
            // Due to RUNTIME-1828 sProcessDefinition can be null. Do not rethrow exception
            log.warn("No process definition found for process definition id {}.",
                    processDefinitionId);
            return null;
        } catch (SBonitaReadException e) {
            throw new SBonitaRuntimeException(e);
        }
    }

    public static ProcessInstance toProcessInstance(final SProcessDefinition definition,
            final SProcessInstance sInstance) {
        final ProcessInstanceBuilder clientProcessInstanceBuilder = ProcessInstanceBuilder.getInstance()
                .createNewInstance(sInstance.getName());
        clientProcessInstanceBuilder.setId(sInstance.getId());

        clientProcessInstanceBuilder
                .setState(ProcessInstanceState.getFromId(sInstance.getStateId()).name().toLowerCase());
        if (sInstance.getStartDate() > 0) {
            clientProcessInstanceBuilder.setStartDate(sInstance.getStartDate());
        }
        clientProcessInstanceBuilder.setStartedBy(sInstance.getStartedBy());
        clientProcessInstanceBuilder.setStartedBySubstitute(sInstance.getStartedBySubstitute());
        if (sInstance.getEndDate() > 0) {
            clientProcessInstanceBuilder.setEndDate(sInstance.getEndDate());
        }
        clientProcessInstanceBuilder.setLastUpdate(sInstance.getLastUpdate());
        clientProcessInstanceBuilder.setProcessDefinitionId(sInstance.getProcessDefinitionId());
        clientProcessInstanceBuilder.setDescription(sInstance.getDescription());
        clientProcessInstanceBuilder.setRootProcessInstanceId(sInstance.getRootProcessInstanceId());
        clientProcessInstanceBuilder.setCallerId(sInstance.getCallerId());

        if (definition != null) {
            for (int i = 1; i <= 5; i++) {
                clientProcessInstanceBuilder.setStringIndexLabel(i, definition.getStringIndexLabel(i));
            }
        }
        clientProcessInstanceBuilder.setStringIndex1(sInstance.getStringIndex1());
        clientProcessInstanceBuilder.setStringIndex2(sInstance.getStringIndex2());
        clientProcessInstanceBuilder.setStringIndex3(sInstance.getStringIndex3());
        clientProcessInstanceBuilder.setStringIndex4(sInstance.getStringIndex4());
        clientProcessInstanceBuilder.setStringIndex5(sInstance.getStringIndex5());
        return clientProcessInstanceBuilder.done();
    }

    public static List toProcessDeploymentInfo(
            final List processDefinitionDIs) {
        final List deploymentInfos = new ArrayList<>();
        for (final SProcessDefinitionDeployInfo processDefinitionDI : processDefinitionDIs) {
            final ProcessDeploymentInfo deploymentInfo = toProcessDeploymentInfo(processDefinitionDI);
            deploymentInfos.add(deploymentInfo);
        }
        return deploymentInfos;
    }

    public static ProcessDeploymentInfo toProcessDeploymentInfo(
            final SProcessDefinitionDeployInfo processDefinitionDI) {
        return new ProcessDeploymentInfoImpl(processDefinitionDI.getId(), processDefinitionDI.getProcessId(),
                processDefinitionDI.getName(),
                processDefinitionDI.getVersion(), processDefinitionDI.getDescription(),
                new Date(processDefinitionDI.getDeploymentDate()),
                processDefinitionDI.getDeployedBy(), ActivationState.valueOf(processDefinitionDI.getActivationState()),
                ConfigurationState.valueOf(processDefinitionDI.getConfigurationState()),
                processDefinitionDI.getDisplayName(), new Date(
                        processDefinitionDI.getLastUpdateDate()),
                processDefinitionDI.getIconPath(), processDefinitionDI.getDisplayDescription());
    }

    public static Map toProcessDeploymentInfos(
            final Map sProcessDeploymentInfos) {
        if (sProcessDeploymentInfos != null && !sProcessDeploymentInfos.isEmpty()) {
            final Map processDeploymentInfos = new HashMap<>();
            final Set> entries = sProcessDeploymentInfos.entrySet();
            for (final Entry entry : entries) {
                processDeploymentInfos.put(entry.getKey(), toProcessDeploymentInfo(entry.getValue()));
            }
            return processDeploymentInfos;
        }
        return Collections.emptyMap();
    }

    public static ArchivedUserTaskInstance toArchivedUserTaskInstance(final SAUserTaskInstance sInstance,
            final FlowNodeStateManager flowNodeStateManager) {
        final ArchivedUserTaskInstanceImpl archivedUserTaskInstanceImpl = new ArchivedUserTaskInstanceImpl(
                sInstance.getName());
        updateArchivedFlowNodeInstance(archivedUserTaskInstanceImpl, sInstance,
                flowNodeStateManager.getState(sInstance.getStateId()).getName());
        updateArchivedHumanTaskInstance(archivedUserTaskInstanceImpl, sInstance);
        return archivedUserTaskInstanceImpl;
    }

    public static ArchivedReceiveTaskInstance toArchivedReceiveTaskInstance(final SAReceiveTaskInstance sInstance,
            final FlowNodeStateManager flowNodeStateManager) {
        final ArchivedReceiveTaskInstanceImpl archivedReceiveTaskInstanceImpl = new ArchivedReceiveTaskInstanceImpl(
                sInstance.getName());
        updateArchivedFlowNodeInstance(archivedReceiveTaskInstanceImpl, sInstance,
                flowNodeStateManager.getState(sInstance.getStateId()).getName());
        return archivedReceiveTaskInstanceImpl;
    }

    public static ArchivedSendTaskInstance toArchivedSendTaskInstance(final SASendTaskInstance sInstance,
            final FlowNodeStateManager flowNodeStateManager) {
        final ArchivedSendTaskInstanceImpl archivedSendTaskInstanceImpl = new ArchivedSendTaskInstanceImpl(
                sInstance.getName());
        updateArchivedFlowNodeInstance(archivedSendTaskInstanceImpl, sInstance,
                flowNodeStateManager.getState(sInstance.getStateId()).getName());
        return archivedSendTaskInstanceImpl;
    }

    /**
     * Update the fields of ArchivedHumanTaskInstance from a SAHumanTaskInstance
     */
    private static void updateArchivedHumanTaskInstance(final ArchivedHumanTaskInstanceImpl activity,
            final SAHumanTaskInstance saHumanTask) {
        activity.setAssigneeId(saHumanTask.getAssigneeId());
        activity.setPriority(TaskPriority.valueOf(saHumanTask.getPriority().name()));
        activity.setActorId(saHumanTask.getActorId());
        if (saHumanTask.getExpectedEndDate() != null) {
            activity.setExpectedEndDate(new Date(saHumanTask.getExpectedEndDate()));
        }
        if (saHumanTask.getClaimedDate() > 0) {
            activity.setClaimedDate(new Date(saHumanTask.getClaimedDate()));
        }
    }

    private static void updateArchivedFlowNodeInstance(final ArchivedFlowNodeInstanceImpl aFlowNode,
            final SAFlowNodeInstance saFlowNode, final String state) {
        aFlowNode.setId(saFlowNode.getId());
        aFlowNode.setState(state);
        aFlowNode.setParentContainerId(saFlowNode.getParentContainerId());
        aFlowNode.setRootContainerId(saFlowNode.getRootContainerId());
        aFlowNode.setSourceObjectId(saFlowNode.getSourceObjectId());
        aFlowNode.setProcessDefinitionId(saFlowNode.getProcessDefinitionId());
        aFlowNode.setProcessInstanceId(saFlowNode.getParentProcessInstanceId());
        aFlowNode.setParentActivityInstanceId(saFlowNode.getParentActivityInstanceId());
        aFlowNode.setDescription(saFlowNode.getDescription());
        aFlowNode.setDisplayName(saFlowNode.getDisplayName());
        aFlowNode.setDisplayDescription(saFlowNode.getDisplayDescription());
        if (saFlowNode.getArchiveDate() > 0) {
            aFlowNode.setArchiveDate(new Date(saFlowNode.getArchiveDate()));
        }
        aFlowNode.setExecutedBy(saFlowNode.getExecutedBy());
        aFlowNode.setExecutedBySubstitute(saFlowNode.getExecutedBySubstitute());
        aFlowNode.setFlownodeDefinitionId(saFlowNode.getFlowNodeDefinitionId());
        aFlowNode.setTerminal(saFlowNode.isTerminal());
        aFlowNode.setReachedStateDate(new Date(saFlowNode.getReachedStateDate()));
        aFlowNode.setLastUpdateDate(new Date(saFlowNode.getLastUpdateDate()));
    }

    public static List toArchivedUserTaskInstances(final List sInstances,
            final FlowNodeStateManager flowNodeStateManager) {
        final List archivedUserTaskInstances = new ArrayList<>();
        for (final SAUserTaskInstance sAUserTaskInstance : sInstances) {
            final ArchivedUserTaskInstance archivedUserTaskInstance = toArchivedUserTaskInstance(sAUserTaskInstance,
                    flowNodeStateManager);
            archivedUserTaskInstances.add(archivedUserTaskInstance);
        }
        return archivedUserTaskInstances;
    }

    public static List toArchivedReceiveTaskInstances(
            final List sInstances,
            final FlowNodeStateManager flowNodeStateManager) {
        final List archivedReceiveTaskInstances = new ArrayList<>();
        for (final SAReceiveTaskInstance sAReceiveTaskInstance : sInstances) {
            final ArchivedReceiveTaskInstance archivedReceiveTaskInstance = toArchivedReceiveTaskInstance(
                    sAReceiveTaskInstance, flowNodeStateManager);
            archivedReceiveTaskInstances.add(archivedReceiveTaskInstance);
        }
        return archivedReceiveTaskInstances;
    }

    public static List toArchivedHumanTaskInstances(
            final List sInstances,
            final FlowNodeStateManager flowNodeStateManager) {
        final List archivedUserTaskInstances = new ArrayList<>();
        for (final SAHumanTaskInstance sInstance : sInstances) {
            final ArchivedHumanTaskInstance archivedUserTaskInstance = toArchivedHumanTaskInstance(sInstance,
                    flowNodeStateManager);
            archivedUserTaskInstances.add(archivedUserTaskInstance);
        }
        return archivedUserTaskInstances;
    }

    public static ArchivedHumanTaskInstance toArchivedHumanTaskInstance(final SAHumanTaskInstance sInstance,
            final FlowNodeStateManager flowNodeStateManager) {
        switch (sInstance.getType()) {
            case MANUAL_TASK:
                return toArchivedManualTaskInstance((SAManualTaskInstance) sInstance, flowNodeStateManager);
            case USER_TASK:
                return toArchivedUserTaskInstance((SAUserTaskInstance) sInstance, flowNodeStateManager);
            default:
                throw new UnknownElementType(sInstance.getType().name());
        }
    }

    public static ArchivedActivityInstance toArchivedActivityInstance(final SAActivityInstance sInstance,
            final FlowNodeStateManager flowNodeStateManager) {
        switch (sInstance.getType()) {
            case AUTOMATIC_TASK:
                return toArchivedAutomaticTaskInstance(sInstance, flowNodeStateManager);
            case MANUAL_TASK:
                return toArchivedManualTaskInstance((SAManualTaskInstance) sInstance, flowNodeStateManager);
            case USER_TASK:
                return toArchivedUserTaskInstance((SAUserTaskInstance) sInstance, flowNodeStateManager);
            case RECEIVE_TASK:
                return toArchivedReceiveTaskInstance((SAReceiveTaskInstance) sInstance, flowNodeStateManager);
            case SEND_TASK:
                return toArchivedSendTaskInstance((SASendTaskInstance) sInstance, flowNodeStateManager);
            case LOOP_ACTIVITY:
                return toArchivedLoopActivityInstance((SALoopActivityInstance) sInstance, flowNodeStateManager);
            case CALL_ACTIVITY:
                return toArchivedCallActivityInstance((SACallActivityInstance) sInstance, flowNodeStateManager);
            case SUB_PROCESS:
                return toArchivedSubProcessActivityInstance((SASubProcessActivityInstance) sInstance,
                        flowNodeStateManager);
            case MULTI_INSTANCE_ACTIVITY:
                return toArchivedMultiInstanceActivityInstance((SAMultiInstanceActivityInstance) sInstance,
                        flowNodeStateManager);
            case BOUNDARY_EVENT:
            case END_EVENT:
            case GATEWAY:
            case INTERMEDIATE_CATCH_EVENT:
            case INTERMEDIATE_THROW_EVENT:
            case START_EVENT:
                throw new UnknownElementType("Events are not yet archived");
            default:
                throw new UnknownElementType(sInstance.getType().name());
        }
    }

    private static ArchivedLoopActivityInstance toArchivedLoopActivityInstance(final SALoopActivityInstance sInstance,
            final FlowNodeStateManager flowNodeStateManager) {
        final ArchivedLoopActivityInstanceImpl archivedloopActivityInstanceImpl = new ArchivedLoopActivityInstanceImpl(
                sInstance.getName());
        updateArchivedFlowNodeInstance(archivedloopActivityInstanceImpl, sInstance,
                flowNodeStateManager.getState(sInstance.getStateId()).getName());
        archivedloopActivityInstanceImpl.setLoopCounter(sInstance.getLoopCounter());
        archivedloopActivityInstanceImpl.setLoopMax(sInstance.getLoopMax());
        return archivedloopActivityInstanceImpl;
    }

    private static ArchivedMultiInstanceActivityInstanceImpl toArchivedMultiInstanceActivityInstance(
            final SAMultiInstanceActivityInstance sInstance,
            final FlowNodeStateManager flowNodeStateManager) {
        final ArchivedMultiInstanceActivityInstanceImpl archivedMultiInstanceActivityInstanceImpl = new ArchivedMultiInstanceActivityInstanceImpl(
                sInstance.getName(), sInstance.getFlowNodeDefinitionId(), sInstance.isSequential(),
                sInstance.getLoopDataInputRef(),
                sInstance.getLoopDataOutputRef(), sInstance.getDataInputItemRef(), sInstance.getDataOutputItemRef(),
                sInstance.getNumberOfActiveInstances(),
                sInstance.getNumberOfCompletedInstances(), sInstance.getNumberOfTerminatedInstances(),
                sInstance.getLoopCardinality());
        updateArchivedFlowNodeInstance(archivedMultiInstanceActivityInstanceImpl, sInstance,
                flowNodeStateManager.getState(sInstance.getStateId()).getName());
        return archivedMultiInstanceActivityInstanceImpl;
    }

    public static ArchivedManualTaskInstance toArchivedManualTaskInstance(final SAManualTaskInstance sInstance,
            final FlowNodeStateManager flowNodeStateManager) {
        final ArchivedManualTaskInstanceImpl archivedManualTaskInstance = new ArchivedManualTaskInstanceImpl(
                sInstance.getName());
        updateArchivedFlowNodeInstance(archivedManualTaskInstance, sInstance,
                flowNodeStateManager.getState(sInstance.getStateId()).getName());
        updateArchivedHumanTaskInstance(archivedManualTaskInstance, sInstance);
        return archivedManualTaskInstance;
    }

    public static ArchivedCallActivityInstance toArchivedCallActivityInstance(final SACallActivityInstance sInstance,
            final FlowNodeStateManager flowNodeStateManager) {
        final ArchivedCallActivityInstanceImpl archivedCallActivityInstanceImpl = new ArchivedCallActivityInstanceImpl(
                sInstance.getName());
        updateArchivedFlowNodeInstance(archivedCallActivityInstanceImpl, sInstance,
                flowNodeStateManager.getState(sInstance.getStateId()).getName());
        return archivedCallActivityInstanceImpl;
    }

    public static ArchivedSubProcessActivityInstance toArchivedSubProcessActivityInstance(
            final SASubProcessActivityInstance sInstance,
            final FlowNodeStateManager flowNodeStateManager) {
        final ArchivedSubProcessActivityInstanceImpl archivedSubProcActivityInstanceImpl = new ArchivedSubProcessActivityInstanceImpl(
                sInstance.getName(),
                sInstance.isTriggeredByEvent());
        updateArchivedFlowNodeInstance(archivedSubProcActivityInstanceImpl, sInstance,
                flowNodeStateManager.getState(sInstance.getStateId()).getName());
        return archivedSubProcActivityInstanceImpl;
    }

    public static ArchivedAutomaticTaskInstance toArchivedAutomaticTaskInstance(final SAActivityInstance sInstance,
            final FlowNodeStateManager flowNodeStateManager) {
        final ArchivedAutomaticTaskInstanceImpl archivedUserTaskInstanceImpl = new ArchivedAutomaticTaskInstanceImpl(
                sInstance.getName());
        updateArchivedFlowNodeInstance(archivedUserTaskInstanceImpl, sInstance,
                flowNodeStateManager.getState(sInstance.getStateId()).getName());
        return archivedUserTaskInstanceImpl;
    }

    public static ArchivedGatewayInstance toArchivedGatewayInstance(final SAActivityInstance sInstance,
            final FlowNodeStateManager flowNodeStateManager) {
        final ArchivedGatewayInstanceImpl archGatewayInstanceImpl = new ArchivedGatewayInstanceImpl(
                sInstance.getName());
        updateArchivedFlowNodeInstance(archGatewayInstanceImpl, sInstance,
                flowNodeStateManager.getState(sInstance.getStateId()).getName());
        return archGatewayInstanceImpl;
    }

    public static List toArchivedActivityInstances(
            final List saActivityInstances,
            final FlowNodeStateManager flowNodeStateManager) {
        final List archivedActivityInstances = new ArrayList<>();
        for (final SAActivityInstance saActivityInstance : saActivityInstances) {
            final ArchivedActivityInstance archivedActivityInstance = toArchivedActivityInstance(saActivityInstance,
                    flowNodeStateManager);
            archivedActivityInstances.add(archivedActivityInstance);
        }
        return archivedActivityInstances;
    }

    public static List toArchivedProcessInstances(
            final List saProcessInstances,
            final ProcessDefinitionService processDefinitionService) {
        if (saProcessInstances != null) {
            final List clientProcessInstances = new ArrayList<>(saProcessInstances.size());
            final Map processDefinitions = new HashMap<>(saProcessInstances.size());
            for (final SAProcessInstance saProcessInstance : saProcessInstances) {
                SProcessDefinition sProcessDefinition = processDefinitions.computeIfAbsent(
                        saProcessInstance.getProcessDefinitionId(),
                        processDefinitionId -> getProcessDefinition(processDefinitionService, processDefinitionId));
                clientProcessInstances.add(toArchivedProcessInstance(saProcessInstance, sProcessDefinition));
            }
            return Collections.unmodifiableList(clientProcessInstances);
        }
        return Collections.unmodifiableList(new ArrayList(1));
    }

    public static List toArchivedProcessInstances(
            final List sProcessInstances,
            final SProcessDefinition sProcessDefinition) {
        final List clientProcessInstances = new ArrayList<>(sProcessInstances.size());
        for (final SAProcessInstance sProcessInstance : sProcessInstances) {
            clientProcessInstances.add(toArchivedProcessInstance(sProcessInstance, sProcessDefinition));
        }
        return Collections.unmodifiableList(clientProcessInstances);
    }

    public static ArchivedProcessInstance toArchivedProcessInstance(final SAProcessInstance sInstance,
            final SProcessDefinition sProcessDefinition) {
        final ArchivedProcessInstanceImpl archivedInstance = new ArchivedProcessInstanceImpl(sInstance.getName());
        archivedInstance.setId(sInstance.getId());
        final int stateId = sInstance.getStateId();
        archivedInstance.setStateId(stateId);
        archivedInstance.setState(ProcessInstanceState.getFromId(stateId).name().toLowerCase());
        if (sInstance.getStartDate() > 0) {
            archivedInstance.setStartDate(new Date(sInstance.getStartDate()));
        }
        archivedInstance.setStartedBy(sInstance.getStartedBy());
        archivedInstance.setStartedBySubstitute(sInstance.getStartedBySubstitute());
        if (sInstance.getEndDate() > 0) {
            archivedInstance.setEndDate(new Date(sInstance.getEndDate()));
        }
        if (sInstance.getArchiveDate() > 0) {
            archivedInstance.setArchiveDate(new Date(sInstance.getArchiveDate()));
        }
        if (sInstance.getLastUpdate() > 0) {
            archivedInstance.setLastUpdate(new Date(sInstance.getLastUpdate()));
        }
        archivedInstance.setProcessDefinitionId(sInstance.getProcessDefinitionId());
        archivedInstance.setDescription(sInstance.getDescription());
        archivedInstance.setSourceObjectId(sInstance.getSourceObjectId());
        archivedInstance.setRootProcessInstanceId(sInstance.getRootProcessInstanceId());
        archivedInstance.setCallerId(sInstance.getCallerId());

        if (sProcessDefinition != null) {
            for (int i = 1; i <= 5; i++) {
                archivedInstance.setStringIndexLabel(i, sProcessDefinition.getStringIndexLabel(i));
            }
        }
        archivedInstance.setStringIndexValue(1, sInstance.getStringIndex1());
        archivedInstance.setStringIndexValue(2, sInstance.getStringIndex2());
        archivedInstance.setStringIndexValue(3, sInstance.getStringIndex3());
        archivedInstance.setStringIndexValue(4, sInstance.getStringIndex4());
        archivedInstance.setStringIndexValue(5, sInstance.getStringIndex5());
        return archivedInstance;
    }

    public static List toGroups(final List sGroups) {
        final List clientGroups = new ArrayList<>();
        if (sGroups != null) {
            for (final SGroup sGroup : sGroups) {
                clientGroups.add(toGroup(sGroup));
            }
        }
        return Collections.unmodifiableList(clientGroups);
    }

    public static List toExportedGroups(final List sGroups) {
        final List clientGroups = new ArrayList<>();
        if (sGroups != null) {
            for (final SGroup sGroup : sGroups) {
                clientGroups.add(toExportedGroup(sGroup));
            }
        }
        return Collections.unmodifiableList(clientGroups);
    }

    public static Group toGroup(final SGroup sGroup) {
        final GroupImpl group = new GroupImpl(sGroup.getId(), sGroup.getName());
        group.setParentPath(sGroup.getParentPath());
        group.setCreatedBy(sGroup.getCreatedBy());
        group.setCreationDate(new Date(sGroup.getCreationDate()));
        group.setDescription(sGroup.getDescription());
        group.setDisplayName(sGroup.getDisplayName());
        group.setIconId(sGroup.getIconId());
        group.setLastUpdate(new Date(sGroup.getLastUpdate()));
        return group;
    }

    private static ExportedGroup toExportedGroup(final SGroup sGroup) {
        final ExportedGroup group = new ExportedGroup();
        group.setName(sGroup.getName());
        group.setParentPath(sGroup.getParentPath());
        group.setDescription(sGroup.getDescription());
        group.setDisplayName(sGroup.getDisplayName());
        return group;
    }

    public static User toUser(final SUser sUser) {
        final UserImpl user = new UserImpl(sUser.getId(), sUser.getUserName());
        user.setFirstName(sUser.getFirstName());
        user.setLastName(sUser.getLastName());
        user.setTitle(sUser.getTitle());
        user.setJobTitle(sUser.getJobTitle());
        user.setCreatedBy(sUser.getCreatedBy());
        user.setCreationDate(new Date(sUser.getCreationDate()));
        user.setIconId(sUser.getIconId());
        user.setLastUpdate(new Date(sUser.getLastUpdate()));
        user.setEnabled(sUser.isEnabled());
        final long managerUserId = sUser.getManagerUserId();
        user.setManagerUserId(managerUserId);
        final SUserLogin sUserLogin = sUser.getSUserLogin();
        if (sUserLogin != null && sUserLogin.getLastConnection() != null) {
            user.setLastConnection(new Date(sUserLogin.getLastConnection()));
        }
        return user;
    }

    public static ContactData toUserContactData(final SContactInfo sContactData) {
        final ContactDataImpl contactData = new ContactDataImpl(sContactData.getUserId());
        contactData.setAddress(sContactData.getAddress());
        contactData.setBuilding(sContactData.getBuilding());
        contactData.setCity(sContactData.getCity());
        contactData.setCountry(sContactData.getCountry());
        contactData.setEmail(sContactData.getEmail());
        contactData.setFaxNumber(sContactData.getFaxNumber());
        contactData.setMobileNumber(sContactData.getMobileNumber());
        contactData.setPersonal(sContactData.isPersonal());
        contactData.setPhoneNumber(sContactData.getPhoneNumber());
        contactData.setRoom(sContactData.getRoom());
        contactData.setState(sContactData.getState());
        contactData.setWebsite(sContactData.getWebsite());
        contactData.setZipCode(sContactData.getZipCode());
        return contactData;
    }

    public static List toUsers(final List sUsers) {
        final List users = new ArrayList<>();
        if (sUsers != null) {
            for (final SUser sUser : sUsers) {
                final User user = ModelConvertor.toUser(sUser);
                users.add(user);
            }
        }
        return Collections.unmodifiableList(users);
    }

    public static Role toRole(final SRole sRole) {
        final RoleImpl role = new RoleImpl(sRole.getId(), sRole.getName());
        role.setDisplayName(sRole.getDisplayName());
        role.setDescription(sRole.getDescription());
        role.setIconId(sRole.getIconId());
        role.setCreatedBy(sRole.getCreatedBy());
        role.setCreationDate(new Date(sRole.getCreationDate()));
        role.setLastUpdate(new Date(sRole.getLastUpdate()));
        return role;
    }

    private static ExportedRole toExportedRole(final SRole sRole) {
        final ExportedRole role = new ExportedRole(sRole.getName());
        role.setDisplayName(sRole.getDisplayName());
        role.setDescription(sRole.getDescription());
        return role;
    }

    public static List toRoles(final List sRoles) {
        final List lightRoles = new ArrayList<>();
        if (sRoles != null) {
            for (final SRole sRole : sRoles) {
                final Role role = toRole(sRole);
                lightRoles.add(role);
            }
        }
        return Collections.unmodifiableList(lightRoles);
    }

    public static List toExportedRoles(final List sRoles) {
        final List lightRoles = new ArrayList<>();
        if (sRoles != null) {
            for (final SRole sRole : sRoles) {
                final ExportedRole role = toExportedRole(sRole);
                lightRoles.add(role);
            }
        }
        return Collections.unmodifiableList(lightRoles);
    }

    public static UserMembership toUserMembership(final SUserMembership sUserMembership) {
        final UserMembershipImpl userMembership = new UserMembershipImpl(sUserMembership.getId(),
                sUserMembership.getUserId(), sUserMembership.getGroupId(),
                sUserMembership.getRoleId());
        userMembership.setAssignedBy(sUserMembership.getAssignedBy());
        userMembership.setAssignedDate(new Date(sUserMembership.getAssignedDate()));
        userMembership.setGroupName(sUserMembership.getGroupName());
        userMembership.setRoleName(sUserMembership.getRoleName());
        userMembership.setUsername(sUserMembership.getUsername());
        userMembership.setGroupParentPath(sUserMembership.getGroupParentPath());
        return userMembership;
    }

    public static List toUserMembership(final List sUserMemberships) {
        final List userMemberships = new ArrayList<>();
        if (sUserMemberships != null) {
            for (final SUserMembership sMembership : sUserMemberships) {
                final UserMembership userMembership = toUserMembership(sMembership);
                userMemberships.add(userMembership);
            }
        }
        return Collections.unmodifiableList(userMemberships);
    }

    public static List toUserMembership(final List sUserMemberships,
            final Map userNames,
            final Map groupIdToGroup) {
        final List userMemberships = new ArrayList<>();
        if (sUserMemberships != null) {
            for (final SUserMembership sMembership : sUserMemberships) {
                final UserMembership userMembership = toUserMembership(sMembership, userNames, groupIdToGroup);
                userMemberships.add(userMembership);
            }
        }
        return Collections.unmodifiableList(userMemberships);
    }

    public static List toExportedUserMembership(final List sUserMemberships,
            final Map userNames,
            final Map groupIdToGroup) {
        final List userMemberships = new ArrayList<>();
        if (sUserMemberships != null) {
            for (final SUserMembership sMembership : sUserMemberships) {
                final ExportedUserMembership userMembership = toExportedUserMembership(sMembership, userNames,
                        groupIdToGroup);
                userMemberships.add(userMembership);
            }
        }
        return Collections.unmodifiableList(userMemberships);
    }

    private static UserMembership toUserMembership(final SUserMembership sUserMembership,
            final Map userNames,
            final Map groupIdToGroup) {
        final UserMembershipImpl userMembership = new UserMembershipImpl(sUserMembership.getId(),
                sUserMembership.getUserId(), sUserMembership.getGroupId(),
                sUserMembership.getRoleId());
        userMembership.setGroupName(sUserMembership.getGroupName());
        userMembership.setGroupParentPath(groupIdToGroup.get(sUserMembership.getGroupId()));
        userMembership.setRoleName(sUserMembership.getRoleName());
        userMembership.setUsername(sUserMembership.getUsername());
        final long assignedBy = sUserMembership.getAssignedBy();
        userMembership.setAssignedBy(assignedBy);
        if (assignedBy > 0) {
            userMembership.setAssignedByName(userNames.get(assignedBy));
        }
        userMembership.setAssignedDate(new Date(sUserMembership.getAssignedDate()));
        return userMembership;
    }

    private static ExportedUserMembership toExportedUserMembership(final SUserMembership sUserMembership,
            final Map userNames,
            final Map groupIdToGroup) {
        final ExportedUserMembership userMembership = new ExportedUserMembership();
        userMembership.setGroupName(sUserMembership.getGroupName());
        userMembership.setGroupParentPath(groupIdToGroup.get(sUserMembership.getGroupId()));
        userMembership.setRoleName(sUserMembership.getRoleName());
        userMembership.setUserName(sUserMembership.getUsername());
        final long assignedBy = sUserMembership.getAssignedBy();
        userMembership.setAssignedBy(userNames.get(assignedBy));
        userMembership.setAssignedDate(sUserMembership.getAssignedDate());
        return userMembership;
    }

    public static Category toCategory(final SCategory sCategory) {
        final CategoryImpl category = new CategoryImpl(sCategory.getId(), sCategory.getName());
        category.setDescription(sCategory.getDescription());
        category.setCreator(sCategory.getCreator());
        category.setCreationDate(new Date(sCategory.getCreationDate()));
        category.setLastUpdate(new Date(sCategory.getLastUpdateDate()));
        return category;
    }

    public static CommandDescriptor toCommandDescriptor(final SCommand command) {
        final CommandDescriptorImpl commandDescriptor = new CommandDescriptorImpl(command.getName(),
                command.getDescription(), command.getImplementation());
        commandDescriptor.setId(command.getId());
        commandDescriptor.setSystem(command.isSystem());
        return commandDescriptor;
    }

    public static CommandDescriptor toCommandDescriptor(final SPlatformCommand platformCommand) {
        final CommandDescriptorImpl commandDescriptor = new CommandDescriptorImpl(platformCommand.getName(),
                platformCommand.getDescription(),
                platformCommand.getImplementation());
        commandDescriptor.setId(platformCommand.getId());
        return commandDescriptor;
    }

    public static List toCommandDescriptors(final List sCommands) {
        if (sCommands != null) {
            final List commandList = new ArrayList<>();
            for (final SCommand sCommand : sCommands) {
                commandList.add(toCommandDescriptor(sCommand));
            }
            return Collections.unmodifiableList(commandList);
        }
        return Collections.emptyList();
    }

    public static List toPlatformCommandDescriptors(final List sPlatformCommands) {
        if (sPlatformCommands != null) {
            final List platformCommandList = new ArrayList<>();
            for (final SPlatformCommand sCommand : sPlatformCommands) {
                platformCommandList.add(toCommandDescriptor(sCommand));
            }
            return Collections.unmodifiableList(platformCommandList);
        }
        return Collections.emptyList();
    }

    public static List toCategories(final List sCategories) {
        if (sCategories != null) {
            final List categoryList = new ArrayList<>();
            for (final SCategory sCategory : sCategories) {
                categoryList.add(toCategory(sCategory));
            }
            return Collections.unmodifiableList(categoryList);
        }
        return Collections.emptyList();
    }

    public static List toEventInstances(final Collection sEvents,
            final FlowNodeStateManager flowNodeStateManager) {
        final List eventInstances = new ArrayList<>();
        for (final SEventInstance sEvent : sEvents) {
            final EventInstance eventInstance = toEventInstance(sEvent, flowNodeStateManager);
            eventInstances.add(eventInstance);
        }
        return eventInstances;
    }

    public static EventInstance toEventInstance(final SEventInstance sEvent,
            final FlowNodeStateManager flowNodeStateManager) {
        final EventInstanceImpl eventInstance = getEventInstance(sEvent);
        updateFlowNode(eventInstance, sEvent, flowNodeStateManager.getState(sEvent.getStateId()).getName());
        return eventInstance;
    }

    public static List toTimerEventTriggerInstances(
            final List sEventTriggerInstances) {
        final List eventTriggerInstances = new ArrayList<>();
        for (final STimerEventTriggerInstance sEventTriggerInstance : sEventTriggerInstances) {
            final TimerEventTriggerInstance eventTriggerInstance = toTimerEventTriggerInstance(sEventTriggerInstance);
            eventTriggerInstances.add(eventTriggerInstance);
        }
        return eventTriggerInstances;
    }

    public static TimerEventTriggerInstance toTimerEventTriggerInstance(
            final STimerEventTriggerInstance sTimerEventTriggerInstance) {
        return new TimerEventTriggerInstanceImpl(sTimerEventTriggerInstance.getId(),
                sTimerEventTriggerInstance.getEventInstanceId(),
                sTimerEventTriggerInstance.getEventInstanceName(),
                new Date(sTimerEventTriggerInstance.getExecutionDate()));
    }

    public static WaitingEvent toWaitingEvent(final SWaitingEvent sWaitingEvent) {
        WaitingEventImpl waitingEvent;
        final BPMEventType bpmEventType = BPMEventType.valueOf(sWaitingEvent.getEventType().name());
        final long processDefinitionId = sWaitingEvent.getProcessDefinitionId();
        final String processName = sWaitingEvent.getProcessName();
        final long flowNodeDefinitionId = sWaitingEvent.getFlowNodeDefinitionId();
        switch (sWaitingEvent.getEventTriggerType()) {
            case ERROR:
                final SWaitingErrorEvent sWaitingErrorEvent = (SWaitingErrorEvent) sWaitingEvent;
                waitingEvent = new WaitingErrorEventImpl(bpmEventType, processDefinitionId, processName,
                        flowNodeDefinitionId,
                        sWaitingErrorEvent.getErrorCode());
                break;
            case MESSAGE:
                final SWaitingMessageEvent sWaitingMessageEvent = (SWaitingMessageEvent) sWaitingEvent;
                waitingEvent = new WaitingMessageEventImpl(bpmEventType, processDefinitionId, processName,
                        flowNodeDefinitionId,
                        sWaitingMessageEvent.getMessageName());
                break;
            case SIGNAL:
                final SWaitingSignalEvent sWaitingSignalEvent = (SWaitingSignalEvent) sWaitingEvent;
                waitingEvent = new WaitingSignalEventImpl(bpmEventType, processDefinitionId, processName,
                        flowNodeDefinitionId,
                        sWaitingSignalEvent.getSignalName());
                break;
            default:
                throw new UnknownElementType(sWaitingEvent.getClass().getName());
        }
        waitingEvent.setRootProcessInstanceId(sWaitingEvent.getRootProcessInstanceId());
        waitingEvent.setParentProcessInstanceId(sWaitingEvent.getParentProcessInstanceId());
        return waitingEvent;
    }

    public static List toWaitingEvents(final List sWaitingEvents) {
        final List waitingEvents = new ArrayList<>(sWaitingEvents.size());
        for (final SWaitingEvent sWaitingEvent : sWaitingEvents) {
            waitingEvents.add(toWaitingEvent(sWaitingEvent));
        }
        return Collections.unmodifiableList(waitingEvents);
    }

    private static EventInstanceImpl getEventInstance(final SEventInstance sEvent) {
        switch (sEvent.getType()) {
            case END_EVENT:
                return new EndEventInstanceImpl(sEvent.getName(), sEvent.getFlowNodeDefinitionId());
            case INTERMEDIATE_CATCH_EVENT:
                return new IntermediateCatchEventInstanceImpl(sEvent.getName(), sEvent.getFlowNodeDefinitionId());
            case INTERMEDIATE_THROW_EVENT:
                return new IntermediateThrowEventInstanceImpl(sEvent.getName(), sEvent.getFlowNodeDefinitionId());
            case BOUNDARY_EVENT:
                return new BoundaryEventInstanceImpl(sEvent.getName(), sEvent.getFlowNodeDefinitionId(),
                        ((SBoundaryEventInstance) sEvent).getActivityInstanceId());
            case START_EVENT:
                return new StartEventInstanceImpl(sEvent.getName(), sEvent.getFlowNodeDefinitionId());
            default:
                throw new UnknownElementType(sEvent.getType().name());
        }
    }

    public static List toDataInstances(final List sDataInstances) {
        if (sDataInstances != null) {
            final List dataInstanceList = new ArrayList<>();
            for (final SDataInstance sDataInstance : sDataInstances) {
                dataInstanceList.add(toDataInstance(sDataInstance));
            }
            return Collections.unmodifiableList(dataInstanceList);
        }
        return Collections.emptyList();
    }

    public static List toDataDefinitions(final List sDataDefinitions) {
        if (sDataDefinitions != null) {
            final List dataDefinitionList = new ArrayList<>();
            for (final SDataDefinition sDataDefinition : sDataDefinitions) {
                dataDefinitionList.add(toDataDefinition(sDataDefinition));
            }
            return Collections.unmodifiableList(dataDefinitionList);
        }
        return Collections.emptyList();
    }

    public static DataDefinition toDataDefinition(final SDataDefinition sDataDefinition) {
        DataDefinitionImpl dataDefinitionImpl = null;
        if (sDataDefinition != null) {
            dataDefinitionImpl = new DataDefinitionImpl(sDataDefinition.getName(),
                    toExpression(sDataDefinition.getDefaultValueExpression()));
            dataDefinitionImpl.setClassName(sDataDefinition.getClassName());
            dataDefinitionImpl.setDescription(sDataDefinition.getDescription());
            dataDefinitionImpl.setTransientData(sDataDefinition.isTransientData());
        }
        return dataDefinitionImpl;
    }

    public static List toExpressions(final List sExpressions) {
        if (sExpressions != null && !sExpressions.isEmpty()) {
            final List expList = new ArrayList<>(sExpressions.size());
            for (final SExpression sexp : sExpressions) {
                expList.add(toExpression(sexp));
            }
            return expList;
        }
        return Collections.emptyList();
    }

    public static Expression toExpression(final SExpression sexp) {
        final ExpressionImpl exp = new ExpressionImpl();
        if (sexp != null) {
            exp.setContent(sexp.getContent());
            exp.setExpressionType(sexp.getExpressionType());
            exp.setInterpreter(sexp.getInterpreter());
            exp.setName(sexp.getName());
            exp.setReturnType(sexp.getReturnType());
            exp.setDependencies(toExpressions(sexp.getDependencies()));
        }
        return exp;
    }

    public static DataInstance toDataInstance(final SDataInstance sDataInstance) {
        DataInstanceImpl dataInstance;
        if (sDataInstance.getClassName().equals(Integer.class.getName())) {
            dataInstance = new IntegerDataInstanceImpl();
        } else if (sDataInstance.getClassName().equals(Long.class.getName())) {
            dataInstance = new LongDataInstanceImpl();
        } else if (sDataInstance.getClassName().equals(Boolean.class.getName())) {
            dataInstance = new BooleanDataInstanceImpl();
        } else if (sDataInstance.getClassName().equals(Date.class.getName())) {
            dataInstance = new DateDataInstanceImpl();
        } else if (sDataInstance.getClassName().equals(Double.class.getName())) {
            dataInstance = new DoubleDataInstanceImpl();
        } else if (sDataInstance.getClassName().equals(Float.class.getName())) {
            dataInstance = new FloatDataInstanceImpl();
        } else if (sDataInstance.getClassName().equals(String.class.getName())) {
            dataInstance = new ShortTextDataInstanceImpl();
        } else {
            dataInstance = new BlobDataInstanceImpl();
        }
        dataInstance.setTransientData(sDataInstance.isTransientData());
        dataInstance.setClassName(sDataInstance.getClassName());
        dataInstance.setContainerId(sDataInstance.getContainerId());
        dataInstance.setContainerType(sDataInstance.getContainerType());
        dataInstance.setDataTypeClassName(sDataInstance.getClassName());
        dataInstance.setDescription(sDataInstance.getDescription());
        dataInstance.setId(sDataInstance.getId());
        dataInstance.setName(sDataInstance.getName());
        dataInstance.setValue(sDataInstance.getValue());
        return dataInstance;
    }

    public static List toArchivedDataInstances(final List sADataInstances) {
        final List dataInstances = new ArrayList<>();
        for (final SADataInstance sADataInstance : sADataInstances) {
            final ArchivedDataInstance dataInstance = toArchivedDataInstance(sADataInstance);
            dataInstances.add(dataInstance);
        }
        return dataInstances;
    }

    public static ArchivedDataInstance toArchivedDataInstance(final SADataInstance sDataInstance) {
        final ArchivedDataInstanceImpl dataInstance = new ArchivedDataInstanceImpl();
        dataInstance.setClassName(sDataInstance.getClassName());
        dataInstance.setContainerId(sDataInstance.getContainerId());
        dataInstance.setContainerType(sDataInstance.getContainerType());
        dataInstance.setDataTypeClassName(sDataInstance.getClassName());
        dataInstance.setDescription(sDataInstance.getDescription());
        dataInstance.setId(sDataInstance.getId());
        dataInstance.setName(sDataInstance.getName());
        dataInstance.setValue(sDataInstance.getValue());
        dataInstance.setArchiveDate(new Date(sDataInstance.getArchiveDate()));
        dataInstance.setSourceObjectId(sDataInstance.getSourceObjectId());
        return dataInstance;
    }

    public static ActorMember toActorMember(final SActorMember sActorMember) {
        return new ActorMemberImpl(sActorMember.getId(), sActorMember.getUserId(), sActorMember.getGroupId(),
                sActorMember.getRoleId());
    }

    public static List toActorMembers(final List sActorMembers) {
        final List actorMembers = new ArrayList<>();
        for (final SActorMember sActorMember : sActorMembers) {
            final ActorMember actorMember = toActorMember(sActorMember);
            actorMembers.add(actorMember);
        }
        return actorMembers;
    }

    public static ActorInstance toActorInstance(final SActor actor) {
        final String name = actor.getName();
        final String description = actor.getDescription();
        final long scopeId = actor.getScopeId();
        final String displayName = actor.getDisplayName();
        final boolean initiator = actor.isInitiator();
        final ActorInstanceImpl actorInstance = new ActorInstanceImpl(name, description, displayName, scopeId,
                initiator);
        actorInstance.setId(actor.getId());
        return actorInstance;
    }

    public static SUser constructSUser(final UserCreator creator) {
        final long now = System.currentTimeMillis();
        final SUser.SUserBuilder userBuilder = SUser.builder();
        final Map fields = creator.getFields();
        userBuilder.userName((String) fields.get(UserField.NAME));
        userBuilder.password((String) fields.get(UserField.PASSWORD));
        final String firstName = (String) fields.get(UserField.FIRST_NAME);
        if (firstName != null) {
            userBuilder.firstName(firstName);
        }
        final String lastName = (String) fields.get(UserField.LAST_NAME);
        if (lastName != null) {
            userBuilder.lastName(lastName);
        }
        final String jobTitle = (String) fields.get(UserField.JOB_TITLE);
        if (jobTitle != null) {
            userBuilder.jobTitle(jobTitle);
        }
        final String title = (String) fields.get(UserField.TITLE);
        if (title != null) {
            userBuilder.title(title);
        }
        userBuilder.createdBy(SessionInfos.getUserIdFromSession());

        final Long managerUserId = (Long) fields.get(UserField.MANAGER_ID);
        if (managerUserId != null) {
            userBuilder.managerUserId(managerUserId);
        }

        final Boolean enabled = (Boolean) fields.get(UserField.ENABLED);
        if (enabled != null) {
            userBuilder.enabled(enabled);
        } else {
            userBuilder.enabled(Boolean.TRUE);
        }
        userBuilder.creationDate(now);
        userBuilder.lastUpdate(now);
        return userBuilder.build();
    }

    public static SContactInfo constructSUserContactInfo(final UserCreator creator, final long userId,
            final boolean personal) {
        Map fields;
        if (personal) {
            fields = creator.getPersoFields();
        } else {
            fields = creator.getProFields();
        }
        if (fields != null && !fields.isEmpty()) {
            final SContactInfo.SContactInfoBuilder contactInfoBuilder = SContactInfo.builder().userId(userId)
                    .personal(personal);
            final String address = (String) fields.get(ContactDataField.ADDRESS);
            if (address != null) {
                contactInfoBuilder.address(address);
            }
            final String email = (String) fields.get(ContactDataField.EMAIL);
            if (email != null) {
                contactInfoBuilder.email(email);
            }
            final String building = (String) fields.get(ContactDataField.BUILDING);
            if (building != null) {
                contactInfoBuilder.building(building);
            }
            final String city = (String) fields.get(ContactDataField.CITY);
            if (city != null) {
                contactInfoBuilder.city(city);
            }
            final String country = (String) fields.get(ContactDataField.COUNTRY);
            if (country != null) {
                contactInfoBuilder.country(country);
            }
            final String fax = (String) fields.get(ContactDataField.FAX);
            if (fax != null) {
                contactInfoBuilder.faxNumber(fax);
            }
            final String mobile = (String) fields.get(ContactDataField.MOBILE);
            if (mobile != null) {
                contactInfoBuilder.mobileNumber(mobile);
            }
            final String phone = (String) fields.get(ContactDataField.PHONE);
            if (phone != null) {
                contactInfoBuilder.phoneNumber(phone);
            }
            final String room = (String) fields.get(ContactDataField.ROOM);
            if (room != null) {
                contactInfoBuilder.room(room);
            }
            final String state = (String) fields.get(ContactDataField.STATE);
            if (state != null) {
                contactInfoBuilder.state(state);
            }
            final String website = (String) fields.get(ContactDataField.WEBSITE);
            if (website != null) {
                contactInfoBuilder.website(website);
            }
            final String zipCode = (String) fields.get(ContactDataField.ZIP_CODE);
            if (zipCode != null) {
                contactInfoBuilder.zipCode(zipCode);
            }
            return contactInfoBuilder.build();
        }
        return null;
    }

    public static SContactInfo constructSUserContactInfo(final ExportedUser user, final boolean isPersonal,
            final long userId) {
        final SContactInfo.SContactInfoBuilder contactInfoBuilder = SContactInfo.builder().userId(userId)
                .personal(isPersonal);
        if (isPersonal) {
            contactInfoBuilder.address(user.getPersonalAddress());
            contactInfoBuilder.building(user.getPersonalBuilding());
            contactInfoBuilder.city(user.getPersonalCity());
            contactInfoBuilder.country(user.getPersonalCountry());
            contactInfoBuilder.email(user.getPersonalEmail());
            contactInfoBuilder.faxNumber(user.getPersonalFaxNumber());
            contactInfoBuilder.mobileNumber(user.getPersonalMobileNumber());
            contactInfoBuilder.phoneNumber(user.getPersonalPhoneNumber());
            contactInfoBuilder.room(user.getPersonalRoom());
            contactInfoBuilder.state(user.getPersonalState());
            contactInfoBuilder.website(user.getPersonalWebsite());
            contactInfoBuilder.zipCode(user.getPersonalZipCode());
        } else {
            contactInfoBuilder.address(user.getProfessionalAddress());
            contactInfoBuilder.building(user.getProfessionalBuilding());
            contactInfoBuilder.city(user.getProfessionalCity());
            contactInfoBuilder.country(user.getProfessionalCountry());
            contactInfoBuilder.email(user.getProfessionalEmail());
            contactInfoBuilder.faxNumber(user.getProfessionalFaxNumber());
            contactInfoBuilder.mobileNumber(user.getProfessionalMobileNumber());
            contactInfoBuilder.phoneNumber(user.getProfessionalPhoneNumber());
            contactInfoBuilder.room(user.getProfessionalRoom());
            contactInfoBuilder.state(user.getProfessionalState());
            contactInfoBuilder.website(user.getProfessionalWebsite());
            contactInfoBuilder.zipCode(user.getProfessionalZipCode());
        }
        return contactInfoBuilder.build();
    }

    public static SRole constructSRole(final RoleCreator creator) {
        final long now = System.currentTimeMillis();
        final SRole.SRoleBuilder roleBuilder = SRole.builder();
        roleBuilder.createdBy(SessionInfos.getUserIdFromSession());
        roleBuilder.creationDate(now).lastUpdate(now);
        final Map fields = creator.getFields();
        roleBuilder.name((String) fields.get(RoleField.NAME));
        final String displayName = (String) fields.get(RoleField.DISPLAY_NAME);
        if (displayName != null) {
            roleBuilder.displayName(displayName);
        }
        final String description = (String) fields.get(RoleField.DESCRIPTION);
        if (description != null) {
            roleBuilder.description(description);
        }
        return roleBuilder.build();
    }

    public static SRole constructSRole(final ExportedRole exportedRole) {
        final long now = System.currentTimeMillis();
        final SRole.SRoleBuilder roleBuilder = SRole.builder();
        roleBuilder.createdBy(SessionInfos.getUserIdFromSession());
        roleBuilder.creationDate(now).lastUpdate(now);
        roleBuilder.name(exportedRole.getName());
        roleBuilder.displayName(exportedRole.getDisplayName());
        roleBuilder.description(exportedRole.getDescription());
        return roleBuilder.build();
    }

    public static SGroup constructSGroup(final GroupCreator creator) {
        final long now = System.currentTimeMillis();
        final SGroup.SGroupBuilder groupBuilder = SGroup.builder();
        groupBuilder.createdBy(SessionInfos.getUserIdFromSession());
        groupBuilder.creationDate(now).lastUpdate(now);
        final Map fields = creator.getFields();
        groupBuilder.name((String) fields.get(GroupField.NAME));
        final String parentPath = (String) fields.get(GroupField.PARENT_PATH);
        if (parentPath != null && !parentPath.isEmpty()) {
            groupBuilder.parentPath(parentPath);
        }
        final String displayName = (String) fields.get(GroupField.DISPLAY_NAME);
        if (displayName != null) {
            groupBuilder.displayName(displayName);
        }
        final String description = (String) fields.get(GroupField.DESCRIPTION);
        if (description != null) {
            groupBuilder.description(description);
        }
        return groupBuilder.build();
    }

    public static SGroup constructSGroup(final ExportedGroup exportedGroup) {
        final long now = System.currentTimeMillis();
        final SGroup.SGroupBuilder groupBuilder = SGroup.builder();
        groupBuilder.createdBy(SessionInfos.getUserIdFromSession());
        groupBuilder.creationDate(now).lastUpdate(now);
        groupBuilder.name(exportedGroup.getName());
        groupBuilder.parentPath(exportedGroup.getParentPath());
        groupBuilder.displayName(exportedGroup.getDisplayName());
        groupBuilder.description(exportedGroup.getDescription());
        return groupBuilder.build();
    }

    public static List toProcessSupervisors(final List sSupervisors) {
        final List processSupervisors = new ArrayList<>();
        if (sSupervisors != null) {
            for (final SProcessSupervisor sSupervisor : sSupervisors) {
                processSupervisors.add(toProcessSupervisor(sSupervisor));
            }
        }
        return processSupervisors;
    }

    public static ProcessSupervisor toProcessSupervisor(final SProcessSupervisor sSupervisor) {
        final ProcessSupervisorImpl supervisor = new ProcessSupervisorImpl();
        supervisor.setId(sSupervisor.getId());
        supervisor.setProcessDefinitionId(sSupervisor.getProcessDefId());
        supervisor.setUserId(sSupervisor.getUserId());
        supervisor.setGroupId(sSupervisor.getGroupId());
        supervisor.setRoleId(sSupervisor.getRoleId());
        return supervisor;
    }

    public static List toDocuments(final Collection mappedDocuments,
            final DocumentService documentService) {
        final List documents = new ArrayList<>();
        for (final AbstractSMappedDocument mappedDocument : mappedDocuments) {
            final Document document = toDocument(mappedDocument, documentService);
            documents.add(document);
        }
        return documents;
    }

    public static Document toDocument(final AbstractSMappedDocument mappedDocument,
            final DocumentService documentService) {

        final DocumentImpl documentImpl = new DocumentImpl();
        if (mappedDocument instanceof SAMappedDocument) {
            documentImpl.setId(((SAMappedDocument) mappedDocument).getSourceObjectId());
        } else {
            documentImpl.setId(mappedDocument.getId());
        }
        setDocumentFields(mappedDocument, documentService, documentImpl);
        return documentImpl;
    }

    private static void setDocumentFields(final AbstractSMappedDocument mappedDocument,
            final DocumentService documentService,
            final DocumentImpl documentImpl) {
        documentImpl.setProcessInstanceId(mappedDocument.getProcessInstanceId());
        documentImpl.setName(mappedDocument.getName());
        documentImpl.setDescription(mappedDocument.getDescription());
        documentImpl.setVersion(mappedDocument.getVersion());
        documentImpl.setAuthor(mappedDocument.getAuthor());
        documentImpl.setCreationDate(new Date(mappedDocument.getCreationDate()));
        documentImpl.setHasContent(mappedDocument.hasContent());
        documentImpl.setContentMimeType(mappedDocument.getMimeType());
        documentImpl.setFileName(mappedDocument.getFileName());
        documentImpl.setContentStorageId(String.valueOf(mappedDocument.getDocumentId()));
        documentImpl.setIndex(mappedDocument.getIndex());
        if (mappedDocument.hasContent()) {
            documentImpl.setUrl(documentService.generateDocumentURL(mappedDocument.getFileName(),
                    String.valueOf(mappedDocument.getDocumentId())));
        } else {
            documentImpl.setUrl(mappedDocument.getUrl());
        }
    }

    public static List toArchivedDocuments(final Collection mappedDocuments,
            final DocumentService documentService) {
        final List documents = new ArrayList<>();
        for (final SAMappedDocument mappedDocument : mappedDocuments) {
            final ArchivedDocument document = toArchivedDocument(mappedDocument, documentService);
            documents.add(document);
        }
        return documents;
    }

    public static ArchivedDocument toArchivedDocument(final SAMappedDocument mappedDocument,
            final DocumentService documentService) {
        final ArchivedDocumentImpl documentImpl = new ArchivedDocumentImpl(mappedDocument.getName());
        documentImpl.setId(mappedDocument.getId());
        setDocumentFields(mappedDocument, documentService, documentImpl);
        documentImpl.setArchiveDate(new Date(mappedDocument.getArchiveDate()));
        documentImpl.setSourceObjectId(mappedDocument.getSourceObjectId());
        return documentImpl;
    }

    public static int getServerActivityStateId(final String state) {
        int stateId;
        if (state.equalsIgnoreCase(ActivityStates.READY_STATE)) {
            stateId = 4;
        } else if (state.equalsIgnoreCase(ActivityStates.COMPLETING_STATE)) {
            stateId = 9;
        } else if (state.equalsIgnoreCase(ActivityStates.COMPLETED_STATE)) {
            stateId = 2;
        } else if (state.equalsIgnoreCase(ActivityStates.EXECUTING_STATE)) {
            stateId = 1;
        } else if (state.equalsIgnoreCase(ActivityStates.INITIALIZING_STATE)) {
            stateId = 0;
        } else if (state.equalsIgnoreCase(ActivityStates.SKIPPED_STATE)) {
            stateId = 12;
        } else if (state.equalsIgnoreCase(ActivityStates.CANCELLING_SUBTASKS_STATE)) {
            stateId = 13;
        } else if (state.equalsIgnoreCase(ActivityStates.CANCELLED_STATE)) {
            stateId = 14;
        } else if (state.equalsIgnoreCase(ActivityStates.FAILED_STATE)) {
            stateId = 3;
        } else {
            throw new IllegalArgumentException("Unknown activity state " + state);
        }
        return stateId;
    }

    public static ProcessInstanceState getProcessInstanceState(final String state) {
        if (state != null) {
            if (state.equalsIgnoreCase(ProcessInstanceState.ABORTED.toString())) {
                return ProcessInstanceState.ABORTED;
            } else if (state.equalsIgnoreCase(ProcessInstanceState.CANCELLED.toString())) {
                return ProcessInstanceState.CANCELLED;
            } else if (state.equalsIgnoreCase(ProcessInstanceState.COMPLETED.toString())) {
                return ProcessInstanceState.COMPLETED;
            } else if (state.equalsIgnoreCase(ProcessInstanceState.COMPLETING.toString())) {
                return ProcessInstanceState.COMPLETING;
            } else if (state.equalsIgnoreCase(ProcessInstanceState.ERROR.toString())) {
                return ProcessInstanceState.ERROR;
            } else if (state.equalsIgnoreCase(ProcessInstanceState.INITIALIZING.toString())) {
                return ProcessInstanceState.INITIALIZING;
            } else if (state.equalsIgnoreCase(ProcessInstanceState.STARTED.toString())) {
                return ProcessInstanceState.STARTED;
            } else if (state.equalsIgnoreCase(ProcessInstanceState.SUSPENDED.toString())) {
                return ProcessInstanceState.SUSPENDED;
            }
        }
        throw new IllegalArgumentException("Invalid process instance state: " + state);
    }

    public static Comment toComment(final SComment sComment) {
        final CommentImpl commentImpl = new CommentImpl();
        commentImpl.setTenantId(sComment.getTenantId());
        commentImpl.setId(sComment.getId());
        commentImpl.setUserId(sComment.getUserId());
        commentImpl.setProcessInstanceId(sComment.getProcessInstanceId());
        commentImpl.setPostDate(sComment.getPostDate());
        commentImpl.setContent(sComment.getContent());
        return commentImpl;
    }

    public static List toComments(final List sComments) {
        final List comments = new ArrayList<>();
        for (final SComment sComment : sComments) {
            comments.add(toComment(sComment));
        }
        return comments;
    }

    public static Map constructExpressions(final Map inputs) {

        final Map result = new HashMap<>(inputs.size());
        for (final Entry expression : inputs.entrySet()) {
            result.put(expression.getKey(), constructSExpression(expression.getValue()));
        }
        return result;
    }

    public static SExpression constructSExpression(final Expression model) {
        final ArrayList dependencies = new ArrayList<>();
        for (final Expression dep : model.getDependencies()) {
            dependencies.add(constructSExpression(dep));
        }
        final SExpressionBuilder expressionBuilder = BuilderFactory.get(SExpressionBuilderFactory.class)
                .createNewInstance();
        expressionBuilder.setName(model.getName());
        expressionBuilder.setContent(model.getContent());
        expressionBuilder.setExpressionType(model.getExpressionType());
        expressionBuilder.setInterpreter(model.getInterpreter());
        expressionBuilder.setReturnType(model.getReturnType());
        expressionBuilder.setDependencies(dependencies);
        try {
            return expressionBuilder.done();
        } catch (final SInvalidExpressionException e) {
            throw new IllegalArgumentException("Error constructing SExpression");
        }
    }

    public static SOperation convertOperation(final Operation operation) {
        if (operation == null) {
            return null;
        }
        return BuilderFactory
                .get(SOperationBuilderFactory.class)
                .createNewInstance()
                .setOperator(operation.getOperator())
                .setType(SOperatorType.valueOf(operation.getType().name()))
                .setRightOperand(ModelConvertor.constructSExpression(operation.getRightOperand()))
                .setLeftOperand(
                        BuilderFactory.get(SLeftOperandBuilderFactory.class).createNewInstance()
                                .setName(operation.getLeftOperand().getName())
                                .setType(operation.getLeftOperand().getType()).done())
                .done();
    }

    public static List convertOperations(final List operations) {
        if (operations == null) {
            return Collections.emptyList();
        }
        final List sOperations = new ArrayList<>(operations.size());
        for (final Operation operation : operations) {
            sOperations.add(convertOperation(operation));
        }
        return sOperations;
    }

    public static List toConnectorImplementationDescriptors(
            final List sConnectorImplementationDescriptors) {
        if (sConnectorImplementationDescriptors != null) {
            final List connectorImplementationDescriptors = new ArrayList<>(
                    sConnectorImplementationDescriptors.size());
            for (final SConnectorImplementationDescriptor sConnectorImplementationDescriptor : sConnectorImplementationDescriptors) {
                connectorImplementationDescriptors
                        .add(toConnectorImplementationDescriptor(sConnectorImplementationDescriptor));
            }
            return connectorImplementationDescriptors;
        }
        return Collections.emptyList();
    }

    public static ConnectorImplementationDescriptor toConnectorImplementationDescriptor(
            final SConnectorImplementationDescriptor sConnectorImplementationDescriptor) {
        return new ConnectorImplementationDescriptor(sConnectorImplementationDescriptor.getImplementationClassName(),
                sConnectorImplementationDescriptor.getId(), sConnectorImplementationDescriptor.getVersion(),
                sConnectorImplementationDescriptor.getDefinitionId(),
                sConnectorImplementationDescriptor.getDefinitionVersion(),
                sConnectorImplementationDescriptor.getJarDependencies());
    }

    public static List toArchivedComments(final List serverObjects) {
        final List comments = new ArrayList<>();
        for (final SAComment saComment : serverObjects) {
            final ArchivedComment comment = toArchivedComment(saComment);
            comments.add(comment);
        }
        return comments;
    }

    public static ArchivedComment toArchivedComment(final SAComment saComment) {
        final ArchivedCommentImpl commentImpl = new ArchivedCommentImpl(saComment.getContent());
        commentImpl.setId(saComment.getId());
        commentImpl.setProcessInstanceId(saComment.getProcessInstanceId());
        commentImpl.setArchiveDate(new Date(saComment.getArchiveDate()));
        commentImpl.setContent(saComment.getContent());
        commentImpl.setSourceObjectId(saComment.getSourceObjectId());
        commentImpl.setUserId(saComment.getUserId());
        commentImpl.setPostDate(new Date(saComment.getPostDate()));
        return commentImpl;
    }

    public static Operation toOperation(final SOperation operation) {
        final OperationImpl operationImpl = new OperationImpl();
        operationImpl.setRightOperand(toExpression(operation.getRightOperand()));
        operationImpl.setOperator(operation.getOperator());
        operationImpl.setType(toOperatorType(operation.getType()));
        final LeftOperandImpl leftOperand = new LeftOperandImpl();
        final SLeftOperand sLeftOperand = operation.getLeftOperand();
        leftOperand.setName(sLeftOperand.getName());
        leftOperand.setType(sLeftOperand.getType());
        operationImpl.setLeftOperand(leftOperand);
        return operationImpl;
    }

    private static OperatorType toOperatorType(final SOperatorType type) {
        OperatorType operatorType = null;
        if (SOperatorType.ASSIGNMENT.equals(type)) {
            operatorType = OperatorType.ASSIGNMENT;
        } else if (SOperatorType.JAVA_METHOD.equals(type)) {
            operatorType = OperatorType.JAVA_METHOD;
        } else if (SOperatorType.XPATH_UPDATE_QUERY.equals(type)) {
            operatorType = OperatorType.XPATH_UPDATE_QUERY;
        }
        return operatorType;
    }

    public static List toActors(final List sActors) {
        final List actors = new ArrayList<>();
        for (final SActor sActor : sActors) {
            final ActorInstance actor = toActorInstance(sActor);
            actors.add(actor);
        }
        return actors;
    }

    public static List toArchivedFlowNodeInstances(final List saFlowNodes,
            final FlowNodeStateManager flowNodeStateManager) {
        final List flowNodeInstances = new ArrayList<>();
        for (final SAFlowNodeInstance saFlowNode : saFlowNodes) {
            final ArchivedFlowNodeInstance flowNodeInstance = toArchivedFlowNodeInstance(saFlowNode,
                    flowNodeStateManager);
            flowNodeInstances.add(flowNodeInstance);
        }
        return flowNodeInstances;
    }

    public static ArchivedFlowNodeInstance toArchivedFlowNodeInstance(final SAFlowNodeInstance saFlowNode,
            final FlowNodeStateManager flowNodeStateManager) {
        ArchivedFlowNodeInstance archiveFlowNodeInstance = null;
        switch (saFlowNode.getType()) {
            case AUTOMATIC_TASK:
                archiveFlowNodeInstance = toArchivedAutomaticTaskInstance((SAAutomaticTaskInstance) saFlowNode,
                        flowNodeStateManager);
                break;
            case MANUAL_TASK:
                archiveFlowNodeInstance = toArchivedManualTaskInstance((SAManualTaskInstance) saFlowNode,
                        flowNodeStateManager);
                break;
            case USER_TASK:
                archiveFlowNodeInstance = toArchivedUserTaskInstance((SAUserTaskInstance) saFlowNode,
                        flowNodeStateManager);
                break;
            case RECEIVE_TASK:
                archiveFlowNodeInstance = toArchivedReceiveTaskInstance((SAReceiveTaskInstance) saFlowNode,
                        flowNodeStateManager);
                break;
            case SEND_TASK:
                archiveFlowNodeInstance = toArchivedSendTaskInstance((SASendTaskInstance) saFlowNode,
                        flowNodeStateManager);
                break;
            case CALL_ACTIVITY:
                archiveFlowNodeInstance = toArchivedCallActivityInstance((SACallActivityInstance) saFlowNode,
                        flowNodeStateManager);
                break;
            case LOOP_ACTIVITY:
                archiveFlowNodeInstance = toArchivedLoopActivityInstance((SALoopActivityInstance) saFlowNode,
                        flowNodeStateManager);
                break;
            case SUB_PROCESS:
                archiveFlowNodeInstance = toArchivedSubProcessActivityInstance(
                        (SASubProcessActivityInstance) saFlowNode, flowNodeStateManager);
                break;
            case GATEWAY:
                archiveFlowNodeInstance = toArchivedGatewayInstance((SAGatewayInstance) saFlowNode,
                        flowNodeStateManager);
                break;
            case MULTI_INSTANCE_ACTIVITY:
                archiveFlowNodeInstance = toArchivedMultiInstanceActivityInstance(
                        (SAMultiInstanceActivityInstance) saFlowNode, flowNodeStateManager);
                break;
            case BOUNDARY_EVENT:
            case START_EVENT:
            case INTERMEDIATE_CATCH_EVENT:
            case INTERMEDIATE_THROW_EVENT:
            case END_EVENT:
                // archiveFlowNodeInstance = toArchivedEventInstance((SAEventInstance) saFlowNode, flowNodeStateManager);
                break;
            default:
                throw new UnknownElementType(saFlowNode.getType().name());
        }
        return archiveFlowNodeInstance;
    }

    public static List toConnectorInstances(final List sConnectorInstances) {
        final ArrayList connectorInstances = new ArrayList<>(sConnectorInstances.size());
        for (final SConnectorInstance sConnectorInstance : sConnectorInstances) {
            connectorInstances.add(toConnectorInstance(sConnectorInstance));
        }
        return connectorInstances;
    }

    private static ConnectorInstance toConnectorInstance(final SConnectorInstance sConnectorInstance) {
        final ConnectorInstanceImpl connectorInstanceImpl = new ConnectorInstanceImpl(sConnectorInstance.getName(),
                sConnectorInstance.getContainerId(),
                sConnectorInstance.getContainerType(), sConnectorInstance.getConnectorId(),
                sConnectorInstance.getVersion(),
                ConnectorState.valueOf(sConnectorInstance.getState()), sConnectorInstance.getActivationEvent());
        connectorInstanceImpl.setId(sConnectorInstance.getId());
        return connectorInstanceImpl;
    }

    public static ConnectorInstanceWithFailureInfo toConnectorInstanceWithFailureInfo(
            final SConnectorInstanceWithFailureInfo sConnectorInstanceWithFailureInfo) {
        final ConnectorInstanceWithFailureInfoImpl connectorInstanceImpl = new ConnectorInstanceWithFailureInfoImpl(
                sConnectorInstanceWithFailureInfo.getName(), sConnectorInstanceWithFailureInfo.getContainerId(),
                sConnectorInstanceWithFailureInfo.getContainerType(),
                sConnectorInstanceWithFailureInfo.getConnectorId(),
                sConnectorInstanceWithFailureInfo.getVersion(),
                ConnectorState.valueOf(sConnectorInstanceWithFailureInfo.getState()),
                sConnectorInstanceWithFailureInfo.getActivationEvent(),
                sConnectorInstanceWithFailureInfo.getExceptionMessage(),
                sConnectorInstanceWithFailureInfo.getStackTrace());
        connectorInstanceImpl.setId(sConnectorInstanceWithFailureInfo.getId());
        return connectorInstanceImpl;
    }

    public static ArchivedConnectorInstance toArchivedConnectorInstance(final SAConnectorInstance sAConnectorInstance) {
        final ArchivedConnectorInstanceImpl connectorInstanceImpl = new ArchivedConnectorInstanceImpl(
                sAConnectorInstance.getName(), new Date(
                        sAConnectorInstance.getArchiveDate()),
                sAConnectorInstance.getContainerId(), sAConnectorInstance.getContainerType(),
                sAConnectorInstance.getConnectorId(), sAConnectorInstance.getVersion(),
                sAConnectorInstance.getActivationEvent(),
                ConnectorState.valueOf(sAConnectorInstance.getState()), sAConnectorInstance.getSourceObjectId());
        connectorInstanceImpl.setId(sAConnectorInstance.getId());
        return connectorInstanceImpl;
    }

    public static List toArchivedConnectorInstances(
            final List serverObjects) {
        final List commments = new ArrayList<>();
        for (final SAConnectorInstance saConnectorInstance : serverObjects) {
            final ArchivedConnectorInstance archivedConnectorInstance = toArchivedConnectorInstance(
                    saConnectorInstance);
            commments.add(archivedConnectorInstance);
        }
        return commments;
    }

    public static List toProfiles(final List sProfiles) {
        final List profiles = new ArrayList<>(sProfiles.size());
        for (final SProfile sProfile : sProfiles) {
            final Profile profile = toProfile(sProfile);
            profiles.add(profile);
        }
        return profiles;
    }

    public static Profile toProfile(final SProfile sProfile) {
        final ProfileImpl profileImpl = new ProfileImpl(sProfile.getName());
        profileImpl.setId(sProfile.getId());
        profileImpl.setDefault(sProfile.isDefault());
        profileImpl.setDescription(sProfile.getDescription());
        profileImpl.setCreationDate(new Date(sProfile.getCreationDate()));
        profileImpl.setCreatedBy(sProfile.getCreatedBy());
        profileImpl.setLastUpdateDate(new Date(sProfile.getLastUpdateDate()));
        profileImpl.setLastUpdatedBy(sProfile.getLastUpdatedBy());
        return profileImpl;
    }

    public static List toProfileMembers(final List sProfileMembers) {
        final List profiles = new ArrayList<>(sProfileMembers.size());
        for (final SProfileMember sProfileMember : sProfileMembers) {
            final ProfileMember profile = toProfileMember(sProfileMember);
            profiles.add(profile);
        }
        return profiles;
    }

    public static ProfileMember toProfileMember(final SProfileMember sProfileMember) {
        final ProfileMemberImpl profileMemberImpl = new ProfileMemberImpl();
        profileMemberImpl.setId(sProfileMember.getId());
        profileMemberImpl.setDisplayNamePart1(sProfileMember.getDisplayNamePart1());
        profileMemberImpl.setDisplayNamePart2(sProfileMember.getDisplayNamePart2());
        profileMemberImpl.setDisplayNamePart3(sProfileMember.getDisplayNamePart3());
        profileMemberImpl.setGroupId(sProfileMember.getGroupId());
        profileMemberImpl.setProfileId(sProfileMember.getProfileId());
        profileMemberImpl.setRoleId(sProfileMember.getRoleId());
        profileMemberImpl.setUserId(sProfileMember.getUserId());
        return profileMemberImpl;
    }

    public static SProfileMember constructSProfileMember(final ProfileMemberCreator creator) {
        final Map fields = creator.getFields();
        final SProfileMember.SProfileMemberBuilder newSProfileMemberBuilder = SProfileMember.builder()
                .profileId((Long) fields.get(ProfileMemberField.PROFILE_ID));
        final Long groupeId = (Long) fields.get(ProfileMemberField.GROUP_ID);
        if (groupeId != null) {
            newSProfileMemberBuilder.groupId(groupeId);
        }
        final Long roleId = (Long) fields.get(ProfileMemberField.ROLE_ID);
        if (roleId != null) {
            newSProfileMemberBuilder.roleId(roleId);
        }
        final Long userId = (Long) fields.get(ProfileMemberField.USER_ID);
        if (userId != null) {
            newSProfileMemberBuilder.userId(userId);
        }
        return newSProfileMemberBuilder.build();
    }

    public static List toFailedJobs(final List sFailedJobs) {
        final List failedJobs = new ArrayList<>(sFailedJobs.size());
        for (final SFailedJob sFailedJob : sFailedJobs) {
            failedJobs.add(toFailedJob(sFailedJob));
        }
        return failedJobs;
    }

    public static FailedJob toFailedJob(final SFailedJob sFailedJob) {
        final FailedJobImpl failedJob = new FailedJobImpl(sFailedJob.getJobDescriptorId(), sFailedJob.getJobName());
        failedJob.setDescription(sFailedJob.getDescription());
        failedJob.setLastMessage(sFailedJob.getLastMessage());
        failedJob.setNumberOfFailures(sFailedJob.getNumberOfFailures());
        failedJob.setLastUpdateDate(new Date(sFailedJob.getLastUpdateDate()));
        return failedJob;
    }

    public static CustomUserInfoDefinitionImpl convert(final SCustomUserInfoDefinition sDefinition) {
        final CustomUserInfoDefinitionImpl definition = new CustomUserInfoDefinitionImpl();
        definition.setId(sDefinition.getId());
        definition.setName(sDefinition.getName());
        definition.setDescription(sDefinition.getDescription());
        return definition;
    }

    public static CustomUserInfoValueImpl convert(final SCustomUserInfoValue sValue) {
        if (sValue == null) {
            return null;
        }
        final CustomUserInfoValueImpl value = new CustomUserInfoValueImpl();
        value.setDefinitionId(sValue.getDefinitionId());
        value.setUserId(sValue.getUserId());
        value.setValue(sValue.getValue());
        return value;
    }

    public static FormMapping toFormMapping(final SFormMapping sFormMapping,
            final FormRequiredAnalyzer formRequiredAnalyzer) {
        if (sFormMapping == null) {
            return null;
        }
        final FormMapping formMapping = new FormMapping();
        formMapping.setId(sFormMapping.getId());
        formMapping.setTask(sFormMapping.getTask());
        final SPageMapping pageMapping = sFormMapping.getPageMapping();
        if (pageMapping != null) {
            formMapping.setPageMappingKey(pageMapping.getKey());
            formMapping.setPageId(pageMapping.getPageId());
            formMapping.setPageURL(pageMapping.getUrl());
        }
        formMapping.setType(FormMappingType.getTypeFromId(sFormMapping.getType()));
        formMapping.setTarget(
                sFormMapping.getTarget() == null ? null : FormMappingTarget.valueOf(sFormMapping.getTarget()));
        formMapping.setProcessDefinitionId(sFormMapping.getProcessDefinitionId());
        final long lastUpdateDate = sFormMapping.getLastUpdateDate();
        formMapping.setLastUpdateDate(lastUpdateDate > 0 ? new Date(lastUpdateDate) : null);
        formMapping.setLastUpdatedBy(sFormMapping.getLastUpdatedBy());

        formMapping.setFormRequired(formRequiredAnalyzer.isFormRequired(sFormMapping));

        return formMapping;
    }

    public static List toFormMappings(final List serverObjects,
            final FormRequiredAnalyzer formRequiredAnalyzer) {
        final List clientObjects = new ArrayList<>(serverObjects.size());
        for (final SFormMapping serverObject : serverObjects) {
            clientObjects.add(toFormMapping(serverObject, formRequiredAnalyzer));
        }
        return clientObjects;
    }

    public static BusinessDataReference toBusinessDataReference(
            final SRefBusinessDataInstance sRefBusinessDataInstance) {
        if (sRefBusinessDataInstance == null) {
            return null;
        }
        if (sRefBusinessDataInstance instanceof SProcessMultiRefBusinessDataInstance) {
            final SProcessMultiRefBusinessDataInstance multi = (SProcessMultiRefBusinessDataInstance) sRefBusinessDataInstance;
            return new MultipleBusinessDataReferenceImpl(multi.getName(), multi.getDataClassName(), multi.getDataIds());
        }
        final SSimpleRefBusinessDataInstance simple = (SSimpleRefBusinessDataInstance) sRefBusinessDataInstance;
        return new SimpleBusinessDataReferenceImpl(simple.getName(), simple.getDataClassName(), simple.getDataId());

    }

    public static ContractDefinition toContract(final SContractDefinition sContract) {
        if (sContract == null) {
            return null;
        }
        final ContractDefinitionImpl contract = new ContractDefinitionImpl();
        for (final SInputDefinition input : sContract.getInputDefinitions()) {
            contract.addInput(toInput(input));
        }
        for (final SConstraintDefinition sConstraintDefinition : sContract.getConstraints()) {
            final ConstraintDefinitionImpl constraint = new ConstraintDefinitionImpl(sConstraintDefinition.getName(),
                    sConstraintDefinition.getExpression(),
                    sConstraintDefinition.getExplanation());
            for (final String inputName : sConstraintDefinition.getInputNames()) {
                constraint.addInputName(inputName);
            }
            contract.addConstraint(constraint);
        }
        return contract;
    }

    private static InputDefinition toInput(final SInputDefinition input) {
        final List inputDefinitions = new ArrayList<>();
        for (final SInputDefinition sInputDefinition : input.getInputDefinitions()) {
            inputDefinitions.add(toInput(sInputDefinition));
        }
        final SType type = input.getType();
        final InputDefinitionImpl inputDefinition = new InputDefinitionImpl(input.getName(),
                type == null ? null : Type.valueOf(type.toString()),
                input.getDescription(), input.isMultiple());
        inputDefinition.getInputs().addAll(inputDefinitions);
        return inputDefinition;

    }

    public static PageURL toPageURL(final SPageURL sPageURL) {
        return new PageURL(sPageURL.getUrl(), sPageURL.getPageId());
    }

    public static List toExportedCustomUserInfoDefinition(
            List customUserInfoDefinitions) {
        ArrayList customUserInfoDefinitionCreators = new ArrayList<>(
                customUserInfoDefinitions.size());
        for (SCustomUserInfoDefinition customUserInfoDefinition : customUserInfoDefinitions) {
            customUserInfoDefinitionCreators
                    .add(new ExportedCustomUserInfoDefinition(customUserInfoDefinition.getName(),
                            customUserInfoDefinition.getDescription()));
        }
        return customUserInfoDefinitionCreators;
    }

    public static Icon toIcon(SIcon icon) {
        return new IconImpl(icon.getId(), icon.getMimeType(), icon.getContent());
    }

    public static TenantResource toTenantResource(STenantResourceLight r) {
        if (r == null) {
            return TenantResource.NONE;
        }
        return new TenantResource(r.getId(), r.getName(),
                org.bonitasoft.engine.tenant.TenantResourceType.valueOf(r.getType().name()), r.getLastUpdateDate(),
                r.getLastUpdatedBy(), TenantResourceState.valueOf(r.getState().name()));
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy