@Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, AssetTag assetTag)
      throws Exception {

    long userId = portletDataContext.getUserId(assetTag.getUserUuid());

    ServiceContext serviceContext = createServiceContext(portletDataContext, assetTag);

    AssetTag existingAssetTag =
        fetchStagedModelByUuidAndGroupId(assetTag.getUuid(), portletDataContext.getScopeGroupId());

    AssetTag importedAssetTag = null;

    if (existingAssetTag == null) {
      serviceContext.setUuid(assetTag.getUuid());

      importedAssetTag =
          AssetTagLocalServiceUtil.addTag(
              userId, portletDataContext.getScopeGroupId(), assetTag.getName(), serviceContext);
    } else {
      importedAssetTag =
          AssetTagLocalServiceUtil.updateTag(
              userId, existingAssetTag.getTagId(), assetTag.getName(), serviceContext);
    }

    portletDataContext.importClassedModel(assetTag, importedAssetTag);
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, WikiNode node)
      throws Exception {

    long userId = portletDataContext.getUserId(node.getUserUuid());

    ServiceContext serviceContext = portletDataContext.createServiceContext(node);

    WikiNode importedNode = null;

    if (portletDataContext.isDataStrategyMirror()) {
      WikiNode existingNode =
          WikiNodeLocalServiceUtil.fetchNodeByUuidAndGroupId(
              node.getUuid(), portletDataContext.getScopeGroupId());

      String initialNodeName = PropsValues.WIKI_INITIAL_NODE_NAME;

      if ((existingNode == null) && initialNodeName.equals(node.getName())) {

        WikiNode initialNode =
            WikiNodeLocalServiceUtil.fetchNode(
                portletDataContext.getScopeGroupId(), node.getName());

        if (initialNode != null) {
          WikiNodeLocalServiceUtil.deleteWikiNode(initialNode);
        }
      }

      if (existingNode == null) {
        serviceContext.setUuid(node.getUuid());

        importedNode =
            WikiNodeLocalServiceUtil.addNode(
                userId, node.getName(), node.getDescription(), serviceContext);
      } else {
        importedNode =
            WikiNodeLocalServiceUtil.updateNode(
                existingNode.getNodeId(), node.getName(), node.getDescription(), serviceContext);
      }
    } else {
      String initialNodeName = PropsValues.WIKI_INITIAL_NODE_NAME;

      if (initialNodeName.equals(node.getName())) {
        WikiNode initialNode =
            WikiNodeLocalServiceUtil.fetchNode(
                portletDataContext.getScopeGroupId(), node.getName());

        if (initialNode != null) {
          WikiNodeLocalServiceUtil.deleteWikiNode(initialNode);
        }
      }

      String nodeName = getNodeName(portletDataContext, node, node.getName(), 2);

      importedNode =
          WikiNodeLocalServiceUtil.addNode(userId, nodeName, node.getDescription(), serviceContext);
    }

    portletDataContext.importClassedModel(node, importedNode);
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, PollsVote vote)
      throws Exception {

    Map<Long, Long> questionIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(PollsQuestion.class);

    long questionId = MapUtil.getLong(questionIds, vote.getQuestionId(), vote.getQuestionId());

    Map<Long, Long> choiceIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(PollsChoice.class);

    long choiceId = MapUtil.getLong(choiceIds, vote.getChoiceId(), vote.getChoiceId());

    ServiceContext serviceContext = portletDataContext.createServiceContext(vote);

    serviceContext.setCreateDate(vote.getVoteDate());

    if (portletDataContext.isDataStrategyMirror()) {
      PollsVote existingVote =
          fetchStagedModelByUuidAndGroupId(vote.getUuid(), portletDataContext.getScopeGroupId());

      if (existingVote == null) {
        serviceContext.setUuid(vote.getUuid());
      }
    }

    try {
      PollsVoteLocalServiceUtil.addVote(vote.getUserId(), questionId, choiceId, serviceContext);
    } catch (DuplicateVoteException dve) {
    }
  }
  protected void importWSRPProducer(
      PortletDataContext portletDataContext, Element wsrpProducerElement, WSRPProducer wsrpProducer)
      throws Exception {

    try {
      WSRPProducer importedWSRPProducer =
          WSRPProducerLocalServiceUtil.getWSRPProducer(wsrpProducer.getUuid());

      importedWSRPProducer.setName(wsrpProducer.getName());
      importedWSRPProducer.setVersion(wsrpProducer.getVersion());
      importedWSRPProducer.setPortletIds(wsrpProducer.getPortletIds());

      WSRPProducerLocalServiceUtil.updateWSRPProducer(importedWSRPProducer, false);
    } catch (NoSuchProducerException nspe) {
      ServiceContext serviceContext =
          portletDataContext.createServiceContext(wsrpProducerElement, wsrpProducer, _NAMESPACE);

      serviceContext.setUuid(wsrpProducer.getUuid());

      WSRPProducerLocalServiceUtil.addWSRPProducer(
          portletDataContext.getUserId(null),
          wsrpProducer.getName(),
          wsrpProducer.getVersion(),
          wsrpProducer.getPortletIds(),
          serviceContext);
    }
  }
  protected void importAssetVocabulary(
      PortletDataContext portletDataContext,
      Map<Long, Long> assetVocabularyPKs,
      Element assetVocabularyElement,
      AssetVocabulary assetVocabulary)
      throws Exception {

    long userId = portletDataContext.getUserId(assetVocabulary.getUserUuid());
    long groupId = portletDataContext.getScopeGroupId();

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);
    serviceContext.setCreateDate(assetVocabulary.getCreateDate());
    serviceContext.setModifiedDate(assetVocabulary.getModifiedDate());
    serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId());

    AssetVocabulary importedAssetVocabulary = null;

    AssetVocabulary existingAssetVocabulary =
        AssetVocabularyUtil.fetchByG_N(groupId, assetVocabulary.getName());

    if (existingAssetVocabulary == null) {
      Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(portletDataContext.getCompanyId());

      existingAssetVocabulary =
          AssetVocabularyUtil.fetchByG_N(companyGroup.getGroupId(), assetVocabulary.getName());
    }

    if (existingAssetVocabulary == null) {
      serviceContext.setUuid(assetVocabulary.getUuid());

      importedAssetVocabulary =
          AssetVocabularyLocalServiceUtil.addVocabulary(
              userId,
              assetVocabulary.getTitle(),
              getAssetVocabularyTitleMap(assetVocabulary),
              assetVocabulary.getDescriptionMap(),
              assetVocabulary.getSettings(),
              serviceContext);
    } else {
      importedAssetVocabulary =
          AssetVocabularyLocalServiceUtil.updateVocabulary(
              existingAssetVocabulary.getVocabularyId(),
              assetVocabulary.getTitle(),
              getAssetVocabularyTitleMap(assetVocabulary),
              assetVocabulary.getDescriptionMap(),
              assetVocabulary.getSettings(),
              serviceContext);
    }

    assetVocabularyPKs.put(
        assetVocabulary.getVocabularyId(), importedAssetVocabulary.getVocabularyId());

    portletDataContext.importPermissions(
        AssetVocabulary.class,
        assetVocabulary.getVocabularyId(),
        importedAssetVocabulary.getVocabularyId());
  }
  protected WSRPConsumer importWSRPConsumer(
      PortletDataContext portletDataContext, Element wsrpConsumerElement, WSRPConsumer wsrpConsumer)
      throws Exception {

    WSRPConsumer importedWSRPConsumer = null;

    try {
      importedWSRPConsumer = WSRPConsumerLocalServiceUtil.getWSRPConsumer(wsrpConsumer.getUuid());

      importedWSRPConsumer.setName(wsrpConsumer.getName());
      importedWSRPConsumer.setUrl(wsrpConsumer.getUrl());
      importedWSRPConsumer.setWsdl(wsrpConsumer.getWsdl());
      importedWSRPConsumer.setForwardCookies(wsrpConsumer.getForwardCookies());

      WSRPConsumerLocalServiceUtil.updateWSRPConsumer(importedWSRPConsumer, false);
    } catch (NoSuchConsumerException nsce) {
      ServiceContext serviceContext =
          portletDataContext.createServiceContext(wsrpConsumerElement, wsrpConsumer, _NAMESPACE);

      serviceContext.setUuid(wsrpConsumer.getUuid());

      importedWSRPConsumer =
          WSRPConsumerLocalServiceUtil.addWSRPConsumer(
              portletDataContext.getCompanyId(),
              null,
              wsrpConsumer.getName(),
              wsrpConsumer.getUrl(),
              wsrpConsumer.getForwardCookies(),
              null,
              serviceContext);
    }

    return importedWSRPConsumer;
  }
  protected void importWSRPConsumerPortlet(
      PortletDataContext portletDataContext,
      WSRPConsumer wsrpConsumer,
      Element wsrpConsumerPortletElement,
      WSRPConsumerPortlet wsrpConsumerPortlet)
      throws Exception {

    try {
      WSRPConsumerPortlet importedWSRPConsumerPortlet =
          WSRPConsumerPortletLocalServiceUtil.getWSRPConsumerPortlet(wsrpConsumerPortlet.getUuid());

      importedWSRPConsumerPortlet.setWsrpConsumerId(wsrpConsumer.getWsrpConsumerId());
      importedWSRPConsumerPortlet.setName(wsrpConsumerPortlet.getName());
      importedWSRPConsumerPortlet.setPortletHandle(wsrpConsumerPortlet.getPortletHandle());

      WSRPConsumerPortletLocalServiceUtil.updateWSRPConsumerPortlet(
          importedWSRPConsumerPortlet, false);
    } catch (NoSuchConsumerPortletException nscpe) {
      ServiceContext serviceContext =
          portletDataContext.createServiceContext(
              wsrpConsumerPortletElement, wsrpConsumerPortlet, _NAMESPACE);

      serviceContext.setUuid(wsrpConsumerPortlet.getUuid());

      WSRPConsumerPortletLocalServiceUtil.addWSRPConsumerPortlet(
          wsrpConsumer.getUuid(),
          wsrpConsumerPortlet.getName(),
          wsrpConsumerPortlet.getPortletHandle(),
          null,
          serviceContext);
    }
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, Website website)
      throws Exception {

    long userId = portletDataContext.getUserId(website.getUserUuid());

    ServiceContext serviceContext = portletDataContext.createServiceContext(website);

    Website existingWebsite =
        _websiteLocalService.fetchWebsiteByUuidAndCompanyId(
            website.getUuid(), portletDataContext.getCompanyGroupId());

    Website importedWebsite = null;

    if (existingWebsite == null) {
      serviceContext.setUuid(website.getUuid());

      importedWebsite =
          _websiteLocalService.addWebsite(
              userId,
              website.getClassName(),
              website.getClassPK(),
              website.getUrl(),
              website.getTypeId(),
              website.isPrimary(),
              serviceContext);
    } else {
      importedWebsite =
          _websiteLocalService.updateWebsite(
              existingWebsite.getWebsiteId(), website.getUrl(),
              website.getTypeId(), website.isPrimary());
    }

    portletDataContext.importClassedModel(website, importedWebsite);
  }
  public MDRRuleGroup copyRuleGroup(
      MDRRuleGroup ruleGroup, long groupId, ServiceContext serviceContext)
      throws PortalException, SystemException {

    Group group = groupPersistence.findByPrimaryKey(groupId);

    Map<Locale, String> nameMap = ruleGroup.getNameMap();

    for (Map.Entry<Locale, String> entry : nameMap.entrySet()) {
      Locale locale = entry.getKey();
      String name = entry.getValue();

      if (Validator.isNull(name)) {
        continue;
      }

      String postfix =
          LanguageUtil.get(locale, PropsValues.MOBILE_DEVICE_RULES_RULE_GROUP_COPY_POSTFIX);

      nameMap.put(locale, name.concat(StringPool.SPACE).concat(postfix));
    }

    MDRRuleGroup newRuleGroup =
        addRuleGroup(group.getGroupId(), nameMap, ruleGroup.getDescriptionMap(), serviceContext);

    List<MDRRule> rules = mdrRulePersistence.findByRuleGroupId(ruleGroup.getRuleGroupId());

    for (MDRRule rule : rules) {
      serviceContext.setUuid(PortalUUIDUtil.generate());

      mdrRuleLocalService.copyRule(rule, newRuleGroup.getRuleGroupId(), serviceContext);
    }

    return newRuleGroup;
  }
  @Override
  protected void doImportStagedModel(
      PortletDataContext portletDataContext, WSRPConsumerPortlet wsrpConsumerPortlet)
      throws Exception {

    StagedModelDataHandlerUtil.importReferenceStagedModel(
        portletDataContext,
        wsrpConsumerPortlet,
        WSRPConsumer.class,
        wsrpConsumerPortlet.getWsrpConsumerId());

    Map<Long, Long> wsrpConsumerIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(WSRPConsumer.class);

    long wsrpConsumerId =
        MapUtil.getLong(
            wsrpConsumerIds,
            wsrpConsumerPortlet.getWsrpConsumerId(),
            wsrpConsumerPortlet.getWsrpConsumerId());

    ServiceContext serviceContext = portletDataContext.createServiceContext(wsrpConsumerPortlet);

    WSRPConsumerPortlet importedWSRPConsumerPortlet = null;

    if (portletDataContext.isDataStrategyMirror()) {
      WSRPConsumerPortlet existingWSRPConsumerPortlet =
          WSRPConsumerPortletLocalServiceUtil.fetchWSRPConsumerPortletByUuidAndCompanyId(
              wsrpConsumerPortlet.getUuid(), portletDataContext.getCompanyId());

      if (existingWSRPConsumerPortlet == null) {
        serviceContext.setUuid(wsrpConsumerPortlet.getUuid());

        importedWSRPConsumerPortlet =
            WSRPConsumerPortletLocalServiceUtil.addWSRPConsumerPortlet(
                wsrpConsumerId,
                wsrpConsumerPortlet.getName(),
                wsrpConsumerPortlet.getPortletHandle(),
                serviceContext);
      } else {
        existingWSRPConsumerPortlet.setWsrpConsumerId(wsrpConsumerId);
        existingWSRPConsumerPortlet.setName(wsrpConsumerPortlet.getName());
        existingWSRPConsumerPortlet.setPortletHandle(wsrpConsumerPortlet.getPortletHandle());

        importedWSRPConsumerPortlet =
            WSRPConsumerPortletLocalServiceUtil.updateWSRPConsumerPortlet(
                existingWSRPConsumerPortlet);
      }
    } else {
      importedWSRPConsumerPortlet =
          WSRPConsumerPortletLocalServiceUtil.addWSRPConsumerPortlet(
              wsrpConsumerId,
              wsrpConsumerPortlet.getName(),
              wsrpConsumerPortlet.getPortletHandle(),
              serviceContext);
    }

    portletDataContext.importClassedModel(wsrpConsumerPortlet, importedWSRPConsumerPortlet);
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, MDRAction action)
      throws Exception {

    Map<Long, Long> ruleGroupInstanceIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(MDRRuleGroupInstance.class);

    long ruleGroupInstanceId =
        MapUtil.getLong(
            ruleGroupInstanceIds, action.getRuleGroupInstanceId(), action.getRuleGroupInstanceId());

    ServiceContext serviceContext = portletDataContext.createServiceContext(action);

    serviceContext.setUserId(portletDataContext.getUserId(action.getUserUuid()));

    Element element = portletDataContext.getImportDataStagedModelElement(action);

    validateLayout(element, action);

    MDRAction importedAction = null;

    if (portletDataContext.isDataStrategyMirror()) {
      MDRAction existingAction =
          fetchStagedModelByUuidAndGroupId(action.getUuid(), portletDataContext.getScopeGroupId());

      if (existingAction == null) {
        serviceContext.setUuid(action.getUuid());

        importedAction =
            _mdrActionLocalService.addAction(
                ruleGroupInstanceId,
                action.getNameMap(),
                action.getDescriptionMap(),
                action.getType(),
                action.getTypeSettingsProperties(),
                serviceContext);
      } else {
        importedAction =
            _mdrActionLocalService.updateAction(
                existingAction.getActionId(), action.getNameMap(),
                action.getDescriptionMap(), action.getType(),
                action.getTypeSettingsProperties(), serviceContext);
      }
    } else {
      importedAction =
          _mdrActionLocalService.addAction(
              ruleGroupInstanceId,
              action.getNameMap(),
              action.getDescriptionMap(),
              action.getType(),
              action.getTypeSettingsProperties(),
              serviceContext);
    }

    portletDataContext.importClassedModel(action, importedAction);
  }
  @Override
  protected void doImportStagedModel(
      PortletDataContext portletDataContext, LayoutPrototype layoutPrototype) throws Exception {

    long userId = portletDataContext.getUserId(layoutPrototype.getUserUuid());

    ServiceContext serviceContext =
        portletDataContext.createServiceContext(
            layoutPrototype, LayoutPrototypePortletDataHandler.NAMESPACE);

    serviceContext.setAttribute("addDefaultLayout", false);

    LayoutPrototype importedLayoutPrototype = null;

    if (portletDataContext.isDataStrategyMirror()) {
      LayoutPrototype existingLayoutPrototype =
          LayoutPrototypeLocalServiceUtil.fetchLayoutPrototypeByUuidAndCompanyId(
              layoutPrototype.getUuid(), portletDataContext.getCompanyId());

      if (existingLayoutPrototype == null) {
        serviceContext.setUuid(layoutPrototype.getUuid());

        importedLayoutPrototype =
            LayoutPrototypeLocalServiceUtil.addLayoutPrototype(
                userId,
                portletDataContext.getCompanyId(),
                layoutPrototype.getNameMap(),
                layoutPrototype.getDescription(),
                layoutPrototype.isActive(),
                serviceContext);
      } else {
        importedLayoutPrototype =
            LayoutPrototypeLocalServiceUtil.updateLayoutPrototype(
                existingLayoutPrototype.getLayoutPrototypeId(),
                layoutPrototype.getNameMap(),
                layoutPrototype.getDescription(),
                layoutPrototype.isActive(),
                serviceContext);
      }
    } else {
      importedLayoutPrototype =
          LayoutPrototypeLocalServiceUtil.addLayoutPrototype(
              userId,
              portletDataContext.getCompanyId(),
              layoutPrototype.getNameMap(),
              layoutPrototype.getDescription(),
              layoutPrototype.isActive(),
              serviceContext);
    }

    importLayouts(portletDataContext, layoutPrototype, importedLayoutPrototype.getGroupId());

    portletDataContext.importClassedModel(
        layoutPrototype, importedLayoutPrototype, LayoutPrototypePortletDataHandler.NAMESPACE);
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, Address address)
      throws Exception {

    long userId = portletDataContext.getUserId(address.getUserUuid());

    ServiceContext serviceContext = portletDataContext.createServiceContext(address);

    Address existingAddress =
        AddressLocalServiceUtil.fetchAddressByUuidAndCompanyId(
            address.getUuid(), portletDataContext.getCompanyId());

    Address importedAddress = null;

    if (existingAddress == null) {
      serviceContext.setUuid(address.getUuid());

      importedAddress =
          AddressLocalServiceUtil.addAddress(
              userId,
              address.getClassName(),
              address.getClassPK(),
              address.getStreet1(),
              address.getStreet2(),
              address.getStreet3(),
              address.getCity(),
              address.getZip(),
              address.getRegionId(),
              address.getCountryId(),
              address.getTypeId(),
              address.getMailing(),
              address.isPrimary(),
              serviceContext);
    } else {
      importedAddress =
          AddressLocalServiceUtil.updateAddress(
              existingAddress.getAddressId(),
              address.getStreet1(),
              address.getStreet2(),
              address.getStreet3(),
              address.getCity(),
              address.getZip(),
              address.getRegionId(),
              address.getCountryId(),
              address.getTypeId(),
              address.getMailing(),
              address.isPrimary());
    }

    portletDataContext.importClassedModel(address, importedAddress);
  }
  @Override
  protected void doImportStagedModel(
      PortletDataContext portletDataContext, RepositoryEntry repositoryEntry) throws Exception {

    long userId = portletDataContext.getUserId(repositoryEntry.getUserUuid());

    Map<Long, Long> repositoryIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(Repository.class);

    long repositoryId =
        MapUtil.getLong(
            repositoryIds, repositoryEntry.getRepositoryId(), repositoryEntry.getRepositoryId());

    ServiceContext serviceContext = portletDataContext.createServiceContext(repositoryEntry);

    RepositoryEntry importedRepositoryEntry = null;

    if (portletDataContext.isDataStrategyMirror()) {
      RepositoryEntry existingRepositoryEntry =
          fetchStagedModelByUuidAndGroupId(
              repositoryEntry.getUuid(), portletDataContext.getScopeGroupId());

      if (existingRepositoryEntry == null) {
        serviceContext.setUuid(repositoryEntry.getUuid());

        importedRepositoryEntry =
            RepositoryEntryLocalServiceUtil.addRepositoryEntry(
                userId,
                portletDataContext.getScopeGroupId(),
                repositoryId,
                repositoryEntry.getMappedId(),
                serviceContext);
      } else {
        importedRepositoryEntry =
            RepositoryEntryLocalServiceUtil.updateRepositoryEntry(
                existingRepositoryEntry.getRepositoryEntryId(), repositoryEntry.getMappedId());
      }
    } else {
      importedRepositoryEntry =
          RepositoryEntryLocalServiceUtil.addRepositoryEntry(
              userId,
              portletDataContext.getScopeGroupId(),
              repositoryId,
              repositoryEntry.getMappedId(),
              serviceContext);
    }

    portletDataContext.importClassedModel(repositoryEntry, importedRepositoryEntry);
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, MDRRuleGroup ruleGroup)
      throws Exception {

    long userId = portletDataContext.getUserId(ruleGroup.getUserUuid());

    ServiceContext serviceContext = portletDataContext.createServiceContext(ruleGroup);

    serviceContext.setUserId(userId);

    MDRRuleGroup importedRuleGroup = null;

    if (portletDataContext.isDataStrategyMirror()) {
      MDRRuleGroup existingRuleGroup =
          fetchStagedModelByUuidAndGroupId(
              ruleGroup.getUuid(), portletDataContext.getScopeGroupId());

      if (existingRuleGroup == null) {
        serviceContext.setUuid(ruleGroup.getUuid());

        importedRuleGroup =
            MDRRuleGroupLocalServiceUtil.addRuleGroup(
                portletDataContext.getScopeGroupId(),
                ruleGroup.getNameMap(),
                ruleGroup.getDescriptionMap(),
                serviceContext);
      } else {
        importedRuleGroup =
            MDRRuleGroupLocalServiceUtil.updateRuleGroup(
                existingRuleGroup.getRuleGroupId(),
                ruleGroup.getNameMap(),
                ruleGroup.getDescriptionMap(),
                serviceContext);
      }
    } else {
      importedRuleGroup =
          MDRRuleGroupLocalServiceUtil.addRuleGroup(
              portletDataContext.getScopeGroupId(),
              ruleGroup.getNameMap(),
              ruleGroup.getDescriptionMap(),
              serviceContext);
    }

    portletDataContext.importClassedModel(ruleGroup, importedRuleGroup);
  }
  /**
   * Returns a new service context object identical to this service context object.
   *
   * @return a new service context object
   */
  @Override
  public Object clone() {
    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(isAddGroupPermissions());
    serviceContext.setAddGuestPermissions(isAddGuestPermissions());
    serviceContext.setAssetCategoryIds(getAssetCategoryIds());
    serviceContext.setAssetEntryVisible(isAssetEntryVisible());
    serviceContext.setAssetLinkEntryIds(getAssetLinkEntryIds());
    serviceContext.setAssetTagNames(getAssetTagNames());
    serviceContext.setAttributes(getAttributes());
    serviceContext.setCommand(getCommand());
    serviceContext.setCompanyId(getCompanyId());
    serviceContext.setCreateDate(getCreateDate());
    serviceContext.setCurrentURL(getCurrentURL());
    serviceContext.setExpandoBridgeAttributes(getExpandoBridgeAttributes());
    serviceContext.setFailOnPortalException(isFailOnPortalException());
    serviceContext.setGroupPermissions(getGroupPermissions());
    serviceContext.setGuestPermissions(getGuestPermissions());
    serviceContext.setHeaders(getHeaders());
    serviceContext.setIndexingEnabled(isIndexingEnabled());
    serviceContext.setLanguageId(getLanguageId());
    serviceContext.setLayoutFullURL(getLayoutFullURL());
    serviceContext.setLayoutURL(getLayoutURL());
    serviceContext.setModifiedDate(getModifiedDate());
    serviceContext.setPathFriendlyURLPrivateGroup(getPathFriendlyURLPrivateGroup());
    serviceContext.setPathFriendlyURLPrivateUser(getPathFriendlyURLPrivateUser());
    serviceContext.setPathFriendlyURLPublic(getPathFriendlyURLPublic());
    serviceContext.setPathMain(getPathMain());
    serviceContext.setPlid(getPlid());
    serviceContext.setPortalURL(getPortalURL());
    serviceContext.setPortletPreferencesIds(getPortletPreferencesIds());
    serviceContext.setRemoteAddr(getRemoteAddr());
    serviceContext.setRemoteHost(getRemoteHost());
    serviceContext.setRequest(getRequest());
    serviceContext.setScopeGroupId(getScopeGroupId());
    serviceContext.setSignedIn(isSignedIn());
    serviceContext.setUserDisplayURL(getUserDisplayURL());
    serviceContext.setUserId(getUserId());
    serviceContext.setUuid(getUuid());
    serviceContext.setWorkflowAction(getWorkflowAction());

    return serviceContext;
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, UserGroup userGroup)
      throws Exception {

    long userId = portletDataContext.getUserId(userGroup.getUserUuid());

    ServiceContext serviceContext = portletDataContext.createServiceContext(userGroup);

    UserGroup existingUserGroup =
        fetchStagedModelByUuidAndGroupId(userGroup.getUuid(), portletDataContext.getGroupId());

    if (existingUserGroup == null) {
      existingUserGroup =
          _userGroupLocalService.fetchUserGroup(
              portletDataContext.getCompanyId(), userGroup.getName());
    }

    UserGroup importedUserGroup = null;

    if (existingUserGroup == null) {
      serviceContext.setUuid(userGroup.getUuid());

      importedUserGroup =
          _userGroupLocalService.addUserGroup(
              userId,
              portletDataContext.getCompanyId(),
              userGroup.getName(),
              userGroup.getDescription(),
              serviceContext);
    } else {
      importedUserGroup =
          _userGroupLocalService.updateUserGroup(
              portletDataContext.getCompanyId(),
              existingUserGroup.getUserGroupId(),
              userGroup.getName(),
              userGroup.getDescription(),
              serviceContext);
    }

    portletDataContext.importClassedModel(userGroup, importedUserGroup);
  }
  protected void importLayoutSetPrototype(
      PortletDataContext portletDataContext,
      User user,
      String layoutSetPrototypeUuid,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    String path = getLayoutSetPrototype(portletDataContext, layoutSetPrototypeUuid);

    LayoutSetPrototype layoutSetPrototype = null;

    try {
      layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuid(layoutSetPrototypeUuid);
    } catch (NoSuchLayoutSetPrototypeException nslspe) {
    }

    if (layoutSetPrototype == null) {
      layoutSetPrototype =
          (LayoutSetPrototype) portletDataContext.getZipEntryAsObject(path.concat(".xml"));

      serviceContext.setUuid(layoutSetPrototypeUuid);

      layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.addLayoutSetPrototype(
              user.getUserId(),
              user.getCompanyId(),
              layoutSetPrototype.getNameMap(),
              layoutSetPrototype.getDescription(),
              layoutSetPrototype.getActive(),
              true,
              serviceContext);
    }

    InputStream inputStream = portletDataContext.getZipEntryAsInputStream(path.concat(".lar"));

    SitesUtil.importLayoutSetPrototype(layoutSetPrototype, inputStream, serviceContext);
  }
  @Override
  public void setUp() throws Exception {
    super.setUp();

    layout = LayoutTestUtil.addLayout(stagingGroup.getGroupId(), ServiceTestUtil.randomString());

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setUuid(layout.getUuid());

    LayoutLocalServiceUtil.addLayout(
        TestPropsValues.getUserId(),
        liveGroup.getGroupId(),
        layout.getPrivateLayout(),
        layout.getParentLayoutId(),
        layout.getName(),
        layout.getTitle(),
        layout.getDescription(),
        layout.getType(),
        layout.getHidden(),
        layout.getFriendlyURL(),
        serviceContext);
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, KBTemplate kbTemplate)
      throws Exception {

    long userId = portletDataContext.getUserId(kbTemplate.getUserUuid());

    ServiceContext serviceContext = portletDataContext.createServiceContext(kbTemplate);

    KBTemplate importedKBTemplate = null;

    if (portletDataContext.isDataStrategyMirror()) {
      KBTemplate existingKBTemplate =
          fetchStagedModelByUuidAndGroupId(
              kbTemplate.getUuid(), portletDataContext.getScopeGroupId());

      if (existingKBTemplate == null) {
        serviceContext.setUuid(kbTemplate.getUuid());

        importedKBTemplate =
            KBTemplateLocalServiceUtil.addKBTemplate(
                userId, kbTemplate.getTitle(), kbTemplate.getContent(), serviceContext);
      } else {
        importedKBTemplate =
            KBTemplateLocalServiceUtil.updateKBTemplate(
                existingKBTemplate.getKbTemplateId(),
                kbTemplate.getTitle(),
                kbTemplate.getContent(),
                serviceContext);
      }
    } else {
      importedKBTemplate =
          KBTemplateLocalServiceUtil.addKBTemplate(
              userId, kbTemplate.getTitle(), kbTemplate.getContent(), serviceContext);
    }

    portletDataContext.importClassedModel(kbTemplate, importedKBTemplate);
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, MBMessage message)
      throws Exception {

    long userId = portletDataContext.getUserId(message.getUserUuid());

    String userName = message.getUserName();

    Map<Long, Long> categoryIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(MBCategory.class);

    long parentCategoryId =
        MapUtil.getLong(categoryIds, message.getCategoryId(), message.getCategoryId());

    Map<Long, Long> threadIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(MBThread.class);

    long threadId = MapUtil.getLong(threadIds, message.getThreadId(), 0);

    Map<Long, Long> messageIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(MBMessage.class);

    long parentMessageId =
        MapUtil.getLong(messageIds, message.getParentMessageId(), message.getParentMessageId());

    Element element = portletDataContext.getImportDataStagedModelElement(message);

    List<ObjectValuePair<String, InputStream>> inputStreamOVPs =
        getAttachments(portletDataContext, element, message);

    try {
      ServiceContext serviceContext =
          portletDataContext.createServiceContext(message, MBPortletDataHandler.NAMESPACE);

      if (message.getStatus() != WorkflowConstants.STATUS_APPROVED) {
        serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);
      }

      if ((parentCategoryId != MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID)
          && (parentCategoryId != MBCategoryConstants.DISCUSSION_CATEGORY_ID)
          && (parentCategoryId == message.getCategoryId())) {

        String categoryPath =
            ExportImportPathUtil.getModelPath(
                portletDataContext, MBCategory.class.getName(), parentCategoryId);

        MBCategory category = (MBCategory) portletDataContext.getZipEntryAsObject(categoryPath);

        StagedModelDataHandlerUtil.importStagedModel(portletDataContext, category);

        parentCategoryId =
            MapUtil.getLong(categoryIds, message.getCategoryId(), message.getCategoryId());
      }

      MBMessage importedMessage = null;

      if (portletDataContext.isDataStrategyMirror()) {
        MBMessage existingMessage =
            MBMessageUtil.fetchByUUID_G(message.getUuid(), portletDataContext.getScopeGroupId());

        if (existingMessage == null) {
          serviceContext.setUuid(message.getUuid());

          importedMessage =
              MBMessageLocalServiceUtil.addMessage(
                  userId,
                  userName,
                  portletDataContext.getScopeGroupId(),
                  parentCategoryId,
                  threadId,
                  parentMessageId,
                  message.getSubject(),
                  message.getBody(),
                  message.getFormat(),
                  inputStreamOVPs,
                  message.getAnonymous(),
                  message.getPriority(),
                  message.getAllowPingbacks(),
                  serviceContext);
        } else {
          importedMessage =
              MBMessageLocalServiceUtil.updateMessage(
                  userId,
                  existingMessage.getMessageId(),
                  message.getSubject(),
                  message.getBody(),
                  inputStreamOVPs,
                  new ArrayList<String>(),
                  message.getPriority(),
                  message.getAllowPingbacks(),
                  serviceContext);
        }
      } else {
        importedMessage =
            MBMessageLocalServiceUtil.addMessage(
                userId,
                userName,
                portletDataContext.getScopeGroupId(),
                parentCategoryId,
                threadId,
                parentMessageId,
                message.getSubject(),
                message.getBody(),
                message.getFormat(),
                inputStreamOVPs,
                message.getAnonymous(),
                message.getPriority(),
                message.getAllowPingbacks(),
                serviceContext);
      }

      importedMessage.setAnswer(message.getAnswer());

      if (importedMessage.isRoot()) {
        MBThreadLocalServiceUtil.updateQuestion(
            importedMessage.getThreadId(),
            GetterUtil.getBoolean(element.attributeValue("question")));
      }

      threadIds.put(message.getThreadId(), importedMessage.getThreadId());

      portletDataContext.importClassedModel(
          message, importedMessage, MBPortletDataHandler.NAMESPACE);
    } finally {
      for (ObjectValuePair<String, InputStream> inputStreamOVP : inputStreamOVPs) {

        InputStream inputStream = inputStreamOVP.getValue();

        StreamUtil.cleanUp(inputStream);
      }
    }
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, Calendar calendar)
      throws Exception {

    long userId = portletDataContext.getUserId(calendar.getUserUuid());

    Map<Long, Long> calendarResourceIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(CalendarResource.class);

    long calendarResourceId =
        MapUtil.getLong(
            calendarResourceIds,
            calendar.getCalendarResourceId(),
            calendar.getCalendarResourceId());

    Map<Locale, String> calendarNameMap = getCalendarNameMap(portletDataContext, calendar);

    ServiceContext serviceContext = portletDataContext.createServiceContext(calendar);

    Calendar importedCalendar = null;

    if (portletDataContext.isDataStrategyMirror()) {
      Calendar existingCalendar =
          fetchStagedModelByUuidAndGroupId(
              calendar.getUuid(), portletDataContext.getScopeGroupId());

      if (existingCalendar == null) {
        serviceContext.setUuid(calendar.getUuid());

        importedCalendar =
            CalendarLocalServiceUtil.addCalendar(
                userId,
                portletDataContext.getScopeGroupId(),
                calendarResourceId,
                calendarNameMap,
                calendar.getDescriptionMap(),
                calendar.getTimeZoneId(),
                calendar.getColor(),
                calendar.isDefaultCalendar(),
                calendar.isEnableComments(),
                calendar.isEnableRatings(),
                serviceContext);
      } else {
        importedCalendar =
            CalendarLocalServiceUtil.updateCalendar(
                existingCalendar.getCalendarId(),
                calendar.getNameMap(),
                calendar.getDescriptionMap(),
                calendar.getTimeZoneId(),
                calendar.getColor(),
                calendar.isDefaultCalendar(),
                calendar.isEnableComments(),
                calendar.isEnableRatings(),
                serviceContext);
      }
    } else {
      importedCalendar =
          CalendarLocalServiceUtil.addCalendar(
              userId,
              portletDataContext.getScopeGroupId(),
              calendarResourceId,
              calendarNameMap,
              calendar.getDescriptionMap(),
              calendar.getTimeZoneId(),
              calendar.getColor(),
              calendar.isDefaultCalendar(),
              calendar.isEnableComments(),
              calendar.isEnableRatings(),
              serviceContext);
    }

    portletDataContext.importClassedModel(calendar, importedCalendar);
  }
  @Override
  protected void doImportStagedModel(
      PortletDataContext portletDataContext,
      CalendarNotificationTemplate calendarNotificationTemplate)
      throws Exception {

    long userId = portletDataContext.getUserId(calendarNotificationTemplate.getUserUuid());

    Map<Long, Long> calendarIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(Calendar.class);

    long calendarId =
        MapUtil.getLong(
            calendarIds,
            calendarNotificationTemplate.getCalendarId(),
            calendarNotificationTemplate.getCalendarId());

    NotificationType notificationType =
        NotificationType.parse(calendarNotificationTemplate.getNotificationType());
    NotificationTemplateType notificationTemplateType =
        NotificationTemplateType.parse(calendarNotificationTemplate.getNotificationTemplateType());

    ServiceContext serviceContext =
        portletDataContext.createServiceContext(calendarNotificationTemplate);

    CalendarNotificationTemplate importedCalendarNotificationTemplate = null;

    String body =
        ExportImportHelperUtil.replaceImportContentReferences(
            portletDataContext,
            calendarNotificationTemplate,
            calendarNotificationTemplate.getBody());

    if (portletDataContext.isDataStrategyMirror()) {
      CalendarNotificationTemplate existingCalendarNotificationTemplate =
          fetchStagedModelByUuidAndGroupId(
              calendarNotificationTemplate.getUuid(), portletDataContext.getScopeGroupId());

      if (existingCalendarNotificationTemplate == null) {
        serviceContext.setUuid(calendarNotificationTemplate.getUuid());

        importedCalendarNotificationTemplate =
            CalendarNotificationTemplateLocalServiceUtil.addCalendarNotificationTemplate(
                userId,
                calendarId,
                notificationType,
                calendarNotificationTemplate.getNotificationTypeSettings(),
                notificationTemplateType,
                calendarNotificationTemplate.getSubject(),
                body,
                serviceContext);
      } else {
        importedCalendarNotificationTemplate =
            CalendarNotificationTemplateLocalServiceUtil.updateCalendarNotificationTemplate(
                existingCalendarNotificationTemplate.getCalendarNotificationTemplateId(),
                calendarNotificationTemplate.getNotificationTypeSettings(),
                calendarNotificationTemplate.getSubject(),
                body,
                serviceContext);
      }
    } else {
      importedCalendarNotificationTemplate =
          CalendarNotificationTemplateLocalServiceUtil.addCalendarNotificationTemplate(
              userId,
              calendarId,
              notificationType,
              calendarNotificationTemplate.getNotificationTypeSettings(),
              notificationTemplateType,
              calendarNotificationTemplate.getSubject(),
              body,
              serviceContext);
    }

    portletDataContext.importClassedModel(
        calendarNotificationTemplate, importedCalendarNotificationTemplate);
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, BlogsEntry entry)
      throws Exception {

    long userId = portletDataContext.getUserId(entry.getUserUuid());

    Element entryElement = portletDataContext.getImportDataStagedModelElement(entry);

    String content =
        _blogsEntryExportImportContentProcessor.replaceImportContentReferences(
            portletDataContext, entry, entry.getContent());

    entry.setContent(content);

    Calendar displayDateCal = CalendarFactoryUtil.getCalendar();

    displayDateCal.setTime(entry.getDisplayDate());

    int displayDateMonth = displayDateCal.get(Calendar.MONTH);
    int displayDateDay = displayDateCal.get(Calendar.DATE);
    int displayDateYear = displayDateCal.get(Calendar.YEAR);
    int displayDateHour = displayDateCal.get(Calendar.HOUR);
    int displayDateMinute = displayDateCal.get(Calendar.MINUTE);

    if (displayDateCal.get(Calendar.AM_PM) == Calendar.PM) {
      displayDateHour += 12;
    }

    boolean allowPingbacks = entry.isAllowPingbacks();
    boolean allowTrackbacks = entry.isAllowTrackbacks();
    String[] trackbacks = StringUtil.split(entry.getTrackbacks());

    ServiceContext serviceContext = portletDataContext.createServiceContext(entry);

    BlogsEntry importedEntry = null;

    if (portletDataContext.isDataStrategyMirror()) {
      serviceContext.setAttribute("urlTitle", entry.getUrlTitle());

      BlogsEntry existingEntry =
          fetchStagedModelByUuidAndGroupId(entry.getUuid(), portletDataContext.getScopeGroupId());

      if (existingEntry == null) {
        serviceContext.setUuid(entry.getUuid());

        importedEntry =
            _blogsEntryLocalService.addEntry(
                userId,
                entry.getTitle(),
                entry.getSubtitle(),
                entry.getDescription(),
                entry.getContent(),
                displayDateMonth,
                displayDateDay,
                displayDateYear,
                displayDateHour,
                displayDateMinute,
                allowPingbacks,
                allowTrackbacks,
                trackbacks,
                entry.getCoverImageCaption(),
                null,
                null,
                serviceContext);
      } else {
        importedEntry =
            _blogsEntryLocalService.updateEntry(
                userId,
                existingEntry.getEntryId(),
                entry.getTitle(),
                entry.getSubtitle(),
                entry.getDescription(),
                entry.getContent(),
                displayDateMonth,
                displayDateDay,
                displayDateYear,
                displayDateHour,
                displayDateMinute,
                allowPingbacks,
                allowTrackbacks,
                trackbacks,
                entry.getCoverImageCaption(),
                new ImageSelector(),
                new ImageSelector(),
                serviceContext);
      }
    } else {
      importedEntry =
          _blogsEntryLocalService.addEntry(
              userId,
              entry.getTitle(),
              entry.getSubtitle(),
              entry.getDescription(),
              entry.getContent(),
              displayDateMonth,
              displayDateDay,
              displayDateYear,
              displayDateHour,
              displayDateMinute,
              allowPingbacks,
              allowTrackbacks,
              trackbacks,
              entry.getCoverImageCaption(),
              null,
              null,
              serviceContext);
    }

    if ((entry.getCoverImageFileEntryId() == 0)
        && Validator.isNull(entry.getCoverImageURL())
        && (entry.getSmallImageFileEntryId() == 0)
        && Validator.isNull(entry.getSmallImageURL())
        && !entry.isSmallImage()) {

      portletDataContext.importClassedModel(entry, importedEntry);

      return;
    }

    // Cover image

    ImageSelector coverImageSelector = null;

    List<Element> attachmentElements =
        portletDataContext.getReferenceDataElements(
            entry, DLFileEntry.class, PortletDataContext.REFERENCE_TYPE_WEAK);

    if (Validator.isNotNull(entry.getCoverImageURL())) {
      coverImageSelector = new ImageSelector(entry.getCoverImageURL());
    } else if (entry.getCoverImageFileEntryId() != 0) {
      coverImageSelector =
          _getImageSelector(
              portletDataContext, entry.getCoverImageFileEntryId(), attachmentElements);
    }

    if (coverImageSelector != null) {
      _blogsEntryLocalService.addCoverImage(importedEntry.getEntryId(), coverImageSelector);
    }

    // Small image

    ImageSelector smallImageSelector = null;

    if (entry.isSmallImage()) {
      String smallImagePath = entryElement.attributeValue("small-image-path");

      if (Validator.isNotNull(entry.getSmallImageURL())) {
        smallImageSelector = new ImageSelector(entry.getSmallImageURL());
      } else if (Validator.isNotNull(smallImagePath)) {
        String smallImageFileName =
            entry.getSmallImageId() + StringPool.PERIOD + entry.getSmallImageType();

        InputStream inputStream = null;

        try {
          inputStream = portletDataContext.getZipEntryAsInputStream(smallImagePath);

          smallImageSelector =
              new ImageSelector(
                  FileUtil.getBytes(inputStream),
                  smallImageFileName,
                  MimeTypesUtil.getContentType(smallImageFileName),
                  null);
        } finally {
          StreamUtil.cleanUp(inputStream);
        }
      } else if (entry.getSmallImageFileEntryId() != 0) {
        smallImageSelector =
            _getImageSelector(
                portletDataContext, entry.getSmallImageFileEntryId(), attachmentElements);
      }
    }

    if (smallImageSelector != null) {
      _blogsEntryLocalService.addSmallImage(importedEntry.getEntryId(), smallImageSelector);
    }

    if ((coverImageSelector != null) || (smallImageSelector != null)) {
      importedEntry = _blogsEntryLocalService.getBlogsEntry(importedEntry.getEntryId());
    }

    portletDataContext.importClassedModel(entry, importedEntry);
  }
  @Override
  protected void doImportStagedModel(
      PortletDataContext portletDataContext, Element element, String path, BookmarksFolder folder)
      throws Exception {

    long userId = portletDataContext.getUserId(folder.getUserUuid());

    Map<Long, Long> folderIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(BookmarksFolder.class);

    long parentFolderId =
        MapUtil.getLong(folderIds, folder.getParentFolderId(), folder.getParentFolderId());

    if ((parentFolderId != BookmarksFolderConstants.DEFAULT_PARENT_FOLDER_ID)
        && (parentFolderId == folder.getParentFolderId())) {

      String parentFolderPath =
          StagedModelPathUtil.getPath(
              portletDataContext, BookmarksFolder.class.getName(), parentFolderId);

      BookmarksFolder parentFolder =
          (BookmarksFolder) portletDataContext.getZipEntryAsObject(parentFolderPath);

      importStagedModel(portletDataContext, element, parentFolderPath, parentFolder);

      parentFolderId =
          MapUtil.getLong(folderIds, folder.getParentFolderId(), folder.getParentFolderId());
    }

    ServiceContext serviceContext =
        portletDataContext.createServiceContext(
            path, folder, BookmarksPortletDataHandler.NAMESPACE);

    BookmarksFolder importedFolder = null;

    if (portletDataContext.isDataStrategyMirror()) {
      BookmarksFolder existingFolder =
          BookmarksFolderUtil.fetchByUUID_G(folder.getUuid(), portletDataContext.getScopeGroupId());

      if (existingFolder == null) {
        serviceContext.setUuid(folder.getUuid());

        importedFolder =
            BookmarksFolderLocalServiceUtil.addFolder(
                userId, parentFolderId, folder.getName(), folder.getDescription(), serviceContext);
      } else {
        importedFolder =
            BookmarksFolderLocalServiceUtil.updateFolder(
                userId,
                existingFolder.getFolderId(),
                parentFolderId,
                folder.getName(),
                folder.getDescription(),
                false,
                serviceContext);
      }
    } else {
      importedFolder =
          BookmarksFolderLocalServiceUtil.addFolder(
              userId, parentFolderId, folder.getName(), folder.getDescription(), serviceContext);
    }

    portletDataContext.importClassedModel(
        folder, importedFolder, BookmarksPortletDataHandler.NAMESPACE);
  }
  public void importComments(Class<?> clazz, long classPK, long newClassPK, long groupId)
      throws PortalException, SystemException {

    Map<Long, Long> messagePKs = new HashMap<Long, Long>();
    Map<Long, Long> threadPKs = new HashMap<Long, Long>();

    List<MBMessage> messages = _commentsMap.get(getPrimaryKeyString(clazz, classPK));

    if (messages == null) {
      return;
    }

    MBDiscussion discussion = null;

    try {
      discussion = MBDiscussionLocalServiceUtil.getDiscussion(clazz.getName(), newClassPK);
    } catch (NoSuchDiscussionException nsde) {
    }

    for (MBMessage message : messages) {
      long userId = getUserId(message.getUserUuid());
      long parentMessageId =
          MapUtil.getLong(messagePKs, message.getParentMessageId(), message.getParentMessageId());
      long threadId = MapUtil.getLong(threadPKs, message.getThreadId(), message.getThreadId());

      if ((message.getParentMessageId() == MBMessageConstants.DEFAULT_PARENT_MESSAGE_ID)
          && (discussion != null)) {

        MBThread thread = MBThreadLocalServiceUtil.getThread(discussion.getThreadId());

        long rootMessageId = thread.getRootMessageId();

        messagePKs.put(message.getMessageId(), rootMessageId);
        threadPKs.put(message.getThreadId(), thread.getThreadId());
      } else {
        ServiceContext serviceContext = new ServiceContext();

        serviceContext.setCreateDate(message.getCreateDate());
        serviceContext.setModifiedDate(message.getModifiedDate());
        serviceContext.setScopeGroupId(groupId);

        MBMessage importedMessage = null;

        if (_dataStrategy.equals(PortletDataHandlerKeys.DATA_STRATEGY_MIRROR)
            || _dataStrategy.equals(PortletDataHandlerKeys.DATA_STRATEGY_MIRROR_OVERWRITE)) {

          MBMessage existingMessage = MBMessageUtil.fetchByUUID_G(message.getUuid(), groupId);

          if (existingMessage == null) {
            serviceContext.setUuid(message.getUuid());

            importedMessage =
                MBMessageLocalServiceUtil.addDiscussionMessage(
                    userId,
                    message.getUserName(),
                    groupId,
                    clazz.getName(),
                    newClassPK,
                    threadId,
                    parentMessageId,
                    message.getSubject(),
                    message.getBody(),
                    serviceContext);
          } else {
            serviceContext.setWorkflowAction(WorkflowConstants.ACTION_PUBLISH);

            importedMessage =
                MBMessageLocalServiceUtil.updateDiscussionMessage(
                    userId,
                    existingMessage.getMessageId(),
                    clazz.getName(),
                    newClassPK,
                    message.getSubject(),
                    message.getBody(),
                    serviceContext);
          }
        } else {
          importedMessage =
              MBMessageLocalServiceUtil.addDiscussionMessage(
                  userId,
                  message.getUserName(),
                  groupId,
                  clazz.getName(),
                  newClassPK,
                  threadId,
                  parentMessageId,
                  message.getSubject(),
                  message.getBody(),
                  serviceContext);
        }

        messagePKs.put(message.getMessageId(), importedMessage.getMessageId());
        threadPKs.put(message.getThreadId(), importedMessage.getThreadId());
      }

      importRatingsEntries(
          MBDiscussion.class, message.getPrimaryKey(), messagePKs.get(message.getPrimaryKey()));
    }
  }
  @Override
  protected void doImportStagedModel(
      PortletDataContext portletDataContext, PasswordPolicy passwordPolicy) throws Exception {

    long userId = portletDataContext.getUserId(passwordPolicy.getUserUuid());

    ServiceContext serviceContext =
        portletDataContext.createServiceContext(
            passwordPolicy, PasswordPolicyPortletDataHandler.NAMESPACE);

    PasswordPolicy existingPasswordPolicy =
        PasswordPolicyLocalServiceUtil.fetchPasswordPolicyByUuidAndCompanyId(
            passwordPolicy.getUuid(), portletDataContext.getCompanyId());

    if (existingPasswordPolicy == null) {
      existingPasswordPolicy =
          PasswordPolicyLocalServiceUtil.fetchPasswordPolicy(
              portletDataContext.getCompanyId(), passwordPolicy.getName());
    }

    PasswordPolicy importedPasswordPolicy = null;

    if (existingPasswordPolicy == null) {
      serviceContext.setUuid(passwordPolicy.getUuid());

      importedPasswordPolicy =
          PasswordPolicyLocalServiceUtil.addPasswordPolicy(
              userId,
              passwordPolicy.isDefaultPolicy(),
              passwordPolicy.getName(),
              passwordPolicy.getDescription(),
              passwordPolicy.getChangeable(),
              passwordPolicy.isChangeRequired(),
              passwordPolicy.getMinAge(),
              passwordPolicy.getCheckSyntax(),
              passwordPolicy.isAllowDictionaryWords(),
              passwordPolicy.getMinAlphanumeric(),
              passwordPolicy.getMinLength(),
              passwordPolicy.getMinLowerCase(),
              passwordPolicy.getMinNumbers(),
              passwordPolicy.getMinSymbols(),
              passwordPolicy.getMinUpperCase(),
              passwordPolicy.getRegex(),
              passwordPolicy.isHistory(),
              passwordPolicy.getHistoryCount(),
              passwordPolicy.isExpireable(),
              passwordPolicy.getMaxAge(),
              passwordPolicy.getWarningTime(),
              passwordPolicy.getGraceLimit(),
              passwordPolicy.isLockout(),
              passwordPolicy.getMaxFailure(),
              passwordPolicy.getLockoutDuration(),
              passwordPolicy.getResetFailureCount(),
              passwordPolicy.getResetTicketMaxAge(),
              serviceContext);
    } else {
      importedPasswordPolicy =
          PasswordPolicyLocalServiceUtil.updatePasswordPolicy(
              existingPasswordPolicy.getPasswordPolicyId(),
              passwordPolicy.getName(),
              passwordPolicy.getDescription(),
              passwordPolicy.isChangeable(),
              passwordPolicy.isChangeRequired(),
              passwordPolicy.getMinAge(),
              passwordPolicy.isCheckSyntax(),
              passwordPolicy.isAllowDictionaryWords(),
              passwordPolicy.getMinAlphanumeric(),
              passwordPolicy.getMinLength(),
              passwordPolicy.getMinLowerCase(),
              passwordPolicy.getMinNumbers(),
              passwordPolicy.getMinSymbols(),
              passwordPolicy.getMinUpperCase(),
              passwordPolicy.getRegex(),
              passwordPolicy.isHistory(),
              passwordPolicy.getHistoryCount(),
              passwordPolicy.isExpireable(),
              passwordPolicy.getMaxAge(),
              passwordPolicy.getWarningTime(),
              passwordPolicy.getGraceLimit(),
              passwordPolicy.isLockout(),
              passwordPolicy.getMaxFailure(),
              passwordPolicy.getLockoutDuration(),
              passwordPolicy.getResetFailureCount(),
              passwordPolicy.getResetTicketMaxAge(),
              serviceContext);
    }

    portletDataContext.importClassedModel(
        passwordPolicy, importedPasswordPolicy, PasswordPolicyPortletDataHandler.NAMESPACE);
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, Role role)
      throws Exception {

    long userId = portletDataContext.getUserId(role.getUserUuid());

    ServiceContext serviceContext = portletDataContext.createServiceContext(role);

    Role existingRole =
        RoleLocalServiceUtil.fetchRoleByUuidAndCompanyId(
            role.getUuid(), portletDataContext.getCompanyId());

    if (existingRole == null) {
      existingRole =
          RoleLocalServiceUtil.fetchRole(portletDataContext.getCompanyId(), role.getName());
    }

    Role importedRole = null;

    if (existingRole == null) {
      serviceContext.setUuid(role.getUuid());

      importedRole =
          RoleLocalServiceUtil.addRole(
              userId,
              null,
              0,
              role.getName(),
              role.getTitleMap(),
              role.getDescriptionMap(),
              role.getType(),
              role.getSubtype(),
              serviceContext);
    } else {
      importedRole =
          RoleLocalServiceUtil.updateRole(
              existingRole.getRoleId(),
              role.getName(),
              role.getTitleMap(),
              role.getDescriptionMap(),
              role.getSubtype(),
              serviceContext);

      deleteRolePermissions(portletDataContext, importedRole);
    }

    String permissionsPath = ExportImportPathUtil.getModelPath(role, "permissions.xml");

    List<Permission> permissions =
        (List<Permission>) portletDataContext.getZipEntryAsObject(permissionsPath);

    for (Permission permission : permissions) {
      if (ResourceBlockLocalServiceUtil.isSupported(permission.getName())) {

        importResourceBlock(portletDataContext, importedRole, permission);
      } else {
        importResourcePermissions(portletDataContext, importedRole, permission);
      }
    }

    portletDataContext.importClassedModel(role, importedRole);
  }
