protected String getSaveAndContinueRedirect(
      ActionRequest actionRequest, BlogsEntry entry, String redirect) throws Exception {

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

    PortletConfig portletConfig =
        (PortletConfig) actionRequest.getAttribute(JavaConstants.JAVAX_PORTLET_CONFIG);

    String backURL = ParamUtil.getString(actionRequest, "backURL");

    PortletURLImpl portletURL =
        new PortletURLImpl(
            actionRequest,
            portletConfig.getPortletName(),
            themeDisplay.getPlid(),
            PortletRequest.RENDER_PHASE);

    portletURL.setParameter("mvcRenderCommandName", "/blogs/edit_entry");

    portletURL.setParameter(Constants.CMD, Constants.UPDATE, false);
    portletURL.setParameter("redirect", redirect, false);
    portletURL.setParameter("backURL", backURL, false);
    portletURL.setParameter("groupId", String.valueOf(entry.getGroupId()), false);
    portletURL.setParameter("entryId", String.valueOf(entry.getEntryId()), false);
    portletURL.setWindowState(actionRequest.getWindowState());

    return portletURL.toString();
  }
  @Override
  public ActionForward render(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig portletConfig,
      RenderRequest renderRequest,
      RenderResponse renderResponse)
      throws Exception {

    try {
      ActionUtil.getEntry(renderRequest);

      if (PropsValues.BLOGS_PINGBACK_ENABLED) {
        BlogsEntry entry = (BlogsEntry) renderRequest.getAttribute(WebKeys.BLOGS_ENTRY);

        if ((entry != null) && entry.isAllowPingbacks()) {
          HttpServletResponse response = PortalUtil.getHttpServletResponse(renderResponse);

          response.addHeader(
              "X-Pingback", PortalUtil.getPortalURL(renderRequest) + "/xmlrpc/pingback");
        }
      }
    } catch (Exception e) {
      if (e instanceof NoSuchEntryException || e instanceof PrincipalException) {

        SessionErrors.add(renderRequest, e.getClass().getName());

        return mapping.findForward("portlet.blogs.error");
      } else {
        throw e;
      }
    }

    return mapping.findForward(getForward(renderRequest, "portlet.blogs.edit_entry"));
  }
  @Override
  public void serveResource(
      StrutsPortletAction originalStrutsPortletAction,
      PortletConfig portletConfig,
      ResourceRequest resourceRequest,
      ResourceResponse resourceResponse) {

    long entryId = ParamUtil.getLong(resourceRequest, "entryId");
    ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);

    BlogsEntry entry;
    try {
      entry = BlogsEntryServiceUtil.getEntry(entryId);
      StringBundler sb = new StringBundler();

      sb.append("<html>");

      sb.append("<head>");
      sb.append("<meta content=\"");
      sb.append(ContentTypes.TEXT_HTML_UTF8);
      sb.append("\" http-equiv=\"content-type\" />");
      sb.append("<base href=\"");
      sb.append(themeDisplay.getPortalURL());
      sb.append("\" />");
      sb.append("</head>");

      sb.append("<body>");
      sb.append(entry.getContent());
      sb.append("</body>");
      sb.append("</html>");

      InputStream is = new UnsyncByteArrayInputStream(sb.toString().getBytes(StringPool.UTF8));
      File destinationFile = null;

      destinationFile = DocumentConversionUtil.convert(entry.getEntryId() + "", is, "html", "pdf");
      OutputStream out = resourceResponse.getPortletOutputStream();
      InputStream in = new FileInputStream(destinationFile);
      HttpServletResponse httpRes = PortalUtil.getHttpServletResponse(resourceResponse);
      HttpServletRequest httpReq = PortalUtil.getHttpServletRequest(resourceRequest);
      String contentType = MimeTypesUtil.getContentType(destinationFile);
      ServletResponseUtil.sendFile(httpReq, httpRes, destinationFile.getName(), in, contentType);
      out.close();

    } catch (PortalException e) {
      System.out.println("PortalException : " + getClass().getName() + "\n" + e);
      // e.printStackTrace();
    } catch (SystemException e) {
      System.out.println("SystemException : " + getClass().getName() + "\n" + e);
      // e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      System.out.println("UnsupportedEncodingException : " + getClass().getName() + "\n" + e);
      // e.printStackTrace();
    } catch (Exception e) {
      System.out.println("Exception : " + getClass().getName() + "\n" + e);
      // e.printStackTrace();
    }
  }
  public BlogsEntry getEntry(long groupId, String urlTitle)
      throws PortalException, SystemException {

    BlogsEntry entry = blogsEntryLocalService.getEntry(groupId, urlTitle);

    BlogsEntryPermission.check(getPermissionChecker(), entry.getEntryId(), ActionKeys.VIEW);

    return entry;
  }
