protected boolean isValidStructureField(long groupId, String structureId, String contentField) {

    if (contentField.equals(JournalFeedConstants.WEB_CONTENT_DESCRIPTION)
        || contentField.equals(JournalFeedConstants.RENDERED_WEB_CONTENT)) {

      return true;
    } else {
      try {
        JournalStructure structure = journalStructurePersistence.findByG_S(groupId, structureId);

        Document document = SAXReaderUtil.read(structure.getXsd());

        XPath xPathSelector =
            SAXReaderUtil.createXPath("//dynamic-element[@name='" + contentField + "']");

        Node node = xPathSelector.selectSingleNode(document);

        if (node != null) {
          return true;
        }
      } catch (Exception e) {
        _log.error(e, e);
      }
    }

    return false;
  }
  protected void validateParentStructureId(
      long groupId, String structureId, String parentStructureId)
      throws PortalException, SystemException {

    if (Validator.isNull(parentStructureId)) {
      return;
    }

    if (parentStructureId.equals(structureId)) {
      throw new StructureInheritanceException();
    }

    JournalStructure parentStructure =
        journalStructurePersistence.fetchByG_S(groupId, parentStructureId);

    while (parentStructure != null) {
      if ((parentStructure != null) && (parentStructure.getStructureId().equals(structureId))
          || (parentStructure.getParentStructureId().equals(structureId))) {

        throw new StructureInheritanceException();
      }

      parentStructure =
          journalStructurePersistence.fetchByG_S(groupId, parentStructure.getParentStructureId());
    }
  }
  @Test
  public void testUpdateTemplate() throws Exception {
    String structureId = generateId();

    addStructure(groupId, structureId, getDefultXsd());

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

    nameMap.put(Locale.US, "New Test Structure");

    StringBundler sb = new StringBundler(5);

    sb.append("<root><dynamic-element name=\"abc\" index-type=\"\" ");
    sb.append("type=\"text\"><meta-data><entry name=\"label\">");
    sb.append("<![CDATA[abc]]></entry><entry name=\"required\">");
    sb.append("<![CDATA[false]]></entry></meta-data></dynamic-element>");
    sb.append("</root>");

    String xsd = sb.toString();

    JournalStructure structure =
        JournalStructureLocalServiceUtil.updateStructure(
            groupId, structureId, null, nameMap, null, xsd, getServiceContext());

    Assert.assertEquals("New Test Structure", structure.getName(Locale.US));
    Assert.assertEquals(
        JournalTestUtil.getXsdMap(xsd), JournalTestUtil.getXsdMap(structure.getXsd()));
  }
  @Test
  public void testAddStrucuture() throws Exception {
    String structureId = generateId();

    JournalStructure structure = addStructure(groupId, structureId, getDefultXsd());

    Assert.assertEquals(structureId, structure.getStructureId());
  }
  public static void getArticle(HttpServletRequest request) throws Exception {
    long groupId = ParamUtil.getLong(request, "groupId");
    long classNameId = ParamUtil.getLong(request, "classNameId");
    long classPK = ParamUtil.getLong(request, "classPK");
    String articleId = ParamUtil.getString(request, "articleId");
    String structureId = ParamUtil.getString(request, "structureId");

    JournalArticle article = null;

    if (Validator.isNotNull(articleId)) {
      article =
          JournalArticleServiceUtil.getLatestArticle(
              groupId, articleId, WorkflowConstants.STATUS_ANY);
    } else if ((classNameId > 0) && (classPK > 0)) {
      String className = PortalUtil.getClassName(classNameId);

      article = JournalArticleServiceUtil.getLatestArticle(groupId, className, classPK);
    } else if (Validator.isNotNull(structureId)) {
      JournalStructure structure = null;

      try {
        structure = JournalStructureServiceUtil.getStructure(groupId, structureId);
      } catch (NoSuchStructureException nsse1) {
        ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

        if (groupId == themeDisplay.getCompanyGroupId()) {
          return;
        }

        try {
          structure =
              JournalStructureServiceUtil.getStructure(
                  themeDisplay.getCompanyGroupId(), structureId);
        } catch (NoSuchStructureException nsse2) {
          return;
        }
      }

      article =
          JournalArticleServiceUtil.getArticle(
              groupId, JournalStructure.class.getName(), structure.getId());

      article.setNew(true);

      article.setId(0);
      article.setClassNameId(0);
      article.setClassPK(0);
      article.setArticleId(null);
      article.setVersion(0);
    }

    request.setAttribute(WebKeys.JOURNAL_ARTICLE, article);
  }
  public void addStructureResources(
      JournalStructure structure, String[] communityPermissions, String[] guestPermissions)
      throws PortalException, SystemException {

    resourceLocalService.addModelResources(
        structure.getCompanyId(),
        structure.getGroupId(),
        structure.getUserId(),
        JournalStructure.class.getName(),
        structure.getId(),
        communityPermissions,
        guestPermissions);
  }
  public void addStructureResources(
      JournalStructure structure, boolean addCommunityPermissions, boolean addGuestPermissions)
      throws PortalException, SystemException {

    resourceLocalService.addResources(
        structure.getCompanyId(),
        structure.getGroupId(),
        structure.getUserId(),
        JournalStructure.class.getName(),
        structure.getId(),
        false,
        addCommunityPermissions,
        addGuestPermissions);
  }
  public void checkNewLine(long groupId, String structureId)
      throws PortalException, SystemException {

    JournalStructure structure = journalStructurePersistence.findByG_S(groupId, structureId);

    String xsd = structure.getXsd();

    if ((xsd != null) && (xsd.indexOf("\\n") != -1)) {
      xsd = StringUtil.replace(xsd, new String[] {"\\n", "\\r"}, new String[] {"\n", "\r"});

      structure.setXsd(xsd);

      journalStructurePersistence.update(structure, false);
    }
  }
  @Test
  public void testCheckNewLine() throws Exception {
    String structureId = generateId();

    String xsd = getDefultXsd();

    xsd.concat("\\n\\n");

    addStructure(groupId, structureId, xsd);

    JournalStructureLocalServiceUtil.checkNewLine(groupId, structureId);

    JournalStructure structure =
        JournalStructureLocalServiceUtil.getStructure(groupId, structureId);

    Assert.assertFalse(structure.getXsd().contains("\\n"));
  }
  @Test
  public void testCopyStructure() throws Exception {
    String oldStructureId = generateId();

    String xsd = getDefultXsd();

    addStructure(groupId, oldStructureId, xsd);

    String newStructureId = generateId();

    JournalStructure structure =
        JournalStructureLocalServiceUtil.copyStructure(
            TestPropsValues.getUserId(), groupId, oldStructureId, newStructureId, false);

    Assert.assertEquals(newStructureId, structure.getStructureId());
    Assert.assertEquals(
        JournalTestUtil.getXsdMap(xsd), JournalTestUtil.getXsdMap(structure.getXsd()));
  }
  public void deleteStructure(JournalStructure structure) throws PortalException, SystemException {

    if (journalArticlePersistence.countByG_S(structure.getGroupId(), structure.getStructureId())
        > 0) {

      throw new RequiredStructureException();
    }

    if (journalStructurePersistence.countByG_P(structure.getGroupId(), structure.getStructureId())
        > 0) {

      throw new RequiredStructureException();
    }

    if (journalTemplatePersistence.countByG_S(structure.getGroupId(), structure.getStructureId())
        > 0) {

      throw new RequiredStructureException();
    }

    // WebDAVProps

    webDAVPropsLocalService.deleteWebDAVProps(JournalStructure.class.getName(), structure.getId());

    // Expando

    expandoValueLocalService.deleteValues(JournalStructure.class.getName(), structure.getId());

    // Resources

    resourceLocalService.deleteResource(
        structure.getCompanyId(),
        JournalStructure.class.getName(),
        ResourceConstants.SCOPE_INDIVIDUAL,
        structure.getId());

    // Structure

    journalStructurePersistence.remove(structure);
  }
  protected void doAddJournalStructures(String name, InputStream inputStream) throws Exception {

    name = getName(name);

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

    String xsd = StringUtil.read(inputStream);

    JournalStructure journalStructure =
        JournalStructureLocalServiceUtil.addStructure(
            userId,
            groupId,
            StringPool.BLANK,
            true,
            StringPool.BLANK,
            nameMap,
            null,
            xsd,
            serviceContext);

    addJournalTemplates(journalStructure.getStructureId(), "/journal/templates/" + name);
  }
  protected void processStructure(JournalStructure structure, Document document, String content) {

    try {
      com.liferay.portal.kernel.xml.Document structureDocument = null;

      if (structure != null) {
        structureDocument = SAXReaderUtil.read(structure.getXsd());
      }

      com.liferay.portal.kernel.xml.Document contentDocument = SAXReaderUtil.read(content);

      Element rootElement = contentDocument.getRootElement();

      processStructure(structureDocument, document, rootElement);
    } catch (Exception e) {
      _log.error(e, e);
    }
  }
  /**
   * Updates the journal structure in the database or adds it if it does not yet exist. Also
   * notifies the appropriate model listeners.
   *
   * @param journalStructure the journal structure
   * @param merge whether to merge the journal structure with the current session. See {@link
   *     com.liferay.portal.service.persistence.BatchSession#update(com.liferay.portal.kernel.dao.orm.Session,
   *     com.liferay.portal.model.BaseModel, boolean)} for an explanation.
   * @return the journal structure that was updated
   * @throws SystemException if a system exception occurred
   */
  public JournalStructure updateJournalStructure(JournalStructure journalStructure, boolean merge)
      throws SystemException {
    journalStructure.setNew(false);

    journalStructure = journalStructurePersistence.update(journalStructure, merge);

    Indexer indexer = IndexerRegistryUtil.getIndexer(getModelClassName());

    if (indexer != null) {
      try {
        indexer.reindex(journalStructure);
      } catch (SearchException se) {
        if (_log.isWarnEnabled()) {
          _log.warn(se, se);
        }
      }
    }

    return journalStructure;
  }
  public JournalStructure updateStructure(
      long groupId,
      String structureId,
      String parentStructureId,
      String name,
      String description,
      String xsd,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    structureId = structureId.trim().toUpperCase();

    try {
      xsd = JournalUtil.formatXML(xsd);
    } catch (Exception e) {
      throw new StructureXsdException();
    }

    validateParentStructureId(groupId, structureId, parentStructureId);
    validate(name, description, xsd);

    JournalStructure structure = journalStructurePersistence.findByG_S(groupId, structureId);

    structure.setModifiedDate(serviceContext.getModifiedDate(null));
    structure.setParentStructureId(parentStructureId);
    structure.setName(name);
    structure.setDescription(description);
    structure.setXsd(xsd);

    journalStructurePersistence.update(structure, false);

    // Expando

    ExpandoBridge expandoBridge = structure.getExpandoBridge();

    expandoBridge.setAttributes(serviceContext);

    return structure;
  }
  @Override
  public int compare(Object obj1, Object obj2) {
    JournalStructure structure1 = (JournalStructure) obj1;
    JournalStructure structure2 = (JournalStructure) obj2;

    int value = 0;

    if (structure1.getId() < structure2.getId()) {
      value = -1;
    } else if (structure1.getId() > structure2.getId()) {
      value = 1;
    }

    if (_ascending) {
      return value;
    } else {
      return -value;
    }
  }
  public JournalStructure addStructure(
      long userId,
      long groupId,
      String structureId,
      boolean autoStructureId,
      String parentStructureId,
      String name,
      String description,
      String xsd,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Structure

    User user = userPersistence.findByPrimaryKey(userId);
    structureId = structureId.trim().toUpperCase();
    Date now = new Date();

    try {
      xsd = JournalUtil.formatXML(xsd);
    } catch (Exception e) {
      throw new StructureXsdException();
    }

    if (autoStructureId) {
      structureId = String.valueOf(counterLocalService.increment());
    }

    validate(groupId, structureId, autoStructureId, parentStructureId, name, description, xsd);

    long id = counterLocalService.increment();

    JournalStructure structure = journalStructurePersistence.create(id);

    structure.setUuid(serviceContext.getUuid());
    structure.setGroupId(groupId);
    structure.setCompanyId(user.getCompanyId());
    structure.setUserId(user.getUserId());
    structure.setUserName(user.getFullName());
    structure.setCreateDate(serviceContext.getCreateDate(now));
    structure.setModifiedDate(serviceContext.getModifiedDate(now));
    structure.setStructureId(structureId);
    structure.setParentStructureId(parentStructureId);
    structure.setName(name);
    structure.setDescription(description);
    structure.setXsd(xsd);

    journalStructurePersistence.update(structure, false);

    // Resources

    if (serviceContext.getAddCommunityPermissions() || serviceContext.getAddGuestPermissions()) {

      addStructureResources(
          structure,
          serviceContext.getAddCommunityPermissions(),
          serviceContext.getAddGuestPermissions());
    } else {
      addStructureResources(
          structure,
          serviceContext.getCommunityPermissions(),
          serviceContext.getGuestPermissions());
    }

    // Expando

    ExpandoBridge expandoBridge = structure.getExpandoBridge();

    expandoBridge.setAttributes(serviceContext);

    return structure;
  }
  public JournalStructure copyStructure(
      long userId,
      long groupId,
      String oldStructureId,
      String newStructureId,
      boolean autoStructureId)
      throws PortalException, SystemException {

    // Structure

    User user = userPersistence.findByPrimaryKey(userId);
    oldStructureId = oldStructureId.trim().toUpperCase();
    newStructureId = newStructureId.trim().toUpperCase();
    Date now = new Date();

    JournalStructure oldStructure = journalStructurePersistence.findByG_S(groupId, oldStructureId);

    if (autoStructureId) {
      newStructureId = String.valueOf(counterLocalService.increment());
    } else {
      validateStructureId(newStructureId);

      JournalStructure newStructure =
          journalStructurePersistence.fetchByG_S(groupId, newStructureId);

      if (newStructure != null) {
        throw new DuplicateStructureIdException();
      }
    }

    long id = counterLocalService.increment();

    JournalStructure newStructure = journalStructurePersistence.create(id);

    newStructure.setGroupId(groupId);
    newStructure.setCompanyId(user.getCompanyId());
    newStructure.setUserId(user.getUserId());
    newStructure.setUserName(user.getFullName());
    newStructure.setCreateDate(now);
    newStructure.setModifiedDate(now);
    newStructure.setStructureId(newStructureId);
    newStructure.setName(oldStructure.getName());
    newStructure.setDescription(oldStructure.getDescription());
    newStructure.setXsd(oldStructure.getXsd());

    journalStructurePersistence.update(newStructure, false);

    // Resources

    addStructureResources(newStructure, true, true);

    return newStructure;
  }