@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 String render(RenderRequest renderRequest, RenderResponse renderResponse)
      throws PortletException {

    HttpServletRequest httpServletRequest = PortalUtil.getHttpServletRequest(renderRequest);

    HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(renderResponse);

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

    if (!_openId.isEnabled(themeDisplay.getCompanyId()) || themeDisplay.isSignedIn()) {

      return "/login.jsp";
    }

    RequestDispatcher requestDispatcher = _servletContext.getRequestDispatcher(_JSP_PATH);

    try {
      requestDispatcher.include(httpServletRequest, httpServletResponse);
    } catch (Exception e) {
      _log.error("Unable to include JSP " + _JSP_PATH, e);

      throw new PortletException("Unable to include JSP " + _JSP_PATH, e);
    }

    return "/navigation.jsp";
  }
Beispiel #3
0
  @Override
  public void processAction(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse)
      throws Exception {

    try {
      String csv = getUsersCSV(actionRequest, actionResponse);

      String fileName = "users.csv";
      byte[] bytes = csv.getBytes();

      HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
      HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

      ServletResponseUtil.sendFile(request, response, fileName, bytes, ContentTypes.TEXT_CSV_UTF8);

      setForward(actionRequest, ActionConstants.COMMON_NULL);
    } catch (Exception e) {
      SessionErrors.add(actionRequest, e.getClass());

      setForward(actionRequest, "portlet.users_admin.error");
    }
  }
  protected void login(
      ThemeDisplay themeDisplay, ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    HttpServletRequest request =
        PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(actionRequest));
    HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

    String login = ParamUtil.getString(actionRequest, "login");
    String password = actionRequest.getParameter("password");
    boolean rememberMe = ParamUtil.getBoolean(actionRequest, "rememberMe");

    if (!themeDisplay.isSignedIn()) {
      String portletId = PortalUtil.getPortletId(actionRequest);

      PortletPreferences portletPreferences =
          PortletPreferencesFactoryUtil.getStrictPortletSetup(themeDisplay.getLayout(), portletId);

      String authType = portletPreferences.getValue("authType", null);

      AuthenticatedSessionManagerUtil.login(
          request, response, login, password, rememberMe, authType);
    }

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

    if (Validator.isNotNull(redirect)) {
      redirect = PortalUtil.escapeRedirect(redirect);

      if (Validator.isNotNull(redirect) && !redirect.startsWith(Http.HTTP)) {

        redirect = getCompleteRedirectURL(request, redirect);
      }
    }

    String mainPath = themeDisplay.getPathMain();

    if (PropsValues.PORTAL_JAAS_ENABLE) {
      if (Validator.isNotNull(redirect)) {
        redirect =
            mainPath.concat("/portal/protected?redirect=").concat(HttpUtil.encodeURL(redirect));
      } else {
        redirect = mainPath.concat("/portal/protected");
      }

      actionResponse.sendRedirect(redirect);
    } else {
      if (Validator.isNotNull(redirect)) {
        actionResponse.sendRedirect(redirect);
      } else {
        boolean doActionAfterLogin = ParamUtil.getBoolean(actionRequest, "doActionAfterLogin");

        if (doActionAfterLogin) {
          return;
        } else {
          actionResponse.sendRedirect(mainPath);
        }
      }
    }
  }
  protected void sendRedirect(
      ActionRequest actionRequest,
      ActionResponse actionResponse,
      ThemeDisplay themeDisplay,
      String login,
      String password)
      throws Exception {

    HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);

    String redirect = PortalUtil.escapeRedirect(ParamUtil.getString(actionRequest, "redirect"));

    if (Validator.isNotNull(redirect)) {
      HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

      AuthenticatedSessionManagerUtil.login(request, response, login, password, false, null);
    } else {
      PortletURL loginURL = LoginUtil.getLoginURL(request, themeDisplay.getPlid());

      loginURL.setParameter("login", login);

      redirect = loginURL.toString();
    }

    actionResponse.sendRedirect(redirect);
  }
  @Override
  public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {

    try {
      ThemeDisplay themeDisplay =
          (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);

      if (!MentionsUtil.isMentionsEnabled(themeDisplay.getSiteGroupId())) {

        return;
      }

      HttpServletRequest request = PortalUtil.getHttpServletRequest(resourceRequest);

      JSONArray jsonArray = getJSONArray(request);

      HttpServletResponse response = PortalUtil.getHttpServletResponse(resourceResponse);

      response.setContentType(ContentTypes.APPLICATION_JSON);

      ServletResponseUtil.write(response, jsonArray.toString());
    } catch (Exception e) {
      _log.error(e, e);
    }

    return;
  }
  @Override
  public AnonymousUser getAnonymousUser(RenderRequest renderRequest, RenderResponse renderResponse)
      throws PortalException, SystemException {

    HttpServletRequest request = PortalUtil.getHttpServletRequest(renderRequest);
    HttpServletResponse response = PortalUtil.getHttpServletResponse(renderResponse);

    return getAnonymousUser(request, response);
  }
  @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();
    }
  }
  @JSON(include = false)
  public HttpServletResponse getResponse() {
    LiferayPortletResponse liferayPortletResponse = getLiferayPortletResponse();

    if (liferayPortletResponse == null) {
      return null;
    }

    return PortalUtil.getHttpServletResponse(liferayPortletResponse);
  }
  public static void writeJSON(
      PortletRequest portletRequest, PortletResponse portletResponse, Object json)
      throws IOException {

    HttpServletResponse response = PortalUtil.getHttpServletResponse(portletResponse);

    response.setContentType(_getContentType(portletRequest));

    ServletResponseUtil.write(response, json.toString());

    response.flushBuffer();
  }
  protected static void writeJSON(
      PortletRequest portletRequest, ActionResponse actionResponse, Object json)
      throws IOException {

    HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

    response.setContentType(ContentTypes.APPLICATION_JSON);

    ServletResponseUtil.write(response, json.toString());

    response.flushBuffer();
  }
