@Override
  public LayoutSet updateImpl(com.liferay.portal.model.LayoutSet layoutSet, boolean merge)
      throws SystemException {
    layoutSet = toUnwrappedModel(layoutSet);

    boolean isNew = layoutSet.isNew();

    LayoutSetModelImpl layoutSetModelImpl = (LayoutSetModelImpl) layoutSet;

    Session session = null;

    try {
      session = openSession();

      BatchSessionUtil.update(session, layoutSet, merge);

      layoutSet.setNew(false);
    } catch (Exception e) {
      throw processException(e);
    } finally {
      closeSession(session);
    }

    FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);

    EntityCacheUtil.putResult(
        LayoutSetModelImpl.ENTITY_CACHE_ENABLED,
        LayoutSetImpl.class,
        layoutSet.getPrimaryKey(),
        layoutSet);

    if (!isNew
        && ((layoutSet.getGroupId() != layoutSetModelImpl.getOriginalGroupId())
            || (layoutSet.getPrivateLayout() != layoutSetModelImpl.getOriginalPrivateLayout()))) {
      FinderCacheUtil.removeResult(
          FINDER_PATH_FETCH_BY_G_P,
          new Object[] {
            Long.valueOf(layoutSetModelImpl.getOriginalGroupId()),
            Boolean.valueOf(layoutSetModelImpl.getOriginalPrivateLayout())
          });
    }

    if (isNew
        || ((layoutSet.getGroupId() != layoutSetModelImpl.getOriginalGroupId())
            || (layoutSet.getPrivateLayout() != layoutSetModelImpl.getOriginalPrivateLayout()))) {
      FinderCacheUtil.putResult(
          FINDER_PATH_FETCH_BY_G_P,
          new Object[] {
            Long.valueOf(layoutSet.getGroupId()), Boolean.valueOf(layoutSet.getPrivateLayout())
          },
          layoutSet);
    }

    return layoutSet;
  }
  public void buildDocument(Element element, LayoutSet layoutSet, ThemeDisplay themeDisplay)
      throws PortalException, SystemException {

    Group suppliedGroup = GroupLocalServiceUtil.getGroup(layoutSet.getGroupId());

    addUsers(element, suppliedGroup, themeDisplay);
  }
  protected LayoutSet toUnwrappedModel(LayoutSet layoutSet) {
    if (layoutSet instanceof LayoutSetImpl) {
      return layoutSet;
    }

    LayoutSetImpl layoutSetImpl = new LayoutSetImpl();

    layoutSetImpl.setNew(layoutSet.isNew());
    layoutSetImpl.setPrimaryKey(layoutSet.getPrimaryKey());

    layoutSetImpl.setLayoutSetId(layoutSet.getLayoutSetId());
    layoutSetImpl.setGroupId(layoutSet.getGroupId());
    layoutSetImpl.setCompanyId(layoutSet.getCompanyId());
    layoutSetImpl.setPrivateLayout(layoutSet.isPrivateLayout());
    layoutSetImpl.setLogo(layoutSet.isLogo());
    layoutSetImpl.setLogoId(layoutSet.getLogoId());
    layoutSetImpl.setThemeId(layoutSet.getThemeId());
    layoutSetImpl.setColorSchemeId(layoutSet.getColorSchemeId());
    layoutSetImpl.setWapThemeId(layoutSet.getWapThemeId());
    layoutSetImpl.setWapColorSchemeId(layoutSet.getWapColorSchemeId());
    layoutSetImpl.setCss(layoutSet.getCss());
    layoutSetImpl.setPageCount(layoutSet.getPageCount());
    layoutSetImpl.setSettings(layoutSet.getSettings());
    layoutSetImpl.setLayoutSetPrototypeId(layoutSet.getLayoutSetPrototypeId());

    return layoutSetImpl;
  }
  protected void updateLayoutSetPrototype(long groupId, boolean privateLayout)
      throws PortalException {

    // Layout

    LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout);

    LayoutSetPrototype layoutSetPrototype =
        LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototype(
            layoutSet.getLayoutSetPrototypeId());

    Group layoutSetPrototypeGroup = layoutSetPrototype.getGroup();

    List<Layout> layoutSetPrototypeLayouts =
        LayoutLocalServiceUtil.getLayouts(layoutSetPrototypeGroup.getGroupId(), true);

    String[] layoutSetPrototypeLayoutUuids = new String[layoutSetPrototypeLayouts.size()];

    for (int i = 0; i < layoutSetPrototypeLayouts.size(); i++) {
      Layout layout = layoutSetPrototypeLayouts.get(i);

      layoutSetPrototypeLayoutUuids[i] = layout.getUuid();
    }

    List<Layout> layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout);

    for (Layout layout : layouts) {
      if (ArrayUtil.contains(
          layoutSetPrototypeLayoutUuids, layout.getSourcePrototypeLayoutUuid())) {

        layout.setLayoutPrototypeUuid(StringPool.BLANK);
        layout.setLayoutPrototypeLinkEnabled(false);
        layout.setSourcePrototypeLayoutUuid(StringPool.BLANK);

        LayoutLocalServiceUtil.updateLayout(layout);
      }
    }

    // Layout set

    UnicodeProperties settingsProperties = layoutSet.getSettingsProperties();

    settingsProperties.remove("last-merge-time");

    layoutSet.setSettingsProperties(settingsProperties);

    layoutSet.setLayoutSetPrototypeUuid(StringPool.BLANK);
    layoutSet.setLayoutSetPrototypeLinkEnabled(false);

    LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet);

    LayoutSetLocalServiceUtil.updateLookAndFeel(
        layoutSet.getGroupId(), null, null, StringPool.BLANK, false);
  }
  /**
   * Clears the cache for the layout set.
   *
   * <p>The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link
   * com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
   */
  @Override
  public void clearCache(LayoutSet layoutSet) {
    EntityCacheUtil.removeResult(
        LayoutSetModelImpl.ENTITY_CACHE_ENABLED, LayoutSetImpl.class, layoutSet.getPrimaryKey());

    FinderCacheUtil.removeResult(
        FINDER_PATH_FETCH_BY_G_P,
        new Object[] {
          Long.valueOf(layoutSet.getGroupId()), Boolean.valueOf(layoutSet.getPrivateLayout())
        });
  }
  public static void updateLastPublishDate(LayoutSet layoutSet, long lastPublishDate)
      throws Exception {

    UnicodeProperties settingsProperties = layoutSet.getSettingsProperties();

    if (lastPublishDate <= 0) {
      settingsProperties.remove("last-publish-date");
    } else {
      settingsProperties.setProperty("last-publish-date", String.valueOf(lastPublishDate));
    }

    LayoutSetLocalServiceUtil.updateSettings(
        layoutSet.getGroupId(), layoutSet.isPrivateLayout(), settingsProperties.toString());
  }
  @Test
  public void testResetOriginalValues() throws Exception {
    LayoutSet newLayoutSet = addLayoutSet();

    _persistence.clearCache();

    LayoutSet existingLayoutSet = _persistence.findByPrimaryKey(newLayoutSet.getPrimaryKey());

    Assert.assertEquals(
        existingLayoutSet.getGroupId(),
        ReflectionTestUtil.invoke(existingLayoutSet, "getOriginalGroupId", new Class<?>[0]));
    Assert.assertEquals(
        existingLayoutSet.getPrivateLayout(),
        ReflectionTestUtil.invoke(existingLayoutSet, "getOriginalPrivateLayout", new Class<?>[0]));
  }
  /**
   * Caches the layout set in the entity cache if it is enabled.
   *
   * @param layoutSet the layout set
   */
  public void cacheResult(LayoutSet layoutSet) {
    EntityCacheUtil.putResult(
        LayoutSetModelImpl.ENTITY_CACHE_ENABLED,
        LayoutSetImpl.class,
        layoutSet.getPrimaryKey(),
        layoutSet);

    FinderCacheUtil.putResult(
        FINDER_PATH_FETCH_BY_G_P,
        new Object[] {
          Long.valueOf(layoutSet.getGroupId()), Boolean.valueOf(layoutSet.getPrivateLayout())
        },
        layoutSet);

    layoutSet.resetOriginalValues();
  }
  protected long getGroupId(String className, long classPK) throws SystemException {

    long groupId = 0;

    if (className.equals(Layout.class.getName())) {
      Layout layout = layoutPersistence.fetchByPrimaryKey(classPK);

      if (layout != null) {
        groupId = layout.getGroupId();
      }
    } else if (className.equals(LayoutSet.class.getName())) {
      LayoutSet layoutSet = layoutSetPersistence.fetchByPrimaryKey(classPK);

      if (layoutSet != null) {
        groupId = layoutSet.getGroupId();
      }
    }

    return groupId;
  }
  protected String importTheme(LayoutSet layoutSet, InputStream themeZip) throws Exception {

    ThemeLoader themeLoader = ThemeLoaderFactory.getDefaultThemeLoader();

    if (themeLoader == null) {
      _log.error("No theme loaders are deployed");

      return null;
    }

    ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(themeZip);

    String lookAndFeelXML = zipReader.getEntryAsString("liferay-look-and-feel.xml");

    String themeId = String.valueOf(layoutSet.getGroupId());

    if (layoutSet.isPrivateLayout()) {
      themeId += "-private";
    } else {
      themeId += "-public";
    }

    if (PropsValues.THEME_LOADER_NEW_THEME_ID_ON_IMPORT) {
      Date now = new Date();

      themeId += "-" + Time.getShortTimestamp(now);
    }

    String themeName = themeId;

    lookAndFeelXML =
        StringUtil.replace(
            lookAndFeelXML,
            new String[] {"[$GROUP_ID$]", "[$THEME_ID$]", "[$THEME_NAME$]"},
            new String[] {String.valueOf(layoutSet.getGroupId()), themeId, themeName});

    FileUtil.deltree(themeLoader.getFileStorage() + StringPool.SLASH + themeId);

    List<String> zipEntries = zipReader.getEntries();

    for (String zipEntry : zipEntries) {
      String key = zipEntry;

      if (key.equals("liferay-look-and-feel.xml")) {
        FileUtil.write(
            themeLoader.getFileStorage() + StringPool.SLASH + themeId + StringPool.SLASH + key,
            lookAndFeelXML.getBytes());
      } else {
        InputStream is = zipReader.getEntryAsInputStream(zipEntry);

        FileUtil.write(
            themeLoader.getFileStorage() + StringPool.SLASH + themeId + StringPool.SLASH + key, is);
      }
    }

    themeLoader.loadThemes();

    ClusterRequest clusterRequest =
        ClusterRequest.createMulticastRequest(_loadThemesMethodHandler, true);

    clusterRequest.setFireAndForget(true);

    ClusterExecutorUtil.execute(clusterRequest);

    themeId += PortletConstants.WAR_SEPARATOR + themeLoader.getServletContextName();

    return PortalUtil.getJsSafePortletId(themeId);
  }
  @Test
  public void testUpdateExisting() throws Exception {
    long pk = RandomTestUtil.nextLong();

    LayoutSet newLayoutSet = _persistence.create(pk);

    newLayoutSet.setMvccVersion(RandomTestUtil.nextLong());

    newLayoutSet.setGroupId(RandomTestUtil.nextLong());

    newLayoutSet.setCompanyId(RandomTestUtil.nextLong());

    newLayoutSet.setCreateDate(RandomTestUtil.nextDate());

    newLayoutSet.setModifiedDate(RandomTestUtil.nextDate());

    newLayoutSet.setPrivateLayout(RandomTestUtil.randomBoolean());

    newLayoutSet.setLogoId(RandomTestUtil.nextLong());

    newLayoutSet.setThemeId(RandomTestUtil.randomString());

    newLayoutSet.setColorSchemeId(RandomTestUtil.randomString());

    newLayoutSet.setWapThemeId(RandomTestUtil.randomString());

    newLayoutSet.setWapColorSchemeId(RandomTestUtil.randomString());

    newLayoutSet.setCss(RandomTestUtil.randomString());

    newLayoutSet.setPageCount(RandomTestUtil.nextInt());

    newLayoutSet.setSettings(RandomTestUtil.randomString());

    newLayoutSet.setLayoutSetPrototypeUuid(RandomTestUtil.randomString());

    newLayoutSet.setLayoutSetPrototypeLinkEnabled(RandomTestUtil.randomBoolean());

    _layoutSets.add(_persistence.update(newLayoutSet));

    LayoutSet existingLayoutSet = _persistence.findByPrimaryKey(newLayoutSet.getPrimaryKey());

    Assert.assertEquals(existingLayoutSet.getMvccVersion(), newLayoutSet.getMvccVersion());
    Assert.assertEquals(existingLayoutSet.getLayoutSetId(), newLayoutSet.getLayoutSetId());
    Assert.assertEquals(existingLayoutSet.getGroupId(), newLayoutSet.getGroupId());
    Assert.assertEquals(existingLayoutSet.getCompanyId(), newLayoutSet.getCompanyId());
    Assert.assertEquals(
        Time.getShortTimestamp(existingLayoutSet.getCreateDate()),
        Time.getShortTimestamp(newLayoutSet.getCreateDate()));
    Assert.assertEquals(
        Time.getShortTimestamp(existingLayoutSet.getModifiedDate()),
        Time.getShortTimestamp(newLayoutSet.getModifiedDate()));
    Assert.assertEquals(existingLayoutSet.getPrivateLayout(), newLayoutSet.getPrivateLayout());
    Assert.assertEquals(existingLayoutSet.getLogoId(), newLayoutSet.getLogoId());
    Assert.assertEquals(existingLayoutSet.getThemeId(), newLayoutSet.getThemeId());
    Assert.assertEquals(existingLayoutSet.getColorSchemeId(), newLayoutSet.getColorSchemeId());
    Assert.assertEquals(existingLayoutSet.getWapThemeId(), newLayoutSet.getWapThemeId());
    Assert.assertEquals(
        existingLayoutSet.getWapColorSchemeId(), newLayoutSet.getWapColorSchemeId());
    Assert.assertEquals(existingLayoutSet.getCss(), newLayoutSet.getCss());
    Assert.assertEquals(existingLayoutSet.getPageCount(), newLayoutSet.getPageCount());
    Assert.assertEquals(existingLayoutSet.getSettings(), newLayoutSet.getSettings());
    Assert.assertEquals(
        existingLayoutSet.getLayoutSetPrototypeUuid(), newLayoutSet.getLayoutSetPrototypeUuid());
    Assert.assertEquals(
        existingLayoutSet.getLayoutSetPrototypeLinkEnabled(),
        newLayoutSet.getLayoutSetPrototypeLinkEnabled());
  }
  /**
   * Returns the layout set where groupId = &#63; and privateLayout = &#63; or returns <code>null
   * </code> if it could not be found, optionally using the finder cache.
   *
   * @param groupId the group ID
   * @param privateLayout the private layout
   * @param retrieveFromCache whether to use the finder cache
   * @return the matching layout set, or <code>null</code> if a matching layout set could not be
   *     found
   * @throws SystemException if a system exception occurred
   */
  public LayoutSet fetchByG_P(long groupId, boolean privateLayout, boolean retrieveFromCache)
      throws SystemException {
    Object[] finderArgs = new Object[] {groupId, privateLayout};

    Object result = null;

    if (retrieveFromCache) {
      result = FinderCacheUtil.getResult(FINDER_PATH_FETCH_BY_G_P, finderArgs, this);
    }

    if (result == null) {
      StringBundler query = new StringBundler(3);

      query.append(_SQL_SELECT_LAYOUTSET_WHERE);

      query.append(_FINDER_COLUMN_G_P_GROUPID_2);

      query.append(_FINDER_COLUMN_G_P_PRIVATELAYOUT_2);

      String sql = query.toString();

      Session session = null;

      try {
        session = openSession();

        Query q = session.createQuery(sql);

        QueryPos qPos = QueryPos.getInstance(q);

        qPos.add(groupId);

        qPos.add(privateLayout);

        List<LayoutSet> list = q.list();

        result = list;

        LayoutSet layoutSet = null;

        if (list.isEmpty()) {
          FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_G_P, finderArgs, list);
        } else {
          layoutSet = list.get(0);

          cacheResult(layoutSet);

          if ((layoutSet.getGroupId() != groupId)
              || (layoutSet.getPrivateLayout() != privateLayout)) {
            FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_G_P, finderArgs, layoutSet);
          }
        }

        return layoutSet;
      } catch (Exception e) {
        throw processException(e);
      } finally {
        if (result == null) {
          FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_G_P, finderArgs);
        }

        closeSession(session);
      }
    } else {
      if (result instanceof List<?>) {
        return null;
      } else {
        return (LayoutSet) result;
      }
    }
  }