Beispiel #29
0
  protected void importEvent(
      PortletDataContext portletDataContext, Element eventElement, CalEvent event)
      throws Exception {

    long userId = portletDataContext.getUserId(event.getUserUuid());

    Date startDate = event.getStartDate();

    int startDateMonth = 0;
    int startDateDay = 0;
    int startDateYear = 0;
    int startDateHour = 0;
    int startDateMinute = 0;

    if (startDate != null) {
      Locale locale = null;
      TimeZone timeZone = null;

      if (event.getTimeZoneSensitive()) {
        User user = UserLocalServiceUtil.getUser(userId);

        locale = user.getLocale();
        timeZone = user.getTimeZone();
      } else {
        locale = LocaleUtil.getDefault();
        timeZone = TimeZoneUtil.getTimeZone(StringPool.UTC);
      }

      Calendar startCal = CalendarFactoryUtil.getCalendar(timeZone, locale);

      startCal.setTime(startDate);

      startDateMonth = startCal.get(Calendar.MONTH);
      startDateDay = startCal.get(Calendar.DATE);
      startDateYear = startCal.get(Calendar.YEAR);
      startDateHour = startCal.get(Calendar.HOUR);
      startDateMinute = startCal.get(Calendar.MINUTE);

      if (startCal.get(Calendar.AM_PM) == Calendar.PM) {
        startDateHour += 12;
      }
    }

    ServiceContext serviceContext =
        portletDataContext.createServiceContext(eventElement, event, NAMESPACE);

    CalEvent importedEvent = null;

    if (portletDataContext.isDataStrategyMirror()) {
      CalEvent existingEvent =
          CalEventUtil.fetchByUUID_G(event.getUuid(), portletDataContext.getScopeGroupId());

      if (existingEvent == null) {
        serviceContext.setUuid(event.getUuid());

        importedEvent =
            CalEventLocalServiceUtil.addEvent(
                userId,
                event.getTitle(),
                event.getDescription(),
                event.getLocation(),
                startDateMonth,
                startDateDay,
                startDateYear,
                startDateHour,
                startDateMinute,
                event.getDurationHour(),
                event.getDurationMinute(),
                event.isAllDay(),
                event.isTimeZoneSensitive(),
                event.getType(),
                event.getRepeating(),
                event.getRecurrenceObj(),
                event.getRemindBy(),
                event.getFirstReminder(),
                event.getSecondReminder(),
                serviceContext);
      } else {
        importedEvent =
            CalEventLocalServiceUtil.updateEvent(
                userId,
                existingEvent.getEventId(),
                event.getTitle(),
                event.getDescription(),
                event.getLocation(),
                startDateMonth,
                startDateDay,
                startDateYear,
                startDateHour,
                startDateMinute,
                event.getDurationHour(),
                event.getDurationMinute(),
                event.isAllDay(),
                event.isTimeZoneSensitive(),
                event.getType(),
                event.getRepeating(),
                event.getRecurrenceObj(),
                event.getRemindBy(),
                event.getFirstReminder(),
                event.getSecondReminder(),
                serviceContext);
      }
    } else {
      importedEvent =
          CalEventLocalServiceUtil.addEvent(
              userId,
              event.getTitle(),
              event.getDescription(),
              event.getLocation(),
              startDateMonth,
              startDateDay,
              startDateYear,
              startDateHour,
              startDateMinute,
              event.getDurationHour(),
              event.getDurationMinute(),
              event.isAllDay(),
              event.isTimeZoneSensitive(),
              event.getType(),
              event.getRepeating(),
              event.getRecurrenceObj(),
              event.getRemindBy(),
              event.getFirstReminder(),
              event.getSecondReminder(),
              serviceContext);
    }

    portletDataContext.importClassedModel(event, importedEvent, NAMESPACE);
  }