Beispiel #12
0
  @Override
  public void processAction(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse)
      throws Exception {

    HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
    HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

    try {
      long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");

      long folderId = ParamUtil.getLong(actionRequest, "folderId");
      String name = ParamUtil.getString(actionRequest, "name");
      String title = ParamUtil.getString(actionRequest, "title");
      String version = ParamUtil.getString(actionRequest, "version");

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

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

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

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

      long groupId = ParamUtil.getLong(actionRequest, "groupId", themeDisplay.getScopeGroupId());

      getFile(
          fileEntryId,
          folderId,
          name,
          title,
          version,
          fileShortcutId,
          uuid,
          groupId,
          targetExtension,
          request,
          response);

      setForward(actionRequest, ActionConstants.COMMON_NULL);
    } catch (NoSuchFileEntryException nsfee) {
      PortalUtil.sendError(HttpServletResponse.SC_NOT_FOUND, nsfee, actionRequest, actionResponse);
    } catch (PrincipalException pe) {
      processPrincipalException(pe, request, response);
    } catch (Exception e) {
      PortalUtil.sendError(e, actionRequest, actionResponse);
    }
  }
  @Override
  protected void doServeResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
      throws Exception {

    HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(resourceResponse);

    HttpServletRequest httpServletRequest = PortalUtil.getHttpServletRequest(resourceRequest);

    DDMFormField ddmFormField = getDDMFormField(httpServletRequest);

    DDMFormFieldRenderer ddmFormFieldRenderer =
        _ddmFormFieldRendererRegistry.getDDMFormFieldRenderer(ddmFormField.getType());

    DDMFormFieldRenderingContext ddmFormFieldRenderingContext =
        createDDMFormFieldRenderingContext(httpServletRequest, httpServletResponse);

    String ddmFormFieldHTML =
        ddmFormFieldRenderer.render(ddmFormField, ddmFormFieldRenderingContext);

    httpServletResponse.setContentType(ContentTypes.TEXT_HTML);

    ServletResponseUtil.write(httpServletResponse, ddmFormFieldHTML);
  }
  @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();
  }
  @Override
  public void processAction(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse)
      throws Exception {

    File file = null;

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

      long groupId = ParamUtil.getLong(actionRequest, "groupId");
      boolean privateLayout = ParamUtil.getBoolean(actionRequest, "privateLayout");
      long[] layoutIds = ParamUtil.getLongValues(actionRequest, "layoutIds");
      String fileName = ParamUtil.getString(actionRequest, "exportFileName");
      String range = ParamUtil.getString(actionRequest, "range");

      Date startDate = null;
      Date endDate = null;

      if (range.equals("dateRange")) {
        int startDateMonth = ParamUtil.getInteger(actionRequest, "startDateMonth");
        int startDateDay = ParamUtil.getInteger(actionRequest, "startDateDay");
        int startDateYear = ParamUtil.getInteger(actionRequest, "startDateYear");
        int startDateHour = ParamUtil.getInteger(actionRequest, "startDateHour");
        int startDateMinute = ParamUtil.getInteger(actionRequest, "startDateMinute");
        int startDateAmPm = ParamUtil.getInteger(actionRequest, "startDateAmPm");

        if (startDateAmPm == Calendar.PM) {
          startDateHour += 12;
        }

        startDate =
            PortalUtil.getDate(
                startDateMonth,
                startDateDay,
                startDateYear,
                startDateHour,
                startDateMinute,
                themeDisplay.getTimeZone(),
                new PortalException());

        int endDateMonth = ParamUtil.getInteger(actionRequest, "endDateMonth");
        int endDateDay = ParamUtil.getInteger(actionRequest, "endDateDay");
        int endDateYear = ParamUtil.getInteger(actionRequest, "endDateYear");
        int endDateHour = ParamUtil.getInteger(actionRequest, "endDateHour");
        int endDateMinute = ParamUtil.getInteger(actionRequest, "endDateMinute");
        int endDateAmPm = ParamUtil.getInteger(actionRequest, "endDateAmPm");

        if (endDateAmPm == Calendar.PM) {
          endDateHour += 12;
        }

        endDate =
            PortalUtil.getDate(
                endDateMonth,
                endDateDay,
                endDateYear,
                endDateHour,
                endDateMinute,
                themeDisplay.getTimeZone(),
                new PortalException());
      } else if (range.equals("fromLastPublishDate")) {
        LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout);

        UnicodeProperties settingsProperties = layoutSet.getSettingsProperties();

        long lastPublishDate =
            GetterUtil.getLong(settingsProperties.getProperty("last-publish-date"));

        if (lastPublishDate > 0) {
          Calendar cal = Calendar.getInstance(themeDisplay.getTimeZone(), themeDisplay.getLocale());

          endDate = cal.getTime();

          cal.setTimeInMillis(lastPublishDate);

          startDate = cal.getTime();
        }
      } else if (range.equals("last")) {
        int rangeLast = ParamUtil.getInteger(actionRequest, "last");

        Date now = new Date();

        startDate = new Date(now.getTime() - (rangeLast * Time.HOUR));

        endDate = now;
      }

      file =
          LayoutServiceUtil.exportLayoutsAsFile(
              groupId,
              privateLayout,
              layoutIds,
              actionRequest.getParameterMap(),
              startDate,
              endDate);

      HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
      HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

      ServletResponseUtil.sendFile(
          request, response, fileName, new FileInputStream(file), ContentTypes.APPLICATION_ZIP);

      setForward(actionRequest, ActionConstants.COMMON_NULL);
    } catch (Exception e) {
      _log.error(e, e);

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

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

      sendRedirect(actionRequest, actionResponse, pagesRedirect);
    } finally {
      FileUtil.delete(file);
    }
  }
  protected void login(
      ThemeDisplay themeDisplay,
      ActionRequest actionRequest,
      ActionResponse actionResponse,
      PortletPreferences preferences)
      throws Exception {

    HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
    HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

    String login = ParamUtil.getString(actionRequest, "login");
    String password = actionRequest.getParameter("password");
    boolean rememberMe = ParamUtil.getBoolean(actionRequest, "rememberMe");

    String authType = preferences.getValue("authType", null);

    // cusotm code =============
    try {
      User tmp = null;
      UserEntry userEntryTmp = null;
      if (Validator.isEmailAddress(login)) {
        tmp = UserLocalServiceUtil.getUserByEmailAddress(PortalUtil.getCompanyId(request), login);
        login = String.valueOf(tmp.getUserId());
        System.out.println("email:" + login);
      } else if (Validator.isNumber(login)) {
        // is mobile number
        //				UserEntryLocalServiceUtil.get
        userEntryTmp = UserEntryLocalServiceUtil.findByMobilePhone(login);
        login = String.valueOf(userEntryTmp.getUserId());
        System.out.println("mobile number:" + login);
      } else {
        // userEntryTmp = UserEntryLocalServiceUtil.findByUserName(login);
        tmp = UserLocalServiceUtil.getUserByScreenName(PortalUtil.getCompanyId(request), login);
        login = String.valueOf(tmp.getUserId());
        System.out.println("userName:"******"/portal/protected");
    } else {
      String redirect = ParamUtil.getString(actionRequest, "redirect");

      if (Validator.isNotNull(redirect)) {
        redirect = PortalUtil.escapeRedirect(redirect);

        if (!redirect.startsWith(Http.HTTP)) {
          redirect = getCompleteRedirectURL(request, redirect);
        }

        actionResponse.sendRedirect(redirect);
      } else {
        boolean doActionAfterLogin = ParamUtil.getBoolean(actionRequest, "doActionAfterLogin");

        if (doActionAfterLogin) {
          return;
        } else {
          actionResponse.sendRedirect(themeDisplay.getPathMain());
        }
      }
    }
  }
  @Override
  protected void doProcessAction(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    try {
      if (cmd.equals(Constants.CANCEL_CHECKOUT)) {
        cancelCheckedOutEntries(actionRequest);
      } else if (cmd.equals(Constants.CHECKIN)) {
        checkInEntries(actionRequest);
      } else if (cmd.equals(Constants.CHECKOUT)) {
        checkOutEntries(actionRequest);
      } else if (cmd.equals(Constants.DELETE)) {
        deleteEntries(actionRequest, false);
      } else if (cmd.equals(Constants.MOVE)) {
        moveEntries(actionRequest);
      } else if (cmd.equals(Constants.MOVE_TO_TRASH)) {
        deleteEntries(actionRequest, true);
      } else if (cmd.equals(Constants.RESTORE)) {
        restoreTrashEntries(actionRequest);
      }

      WindowState windowState = actionRequest.getWindowState();

      if (windowState.equals(LiferayWindowState.POP_UP)) {
        String redirect = PortalUtil.escapeRedirect(ParamUtil.getString(actionRequest, "redirect"));

        if (Validator.isNotNull(redirect)) {
          sendRedirect(actionRequest, actionResponse, redirect);
        }
      }
    } catch (DuplicateLockException
        | NoSuchFileEntryException
        | NoSuchFolderException
        | PrincipalException e) {

      if (e instanceof DuplicateLockException) {
        DuplicateLockException dle = (DuplicateLockException) e;

        SessionErrors.add(actionRequest, dle.getClass(), dle.getLock());
      } else {
        SessionErrors.add(actionRequest, e.getClass());
      }

      actionResponse.setRenderParameter("mvcPath", "/document_library/error.jsp");
    } catch (DuplicateFileEntryException
        | DuplicateFolderNameException
        | SourceFileNameException e) {

      if (e instanceof DuplicateFileEntryException) {
        HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

        response.setStatus(ServletResponseConstants.SC_DUPLICATE_FILE_EXCEPTION);
      }

      SessionErrors.add(actionRequest, e.getClass());
    } catch (AssetCategoryException | AssetTagException | InvalidFolderException e) {

      SessionErrors.add(actionRequest, e.getClass(), e);
    } catch (Exception e) {
      throw new PortletException(e);
    }
  }
  protected void sendOpenIdRequest(
      ThemeDisplay themeDisplay, ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
    HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);
    HttpSession session = request.getSession();

    LiferayPortletResponse liferayPortletResponse =
        PortalUtil.getLiferayPortletResponse(actionResponse);

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

    PortletURL portletURL = liferayPortletResponse.createActionURL();

    portletURL.setParameter("saveLastPath", Boolean.FALSE.toString());
    portletURL.setParameter(Constants.CMD, Constants.READ);
    portletURL.setParameter("struts_action", "/login/open_id");

    List<DiscoveryInformation> discoveryInformationList = _consumerManager.discover(openId);

    DiscoveryInformation discoveryInformation =
        _consumerManager.associate(discoveryInformationList);

    session.setAttribute(OpenIdWebKeys.OPEN_ID_DISCO, discoveryInformation);

    AuthRequest authRequest =
        _consumerManager.authenticate(
            discoveryInformation, portletURL.toString(), themeDisplay.getPortalURL());

    if (_userLocalService.fetchUserByOpenId(themeDisplay.getCompanyId(), openId) != null) {

      response.sendRedirect(authRequest.getDestinationUrl(true));

      return;
    }

    String screenName = getScreenName(openId);

    User user = _userLocalService.fetchUserByScreenName(themeDisplay.getCompanyId(), screenName);

    if (user != null) {
      _userLocalService.updateOpenId(user.getUserId(), openId);

      response.sendRedirect(authRequest.getDestinationUrl(true));

      return;
    }

    FetchRequest fetchRequest = FetchRequest.createFetchRequest();

    OpenIdProvider openIdProvider =
        _openIdProviderRegistry.getOpenIdProvider(discoveryInformation.getOPEndpoint());

    Map<String, String> openIdAXTypes = openIdProvider.getAxTypes();

    for (String openIdAXType : openIdAXTypes.keySet()) {
      fetchRequest.addAttribute(openIdAXType, openIdAXTypes.get(openIdAXType), true);
    }

    authRequest.addExtension(fetchRequest);

    SRegRequest sRegRequest = SRegRequest.createFetchRequest();

    sRegRequest.addAttribute(_OPEN_ID_SREG_ATTR_EMAIL, true);
    sRegRequest.addAttribute(_OPEN_ID_SREG_ATTR_FULLNAME, true);

    authRequest.addExtension(sRegRequest);

    response.sendRedirect(authRequest.getDestinationUrl(true));
  }
  @Override
  public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
      throws IOException, PortletException {

    String resourceID = GetterUtil.getString(resourceRequest.getResourceID());

    HttpServletRequest request = PortalUtil.getHttpServletRequest(resourceRequest);

    HttpServletResponse response = PortalUtil.getHttpServletResponse(resourceResponse);

    if (resourceID.equals("compareVersions")) {
      ThemeDisplay themeDisplay =
          (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);

      long groupId = ParamUtil.getLong(resourceRequest, "groupId");
      String articleId = ParamUtil.getString(resourceRequest, "articleId");
      double sourceVersion = ParamUtil.getDouble(resourceRequest, "filterSourceVersion");
      double targetVersion = ParamUtil.getDouble(resourceRequest, "filterTargetVersion");
      String languageId = ParamUtil.getString(resourceRequest, "languageId");

      String diffHtmlResults = null;

      try {
        diffHtmlResults =
            JournalUtil.diffHtml(
                groupId,
                articleId,
                sourceVersion,
                targetVersion,
                languageId,
                new PortletRequestModel(resourceRequest, resourceResponse),
                themeDisplay);
      } catch (CompareVersionsException cve) {
        resourceRequest.setAttribute(WebKeys.DIFF_VERSION, cve.getVersion());
      } catch (Exception e) {
        try {
          PortalUtil.sendError(e, request, response);
        } catch (ServletException se) {
        }
      }

      resourceRequest.setAttribute(WebKeys.DIFF_HTML_RESULTS, diffHtmlResults);

      PortletSession portletSession = resourceRequest.getPortletSession();

      PortletContext portletContext = portletSession.getPortletContext();

      PortletRequestDispatcher portletRequestDispatcher =
          portletContext.getRequestDispatcher(
              "/html/taglib/ui/diff_version_comparator/diff_html.jsp");

      portletRequestDispatcher.include(resourceRequest, resourceResponse);
    } else if (resourceID.equals("rss")) {
      try {
        byte[] xml = JournalRSSUtil.getRSS(resourceRequest, resourceResponse);

        ServletResponseUtil.sendFile(request, response, null, xml, ContentTypes.TEXT_XML_UTF8);
      } catch (Exception e) {
        try {
          PortalUtil.sendError(e, request, response);
        } catch (ServletException se) {
        }
      }
    } else {
      super.serveResource(resourceRequest, resourceResponse);
    }
  }
  @Override
  public void encodeBegin(FacesContext facesContext, UIComponent uiComponent) throws IOException {

    super.encodeBegin(facesContext, uiComponent);

    InputEditorInternal inputEditorInternal = (InputEditorInternal) uiComponent;
    ResponseWriter responseWriter = facesContext.getResponseWriter();
    ExternalContext externalContext = facesContext.getExternalContext();
    PortletRequest portletRequest = (PortletRequest) externalContext.getRequest();
    PortletResponse portletResponse = (PortletResponse) externalContext.getResponse();
    HttpServletRequest httpServletRequest = PortalUtil.getHttpServletRequest(portletRequest);
    httpServletRequest = new NonNamespacedHttpServletRequest(httpServletRequest);

    HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(portletResponse);
    PortletRequest liferayPortletRequest = getLiferayPortletRequest(portletRequest);
    boolean resourcePhase = (liferayPortletRequest instanceof ResourceRequest);
    Map<String, Object> attributes = inputEditorInternal.getAttributes();
    String onBlurMethod = (String) attributes.get("onBlurMethod");
    String editorImpl = (String) attributes.get("editorImpl");

    if (editorImpl == null) {
      editorImpl = CKEDITOR;
    }

    // Build up a URL that can be used to invoke the liferay-ui:input-editor JSP tag.
    String url = "/resources/liferay-ui/jsp/input-editor.jsp";
    StringBuilder queryString = new StringBuilder();
    queryString.append(StringPool.QUESTION);
    queryString.append("editorImpl");
    queryString.append(StringPool.EQUAL);
    queryString.append(editorImpl);
    queryString.append(StringPool.AMPERSAND);
    queryString.append("height");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("height"));
    queryString.append(StringPool.AMPERSAND);
    queryString.append("initMethod");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("initMethod"));
    queryString.append(StringPool.AMPERSAND);
    queryString.append("name");
    queryString.append(StringPool.EQUAL);

    String editorName = (String) attributes.get("name");
    queryString.append(editorName);
    queryString.append(StringPool.AMPERSAND);
    queryString.append("onChangeMethod");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("onChangeMethod"));
    queryString.append(StringPool.AMPERSAND);
    queryString.append("skipEditorLoading");
    queryString.append(StringPool.EQUAL);

    if (resourcePhase) {

      // FACES-1439: Ensure that the <script src=".../ckeditor.js" /> element is not included in the
      // response by
      // specifying skipEditorLoading="true" during Ajax requests.
      queryString.append(Boolean.TRUE.toString());
    } else {
      queryString.append(Boolean.FALSE.toString());
    }

    queryString.append(StringPool.AMPERSAND);
    queryString.append("toolbarSet");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("toolbarSet"));
    queryString.append(StringPool.AMPERSAND);
    queryString.append("width");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("width"));
    url = url + queryString.toString();

    // Invoke the tag and capture it's output in a String, rather than having the output go directly
    // to the
    // response.
    RequestDispatcher requestDispatcher = httpServletRequest.getRequestDispatcher(url);
    JspIncludeResponse jspIncludeResponse = new JspIncludeResponse(httpServletResponse);

    try {
      requestDispatcher.include(httpServletRequest, jspIncludeResponse);
    } catch (ServletException e) {
      logger.error(e.getMessage());
      throw new IOException(e.getMessage());
    }

    String bufferedResponse = jspIncludeResponse.getBufferedResponse();

    if (bufferedResponse != null) {

      // Note: Trim the buffered response since there is typically over 100 newlines at the
      // beginning.
      bufferedResponse = bufferedResponse.trim();

      // If rendering an instance of the CKEditor, then
      String editorType = EditorUtil.getEditorValue(httpServletRequest, editorImpl);

      if (editorType.indexOf(CKEDITOR) >= 0) {

        String namespace = portletResponse.getNamespace();

        // FACES-1441: The liferay-ui:input-editor JSP tag (and associated ckeditor.jsp file) do not
        // provide a
        // way to hook-in to the "onblur" callback feature of the CKEditor. In order to overcome
        // this
        // limitation, it is necessary to append a <script>...</script> to the response that
        // provides this
        // ability.
        String onBlurScript = getOnBlurScript(editorName, onBlurMethod, namespace);

        // If running within an Ajax request, include the "onblur" callback script must be included
        // directly
        // to the response.
        if (resourcePhase) {

          StringBuilder scriptMarkup = new StringBuilder();
          scriptMarkup.append(StringPool.LESS_THAN);
          scriptMarkup.append(StringPool.SCRIPT);
          scriptMarkup.append(StringPool.GREATER_THAN);
          scriptMarkup.append(StringPool.CDATA_OPEN);
          scriptMarkup.append(onBlurScript);
          scriptMarkup.append(COMMENT_CDATA_CLOSE);
          scriptMarkup.append(StringPool.LESS_THAN);
          scriptMarkup.append(StringPool.FORWARD_SLASH);
          scriptMarkup.append(StringPool.SCRIPT);
          scriptMarkup.append(StringPool.GREATER_THAN);
          bufferedResponse = bufferedResponse.concat(scriptMarkup.toString());
        }

        // Otherwise, append the script to the "LIFERAY_SHARED_AUI_SCRIPT_DATA" request attribute,
        // which will
        // cause the script to be rendered at the bottom of the portal page.
        else {

          ScriptData scriptData =
              (ScriptData) externalContext.getRequestMap().get(WebKeys.AUI_SCRIPT_DATA);
          scriptData.append(getPortletId(portletRequest), onBlurScript, null);
        }

        // FACES-1439: If the component was rendered on the page on the previous JSF lifecycle, then
        // prevent it
        // from being re-initialized by removing all <script>...</script> elements.
        boolean scriptsRemoved = false;

        String clientId = inputEditorInternal.getClientId();

        if (resourcePhase && inputEditorInternal.isPreviouslyRendered()) {

          logger.debug("Preventing re-initialization of CKEditor for clientId=[{0}]", clientId);

          ParsedResponse parsedResponse = new ParsedResponse(bufferedResponse);
          bufferedResponse = parsedResponse.getNonScripts();
          scriptsRemoved = true;
        }

        // FACES-1422: Move the scripts to the <eval>...</eval> section of the partial-response so
        // that they
        // will execute properly. This has the added benefit of preempt a DOM-diff with ICEfaces.
        if (resourcePhase && !scriptsRemoved) {

          logger.debug(
              "Moving CKEditor scripts to <eval>...</eval> section of the partial-response for clientId=[{0}]",
              clientId);

          ParsedResponse parsedResponse = new ParsedResponse(bufferedResponse);
          bufferedResponse = parsedResponse.getNonScripts();

          String scripts = parsedResponse.getScripts();

          LiferayFacesContext liferayFacesContext = LiferayFacesContext.getInstance();
          liferayFacesContext.getJavaScriptMap().put(clientId, scripts);
          logger.trace(scripts);
        }
      }

      // Write the captured output from the JSP tag to the Faces responseWriter.
      logger.trace(bufferedResponse);
      responseWriter.write(bufferedResponse);
    }
  }
