Exemple #1
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 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 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);
  }
  @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;
      }
    }
  }
  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};
  }
  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 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");
    }
  }