Пример #1
0
  protected void verifyPermissionsAndAssets(JournalArticle article) throws PortalException {

    long groupId = article.getGroupId();
    String articleId = article.getArticleId();
    double version = article.getVersion();

    if (article.getResourcePrimKey() <= 0) {
      article =
          JournalArticleLocalServiceUtil.checkArticleResourcePrimKey(groupId, articleId, version);
    }

    ResourceLocalServiceUtil.addResources(
        article.getCompanyId(),
        0,
        0,
        JournalArticle.class.getName(),
        article.getResourcePrimKey(),
        false,
        false,
        false);

    AssetEntry assetEntry =
        AssetEntryLocalServiceUtil.fetchEntry(
            JournalArticle.class.getName(), article.getResourcePrimKey());

    if (assetEntry == null) {
      try {
        JournalArticleLocalServiceUtil.updateAsset(article.getUserId(), article, null, null, null);
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          _log.warn(
              "Unable to update asset for article " + article.getId() + ": " + e.getMessage());
        }
      }
    } else if ((article.getStatus() == WorkflowConstants.STATUS_DRAFT)
        && (article.getVersion() == JournalArticleConstants.VERSION_DEFAULT)) {

      AssetEntryLocalServiceUtil.updateEntry(
          assetEntry.getClassName(), assetEntry.getClassPK(), null, assetEntry.isVisible());
    }

    try {
      JournalArticleLocalServiceUtil.checkStructure(groupId, articleId, version);
    } catch (NoSuchStructureException nsse) {
      if (_log.isWarnEnabled()) {
        _log.warn("Removing reference to missing structure for article " + article.getId());
      }

      article.setStructureId(StringPool.BLANK);
      article.setTemplateId(StringPool.BLANK);

      JournalArticleLocalServiceUtil.updateJournalArticle(article);
    } catch (Exception e) {
      _log.error("Unable to check the structure for article " + article.getId(), e);
    }
  }
  public void addAssetLinks(Class<?> clazz, long classPK) throws PortalException, SystemException {

    AssetEntry assetEntry = null;

    try {
      assetEntry = AssetEntryLocalServiceUtil.getEntry(clazz.getName(), classPK);
    } catch (NoSuchEntryException nsee) {
      return;
    }

    List<AssetLink> directAssetLinks =
        AssetLinkLocalServiceUtil.getDirectLinks(assetEntry.getEntryId());

    if (directAssetLinks.isEmpty()) {
      return;
    }

    Map<Integer, List<AssetLink>> assetLinksMap = new HashMap<Integer, List<AssetLink>>();

    for (AssetLink assetLink : directAssetLinks) {
      List<AssetLink> assetLinks = assetLinksMap.get(assetLink.getType());

      if (assetLinks == null) {
        assetLinks = new ArrayList<AssetLink>();

        assetLinksMap.put(assetLink.getType(), assetLinks);
      }

      assetLinks.add(assetLink);
    }

    for (Map.Entry<Integer, List<AssetLink>> entry : assetLinksMap.entrySet()) {

      int assetLinkType = entry.getKey();
      List<AssetLink> assetLinks = entry.getValue();

      List<String> assetLinkUuids = new ArrayList<String>(directAssetLinks.size());

      for (AssetLink assetLink : assetLinks) {
        try {
          AssetEntry assetLinkEntry = AssetEntryLocalServiceUtil.getEntry(assetLink.getEntryId2());

          assetLinkUuids.add(assetLinkEntry.getClassUuid());
        } catch (NoSuchEntryException nsee) {
        }
      }

      _assetLinkUuidsMap.put(
          getPrimaryKeyString(assetEntry.getClassUuid(), String.valueOf(assetLinkType)),
          assetLinkUuids.toArray(new String[assetLinkUuids.size()]));
    }
  }