Example #5
0
  @Override
  protected void doReindex(Object obj) throws Exception {
    BlogsEntry entry = (BlogsEntry) obj;

    Document document = getDocument(entry);

    SearchEngineUtil.updateDocument(
        getSearchEngineId(), entry.getCompanyId(), document, isCommitImmediately());
  }
  @Test
  public void testEmailEntryUpdatedNotSentIfNotSpecified() throws Exception {
    BlogsEntry entry = BlogsTestUtil.addEntry(_group, true);

    BlogsEntryLocalServiceUtil.subscribe(_user.getUserId(), _group.getGroupId());

    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(entry.getGroupId());

    serviceContext.setAttribute("emailEntryUpdatedComment", "This entry was updated.");

    BlogsTestUtil.updateEntry(entry, StringUtil.randomString(), true, serviceContext);

    Assert.assertEquals(0, MailServiceTestUtil.getInboxSize());
  }
  @Override
  protected void doImportMissingReference(
      PortletDataContext portletDataContext, String uuid, long groupId, long entryId)
      throws Exception {

    BlogsEntry existingEntry = fetchMissingReference(uuid, groupId);

    if (existingEntry == null) {
      return;
    }

    Map<Long, Long> entryIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(BlogsEntry.class);

    entryIds.put(entryId, existingEntry.getEntryId());
  }
  @Override
  protected void doExportStagedModel(PortletDataContext portletDataContext, BlogsEntry entry)
      throws Exception {

    Element entryElement = portletDataContext.getExportDataElement(entry);

    if (entry.isSmallImage()) {
      Image smallImage = _imageLocalService.fetchImage(entry.getSmallImageId());

      if (smallImage != null) {
        String smallImagePath =
            ExportImportPathUtil.getModelPath(
                entry, smallImage.getImageId() + StringPool.PERIOD + smallImage.getType());

        entryElement.addAttribute("small-image-path", smallImagePath);

        entry.setSmallImageType(smallImage.getType());

        portletDataContext.addZipEntry(smallImagePath, smallImage.getTextObj());
      }
    }

    if (entry.getSmallImageFileEntryId() != 0) {
      FileEntry fileEntry =
          PortletFileRepositoryUtil.getPortletFileEntry(entry.getSmallImageFileEntryId());

      StagedModelDataHandlerUtil.exportReferenceStagedModel(
          portletDataContext, entry, fileEntry, PortletDataContext.REFERENCE_TYPE_WEAK);
    }

    if (entry.getCoverImageFileEntryId() != 0) {
      FileEntry fileEntry =
          PortletFileRepositoryUtil.getPortletFileEntry(entry.getCoverImageFileEntryId());

      StagedModelDataHandlerUtil.exportReferenceStagedModel(
          portletDataContext, entry, fileEntry, PortletDataContext.REFERENCE_TYPE_WEAK);
    }

    String content =
        _blogsEntryExportImportContentProcessor.replaceExportContentReferences(
            portletDataContext,
            entry,
            entry.getContent(),
            portletDataContext.getBooleanParameter("blogs", "referenced-content"),
            true);

    entry.setContent(content);

    portletDataContext.addClassedModel(
        entryElement, ExportImportPathUtil.getModelPath(entry), entry);
  }
  @Test
  public void testEmailEntryUpdatedSentWithEmptyEmailEntryUpdatedComment() throws Exception {

    setUpBlogsSettings();

    BlogsEntry entry = BlogsTestUtil.addEntry(_group, true);

    BlogsEntryLocalServiceUtil.subscribe(_user.getUserId(), _group.getGroupId());

    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(entry.getGroupId());

    serviceContext.setAttribute("sendEmailEntryUpdated", Boolean.TRUE.toString());

    BlogsTestUtil.updateEntry(entry, StringUtil.randomString(), true, serviceContext);

    MailMessage message = MailServiceTestUtil.getLastMailMessage();

    Assert.assertEquals(message.getBody(), StringPool.NEW_LINE);
  }
  @Override
  public String render(RenderRequest renderRequest, RenderResponse renderResponse)
      throws PortletException {

    try {
      ActionUtil.getEntry(renderRequest);

      if (PropsValues.BLOGS_PINGBACK_ENABLED) {
        BlogsEntry entry = (BlogsEntry) renderRequest.getAttribute(WebKeys.BLOGS_ENTRY);

        if ((entry != null) && entry.isAllowPingbacks()) {
          HttpServletResponse response = PortalUtil.getHttpServletResponse(renderResponse);

          response.addHeader(
              "X-Pingback", PortalUtil.getPortalURL(renderRequest) + "/xmlrpc/pingback");
        }
      }
    } catch (Exception e) {
      if (e instanceof NoSuchEntryException || e instanceof PrincipalException) {

        SessionErrors.add(renderRequest, e.getClass());

        return "/html/portlet/blogs/error.jsp";
      } else {
        throw new PortletException(e);
      }
    }

    long assetCategoryId = ParamUtil.getLong(renderRequest, "categoryId");
    String assetCategoryName = ParamUtil.getString(renderRequest, "tag");

    if ((assetCategoryId > 0) || Validator.isNotNull(assetCategoryName)) {
      return "/html/portlet/blogs/view.jsp";
    }

    return getPath();
  }
  protected String getSaveAndContinueRedirect(
      PortletConfig portletConfig, ActionRequest actionRequest, BlogsEntry entry, String redirect)
      throws Exception {

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

    String backURL = ParamUtil.getString(actionRequest, "backURL");

    boolean preview = ParamUtil.getBoolean(actionRequest, "preview");

    PortletURLImpl portletURL =
        new PortletURLImpl(
            actionRequest,
            portletConfig.getPortletName(),
            themeDisplay.getPlid(),
            PortletRequest.RENDER_PHASE);

    portletURL.setWindowState(actionRequest.getWindowState());

    String portletName = portletConfig.getPortletName();

    if (portletName.equals(PortletKeys.BLOGS_ADMIN)) {
      portletURL.setParameter("struts_action", "/blogs_admin/edit_entry");
    } else {
      portletURL.setParameter("struts_action", "/blogs/edit_entry");
    }

    portletURL.setParameter(Constants.CMD, Constants.UPDATE, false);
    portletURL.setParameter("redirect", redirect, false);
    portletURL.setParameter("backURL", backURL, false);
    portletURL.setParameter("groupId", String.valueOf(entry.getGroupId()), false);
    portletURL.setParameter("entryId", String.valueOf(entry.getEntryId()), false);
    portletURL.setParameter("preview", String.valueOf(preview), false);

    return portletURL.toString();
  }