Beispiel #21
0
  /** TODO: Remove. This should extend from EditFileEntryAction once it is modularized. */
  protected void handleUploadException(
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse,
      String cmd,
      Exception e)
      throws Exception {

    if (e instanceof AssetCategoryException || e instanceof AssetTagException) {

      SessionErrors.add(actionRequest, e.getClass(), e);
    } else if (e instanceof AntivirusScannerException
        || e instanceof DuplicateFileEntryException
        || e instanceof DuplicateFolderNameException
        || e instanceof FileExtensionException
        || e instanceof FileMimeTypeException
        || e instanceof FileNameException
        || e instanceof FileSizeException
        || e instanceof LiferayFileItemException
        || e instanceof NoSuchFolderException
        || e instanceof SourceFileNameException
        || e instanceof StorageFieldRequiredException) {

      if (!cmd.equals(Constants.ADD_DYNAMIC)
          && !cmd.equals(Constants.ADD_MULTIPLE)
          && !cmd.equals(Constants.ADD_TEMP)) {

        if (e instanceof AntivirusScannerException) {
          SessionErrors.add(actionRequest, e.getClass(), e);
        } else {
          SessionErrors.add(actionRequest, e.getClass());
        }

        return;
      } else if (cmd.equals(Constants.ADD_TEMP)) {
        hideDefaultErrorMessage(actionRequest);
      }

      if (e instanceof AntivirusScannerException
          || e instanceof DuplicateFileEntryException
          || e instanceof FileExtensionException
          || e instanceof FileNameException
          || e instanceof FileSizeException) {

        HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

        response.setContentType(ContentTypes.TEXT_HTML);
        response.setStatus(HttpServletResponse.SC_OK);

        String errorMessage = StringPool.BLANK;
        int errorType = 0;

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

        if (e instanceof AntivirusScannerException) {
          AntivirusScannerException ase = (AntivirusScannerException) e;

          errorMessage = themeDisplay.translate(ase.getMessageKey());
          errorType = ServletResponseConstants.SC_FILE_ANTIVIRUS_EXCEPTION;
        }

        if (e instanceof DuplicateFileEntryException) {
          errorMessage = themeDisplay.translate("please-enter-a-unique-document-name");
          errorType = ServletResponseConstants.SC_DUPLICATE_FILE_EXCEPTION;
        } else if (e instanceof FileExtensionException) {
          errorMessage =
              themeDisplay.translate(
                  "please-enter-a-file-with-a-valid-extension-x",
                  StringUtil.merge(
                      getAllowedFileExtensions(portletConfig, actionRequest, actionResponse)));
          errorType = ServletResponseConstants.SC_FILE_EXTENSION_EXCEPTION;
        } else if (e instanceof FileNameException) {
          errorMessage = themeDisplay.translate("please-enter-a-file-with-a-valid-file-name");
          errorType = ServletResponseConstants.SC_FILE_NAME_EXCEPTION;
        } else if (e instanceof FileSizeException) {
          long fileMaxSize = PrefsPropsUtil.getLong(PropsKeys.DL_FILE_MAX_SIZE);

          if (fileMaxSize == 0) {
            fileMaxSize = PrefsPropsUtil.getLong(PropsKeys.UPLOAD_SERVLET_REQUEST_IMPL_MAX_SIZE);
          }

          errorMessage =
              themeDisplay.translate(
                  "please-enter-a-file-with-a-valid-file-size-no-larger" + "-than-x",
                  TextFormatter.formatStorageSize(fileMaxSize, themeDisplay.getLocale()));

          errorType = ServletResponseConstants.SC_FILE_SIZE_EXCEPTION;
        }

        JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

        jsonObject.put("message", errorMessage);
        jsonObject.put("status", errorType);

        JSONPortletResponseUtil.writeJSON(actionRequest, actionResponse, jsonObject);
      }

      if (e instanceof AntivirusScannerException) {
        SessionErrors.add(actionRequest, e.getClass(), e);
      } else {
        SessionErrors.add(actionRequest, e.getClass());
      }
    } else if (e instanceof DuplicateLockException
        || e instanceof InvalidFileVersionException
        || e instanceof NoSuchFileEntryException
        || e instanceof PrincipalException) {

      if (e instanceof DuplicateLockException) {
        DuplicateLockException dle = (DuplicateLockException) e;

        SessionErrors.add(actionRequest, dle.getClass(), dle.getLock());
      } else {
        SessionErrors.add(actionRequest, e.getClass());
      }

      actionResponse.setRenderParameter("mvcPath", "/html/porltet/document_library/error.jsp");
    } else {
      Throwable cause = e.getCause();

      if (cause instanceof DuplicateFileEntryException) {
        SessionErrors.add(actionRequest, DuplicateFileEntryException.class);
      } else {
        throw e;
      }
    }
  }
  public static void sendFile(PortletRequest portletRequest, PortletResponse portletResponse)
      throws IOException {

    long groupId = ParamUtil.getLong(portletRequest, "groupId");
    String articleId = ParamUtil.getString(portletRequest, "articleId");

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

    PortletPreferences portletPreferences = portletRequest.getPreferences();

    String[] allowedExtensions = StringUtil.split(portletPreferences.getValue("extensions", null));

    String languageId = LanguageUtil.getLanguageId(portletRequest);
    PortletRequestModel portletRequestModel =
        new PortletRequestModel(portletRequest, portletResponse);
    ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY);
    HttpServletRequest request = PortalUtil.getHttpServletRequest(portletRequest);
    HttpServletResponse response = PortalUtil.getHttpServletResponse(portletResponse);

    JournalArticleDisplay articleDisplay =
        JournalContentUtil.getDisplay(
            groupId, articleId, null, "export", languageId, 1, portletRequestModel, themeDisplay);

    int pages = articleDisplay.getNumberOfPages();

    StringBundler sb = new StringBundler(pages + 12);

    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(articleDisplay.getContent());

    for (int i = 2; i <= pages; i++) {
      articleDisplay =
          JournalContentUtil.getDisplay(groupId, articleId, "export", languageId, i, themeDisplay);

      sb.append(articleDisplay.getContent());
    }

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

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

    String title = articleDisplay.getTitle();
    String sourceExtension = "html";

    String fileName = title.concat(StringPool.PERIOD).concat(sourceExtension);

    String contentType = MimeTypesUtil.getContentType(fileName);

    if (Validator.isNull(targetExtension)
        || !ArrayUtil.contains(allowedExtensions, targetExtension)) {

      ServletResponseUtil.sendFile(request, response, fileName, is, contentType);

      return;
    }

    String id =
        DLUtil.getTempFileId(
            articleDisplay.getId(), String.valueOf(articleDisplay.getVersion()), languageId);

    File convertedFile = DocumentConversionUtil.convert(id, is, sourceExtension, targetExtension);

    if (convertedFile != null) {
      fileName = title.concat(StringPool.PERIOD).concat(targetExtension);

      is = new FileInputStream(convertedFile);
    }

    ServletResponseUtil.sendFile(request, response, fileName, is, contentType);
  }