protected void searchStatus() throws Exception {
    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(group.getGroupId());

    SearchContext searchContext = SearchContextTestUtil.getSearchContext(group.getGroupId());

    int initialBaseModelsCount =
        searchBaseModelsCount(getBaseModelClass(), group.getGroupId(), "1.0", searchContext);

    BaseModel<?> parentBaseModel = getParentBaseModel(group, serviceContext);

    baseModel = addBaseModel(parentBaseModel, false, "Version 1.0", serviceContext);

    Assert.assertEquals(
        initialBaseModelsCount,
        searchBaseModelsCount(getBaseModelClass(), group.getGroupId(), searchContext));

    serviceContext.setWorkflowAction(WorkflowConstants.ACTION_PUBLISH);

    baseModel = updateBaseModel(baseModel, "Version 1.1", serviceContext);

    Assert.assertEquals(
        initialBaseModelsCount,
        searchBaseModelsCount(getBaseModelClass(), group.getGroupId(), "1.0", searchContext));
    Assert.assertEquals(
        initialBaseModelsCount + 1,
        searchBaseModelsCount(getBaseModelClass(), group.getGroupId(), "1.1", searchContext));

    serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);

    baseModel = updateBaseModel(baseModel, "Version 1.2", serviceContext);

    Assert.assertEquals(
        initialBaseModelsCount + 1,
        searchBaseModelsCount(getBaseModelClass(), group.getGroupId(), "1.1", searchContext));
    Assert.assertEquals(
        initialBaseModelsCount,
        searchBaseModelsCount(getBaseModelClass(), group.getGroupId(), "1.2", searchContext));

    serviceContext.setWorkflowAction(WorkflowConstants.ACTION_PUBLISH);

    baseModel = updateBaseModel(baseModel, "Version 1.3", serviceContext);

    Assert.assertEquals(
        initialBaseModelsCount,
        searchBaseModelsCount(getBaseModelClass(), group.getGroupId(), "1.2", searchContext));
    Assert.assertEquals(
        initialBaseModelsCount + 1,
        searchBaseModelsCount(getBaseModelClass(), group.getGroupId(), "1.3", searchContext));
  }
  protected FileEntry addFileEntry(
      long folderId, String sourceFileName, String title, byte[] bytes, int workflowAction)
      throws Exception {

    String description = StringPool.BLANK;
    String changeLog = StringPool.BLANK;

    if ((bytes == null) && Validator.isNotNull(sourceFileName)) {
      bytes = CONTENT.getBytes();
    }

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);
    serviceContext.setWorkflowAction(workflowAction);

    return DLAppServiceUtil.addFileEntry(
        TestPropsValues.getGroupId(),
        folderId,
        sourceFileName,
        ContentTypes.TEXT_PLAIN,
        title,
        description,
        changeLog,
        bytes,
        serviceContext);
  }
  @Override
  protected BaseModel<?> addBaseModel(
      BaseModel<?> parentBaseModel, boolean approved, ServiceContext serviceContext)
      throws Exception {

    DLFolder dlFolder = (DLFolder) parentBaseModel;

    String content = "Content: Enterprise. Open Source. For Life.";

    serviceContext = (ServiceContext) serviceContext.clone();

    serviceContext.setWorkflowAction(WorkflowConstants.ACTION_PUBLISH);

    FileEntry fileEntry =
        DLAppServiceUtil.addFileEntry(
            dlFolder.getGroupId(),
            DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
            "Text.txt",
            ContentTypes.TEXT_PLAIN,
            getSearchKeywords(),
            StringPool.BLANK,
            StringPool.BLANK,
            content.getBytes(),
            serviceContext);

    return DLAppServiceUtil.addFileShortcut(
        dlFolder.getGroupId(), dlFolder.getFolderId(), fileEntry.getFileEntryId(), serviceContext);
  }