Example #12
0
  @Override
  protected Document doGetDocument(Object obj) throws Exception {
    BlogsEntry entry = (BlogsEntry) obj;

    Document document = getBaseModelDocument(CLASS_NAME, entry);

    document.addText(Field.CONTENT, HtmlUtil.extractText(entry.getContent()));
    document.addText(Field.SUBTITLE, entry.getSubtitle());
    document.addText(Field.DESCRIPTION, entry.getDescription());
    document.addDate(Field.MODIFIED_DATE, entry.getModifiedDate());
    document.addText(Field.TITLE, entry.getTitle());

    return document;
  }
  @Override
  protected void doRestoreStagedModel(PortletDataContext portletDataContext, BlogsEntry entry)
      throws Exception {

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

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

    if ((existingEntry == null) || !existingEntry.isInTrash()) {
      return;
    }

    TrashHandler trashHandler = existingEntry.getTrashHandler();

    if (trashHandler.isRestorable(existingEntry.getEntryId())) {
      trashHandler.restoreTrashEntry(userId, existingEntry.getEntryId());
    }
  }
  protected Object[] updateEntry(ActionRequest actionRequest) throws Exception {

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

    long entryId = ParamUtil.getLong(actionRequest, "entryId");

    String title = ParamUtil.getString(actionRequest, "title");
    String subtitle = ParamUtil.getString(actionRequest, "subtitle");

    String description = StringPool.BLANK;

    boolean customAbstract = ParamUtil.getBoolean(actionRequest, "customAbstract");

    if (customAbstract) {
      description = ParamUtil.getString(actionRequest, "description");

      if (Validator.isNull(description)) {
        throw new EntryDescriptionException();
      }
    }

    String content = ParamUtil.getString(actionRequest, "content");

    int displayDateMonth = ParamUtil.getInteger(actionRequest, "displayDateMonth");
    int displayDateDay = ParamUtil.getInteger(actionRequest, "displayDateDay");
    int displayDateYear = ParamUtil.getInteger(actionRequest, "displayDateYear");
    int displayDateHour = ParamUtil.getInteger(actionRequest, "displayDateHour");
    int displayDateMinute = ParamUtil.getInteger(actionRequest, "displayDateMinute");
    int displayDateAmPm = ParamUtil.getInteger(actionRequest, "displayDateAmPm");

    if (displayDateAmPm == Calendar.PM) {
      displayDateHour += 12;
    }

    boolean allowPingbacks = ParamUtil.getBoolean(actionRequest, "allowPingbacks");
    boolean allowTrackbacks = ParamUtil.getBoolean(actionRequest, "allowTrackbacks");
    String[] trackbacks = StringUtil.split(ParamUtil.getString(actionRequest, "trackbacks"));

    long coverImageFileEntryId = ParamUtil.getLong(actionRequest, "coverImageFileEntryId");
    String coverImageURL = ParamUtil.getString(actionRequest, "coverImageURL");
    String coverImageFileEntryCropRegion =
        ParamUtil.getString(actionRequest, "coverImageFileEntryCropRegion");

    String coverImageCaption = ParamUtil.getString(actionRequest, "coverImageCaption");

    ImageSelector coverImageImageSelector =
        new ImageSelector(coverImageFileEntryId, coverImageURL, coverImageFileEntryCropRegion);

    long smallImageFileEntryId = ParamUtil.getLong(actionRequest, "smallImageFileEntryId");
    String smallImageURL = ParamUtil.getString(actionRequest, "smallImageURL");

    ImageSelector smallImageImageSelector =
        new ImageSelector(smallImageFileEntryId, smallImageURL, null);

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

    BlogsEntry entry = null;
    String oldUrlTitle = StringPool.BLANK;
    List<BlogsEntryAttachmentFileEntryReference> blogsEntryAttachmentFileEntryReferences =
        new ArrayList<>();

    if (entryId <= 0) {

      // Add entry

      entry =
          BlogsEntryServiceUtil.addEntry(
              title,
              subtitle,
              description,
              content,
              displayDateMonth,
              displayDateDay,
              displayDateYear,
              displayDateHour,
              displayDateMinute,
              allowPingbacks,
              allowTrackbacks,
              trackbacks,
              coverImageCaption,
              coverImageImageSelector,
              smallImageImageSelector,
              serviceContext);

      BlogsEntryAttachmentFileEntryHelper blogsEntryAttachmentFileEntryHelper =
          new BlogsEntryAttachmentFileEntryHelper();

      List<FileEntry> tempBlogsEntryAttachments =
          blogsEntryAttachmentFileEntryHelper.getTempBlogsEntryAttachmentFileEntries(content);

      if (!tempBlogsEntryAttachments.isEmpty()) {
        Folder folder =
            BlogsEntryLocalServiceUtil.addAttachmentsFolder(
                themeDisplay.getUserId(), entry.getGroupId());

        blogsEntryAttachmentFileEntryReferences =
            blogsEntryAttachmentFileEntryHelper.addBlogsEntryAttachmentFileEntries(
                entry.getGroupId(),
                themeDisplay.getUserId(),
                entry.getEntryId(),
                folder.getFolderId(),
                tempBlogsEntryAttachments);

        content =
            blogsEntryAttachmentFileEntryHelper.updateContent(
                content, blogsEntryAttachmentFileEntryReferences);

        entry.setContent(content);

        BlogsEntryLocalServiceUtil.updateBlogsEntry(entry);
      }

      for (FileEntry tempBlogsEntryAttachment : tempBlogsEntryAttachments) {

        PortletFileRepositoryUtil.deletePortletFileEntry(tempBlogsEntryAttachment.getFileEntryId());
      }
    } else {

      // Update entry

      boolean sendEmailEntryUpdated = ParamUtil.getBoolean(actionRequest, "sendEmailEntryUpdated");

      serviceContext.setAttribute("sendEmailEntryUpdated", sendEmailEntryUpdated);

      String emailEntryUpdatedComment =
          ParamUtil.getString(actionRequest, "emailEntryUpdatedComment");

      serviceContext.setAttribute("emailEntryUpdatedComment", emailEntryUpdatedComment);

      entry = BlogsEntryLocalServiceUtil.getEntry(entryId);

      String tempOldUrlTitle = entry.getUrlTitle();

      BlogsEntryAttachmentFileEntryHelper blogsEntryAttachmentHelper =
          new BlogsEntryAttachmentFileEntryHelper();

      List<FileEntry> tempBlogsEntryAttachmentFileEntries =
          blogsEntryAttachmentHelper.getTempBlogsEntryAttachmentFileEntries(content);

      if (!tempBlogsEntryAttachmentFileEntries.isEmpty()) {
        Folder folder =
            BlogsEntryLocalServiceUtil.addAttachmentsFolder(
                themeDisplay.getUserId(), entry.getGroupId());

        blogsEntryAttachmentFileEntryReferences =
            blogsEntryAttachmentHelper.addBlogsEntryAttachmentFileEntries(
                entry.getGroupId(),
                themeDisplay.getUserId(),
                entry.getEntryId(),
                folder.getFolderId(),
                tempBlogsEntryAttachmentFileEntries);

        content =
            blogsEntryAttachmentHelper.updateContent(
                content, blogsEntryAttachmentFileEntryReferences);
      }

      entry =
          BlogsEntryServiceUtil.updateEntry(
              entryId,
              title,
              subtitle,
              description,
              content,
              displayDateMonth,
              displayDateDay,
              displayDateYear,
              displayDateHour,
              displayDateMinute,
              allowPingbacks,
              allowTrackbacks,
              trackbacks,
              coverImageCaption,
              coverImageImageSelector,
              smallImageImageSelector,
              serviceContext);

      for (FileEntry tempBlogsEntryAttachmentFileEntry : tempBlogsEntryAttachmentFileEntries) {

        PortletFileRepositoryUtil.deletePortletFileEntry(
            tempBlogsEntryAttachmentFileEntry.getFileEntryId());
      }

      if (!tempOldUrlTitle.equals(entry.getUrlTitle())) {
        oldUrlTitle = tempOldUrlTitle;
      }
    }

    return new Object[] {entry, oldUrlTitle, blogsEntryAttachmentFileEntryReferences};
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, BlogsEntry entry)
      throws Exception {

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

    Element entryElement = portletDataContext.getImportDataStagedModelElement(entry);

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

    entry.setContent(content);

    Calendar displayDateCal = CalendarFactoryUtil.getCalendar();

    displayDateCal.setTime(entry.getDisplayDate());

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

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

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

    ServiceContext serviceContext = portletDataContext.createServiceContext(entry);

    BlogsEntry importedEntry = null;

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

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

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

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

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

      portletDataContext.importClassedModel(entry, importedEntry);

      return;
    }

    // Cover image

    ImageSelector coverImageSelector = null;

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

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

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

    // Small image

    ImageSelector smallImageSelector = null;

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

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

        InputStream inputStream = null;

        try {
          inputStream = portletDataContext.getZipEntryAsInputStream(smallImagePath);

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

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

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

    portletDataContext.importClassedModel(entry, importedEntry);
  }
  public AssetEntry updateEntry(
      long userId,
      long groupId,
      Date createDate,
      Date modifiedDate,
      String className,
      long classPK,
      String classUuid,
      long classTypeId,
      long[] categoryIds,
      String[] tagNames,
      boolean visible,
      Date startDate,
      Date endDate,
      Date expirationDate,
      String mimeType,
      String title,
      String description,
      String summary,
      String url,
      String layoutUuid,
      int height,
      int width,
      Integer priority,
      boolean sync)
      throws PortalException, SystemException {

    // Entry

    User user = userPersistence.findByPrimaryKey(userId);
    long classNameId = PortalUtil.getClassNameId(className);

    validate(groupId, className, categoryIds, tagNames);

    AssetEntry entry = assetEntryPersistence.fetchByC_C(classNameId, classPK);

    boolean oldVisible = false;

    if (entry != null) {
      oldVisible = entry.isVisible();
    }

    if (modifiedDate == null) {
      modifiedDate = new Date();
    }

    if (entry == null) {
      long entryId = counterLocalService.increment();

      entry = assetEntryPersistence.create(entryId);

      entry.setCompanyId(user.getCompanyId());
      entry.setUserId(user.getUserId());
      entry.setUserName(user.getFullName());

      if (createDate == null) {
        createDate = new Date();
      }

      entry.setCreateDate(createDate);

      entry.setModifiedDate(modifiedDate);
      entry.setClassNameId(classNameId);
      entry.setClassPK(classPK);
      entry.setClassUuid(classUuid);
      entry.setVisible(visible);
      entry.setExpirationDate(expirationDate);

      if (priority == null) {
        entry.setPriority(0);
      }

      entry.setViewCount(0);
    }

    entry.setGroupId(groupId);
    entry.setModifiedDate(modifiedDate);
    entry.setClassTypeId(classTypeId);
    entry.setVisible(visible);
    entry.setStartDate(startDate);
    entry.setEndDate(endDate);
    entry.setExpirationDate(expirationDate);
    entry.setMimeType(mimeType);
    entry.setTitle(title);
    entry.setDescription(description);
    entry.setSummary(summary);
    entry.setUrl(url);
    entry.setLayoutUuid(layoutUuid);
    entry.setHeight(height);
    entry.setWidth(width);

    if (priority != null) {
      entry.setPriority(priority.intValue());
    }

    // Categories

    if (categoryIds != null) {
      assetEntryPersistence.setAssetCategories(entry.getEntryId(), categoryIds);
    }

    // Tags

    if (tagNames != null) {
      long siteGroupId = PortalUtil.getSiteGroupId(groupId);

      List<AssetTag> tags = new ArrayList<AssetTag>(tagNames.length);

      for (String tagName : tagNames) {
        AssetTag tag = null;

        try {
          tag = assetTagLocalService.getTag(siteGroupId, tagName);
        } catch (NoSuchTagException nste) {
          ServiceContext serviceContext = new ServiceContext();

          serviceContext.setAddGroupPermissions(true);
          serviceContext.setAddGuestPermissions(true);
          serviceContext.setScopeGroupId(siteGroupId);

          tag =
              assetTagLocalService.addTag(
                  user.getUserId(),
                  tagName,
                  PropsValues.ASSET_TAG_PROPERTIES_DEFAULT,
                  serviceContext);
        }

        if (tag != null) {
          tags.add(tag);
        }
      }

      List<AssetTag> oldTags = assetEntryPersistence.getAssetTags(entry.getEntryId());

      assetEntryPersistence.setAssetTags(entry.getEntryId(), tags);

      if (entry.isVisible()) {
        boolean isNew = entry.isNew();

        assetEntryPersistence.updateImpl(entry);

        if (isNew) {
          for (AssetTag tag : tags) {
            assetTagLocalService.incrementAssetCount(tag.getTagId(), classNameId);
          }
        } else {
          for (AssetTag oldTag : oldTags) {
            if (!tags.contains(oldTag)) {
              assetTagLocalService.decrementAssetCount(oldTag.getTagId(), classNameId);
            }
          }

          for (AssetTag tag : tags) {
            if (!oldTags.contains(tag)) {
              assetTagLocalService.incrementAssetCount(tag.getTagId(), classNameId);
            }
          }
        }
      } else if (oldVisible) {
        for (AssetTag oldTag : oldTags) {
          assetTagLocalService.decrementAssetCount(oldTag.getTagId(), classNameId);
        }
      }
    }

    // Update entry after tags so that entry listeners have access to the
    // saved categories and tags

    assetEntryPersistence.update(entry);

    // Synchronize

    if (!sync) {
      return entry;
    }

    if (className.equals(BlogsEntry.class.getName())) {
      BlogsEntry blogsEntry = blogsEntryPersistence.findByPrimaryKey(classPK);

      blogsEntry.setTitle(title);

      blogsEntryPersistence.update(blogsEntry);
    } else if (className.equals(BookmarksEntry.class.getName())) {
      BookmarksEntry bookmarksEntry = bookmarksEntryPersistence.findByPrimaryKey(classPK);

      bookmarksEntry.setName(title);
      bookmarksEntry.setDescription(description);
      bookmarksEntry.setUrl(url);

      bookmarksEntryPersistence.update(bookmarksEntry);
    } else if (className.equals(DLFileEntry.class.getName())) {
      DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(classPK);

      dlFileEntry.setTitle(title);
      dlFileEntry.setDescription(description);

      dlFileEntryPersistence.update(dlFileEntry);
    } else if (className.equals(JournalArticle.class.getName())) {
      JournalArticle journalArticle = journalArticlePersistence.findByPrimaryKey(classPK);

      journalArticle.setTitle(title);
      journalArticle.setDescription(description);

      journalArticlePersistence.update(journalArticle);
    } else if (className.equals(MBMessage.class.getName())) {
      MBMessage mbMessage = mbMessagePersistence.findByPrimaryKey(classPK);

      mbMessage.setSubject(title);

      mbMessagePersistence.update(mbMessage);
    } else if (className.equals(WikiPage.class.getName())) {
      WikiPage wikiPage = wikiPagePersistence.findByPrimaryKey(classPK);

      wikiPage.setTitle(title);

      wikiPagePersistence.update(wikiPage);
    }

    return entry;
  }
 @Override
 public String getDisplayName(BlogsEntry entry) {
   return entry.getTitle();
 }
  protected Object[] updateEntry(ActionRequest actionRequest) throws Exception {

    long entryId = ParamUtil.getLong(actionRequest, "entryId");

    String title = ParamUtil.getString(actionRequest, "title");
    String description = ParamUtil.getString(actionRequest, "description");
    String content = ParamUtil.getString(actionRequest, "content");

    int displayDateMonth = ParamUtil.getInteger(actionRequest, "displayDateMonth");
    int displayDateDay = ParamUtil.getInteger(actionRequest, "displayDateDay");
    int displayDateYear = ParamUtil.getInteger(actionRequest, "displayDateYear");
    int displayDateHour = ParamUtil.getInteger(actionRequest, "displayDateHour");
    int displayDateMinute = ParamUtil.getInteger(actionRequest, "displayDateMinute");
    int displayDateAmPm = ParamUtil.getInteger(actionRequest, "displayDateAmPm");

    if (displayDateAmPm == Calendar.PM) {
      displayDateHour += 12;
    }

    boolean allowPingbacks = ParamUtil.getBoolean(actionRequest, "allowPingbacks");
    boolean allowTrackbacks = ParamUtil.getBoolean(actionRequest, "allowTrackbacks");
    String[] trackbacks = StringUtil.split(ParamUtil.getString(actionRequest, "trackbacks"));

    boolean smallImage = false;
    String smallImageURL = null;
    String smallImageFileName = null;
    InputStream smallImageInputStream = null;

    BlogsEntry entry = null;
    String oldUrlTitle = null;

    try {
      boolean ajax = ParamUtil.getBoolean(actionRequest, "ajax");

      if (!ajax) {
        smallImage = ParamUtil.getBoolean(actionRequest, "smallImage");
        smallImageURL = ParamUtil.getString(actionRequest, "smallImageURL");

        if (smallImage && Validator.isNull(smallImageURL)) {
          boolean attachments = ParamUtil.getBoolean(actionRequest, "attachments");

          if (attachments) {
            UploadPortletRequest uploadPortletRequest =
                PortalUtil.getUploadPortletRequest(actionRequest);

            smallImageFileName = uploadPortletRequest.getFileName("smallFile");
            smallImageInputStream = uploadPortletRequest.getFileAsStream("smallFile");
          }
        }
      }

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

      entry = null;
      oldUrlTitle = StringPool.BLANK;

      if (entryId <= 0) {

        // Add entry

        entry =
            BlogsEntryServiceUtil.addEntry(
                title,
                description,
                content,
                displayDateMonth,
                displayDateDay,
                displayDateYear,
                displayDateHour,
                displayDateMinute,
                allowPingbacks,
                allowTrackbacks,
                trackbacks,
                smallImage,
                smallImageURL,
                smallImageFileName,
                smallImageInputStream,
                serviceContext);

        AssetPublisherUtil.addAndStoreSelection(
            actionRequest, BlogsEntry.class.getName(), entry.getEntryId(), -1);
      } else {

        // Update entry

        entry = BlogsEntryLocalServiceUtil.getEntry(entryId);

        String tempOldUrlTitle = entry.getUrlTitle();

        entry =
            BlogsEntryServiceUtil.updateEntry(
                entryId,
                title,
                description,
                content,
                displayDateMonth,
                displayDateDay,
                displayDateYear,
                displayDateHour,
                displayDateMinute,
                allowPingbacks,
                allowTrackbacks,
                trackbacks,
                smallImage,
                smallImageURL,
                smallImageFileName,
                smallImageInputStream,
                serviceContext);

        if (!tempOldUrlTitle.equals(entry.getUrlTitle())) {
          oldUrlTitle = tempOldUrlTitle;
        }

        AssetPublisherUtil.addAndStoreSelection(
            actionRequest, BlogsEntry.class.getName(), entry.getEntryId(), -1);
      }
    } finally {
      StreamUtil.cleanUp(smallImageInputStream);
    }

    return new Object[] {entry, oldUrlTitle};
  }