Beispiel #30
0
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, DDMTemplate template)
      throws Exception {

    long userId = portletDataContext.getUserId(template.getUserUuid());

    Map<Long, Long> structureIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(DDMStructure.class);

    long classPK = MapUtil.getLong(structureIds, template.getClassPK(), template.getClassPK());

    File smallFile = null;

    if (template.isSmallImage()) {
      Element element = portletDataContext.getImportDataStagedModelElement(template);

      String smallImagePath = element.attributeValue("small-image-path");

      if (Validator.isNotNull(template.getSmallImageURL())) {
        String smallImageURL =
            JournalPortletDataHandler.importReferencedContent(
                portletDataContext, element, template.getSmallImageURL());

        template.setSmallImageURL(smallImageURL);
      } else if (Validator.isNotNull(smallImagePath)) {
        byte[] bytes = portletDataContext.getZipEntryAsByteArray(smallImagePath);

        if (bytes != null) {
          smallFile = FileUtil.createTempFile(template.getSmallImageType());

          FileUtil.write(smallFile, bytes);
        }
      }
    }

    ServiceContext serviceContext =
        portletDataContext.createServiceContext(template, DDMPortletDataHandler.NAMESPACE);

    DDMTemplate importedTemplate = null;

    if (portletDataContext.isDataStrategyMirror()) {
      DDMTemplate existingTemplate =
          DDMTemplateUtil.fetchByUUID_G(template.getUuid(), portletDataContext.getScopeGroupId());

      if (existingTemplate == null) {
        serviceContext.setUuid(template.getUuid());

        importedTemplate =
            addTemplate(
                userId,
                portletDataContext.getScopeGroupId(),
                template,
                classPK,
                smallFile,
                serviceContext);
      } else {
        importedTemplate =
            DDMTemplateLocalServiceUtil.updateTemplate(
                existingTemplate.getTemplateId(),
                template.getNameMap(),
                template.getDescriptionMap(),
                template.getType(),
                template.getMode(),
                template.getLanguage(),
                template.getScript(),
                template.isCacheable(),
                template.isSmallImage(),
                template.getSmallImageURL(),
                smallFile,
                serviceContext);
      }
    } else {
      importedTemplate =
          addTemplate(
              userId,
              portletDataContext.getScopeGroupId(),
              template,
              classPK,
              smallFile,
              serviceContext);
    }

    portletDataContext.importClassedModel(
        template, importedTemplate, DDMPortletDataHandler.NAMESPACE);
  }