Example #4
0
  @Override
  protected BaseModel<?> addBaseModel(
      BaseModel<?> parentBaseModel, String keywords, ServiceContext serviceContext)
      throws Exception {

    serviceContext.setWorkflowAction(WorkflowConstants.ACTION_PUBLISH);

    return JournalTestUtil.addArticle(
        serviceContext.getScopeGroupId(), keywords, "Content", serviceContext);
  }
  @Override
  protected BaseModel<?> getParentBaseModel(Group group, ServiceContext serviceContext)
      throws Exception {

    serviceContext = (ServiceContext) serviceContext.clone();

    serviceContext.setWorkflowAction(WorkflowConstants.STATUS_APPROVED);

    return WikiNodeLocalServiceUtil.addNode(
        TestPropsValues.getUserId(),
        RandomTestUtil.randomString(_NODE_NAME_MAX_LENGTH),
        RandomTestUtil.randomString(),
        serviceContext);
  }
  /**
   * 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;
  }
  protected void updateMessage(int workflowAction) throws Exception {
    List<ObjectValuePair<String, InputStream>> inputStreamOVPs = Collections.emptyList();
    List<String> existingFiles = Collections.emptyList();

    ServiceContext serviceContext = ServiceTestUtil.getServiceContext(_group.getGroupId());

    serviceContext.setWorkflowAction(workflowAction);

    _message =
        MBMessageLocalServiceUtil.updateMessage(
            TestPropsValues.getUserId(),
            _message.getMessageId(),
            _message.getSubject(),
            _message.getBody(),
            inputStreamOVPs,
            existingFiles,
            _message.getPriority(),
            _message.getAllowPingbacks(),
            serviceContext);
  }
  @Override
  protected BaseModel<?> addBaseModelWithWorkflow(
      BaseModel<?> parentBaseModel, boolean approved, ServiceContext serviceContext)
      throws Exception {

    serviceContext = (ServiceContext) serviceContext.clone();

    serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);

    String title = getSearchKeywords();

    title += RandomTestUtil.randomString(_PAGE_TITLE_MAX_LENGTH - title.length());

    return WikiTestUtil.addPage(
        TestPropsValues.getUserId(),
        serviceContext.getScopeGroupId(),
        (Long) parentBaseModel.getPrimaryKeyObj(),
        title,
        approved);
  }
Example #9
0
  protected JournalArticle addArticle(long groupId, Date displayDate, int when, boolean approved)
      throws Exception {

    Map<Locale, String> titleMap = new HashMap<Locale, String>();

    titleMap.put(LocaleUtil.getDefault(), ServiceTestUtil.randomString());

    Map<Locale, String> descriptionMap = new HashMap<Locale, String>();

    descriptionMap.put(LocaleUtil.getDefault(), ServiceTestUtil.randomString());

    String content = DDMStructureTestUtil.getSampleStructuredContent();

    String xsd = DDMStructureTestUtil.getSampleStructureXSD();

    DDMStructure ddmStructure =
        DDMStructureTestUtil.addStructure(groupId, JournalArticle.class.getName(), xsd);

    DDMTemplate ddmTemplate =
        DDMTemplateTestUtil.addTemplate(groupId, ddmStructure.getStructureId());

    Calendar displayDateCalendar = getCalendar(displayDate, when);

    ServiceContext serviceContext = ServiceTestUtil.getServiceContext(groupId);

    if (approved) {
      serviceContext.setWorkflowAction(WorkflowConstants.ACTION_PUBLISH);
    } else {
      serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);
    }

    return JournalArticleLocalServiceUtil.addArticle(
        TestPropsValues.getUserId(),
        groupId,
        JournalFolderConstants.DEFAULT_PARENT_FOLDER_ID,
        JournalArticleConstants.CLASSNAME_ID_DEFAULT,
        0,
        StringPool.BLANK,
        true,
        JournalArticleConstants.VERSION_DEFAULT,
        titleMap,
        descriptionMap,
        content,
        "general",
        ddmStructure.getStructureKey(),
        ddmTemplate.getTemplateKey(),
        null,
        displayDateCalendar.get(Calendar.MONTH),
        displayDateCalendar.get(Calendar.DAY_OF_MONTH),
        displayDateCalendar.get(Calendar.YEAR),
        displayDateCalendar.get(Calendar.HOUR_OF_DAY),
        displayDateCalendar.get(Calendar.MINUTE),
        0,
        0,
        0,
        0,
        0,
        true,
        0,
        0,
        0,
        0,
        0,
        true,
        true,
        false,
        null,
        null,
        null,
        null,
        serviceContext);
  }
  @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);
      }
    }
  }
  protected MBMessage addPrivateMessage(
      long userId,
      long mbThreadId,
      long parentMBMessageId,
      List<User> recipients,
      String subject,
      String body,
      List<ObjectValuePair<String, InputStream>> inputStreamOVPs,
      ThemeDisplay themeDisplay)
      throws PortalException {

    User user = UserLocalServiceUtil.getUser(userId);
    Group group = GroupLocalServiceUtil.getCompanyGroup(user.getCompanyId());
    long categoryId = PrivateMessagingConstants.PRIVATE_MESSAGING_CATEGORY_ID;

    if (Validator.isNull(subject)) {
      subject = StringUtil.shorten(body, 50);
    }

    boolean anonymous = false;
    double priority = 0.0;
    boolean allowPingbacks = false;

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);

    MBMessage mbMessage =
        MBMessageLocalServiceUtil.addMessage(
            userId,
            user.getScreenName(),
            group.getGroupId(),
            categoryId,
            mbThreadId,
            parentMBMessageId,
            subject,
            body,
            MBMessageConstants.DEFAULT_FORMAT,
            inputStreamOVPs,
            anonymous,
            priority,
            allowPingbacks,
            serviceContext);

    if (mbThreadId == 0) {
      for (User recipient : recipients) {
        if (recipient.getUserId() != userId) {
          addUserThread(
              recipient.getUserId(),
              mbMessage.getThreadId(),
              mbMessage.getMessageId(),
              false,
              false);
        }
      }

      addUserThread(userId, mbMessage.getThreadId(), mbMessage.getMessageId(), true, false);
    } else {
      List<UserThread> userThreads =
          userThreadPersistence.findByMBThreadId(mbMessage.getThreadId());

      for (UserThread userThread : userThreads) {
        userThread.setModifiedDate(new Date());

        if (userThread.getUserId() == userId) {
          userThread.setRead(true);
        } else {
          userThread.setRead(false);
        }

        if (userThread.isDeleted()) {
          userThread.setTopMBMessageId(mbMessage.getMessageId());
          userThread.setDeleted(false);
        }

        userThreadPersistence.update(userThread);
      }
    }

    // Email

    try {
      sendEmail(mbMessage.getMessageId(), themeDisplay);
    } catch (Exception e) {
      throw new SystemException(e);
    }

    // Notifications

    sendNotificationEvent(mbMessage);

    return mbMessage;
  }
  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()));
    }
  }
  protected void addAnonymousUser(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    boolean autoPassword = true;
    String password1 = null;
    String password2 = null;
    boolean autoScreenName = true;
    String screenName = null;
    String emailAddress = ParamUtil.getString(actionRequest, "emailAddress");
    long facebookId = 0;
    String openId = StringPool.BLANK;
    String firstName = ParamUtil.getString(actionRequest, "firstName");
    String lastName = ParamUtil.getString(actionRequest, "lastName");
    long prefixId = 0;
    long suffixId = 0;
    boolean male = true;
    int birthdayMonth = 0;
    int birthdayDay = 1;
    int birthdayYear = 1970;
    String jobTitle = null;
    long[] groupIds = null;
    long[] organizationIds = null;
    long[] roleIds = null;
    long[] userGroupIds = null;
    boolean sendEmail = false;

    ServiceContext serviceContext =
        ServiceContextFactory.getInstance(User.class.getName(), actionRequest);

    serviceContext.setAttribute("anonymousUser", true);

    if (PropsValues.CAPTCHA_CHECK_PORTAL_CREATE_ACCOUNT) {
      CaptchaUtil.check(actionRequest);
    }

    serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);

    User user =
        _userService.addUser(
            themeDisplay.getCompanyId(),
            autoPassword,
            password1,
            password2,
            autoScreenName,
            screenName,
            emailAddress,
            facebookId,
            openId,
            themeDisplay.getLocale(),
            firstName,
            null,
            lastName,
            prefixId,
            suffixId,
            male,
            birthdayMonth,
            birthdayDay,
            birthdayYear,
            jobTitle,
            groupIds,
            organizationIds,
            roleIds,
            userGroupIds,
            sendEmail,
            serviceContext);

    _userLocalService.updateStatus(
        user.getUserId(), WorkflowConstants.STATUS_INCOMPLETE, new ServiceContext());

    // Session messages

    SessionMessages.add(request, "userAdded", user.getEmailAddress());
    SessionMessages.add(request, "userAddedPassword", user.getPasswordUnencrypted());
  }
  public void merge(ServiceContext serviceContext) {
    setAddGroupPermissions(serviceContext.isAddGroupPermissions());
    setAddGuestPermissions(serviceContext.isAddGuestPermissions());

    if (serviceContext.getAssetCategoryIds() != null) {
      setAssetCategoryIds(serviceContext.getAssetCategoryIds());
    }

    if (serviceContext.getAssetLinkEntryIds() != null) {
      setAssetLinkEntryIds(serviceContext.getAssetLinkEntryIds());
    }

    if (serviceContext.getAssetTagNames() != null) {
      setAssetTagNames(serviceContext.getAssetTagNames());
    }

    if (serviceContext.getAttributes() != null) {
      setAttributes(serviceContext.getAttributes());
    }

    if (Validator.isNotNull(serviceContext.getCommand())) {
      setCommand(serviceContext.getCommand());
    }

    if (serviceContext.getCompanyId() > 0) {
      setCompanyId(serviceContext.getCompanyId());
    }

    if (serviceContext.getCreateDate() != null) {
      setCreateDate(serviceContext.getCreateDate());
    }

    if (Validator.isNotNull(serviceContext.getCurrentURL())) {
      setCurrentURL(serviceContext.getCurrentURL());
    }

    if (serviceContext.getExpandoBridgeAttributes() != null) {
      setExpandoBridgeAttributes(serviceContext.getExpandoBridgeAttributes());
    }

    if (serviceContext.getGroupPermissions() != null) {
      setGroupPermissions(serviceContext.getGroupPermissions());
    }

    if (serviceContext.getGuestPermissions() != null) {
      setGuestPermissions(serviceContext.getGuestPermissions());
    }

    if (serviceContext.getHeaders() != null) {
      setHeaders(serviceContext.getHeaders());
    }

    setFailOnPortalException(serviceContext.isFailOnPortalException());
    setLanguageId(serviceContext.getLanguageId());

    if (Validator.isNotNull(serviceContext.getLayoutFullURL())) {
      setLayoutFullURL(serviceContext.getLayoutFullURL());
    }

    if (Validator.isNotNull(serviceContext.getLayoutURL())) {
      setLayoutURL(serviceContext.getLayoutURL());
    }

    if (serviceContext.getModifiedDate() != null) {
      setModifiedDate(serviceContext.getModifiedDate());
    }

    if (Validator.isNotNull(serviceContext.getPathMain())) {
      setPathMain(serviceContext.getPathMain());
    }

    if (serviceContext.getPlid() > 0) {
      setPlid(serviceContext.getPlid());
    }

    if (Validator.isNotNull(serviceContext.getPortalURL())) {
      setPortalURL(serviceContext.getPortalURL());
    }

    if (serviceContext.getPortletPreferencesIds() != null) {
      setPortletPreferencesIds(serviceContext.getPortletPreferencesIds());
    }

    if (Validator.isNotNull(serviceContext.getRemoteAddr())) {
      setRemoteAddr(serviceContext.getRemoteAddr());
    }

    if (Validator.isNotNull(serviceContext.getRemoteHost())) {
      setRemoteHost(serviceContext.getRemoteHost());
    }

    if (serviceContext.getScopeGroupId() > 0) {
      setScopeGroupId(serviceContext.getScopeGroupId());
    }

    setSignedIn(serviceContext.isSignedIn());

    if (Validator.isNotNull(serviceContext.getUserDisplayURL())) {
      setUserDisplayURL(serviceContext.getUserDisplayURL());
    }

    if (serviceContext.getUserId() > 0) {
      setUserId(serviceContext.getUserId());
    }

    if (Validator.isNotNull(serviceContext.getUuid())) {
      setUuid(serviceContext.getUuid());
    }

    if (serviceContext.getWorkflowAction() > 0) {
      setWorkflowAction(serviceContext.getWorkflowAction());
    }
  }
  private LayoutRevision _getLayoutRevision(Layout layout, LayoutRevision layoutRevision)
      throws PortalException, SystemException {

    if (layoutRevision != null) {
      return layoutRevision;
    }

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (!serviceContext.isSignedIn()) {
      LayoutRevision lastLayoutRevision = null;

      lastLayoutRevision =
          LayoutRevisionLocalServiceUtil.fetchLastLayoutRevision(layout.getPlid(), true);

      if (lastLayoutRevision == null) {
        lastLayoutRevision =
            LayoutRevisionLocalServiceUtil.fetchLastLayoutRevision(layout.getPlid(), false);
      }

      return lastLayoutRevision;
    }

    User user = UserLocalServiceUtil.getUser(serviceContext.getUserId());

    long layoutSetBranchId = ParamUtil.getLong(serviceContext, "layoutSetBranchId");

    LayoutSet layoutSet = layout.getLayoutSet();

    LayoutSetBranch layoutSetBranch =
        LayoutSetBranchLocalServiceUtil.getUserLayoutSetBranch(
            serviceContext.getUserId(),
            layout.getGroupId(),
            layout.isPrivateLayout(),
            layoutSet.getLayoutSetId(),
            layoutSetBranchId);

    layoutSetBranchId = layoutSetBranch.getLayoutSetBranchId();

    long layoutRevisionId = ParamUtil.getLong(serviceContext, "layoutRevisionId");

    if (layoutRevisionId <= 0) {
      layoutRevisionId =
          StagingUtil.getRecentLayoutRevisionId(user, layoutSetBranchId, layout.getPlid());
    }

    if (layoutRevisionId > 0) {
      layoutRevision = LayoutRevisionLocalServiceUtil.fetchLayoutRevision(layoutRevisionId);

      if (layoutRevision.getStatus() != WorkflowConstants.STATUS_INACTIVE) {

        return layoutRevision;
      }

      layoutRevision = null;
    }

    List<LayoutRevision> layoutRevisions =
        LayoutRevisionLocalServiceUtil.getLayoutRevisions(
            layoutSetBranchId,
            layout.getPlid(),
            QueryUtil.ALL_POS,
            QueryUtil.ALL_POS,
            new LayoutRevisionCreateDateComparator(true));

    if (!layoutRevisions.isEmpty()) {
      layoutRevision = layoutRevisions.get(0);

      for (LayoutRevision curLayoutRevision : layoutRevisions) {
        if (curLayoutRevision.isHead()) {
          layoutRevision = curLayoutRevision;

          break;
        }
      }
    }

    if (layoutRevision != null) {
      StagingUtil.setRecentLayoutRevisionId(
          user, layoutSetBranchId, layout.getPlid(), layoutRevision.getLayoutRevisionId());

      return layoutRevision;
    }

    LayoutBranch layoutBranch =
        LayoutBranchLocalServiceUtil.getMasterLayoutBranch(
            layoutSetBranchId, layout.getPlid(), serviceContext);

    if (!MergeLayoutPrototypesThreadLocal.isInProgress()) {
      serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);
    }

    return LayoutRevisionLocalServiceUtil.addLayoutRevision(
        serviceContext.getUserId(),
        layoutSetBranchId,
        layoutBranch.getLayoutBranchId(),
        LayoutRevisionConstants.DEFAULT_PARENT_LAYOUT_REVISION_ID,
        false,
        layout.getPlid(),
        LayoutConstants.DEFAULT_PLID,
        layout.isPrivateLayout(),
        layout.getName(),
        layout.getTitle(),
        layout.getDescription(),
        layout.getKeywords(),
        layout.getRobots(),
        layout.getTypeSettings(),
        layout.getIconImage(),
        layout.getIconImageId(),
        layout.getThemeId(),
        layout.getColorSchemeId(),
        layout.getWapThemeId(),
        layout.getWapColorSchemeId(),
        layout.getCss(),
        serviceContext);
  }