Example #19
0
  @Override
  protected void doDelete(Object obj) throws Exception {
    BlogsEntry entry = (BlogsEntry) obj;

    deleteDocument(entry.getCompanyId(), entry.getEntryId());
  }
  @Override
  public void processAction(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse)
      throws Exception {

    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

    try {
      BlogsEntry entry = null;
      String oldUrlTitle = StringPool.BLANK;

      if (cmd.equals(Constants.ADD) || cmd.equals(Constants.UPDATE)) {
        Object[] returnValue = updateEntry(actionRequest);

        entry = (BlogsEntry) returnValue[0];
        oldUrlTitle = ((String) returnValue[1]);
      } else if (cmd.equals(Constants.DELETE)) {
        deleteEntries(actionRequest);
      } else if (cmd.equals(Constants.SUBSCRIBE)) {
        subscribe(actionRequest);
      } else if (cmd.equals(Constants.UNSUBSCRIBE)) {
        unsubscribe(actionRequest);
      }

      String redirect = ParamUtil.getString(actionRequest, "redirect");
      boolean updateRedirect = false;

      if (redirect.contains("/blogs/" + oldUrlTitle + "/maximized")) {
        oldUrlTitle += "/maximized";
      }

      if ((entry != null)
          && (Validator.isNotNull(oldUrlTitle))
          && (redirect.endsWith("/blogs/" + oldUrlTitle)
              || redirect.contains("/blogs/" + oldUrlTitle + "?")
              || redirect.contains("/blog/" + oldUrlTitle + "?"))) {

        int pos = redirect.indexOf("?");

        if (pos == -1) {
          pos = redirect.length();
        }

        String newRedirect = redirect.substring(0, pos - oldUrlTitle.length());

        newRedirect += entry.getUrlTitle();

        if (oldUrlTitle.indexOf("/maximized") != -1) {
          newRedirect += "/maximized";
        }

        if (pos < redirect.length()) {
          newRedirect += "?" + redirect.substring(pos + 1);
        }

        redirect = newRedirect;
        updateRedirect = true;
      }

      int workflowAction =
          ParamUtil.getInteger(
              actionRequest, "workflowAction", WorkflowConstants.ACTION_SAVE_DRAFT);

      boolean ajax = ParamUtil.getBoolean(actionRequest, "ajax");

      if (ajax) {
        JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

        jsonObject.put("entryId", entry.getEntryId());
        jsonObject.put("redirect", redirect);
        jsonObject.put("updateRedirect", updateRedirect);

        writeJSON(actionRequest, actionResponse, jsonObject);

        return;
      }

      if ((entry != null) && (workflowAction == WorkflowConstants.ACTION_SAVE_DRAFT)) {

        redirect = getSaveAndContinueRedirect(portletConfig, actionRequest, entry, redirect);

        sendRedirect(actionRequest, actionResponse, redirect);
      } else {
        WindowState windowState = actionRequest.getWindowState();

        if (!windowState.equals(LiferayWindowState.POP_UP)) {
          sendRedirect(actionRequest, actionResponse, redirect);
        } else {
          redirect = PortalUtil.escapeRedirect(redirect);

          if (Validator.isNotNull(redirect)) {
            actionResponse.sendRedirect(redirect);
          }
        }
      }
    } catch (Exception e) {
      if (e instanceof NoSuchEntryException || e instanceof PrincipalException) {

        SessionErrors.add(actionRequest, e.getClass().getName());

        setForward(actionRequest, "portlet.blogs.error");
      } else if (e instanceof EntryContentException
          || e instanceof EntryDisplayDateException
          || e instanceof EntrySmallImageNameException
          || e instanceof EntrySmallImageSizeException
          || e instanceof EntryTitleException) {

        SessionErrors.add(actionRequest, e.getClass().getName());
      } else if (e instanceof AssetCategoryException || e instanceof AssetTagException) {

        SessionErrors.add(actionRequest, e.getClass().getName(), e);
      } else {
        throw e;
      }
    }
  }