Пример #3
0
  protected void readAssetLinks(PortletDataContext portletDataContext) throws Exception {

    String xml =
        portletDataContext.getZipEntryAsString(
            portletDataContext.getSourceRootPath() + "/links.xml");

    if (xml == null) {
      return;
    }

    Document document = SAXReaderUtil.read(xml);

    Element rootElement = document.getRootElement();

    List<Element> assetLinkElements = rootElement.elements("asset-link");

    for (Element assetLinkElement : assetLinkElements) {
      String sourceUuid = GetterUtil.getString(assetLinkElement.attributeValue("source-uuid"));
      String[] assetEntryUuidArray =
          StringUtil.split(GetterUtil.getString(assetLinkElement.attributeValue("target-uuids")));
      int assetLinkType = GetterUtil.getInteger(assetLinkElement.attributeValue("type"));

      List<Long> assetEntryIds = new ArrayList<Long>();

      for (String assetEntryUuid : assetEntryUuidArray) {
        try {
          AssetEntry assetEntry =
              AssetEntryLocalServiceUtil.getEntry(
                  portletDataContext.getScopeGroupId(), assetEntryUuid);

          assetEntryIds.add(assetEntry.getEntryId());
        } catch (NoSuchEntryException nsee) {
        }
      }

      if (assetEntryIds.isEmpty()) {
        continue;
      }

      long[] assetEntryIdsArray =
          ArrayUtil.toArray(assetEntryIds.toArray(new Long[assetEntryIds.size()]));

      try {
        AssetEntry assetEntry =
            AssetEntryLocalServiceUtil.getEntry(portletDataContext.getScopeGroupId(), sourceUuid);

        AssetLinkLocalServiceUtil.updateLinks(
            assetEntry.getUserId(), assetEntry.getEntryId(), assetEntryIdsArray, assetLinkType);
      } catch (NoSuchEntryException nsee) {
      }
    }
  }
  protected void checkPopulatedServiceContext(
      ServiceContext serviceContext, WikiPage page, boolean hasExpandoValues) throws Exception {

    long[] assetCategoryIds =
        AssetCategoryLocalServiceUtil.getCategoryIds(
            WikiPage.class.getName(), page.getResourcePrimKey());

    Assert.assertArrayEquals(serviceContext.getAssetCategoryIds(), assetCategoryIds);

    AssetEntry assetEntry =
        AssetEntryLocalServiceUtil.getEntry(WikiPage.class.getName(), page.getResourcePrimKey());

    List<AssetLink> assetLinks = AssetLinkLocalServiceUtil.getLinks(assetEntry.getEntryId());

    long[] assetLinkEntryIds = ListUtil.toLongArray(assetLinks, AssetLink.ENTRY_ID2_ACCESSOR);

    Assert.assertArrayEquals(serviceContext.getAssetLinkEntryIds(), assetLinkEntryIds);

    String[] assetTagNames =
        AssetTagLocalServiceUtil.getTagNames(WikiPage.class.getName(), page.getResourcePrimKey());

    Assert.assertArrayEquals(serviceContext.getAssetTagNames(), assetTagNames);

    if (hasExpandoValues) {
      ExpandoBridge expandoBridge = page.getExpandoBridge();

      AssertUtils.assertEquals(
          expandoBridge.getAttributes(), serviceContext.getExpandoBridgeAttributes());
    }
  }
  @Override
  public AssetEntry getAssetEntry(String className, long classPK)
      throws PortalException, SystemException {

    LayoutRevision layoutRevision = LayoutRevisionLocalServiceUtil.getLayoutRevision(classPK);

    LayoutSetBranch layoutSetBranch =
        LayoutSetBranchLocalServiceUtil.getLayoutSetBranch(layoutRevision.getLayoutSetBranchId());

    User user = UserLocalServiceUtil.getUserById(layoutRevision.getUserId());

    AssetEntry assetEntry = AssetEntryLocalServiceUtil.createAssetEntry(classPK);

    assetEntry.setGroupId(layoutRevision.getGroupId());
    assetEntry.setCompanyId(user.getCompanyId());
    assetEntry.setUserId(user.getUserId());
    assetEntry.setUserName(user.getFullName());
    assetEntry.setCreateDate(layoutRevision.getCreateDate());
    assetEntry.setClassNameId(PortalUtil.getClassNameId(LayoutRevision.class.getName()));
    assetEntry.setClassPK(layoutRevision.getLayoutRevisionId());

    StringBundler sb = new StringBundler(4);

    sb.append(layoutRevision.getHTMLTitle(LocaleUtil.getSiteDefault()));
    sb.append(" [");
    sb.append(layoutSetBranch.getName());
    sb.append("]");

    assetEntry.setTitle(sb.toString());

    return assetEntry;
  }
  @After
  public void tearDown() throws Exception {
    SocialActivityHierarchyEntryThreadLocal.clear();

    if (_actorUser != null) {
      UserLocalServiceUtil.deleteUser(_actorUser);

      _actorUser = null;
    }

    if (_assetEntry != null) {
      AssetEntryLocalServiceUtil.deleteEntry(_assetEntry);

      _assetEntry = null;
    }

    if (_creatorUser != null) {
      UserLocalServiceUtil.deleteUser(_creatorUser);

      _creatorUser = null;
    }

    if (_group != null) {
      GroupLocalServiceUtil.deleteGroup(_group);

      _group = null;
    }
  }
  @Test
  public void testUpdateAssetWhenUpdatingFileEntry() throws Throwable {
    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(_group.getGroupId());

    FileEntry fileEntry =
        DLAppLocalServiceUtil.addFileEntry(
            TestPropsValues.getUserId(),
            _group.getGroupId(),
            DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
            RandomTestUtil.randomString(),
            ContentTypes.TEXT_PLAIN,
            "Old Title",
            RandomTestUtil.randomString(),
            null,
            RandomTestUtil.randomBytes(),
            serviceContext);

    DLAppLocalServiceUtil.updateFileEntry(
        TestPropsValues.getUserId(),
        fileEntry.getFileEntryId(),
        RandomTestUtil.randomString(),
        ContentTypes.TEXT_PLAIN,
        "New Title",
        RandomTestUtil.randomString(),
        null,
        true,
        RandomTestUtil.randomBytes(),
        serviceContext);

    AssetEntry assetEntry =
        AssetEntryLocalServiceUtil.getEntry(
            DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    Assert.assertEquals("New Title", assetEntry.getTitle());
  }
  @Override
  public void updatePortletPreferences(
      PortletPreferences portletPreferences,
      String portletId,
      String className,
      long classPK,
      ThemeDisplay themeDisplay)
      throws Exception {

    portletPreferences.setValue("displayStyle", "full-content");
    portletPreferences.setValue("emailAssetEntryAddedEnabled", Boolean.FALSE.toString());
    portletPreferences.setValue("selectionStyle", "manual");
    portletPreferences.setValue("showAddContentButton", Boolean.FALSE.toString());
    portletPreferences.setValue("showAssetTitle", Boolean.FALSE.toString());
    portletPreferences.setValue("showExtraInfo", Boolean.FALSE.toString());

    AssetEntry assetEntry = AssetEntryLocalServiceUtil.getEntry(className, classPK);

    AssetPublisherUtil.addSelection(
        themeDisplay,
        portletPreferences,
        portletId,
        assetEntry.getEntryId(),
        -1,
        assetEntry.getClassName());
  }
  @Override
  protected AssetEntry getAssetEntry(StagedModel stagedModel) throws PortalException {

    JournalArticle article = (JournalArticle) stagedModel;

    return AssetEntryLocalServiceUtil.getEntry(
        article.getGroupId(), article.getArticleResourceUuid());
  }
  @Test
  public void testGetNoAssetThreads() throws Exception {
    MBTestUtil.addMessage(_group.getGroupId());

    MBMessage message = MBTestUtil.addMessage(_group.getGroupId());

    MBThread thread = message.getThread();

    AssetEntry assetEntry =
        AssetEntryLocalServiceUtil.fetchEntry(MBThread.class.getName(), thread.getThreadId());

    Assert.assertNotNull(assetEntry);

    AssetEntryLocalServiceUtil.deleteAssetEntry(assetEntry);

    List<MBThread> threads = MBThreadLocalServiceUtil.getNoAssetThreads();

    Assert.assertEquals(1, threads.size());
    Assert.assertEquals(thread, threads.get(0));
  }
  public void updateAsset(
      long userId, TasksEntry tasksEntry, long[] assetCategoryIds, String[] assetTagNames)
      throws PortalException, SystemException {

    AssetEntryLocalServiceUtil.updateEntry(
        userId,
        tasksEntry.getGroupId(),
        TasksEntry.class.getName(),
        tasksEntry.getTasksEntryId(),
        assetCategoryIds,
        assetTagNames);
  }
  public void updateAsset(
      MicroblogsEntry microblogsEntry, long[] assetCategoryIds, String[] assetTagNames)
      throws PortalException, SystemException {

    Group group = GroupLocalServiceUtil.getCompanyGroup(microblogsEntry.getCompanyId());

    AssetEntryLocalServiceUtil.updateEntry(
        microblogsEntry.getUserId(),
        group.getGroupId(),
        MicroblogsEntry.class.getName(),
        microblogsEntry.getMicroblogsEntryId(),
        assetCategoryIds,
        assetTagNames);
  }
  @Test
  public void testUpdateAssetWhenUpdatingFolder() throws Throwable {
    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(_group.getGroupId());

    Folder folder = addFolder(false, "Old Name");

    DLAppLocalServiceUtil.updateFolder(
        folder.getFolderId(),
        folder.getParentFolderId(),
        "New Name",
        RandomTestUtil.randomString(),
        serviceContext);

    AssetEntry assetEntry =
        AssetEntryLocalServiceUtil.getEntry(DLFolderConstants.getClassName(), folder.getFolderId());

    Assert.assertEquals("New Name", assetEntry.getTitle());
  }
Пример #14
0
  protected void testScheduleArticle(boolean approved, int when) throws Exception {

    int initialSearchArticlesCount =
        JournalTestUtil.getSearchArticlesCount(_group.getCompanyId(), _group.getGroupId());

    Date now = new Date();

    JournalArticle article = addArticle(_group.getGroupId(), now, when, approved);

    JournalArticleLocalServiceUtil.checkArticles();

    article = JournalArticleLocalServiceUtil.getArticle(article.getId());

    AssetEntry assetEntry =
        AssetEntryLocalServiceUtil.getEntry(
            JournalArticle.class.getName(), article.getResourcePrimKey());

    if (when == _WHEN_FUTURE) {
      Assert.assertFalse(article.isApproved());
      Assert.assertFalse(assetEntry.isVisible());

      if (approved) {
        Assert.assertTrue(article.isScheduled());
      } else {
        Assert.assertTrue(article.isDraft());
      }
    } else {
      Assert.assertFalse(article.isScheduled());
      Assert.assertEquals(approved, article.isApproved());
      Assert.assertEquals(approved, assetEntry.isVisible());

      if (approved) {
        Assert.assertEquals(
            initialSearchArticlesCount + 1,
            JournalTestUtil.getSearchArticlesCount(_group.getCompanyId(), _group.getGroupId()));
      } else {
        Assert.assertEquals(
            initialSearchArticlesCount,
            JournalTestUtil.getSearchArticlesCount(_group.getCompanyId(), _group.getGroupId()));
      }
    }
  }
  @Override
  public MicroblogsEntry deleteMicroblogsEntry(MicroblogsEntry microblogsEntry)
      throws PortalException, SystemException {

    // Microblogs entry

    microblogsEntryPersistence.remove(microblogsEntry);

    // Asset

    AssetEntryLocalServiceUtil.deleteEntry(
        MicroblogsEntry.class.getName(), microblogsEntry.getMicroblogsEntryId());

    // Social

    SocialActivityLocalServiceUtil.deleteActivities(
        MicroblogsEntry.class.getName(), microblogsEntry.getMicroblogsEntryId());

    return microblogsEntry;
  }
Пример #16
0
  public static List<AssetEntry> getAssetEntries(Hits hits) {
    List<AssetEntry> assetEntries = new ArrayList<>();

    if (hits.getDocs() == null) {
      return assetEntries;
    }

    for (Document document : hits.getDocs()) {
      String className = GetterUtil.getString(document.get(Field.ENTRY_CLASS_NAME));
      long classPK = GetterUtil.getLong(document.get(Field.ENTRY_CLASS_PK));

      try {
        AssetEntry assetEntry = AssetEntryLocalServiceUtil.getEntry(className, classPK);

        assetEntries.add(assetEntry);
      } catch (Exception e) {
      }
    }

    return assetEntries;
  }
  @Override
  public void deleteTasksEntry(TasksEntry tasksEntry) throws PortalException, SystemException {

    // Tasks entry

    tasksEntryPersistence.remove(tasksEntry);

    // Asset

    AssetEntryLocalServiceUtil.deleteEntry(
        TasksEntry.class.getName(), tasksEntry.getTasksEntryId());

    // Message boards

    MBMessageLocalServiceUtil.deleteDiscussionMessages(
        TasksEntry.class.getName(), tasksEntry.getTasksEntryId());

    // Social

    SocialActivityLocalServiceUtil.deleteActivities(
        TasksEntry.class.getName(), tasksEntry.getTasksEntryId());
  }
  @Override
  public void addAndStoreSelection(
      PortletRequest portletRequest, String className, long classPK, int assetEntryOrder)
      throws Exception {

    String referringPortletResource =
        ParamUtil.getString(portletRequest, "referringPortletResource");

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

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

    Layout layout = LayoutLocalServiceUtil.getLayout(themeDisplay.getRefererPlid());

    PortletPreferences portletPreferences =
        PortletPreferencesFactoryUtil.getPortletSetup(
            themeDisplay.getScopeGroupId(), layout, referringPortletResource, null);

    String selectionStyle = portletPreferences.getValue("selectionStyle", "dynamic");

    if (selectionStyle.equals("dynamic")) {
      return;
    }

    AssetEntry assetEntry = AssetEntryLocalServiceUtil.getEntry(className, classPK);

    addSelection(
        themeDisplay,
        portletPreferences,
        referringPortletResource,
        assetEntry.getEntryId(),
        assetEntryOrder,
        className);

    portletPreferences.store();
  }
  @Override
  public void addSelection(
      ThemeDisplay themeDisplay,
      PortletPreferences portletPreferences,
      String portletId,
      long assetEntryId,
      int assetEntryOrder,
      String assetEntryType)
      throws Exception {

    AssetEntry assetEntry = AssetEntryLocalServiceUtil.getEntry(assetEntryId);

    String[] assetEntryXmls = portletPreferences.getValues("assetEntryXml", new String[0]);

    String assetEntryXml = _getAssetEntryXml(assetEntryType, assetEntry.getClassUuid());

    if (!ArrayUtil.contains(assetEntryXmls, assetEntryXml)) {
      if (assetEntryOrder > -1) {
        assetEntryXmls[assetEntryOrder] = assetEntryXml;
      } else {
        assetEntryXmls = ArrayUtil.append(assetEntryXmls, assetEntryXml);
      }

      portletPreferences.setValues("assetEntryXml", assetEntryXmls);
    }

    long plid = themeDisplay.getRefererPlid();

    if (plid == 0) {
      plid = themeDisplay.getPlid();
    }

    List<AssetEntry> assetEntries = new ArrayList<AssetEntry>();

    assetEntries.add(assetEntry);

    notifySubscribers(portletPreferences, plid, portletId, assetEntries);
  }
  @Override
  public List<AssetEntry> getAssetEntries(
      PortletPreferences preferences,
      Layout layout,
      long scopeGroupId,
      int max,
      boolean checkPermission)
      throws PortalException, SystemException {

    AssetEntryQuery assetEntryQuery = getAssetEntryQuery(preferences, new long[] {scopeGroupId});

    boolean anyAssetType = GetterUtil.getBoolean(preferences.getValue("anyAssetType", null), true);

    if (!anyAssetType) {
      long[] availableClassNameIds =
          AssetRendererFactoryRegistryUtil.getClassNameIds(layout.getCompanyId());

      long[] classNameIds = getClassNameIds(preferences, availableClassNameIds);

      assetEntryQuery.setClassNameIds(classNameIds);
    }

    long[] classTypeIds = GetterUtil.getLongValues(preferences.getValues("classTypeIds", null));

    assetEntryQuery.setClassTypeIds(classTypeIds);

    boolean enablePermissions =
        GetterUtil.getBoolean(preferences.getValue("enablePermissions", null));

    assetEntryQuery.setEnablePermissions(enablePermissions);

    assetEntryQuery.setEnd(max);

    boolean excludeZeroViewCount =
        GetterUtil.getBoolean(preferences.getValue("excludeZeroViewCount", null));

    assetEntryQuery.setExcludeZeroViewCount(excludeZeroViewCount);

    long[] groupIds = getGroupIds(preferences, scopeGroupId, layout);

    assetEntryQuery.setGroupIds(groupIds);

    boolean showOnlyLayoutAssets =
        GetterUtil.getBoolean(preferences.getValue("showOnlyLayoutAssets", null));

    if (showOnlyLayoutAssets) {
      assetEntryQuery.setLayout(layout);
    }

    String orderByColumn1 =
        GetterUtil.getString(preferences.getValue("orderByColumn1", "modifiedDate"));

    assetEntryQuery.setOrderByCol1(orderByColumn1);

    String orderByColumn2 = GetterUtil.getString(preferences.getValue("orderByColumn2", "title"));

    assetEntryQuery.setOrderByCol2(orderByColumn2);

    String orderByType1 = GetterUtil.getString(preferences.getValue("orderByType1", "DESC"));

    assetEntryQuery.setOrderByType1(orderByType1);

    String orderByType2 = GetterUtil.getString(preferences.getValue("orderByType2", "ASC"));

    assetEntryQuery.setOrderByType2(orderByType2);

    assetEntryQuery.setStart(0);

    if (checkPermission) {
      return AssetEntryServiceUtil.getEntries(assetEntryQuery);
    } else {
      return AssetEntryLocalServiceUtil.getEntries(assetEntryQuery);
    }
  }
  @Test
  public void testAsstTags() throws Exception {
    long folderId = parentFolder.getFolderId();
    String name = "TestTags.txt";
    String description = StringPool.BLANK;
    String changeLog = StringPool.BLANK;
    byte[] bytes = CONTENT.getBytes();

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);
    serviceContext.setScopeGroupId(group.getGroupId());

    String[] assetTagNames = new String[] {"hello", "world"};

    serviceContext.setAssetTagNames(assetTagNames);

    FileEntry fileEntry =
        DLAppServiceUtil.addFileEntry(
            group.getGroupId(),
            folderId,
            name,
            ContentTypes.TEXT_PLAIN,
            name,
            description,
            changeLog,
            bytes,
            serviceContext);

    AssetEntry assetEntry =
        AssetEntryLocalServiceUtil.fetchEntry(
            DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    AssertUtils.assertEqualsSorted(assetTagNames, assetEntry.getTagNames());

    Thread.sleep(1000 * TestPropsValues.JUNIT_DELAY_FACTOR);

    _fileEntry = fileEntry;

    search(_fileEntry, false, "hello", true);
    search(_fileEntry, false, "world", true);
    search(_fileEntry, false, "liferay", false);

    assetTagNames = new String[] {"hello", "world", "liferay"};

    serviceContext.setAssetTagNames(assetTagNames);

    fileEntry =
        DLAppServiceUtil.updateFileEntry(
            fileEntry.getFileEntryId(),
            name,
            ContentTypes.TEXT_PLAIN,
            name,
            description,
            changeLog,
            false,
            bytes,
            serviceContext);

    assetEntry =
        AssetEntryLocalServiceUtil.fetchEntry(
            DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    AssertUtils.assertEqualsSorted(assetTagNames, assetEntry.getTagNames());

    Thread.sleep(1000 * TestPropsValues.JUNIT_DELAY_FACTOR);

    _fileEntry = fileEntry;

    search(_fileEntry, false, "hello", true);
    search(_fileEntry, false, "world", true);
    search(_fileEntry, false, "liferay", true);

    DLAppServiceUtil.deleteFileEntry(_fileEntry.getFileEntryId());

    _fileEntry = null;
  }
Пример #22
0
  private String formatJournalArticleURL() {

    /* This checks if the object is viewable by the current user and, if so, works out
     * the original url for the search results. The "visible" flag variable is set for each one.
     */

    Long lGroupId;
    Long lArticleId;
    Long lUserId;
    String strJournalURL = Global.strNoURLReturned;

    JournalContentSearchLocalServiceUtil jcslu = new JournalContentSearchLocalServiceUtil();
    LayoutLocalServiceUtil llsu = new LayoutLocalServiceUtil();
    List<Long> listLayouts = new ArrayList<Long>();
    Layout layLayout;
    User user;
    int iCount = 0;
    this.isVisible = false;

    try {
      this.context = FacesContext.getCurrentInstance();
      this.portletRequest = (PortletRequest) context.getExternalContext().getRequest();
      this.themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY);
    } catch (Exception e) {
      System.out.println(e);
    }

    try {
      lGroupId = Long.decode(this.getGroupId());
    } catch (NumberFormatException n) {
      lGroupId = 0l; // zero long, not letter O
    }

    try {
      lArticleId = Long.decode(this.getArticleId());
    } catch (NumberFormatException n) {
      lArticleId = 0l; // zero long, not letter O
    }

    try {
      lUserId = Long.decode(this.getUserId());
    } catch (NumberFormatException n) {
      lUserId = 0l; // zero long, not letter O
    }

    if ((lGroupId != 0) && (lArticleId != 0)) {
      try {
        try {
          permissionChecker = themeDisplay.getPermissionChecker();
          this.setIsVisible(
              permissionChecker.hasPermission(
                  lGroupId, this.entryClassName, this.rootEntryClassPK, ActionKeys.VIEW));
          if (this.isIsVisible()) {
            if (getEntryClassName().equalsIgnoreCase(JournalArticle.class.getName())) {
              iCount = jcslu.getLayoutIdsCount(lGroupId, false, articleId);
              listLayouts = jcslu.getLayoutIds(lGroupId, false, articleId);
              if (iCount > 0) {
                layLayout = llsu.getLayout(lGroupId, false, listLayouts.get(0));
                layoutFriendlyURL = PortalUtil.getLayoutFriendlyURL(layLayout, themeDisplay);
                layoutFullURL =
                    PortalUtil.getLayoutActualURL(layLayout, themeDisplay.getPathMain());
                strHost = portletRequest.getServerName();
                iServerPort = portletRequest.getServerPort();
                strScheme = portletRequest.getScheme();

                if (layoutFullURL.startsWith("http://")) {
                  strJournalURL = layoutFullURL;
                } else {
                  if (strHost.equalsIgnoreCase("localhost")) {
                    strJournalURL =
                        strScheme + "://" + strHost + ":" + iServerPort + layoutFriendlyURL;
                  } else {
                    strJournalURL = layoutFriendlyURL;
                  }
                }
              }
            } else if (getEntryClassName().equalsIgnoreCase(BlogsEntry.class.getName())) {
              BlogsEntry entry = BlogsEntryLocalServiceUtil.getEntry(lArticleId);

              Group trgtGroup = GroupLocalServiceUtil.getGroup(lGroupId);
              String strFrUrl = trgtGroup.getFriendlyURL();
              String strUrlPath;
              user = UserLocalServiceUtil.getUser(lUserId);

              if (strFrUrl.equalsIgnoreCase("/fishnet")) {
                strUrlPath = "/home/-/blogs/";
              } else if (strFrUrl.equalsIgnoreCase("/fishlink")) {
                strUrlPath = "/home/-/blogs/";
              } else if (strFrUrl.equalsIgnoreCase("/freshwater-biological-association")) {
                strUrlPath = "/home/-/blogs/";
              } else {
                strUrlPath = "/blog/-/blogs/";
              }
              layoutFriendlyURL = "/web" + strFrUrl + strUrlPath + entry.getUrlTitle();

              strHost = portletRequest.getServerName();
              iServerPort = portletRequest.getServerPort();
              strScheme = portletRequest.getScheme();

              strJournalURL = strScheme + "://" + strHost + ":" + iServerPort + layoutFriendlyURL;
            } else if (getEntryClassName().equalsIgnoreCase(WikiPage.class.getName())) {
              WikiPageResource pageResource =
                  WikiPageResourceLocalServiceUtil.getPageResource(lArticleId);

              WikiPage wikiPage =
                  WikiPageLocalServiceUtil.getPage(
                      pageResource.getNodeId(), pageResource.getTitle());
              WikiNode wikiNode = WikiNodeLocalServiceUtil.getNode(pageResource.getNodeId());
              String strWikiNodeName = wikiNode.getName();
              String strWikiTitle = wikiPage.getTitle();
              Long lPageGroupId = wikiPage.getGroupId();
              Group trgtGroup = GroupLocalServiceUtil.getGroup(lPageGroupId);
              String strFrUrl = trgtGroup.getFriendlyURL();

              strHost = portletRequest.getServerName();
              iServerPort = portletRequest.getServerPort();
              strScheme = portletRequest.getScheme();
              // Extremely nasty hack!
              if (strFrUrl.equalsIgnoreCase("/tera")) {
                String strReplacedTitle = strWikiTitle.replaceAll("\\s", "\\+");
                layoutFriendlyURL =
                    "/web"
                        + strFrUrl
                        + "/home?p_p_id=54_INSTANCE_rU18&p_p_lifecycle=0&p_p_state=normal&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_54_INSTANCE_rU18_struts_action=%2Fwiki_display%2Fview&_54_INSTANCE_rU18_nodeName="
                        + strWikiNodeName
                        + "&_54_INSTANCE_rU18_title="
                        + strReplacedTitle;
              } else if (strFrUrl.equalsIgnoreCase("/fwl")) {
                layoutFriendlyURL =
                    "/web" + strFrUrl + "/wiki/-/wiki/" + strWikiNodeName + "/" + strWikiTitle;
              } else if (strFrUrl.equalsIgnoreCase("/fishlink")) {
                layoutFriendlyURL =
                    "/web"
                        + strFrUrl
                        + strFrUrl
                        + "-wiki/-/wiki/"
                        + strWikiNodeName
                        + "/"
                        + strWikiTitle;
              } else {
                layoutFriendlyURL =
                    "/freshwater-wiki/-/wiki/" + strWikiNodeName + "/" + strWikiTitle;
              }
              // </hack>
              strJournalURL = strScheme + "://" + strHost + ":" + iServerPort + layoutFriendlyURL;

            } else if (getEntryClassName().equalsIgnoreCase(DLFileEntry.class.getName())) {
              DLFileEntry fileEntry = DLFileEntryLocalServiceUtil.getFileEntry(lArticleId);
              lGroupId = fileEntry.getGroupId();

              AssetEntry assetEntry =
                  AssetEntryLocalServiceUtil.getEntry(getEntryClassName(), lArticleId);
              Long lEntryId = assetEntry.getEntryId();

              strHost = portletRequest.getServerName();
              iServerPort = portletRequest.getServerPort();
              strScheme = portletRequest.getScheme();
              // Another hack
              layoutFriendlyURL = "/fwl/documents/-/asset_publisher/8Ztl/document/id/" + lEntryId;
              strJournalURL =
                  strScheme + "://" + strHost + ":" + iServerPort + "/web" + layoutFriendlyURL;
              if (fileEntry.getTitle().isEmpty()) {
                this.setTitle("From Document Library");
              } else {
                this.setTitle(fileEntry.getTitle());
              }
              //

            } else if (getEntryClassName().equalsIgnoreCase(IGImage.class.getName())) {
              IGImage image = IGImageLocalServiceUtil.getImage(lArticleId);

              strHost = portletRequest.getServerName();
              iServerPort = portletRequest.getServerPort();
              strScheme = portletRequest.getScheme();

              layoutFriendlyURL = "igimage.fba.org.uk";
              // if (layoutFullURL.startsWith("http://")) {
              // strJournalURL = layoutFullURL;
              // } else {
              strJournalURL = strScheme + "://" + strHost + ":" + iServerPort + layoutFriendlyURL;
              // }
              // PortletURL viewImageURL = new PortletURLImpl(request, PortletKeys.IMAGE_GALLERY,
              // plid, PortletRequest.RENDER_PHASE);

              // viewImageURL.setWindowState(WindowState.MAXIMIZED);

              // viewImageURL.setParameter("struts_action", "/image_gallery/view");
              // viewImageURL.setParameter("folderId", String.valueOf(image.getFolderId()));

            } else if (getEntryClassName().equalsIgnoreCase(MBMessage.class.getName())) {
              MBMessage message = MBMessageLocalServiceUtil.getMessage(lArticleId);
              String aHref =
                  "<a href="
                      + themeDisplay.getPathMain()
                      + "/message_boards/find_message?messageId="
                      + message.getMessageId()
                      + ">";
              strHost = portletRequest.getServerName();
              iServerPort = portletRequest.getServerPort();
              strScheme = portletRequest.getScheme();

              layoutFriendlyURL = "mbmessage.fba.org.uk";
              // if (layoutFullURL.startsWith("http://")) {
              // strJournalURL = layoutFullURL;
              // } else {
              strJournalURL = strScheme + "://" + strHost + ":" + iServerPort + layoutFriendlyURL;
              // }

            } else if (getEntryClassName().equalsIgnoreCase(BookmarksEntry.class.getName())) {
              BookmarksEntry entry = BookmarksEntryLocalServiceUtil.getEntry(lArticleId);

              String entryURL =
                  themeDisplay.getPathMain()
                      + "/bookmarks/open_entry?entryId="
                      + entry.getEntryId();

              strHost = portletRequest.getServerName();
              iServerPort = portletRequest.getServerPort();
              strScheme = portletRequest.getScheme();

              layoutFriendlyURL = "bookmarks.fba.org.uk";
              // if (layoutFullURL.startsWith("http://")) {
              // strJournalURL = layoutFullURL;
              // } else {
              strJournalURL = strScheme + "://" + strHost + ":" + iServerPort + layoutFriendlyURL;
              // }

            }
          }
        } catch (PortalException ex) {
          Logger.getLogger(Liferay.class.getName()).log(Level.SEVERE, null, ex);
        }
      } catch (SystemException ex) {
        Logger.getLogger(Liferay.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
    return strJournalURL;
  }
  protected void readAssetLinks(PortletDataContext portletDataContext) throws Exception {

    String xml =
        portletDataContext.getZipEntryAsString(
            ExportImportPathUtil.getSourceRootPath(portletDataContext) + "/links.xml");

    if (xml == null) {
      return;
    }

    Document document = SAXReaderUtil.read(xml);

    Element rootElement = document.getRootElement();

    List<Element> assetLinkGroupElements = rootElement.elements("asset-link-group");

    for (Element assetLinkGroupElement : assetLinkGroupElements) {
      String sourceUuid = assetLinkGroupElement.attributeValue("source-uuid");

      AssetEntry sourceAssetEntry =
          AssetEntryLocalServiceUtil.fetchEntry(portletDataContext.getScopeGroupId(), sourceUuid);

      if (sourceAssetEntry == null) {
        sourceAssetEntry =
            AssetEntryLocalServiceUtil.fetchEntry(
                portletDataContext.getCompanyGroupId(), sourceUuid);
      }

      if (sourceAssetEntry == null) {
        if (_log.isWarnEnabled()) {
          _log.warn("Unable to find asset entry with uuid " + sourceUuid);
        }

        continue;
      }

      List<Element> assetLinksElements = assetLinkGroupElement.elements("asset-link");

      for (Element assetLinkElement : assetLinksElements) {
        String path = assetLinkElement.attributeValue("path");

        if (!portletDataContext.isPathNotProcessed(path)) {
          continue;
        }

        String targetUuid = assetLinkElement.attributeValue("target-uuid");

        AssetEntry targetAssetEntry =
            AssetEntryLocalServiceUtil.fetchEntry(portletDataContext.getScopeGroupId(), targetUuid);

        if (targetAssetEntry == null) {
          targetAssetEntry =
              AssetEntryLocalServiceUtil.fetchEntry(
                  portletDataContext.getCompanyGroupId(), targetUuid);
        }

        if (targetAssetEntry == null) {
          if (_log.isWarnEnabled()) {
            _log.warn("Unable to find asset entry with uuid " + targetUuid);
          }

          continue;
        }

        AssetLink assetLink = (AssetLink) portletDataContext.getZipEntryAsObject(path);

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

        AssetLinkLocalServiceUtil.updateLink(
            userId,
            sourceAssetEntry.getEntryId(),
            targetAssetEntry.getEntryId(),
            assetLink.getType(),
            assetLink.getWeight());
      }
    }
  }
Пример #24
0
  @RenderMapping(params = "action=ricercaLibera")
  public String effettuaRicerca(
      RenderRequest renderRequest,
      RenderResponse renderResponse,
      Model model,
      @ModelAttribute("navigaProgetti") NavigaProgetti navigaProgetti,
      @RequestParam("cercaPerKeyword") String cercaPerKeyword) {

    model.addAttribute("currentAction", "ricercaLibera");
    navigaProgetti.setCurrentAction("ricercaLibera");

    model.addAttribute("cercaPerKeyword", cercaPerKeyword);
    model.addAttribute("navigaProgetti", navigaProgetti);

    logger.info("effettuaRicerca.cercaPerKeyword: " + cercaPerKeyword);
    try {

      Document[] documents = null;
      List<DocumentoDTO> risultatiGenerici = new ArrayList<DocumentoDTO>();
      List<Progetto> risultatiProgetti = new ArrayList<Progetto>();

      if (cercaPerKeyword != null && cercaPerKeyword.length() > 3) {
        Query query =
            StringQueryFactoryUtil.create(
                Field.TITLE
                    + ":"
                    + cercaPerKeyword
                    + " or "
                    + Field.CONTENT
                    + ":"
                    + cercaPerKeyword
                    + " or "
                    + Constants.RICERCALIBERA_FIELD_SEARCH
                    + ":"
                    + cercaPerKeyword
                    + " or "
                    + Constants.RICERCALIBERA_FIELD_LOCALIZZAZIONE
                    + ":"
                    + cercaPerKeyword
                    + " or "
                    + Constants.RICERCALIBERA_FIELD_CODICE_CUP
                    + ":"
                    + cercaPerKeyword);

        logger.debug("query = " + query.toString());

        Hits hits =
            SearchEngineUtil.search(
                SearchEngineUtil.SYSTEM_ENGINE_ID, PortalUtil.getDefaultCompanyId(), query, -1, -1);

        logger.info("hits = " + hits.getLength());
        documents = hits.getDocs();
        model.addAttribute("valoreRicercaValido", "SI");
      } else {
        SessionMessages.add(renderRequest, "valore-ricerca-non-valido");
        model.addAttribute("valoreRicercaValido", "NO");
      }

      if (documents != null) {
        DocumentoDTO documento = null;
        Progetto progetto = null;
        int contaDoc = 0;
        for (Document document : documents) {
          logger.debug("Document: " + document.getUID());

          //					for (Map.Entry<String, Field> entry : document.getFields().entrySet() ) {
          //						logger.debug("-- " +  entry.getKey() + ": " + entry.getValue().getValue() );
          //					}

          if (document.get(Field.ENTRY_CLASS_NAME).equals(Progetto.class.getName())) {

            progetto = getProgettoFromDocument(document);
            risultatiProgetti.add(progetto);

          } else {

            documento = new DocumentoDTO();
            documento.setTitolo(document.getField(Field.TITLE).getValue());
            String testo = "non disponibile";
            if (document.getField(Field.CONTENT) != null) {
              testo = trunc(document.getField(Field.CONTENT).getValue(), 37);
            }
            documento.setTesto(testo);
            documento.setId(contaDoc++);

            AssetEntry assetEntry =
                AssetEntryLocalServiceUtil.getEntry(
                    document.get(Field.ENTRY_CLASS_NAME),
                    Long.parseLong(document.get(Field.ENTRY_CLASS_PK)));
            documento.setUrl(
                getAssetViewURL(renderRequest, renderResponse, assetEntry, cercaPerKeyword));

            risultatiGenerici.add(documento);
          }
        }
      }

      // model.addAttribute("risultatiGenerici", risultatiGenerici);
      model.addAttribute("risultatiGenericiSize", risultatiGenerici.size());

      SearchContainer<DocumentoDTO> searchContainerElencoDoc =
          new SearchContainer<DocumentoDTO>(
              renderRequest,
              renderResponse.createRenderURL(),
              null,
              "Nessun dato trovato per la selezione fatta");
      searchContainerElencoDoc.setDelta(risultatiGenerici.size());
      searchContainerElencoDoc.setTotal(risultatiGenerici.size());
      searchContainerElencoDoc.setResults(risultatiGenerici);
      model.addAttribute("searchContainerElencoDoc", searchContainerElencoDoc);

      // model.addAttribute("risultatiProgetti", risultatiProgetti);
      SearchContainer<Progetto> searchContainerElencoPro =
          new SearchContainer<Progetto>(
              renderRequest,
              renderResponse.createRenderURL(),
              null,
              "Nessun dato trovato per la selezione fatta");
      searchContainerElencoPro.setDelta(risultatiProgetti.size());
      searchContainerElencoPro.setTotal(risultatiProgetti.size());
      searchContainerElencoPro.setResults(risultatiProgetti);
      model.addAttribute("searchContainerElenco", searchContainerElencoPro);

    } catch (SearchException e) {
      logger.error("SearchException: ", e);
    } catch (NumberFormatException e) {
      logger.error("NumberFormatException: ", e);
    } catch (PortalException e) {
      logger.error("PortalException: ", e);
    } catch (SystemException e) {
      logger.error("SystemException: ", e);
    }

    return "elenco-progetti-view";
  }