Example #21
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;
  }
Example #22
0
  @Override
  public boolean isVisible(long classPK, int status) throws Exception {
    BlogsEntry entry = BlogsEntryLocalServiceUtil.getEntry(classPK);

    return isVisible(entry.getStatus(), status);
  }
  protected String exportToRSS(
      String name,
      String description,
      String type,
      double version,
      String displayStyle,
      String feedURL,
      String entryURL,
      List blogsEntries)
      throws SystemException {

    SyndFeed syndFeed = new SyndFeedImpl();

    syndFeed.setFeedType(type + "_" + version);
    syndFeed.setTitle(name);
    syndFeed.setLink(feedURL);
    syndFeed.setDescription(GetterUtil.getString(description, name));

    List entries = new ArrayList();

    syndFeed.setEntries(entries);

    Iterator itr = blogsEntries.iterator();

    while (itr.hasNext()) {
      BlogsEntry entry = (BlogsEntry) itr.next();

      String author = PortalUtil.getUserName(entry.getUserId(), entry.getUserName());

      String link = entryURL;

      if (link.endsWith("/blogs/rss")) {
        link = link.substring(0, link.length() - 3) + entry.getUrlTitle();
      } else {
        if (!link.endsWith("?")) {
          link += "&";
        }

        link += "entryId=" + entry.getEntryId();
      }

      String value = null;

      if (displayStyle.equals(RSSUtil.DISPLAY_STYLE_ABSTRACT)) {
        value =
            StringUtil.shorten(
                Html.stripHtml(entry.getContent()), _RSS_ABSTRACT_LENGTH, StringPool.BLANK);
      } else {
        value = entry.getContent();
      }

      SyndEntry syndEntry = new SyndEntryImpl();

      syndEntry.setAuthor(author);
      syndEntry.setTitle(entry.getTitle());
      syndEntry.setLink(link);
      syndEntry.setPublishedDate(entry.getCreateDate());

      SyndContent syndContent = new SyndContentImpl();

      syndContent.setType("html");
      syndContent.setValue(value);

      syndEntry.setDescription(syndContent);

      entries.add(syndEntry);
    }

    try {
      return RSSUtil.export(syndFeed);
    } catch (FeedException fe) {
      throw new SystemException(fe);
    } catch (IOException ioe) {
      throw new SystemException(ioe);
    }
  }
  @Override
  protected void doProcessAction(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

    try {
      BlogsEntry entry = null;
      String oldUrlTitle = StringPool.BLANK;
      List<BlogsEntryAttachmentFileEntryReference> blogsEntryAttachmentFileEntryReferences = null;

      UploadException uploadException =
          (UploadException) actionRequest.getAttribute(WebKeys.UPLOAD_EXCEPTION);

      if (uploadException != null) {
        if (uploadException.isExceededLiferayFileItemSizeLimit()) {
          throw new LiferayFileItemException();
        } else if (uploadException.isExceededSizeLimit()) {
          throw new FileSizeException(uploadException.getCause());
        }

        throw new PortalException(uploadException.getCause());
      } else if (cmd.equals(Constants.ADD) || cmd.equals(Constants.UPDATE)) {

        Callable<Object[]> updateEntryCallable = new UpdateEntryCallable(actionRequest);

        Object[] returnValue =
            TransactionInvokerUtil.invoke(_transactionAttribute, updateEntryCallable);

        entry = (BlogsEntry) returnValue[0];
        oldUrlTitle = ((String) returnValue[1]);
        blogsEntryAttachmentFileEntryReferences =
            ((List<BlogsEntryAttachmentFileEntryReference>) returnValue[2]);
      } else if (cmd.equals(Constants.DELETE)) {
        deleteEntries(actionRequest, false);
      } else if (cmd.equals(Constants.MOVE_TO_TRASH)) {
        deleteEntries(actionRequest, true);
      } else if (cmd.equals(Constants.RESTORE)) {
        restoreTrashEntries(actionRequest);
      } else if (cmd.equals(Constants.SUBSCRIBE)) {
        subscribe(actionRequest);
      } else if (cmd.equals(Constants.UNSUBSCRIBE)) {
        unsubscribe(actionRequest);
      }

      String redirect = ParamUtil.getString(actionRequest, "redirect");
      boolean updateRedirect = false;

      String portletId = HttpUtil.getParameter(redirect, "p_p_id", false);

      if (Validator.isNotNull(oldUrlTitle)) {
        String oldRedirectParam = PortalUtil.getPortletNamespace(portletId) + "redirect";

        String oldRedirect = HttpUtil.getParameter(redirect, oldRedirectParam, false);

        if (Validator.isNotNull(oldRedirect)) {
          String newRedirect = HttpUtil.decodeURL(oldRedirect);

          newRedirect = StringUtil.replace(newRedirect, oldUrlTitle, entry.getUrlTitle());
          newRedirect = StringUtil.replace(newRedirect, oldRedirectParam, "redirect");

          redirect = StringUtil.replace(redirect, oldRedirect, newRedirect);
        } else if (redirect.endsWith("/blogs/" + oldUrlTitle)
            || redirect.contains("/blogs/" + oldUrlTitle + "?")
            || redirect.contains("/blog/" + oldUrlTitle + "?")) {

          redirect = StringUtil.replace(redirect, oldUrlTitle, entry.getUrlTitle());
        }

        updateRedirect = true;
      }

      int workflowAction =
          ParamUtil.getInteger(
              actionRequest, "workflowAction", WorkflowConstants.ACTION_SAVE_DRAFT);

      boolean ajax = ParamUtil.getBoolean(actionRequest, "ajax");

      if (ajax) {
        JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

        JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

        for (BlogsEntryAttachmentFileEntryReference blogsEntryAttachmentFileEntryReference :
            blogsEntryAttachmentFileEntryReferences) {

          JSONObject blogsEntryFileEntryReferencesJSONObject = JSONFactoryUtil.createJSONObject();

          blogsEntryFileEntryReferencesJSONObject.put(
              "attributeDataImageId", EditorConstants.ATTRIBUTE_DATA_IMAGE_ID);
          blogsEntryFileEntryReferencesJSONObject.put(
              "fileEntryId",
              String.valueOf(
                  blogsEntryAttachmentFileEntryReference.getTempBlogsEntryAttachmentFileEntryId()));
          blogsEntryFileEntryReferencesJSONObject.put(
              "fileEntryUrl",
              PortletFileRepositoryUtil.getPortletFileEntryURL(
                  null,
                  blogsEntryAttachmentFileEntryReference.getBlogsEntryAttachmentFileEntry(),
                  StringPool.BLANK));

          jsonArray.put(blogsEntryFileEntryReferencesJSONObject);
        }

        jsonObject.put("blogsEntryAttachmentReferences", jsonArray);

        jsonObject.put("entryId", entry.getEntryId());
        jsonObject.put("redirect", redirect);
        jsonObject.put("updateRedirect", updateRedirect);

        JSONPortletResponseUtil.writeJSON(actionRequest, actionResponse, jsonObject);

        return;
      }

      if ((entry != null) && (workflowAction == WorkflowConstants.ACTION_SAVE_DRAFT)) {

        redirect = getSaveAndContinueRedirect(actionRequest, entry, redirect);

        sendRedirect(actionRequest, actionResponse, redirect);
      } else {
        WindowState windowState = actionRequest.getWindowState();

        if (!windowState.equals(LiferayWindowState.POP_UP)) {
          sendRedirect(actionRequest, actionResponse, redirect);
        } else {
          redirect = PortalUtil.escapeRedirect(redirect);

          if (Validator.isNotNull(redirect)) {
            if (cmd.equals(Constants.ADD) && (entry != null)) {
              String namespace = PortalUtil.getPortletNamespace(portletId);

              redirect =
                  HttpUtil.addParameter(
                      redirect, namespace + "className", BlogsEntry.class.getName());
              redirect = HttpUtil.addParameter(redirect, namespace + "classPK", entry.getEntryId());
            }

            sendRedirect(actionRequest, actionResponse, redirect);
          }
        }
      }
    } catch (Exception e) {
      String mvcPath = "/blogs/edit_entry.jsp";

      if (e instanceof NoSuchEntryException || e instanceof PrincipalException) {

        SessionErrors.add(actionRequest, e.getClass());

        mvcPath = "/blogs/error.jsp";
      } else if (e instanceof EntryContentException
          || e instanceof EntryCoverImageCropException
          || e instanceof EntryDescriptionException
          || e instanceof EntryDisplayDateException
          || e instanceof EntrySmallImageNameException
          || e instanceof EntrySmallImageScaleException
          || e instanceof EntryTitleException
          || e instanceof FileSizeException
          || e instanceof LiferayFileItemException
          || e instanceof SanitizerException) {

        SessionErrors.add(actionRequest, e.getClass());
      } else if (e instanceof AssetCategoryException || e instanceof AssetTagException) {

        SessionErrors.add(actionRequest, e.getClass(), e);
      } else {
        Throwable cause = e.getCause();

        if (cause instanceof SanitizerException) {
          SessionErrors.add(actionRequest, SanitizerException.class);
        } else {
          throw e;
        }
      }

      actionResponse.setRenderParameter("mvcPath", mvcPath);
    } catch (Throwable t) {
      _log.error(t, t);

      actionResponse.setRenderParameter("mvcPath", "/blogs/error.jsp");
    }
  }