@Override
  protected void doProcessAction(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    try {
      if (cmd.equals(Constants.DELETE)) {
        deleteImages(actionRequest);
      }

      sendRedirect(actionRequest, actionResponse);
    } catch (Exception e) {
      if (e instanceof NoSuchEntryException || e instanceof PrincipalException) {

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

        actionResponse.setRenderParameter("mvcPath", "/blogs/error.jsp");
      } else {
        throw e;
      }
    } catch (Throwable t) {
      _log.error(t, t);

      actionResponse.setRenderParameter("mvcPath", "/blogs/error.jsp");
    }
  }
  // Process action is called for action URLs / form posts, etc
  // Process action is called once for each click - doView may be called many times
  // Hence an obsession in process action with putting things in session to
  // Send to the render process.
  public void processAction(ActionRequest request, ActionResponse response)
      throws PortletException, IOException {

    // System.out.println("==== processAction called ====");

    PortletSession pSession = request.getPortletSession(true);

    // Our first challenge is to figure out which action we want to take
    // The view selects the "next action" either as a URL parameter
    // or as a hidden field in the POST data - we check both

    String doCancel = request.getParameter("sakai.cancel");
    String doUpdate = request.getParameter("sakai.update");

    // Our next challenge is to pick which action the previous view
    // has told us to do.  Note that the view may place several actions
    // on the screen and the user may have an option to pick between
    // them.  Make sure we handle the "no action" fall-through.

    pSession.removeAttribute("error.message");

    if (doCancel != null) {
      response.setPortletMode(PortletMode.VIEW);
    } else if (doUpdate != null) {
      processActionEdit(request, response);
    } else {
      // System.out.println("Unknown action");
      response.setPortletMode(PortletMode.VIEW);
    }

    // System.out.println("==== End of ProcessAction  ====");
  }
 @SuppressWarnings("unchecked")
 @ProcessAction(name = "addBookAction")
 public void addBook(ActionRequest request, ActionResponse response)
     throws PortletException, IOException {
   logger.info("addBook action invoked");
   if (!request.isUserInRole("administrator")) {
     response.setRenderParameter("myaction", "error");
     response.setRenderParameter(
         "exceptionMsg",
         "You are not authorized for this action. You must have Administrator role.");
     return;
   }
   request.setAttribute("myaction", "addBookAction");
   PortletRequestDispatcher dispatcher =
       request
           .getPortletSession()
           .getPortletContext()
           .getRequestDispatcher(response.encodeURL("/myservlet/bookServlet"));
   dispatcher.include(request, response);
   Map<String, String> map = (Map<String, String>) request.getAttribute("errors");
   if (map != null && !map.isEmpty()) {
     response.setRenderParameter("myaction", "addBookAction");
   } else {
     response.setRenderParameter("myaction", "showCatalog");
   }
 }
  /**
   * Resets/restores the values in the portletPreferences.xhtml Facelet composition with portlet
   * preference default values.
   */
  public void reset() {

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    PortletRequest portletRequest = (PortletRequest) externalContext.getRequest();
    PortletPreferences portletPreferences = portletRequest.getPreferences();

    try {
      Enumeration<String> preferenceNames = portletPreferences.getNames();

      while (preferenceNames.hasMoreElements()) {
        String preferenceName = preferenceNames.nextElement();
        portletPreferences.reset(preferenceName);
      }

      portletPreferences.store();

      // Switch the portlet mode back to VIEW.
      ActionResponse actionResponse = (ActionResponse) externalContext.getResponse();
      actionResponse.setPortletMode(PortletMode.VIEW);
      actionResponse.setWindowState(WindowState.NORMAL);

      FacesContextHelperUtil.addGlobalSuccessInfoMessage();
    } catch (Exception e) {
      FacesContextHelperUtil.addGlobalUnexpectedErrorMessage();
    }
  }
  /**
   * Handles deletion of announcements
   *
   * @param topicId
   * @param annId
   * @param response
   * @throws PortletException
   */
  @RequestMapping(params = "action=deleteAnnouncement")
  public void actionDeleteAnnouncement(
      @RequestParam("topicId") Long topicId,
      @RequestParam("annId") Long annId,
      ActionRequest request,
      ActionResponse response)
      throws PortletException {

    Topic topic = announcementService.getTopic(topicId);
    Announcement ann = announcementService.getAnnouncement(annId);

    UserPermissionChecker upChecker =
        userPermissionCheckerFactory.createUserPermissionChecker(request, topic);
    if (upChecker.isAdmin()
        || upChecker.isModerator()
        || (upChecker.isAuthor()
            && ann.getAuthor() != null
            && ann.getAuthor().equals(request.getRemoteUser()))) {
      // the person deleting the announcement must be the author, a moderator or an admin
      announcementService.deleteAnnouncement(ann);
    } else {
      throw new UnauthorizedException("You do not have permission to delete this announcement");
    }

    response.setRenderParameter("topicId", topicId.toString());
    response.setRenderParameter("action", "showTopic");
  }
  @ProcessAction(name = "searchBookAction")
  public void searchBook(ActionRequest request, ActionResponse response)
      throws PortletException, IOException {
    logger.info("Inside search Book action");
    request.setAttribute("myaction", "searchBookAction");
    PortletRequestDispatcher dispatcher =
        request
            .getPortletSession()
            .getPortletContext()
            .getRequestDispatcher(response.encodeURL("/myservlet/bookServlet"));
    dispatcher.include(request, response);
    response.setRenderParameter("myaction", "showSearchResults");

    // --store the search criteria in session
    request
        .getPortletSession()
        .setAttribute(
            "authorNameSearchField",
            request.getParameter("authorNameSearchField"),
            PortletSession.APPLICATION_SCOPE);
    request
        .getPortletSession()
        .setAttribute(
            "bookNameSearchField",
            request.getParameter("bookNameSearchField"),
            PortletSession.APPLICATION_SCOPE);
    // retrieving the matchingBooks request attribute set by BookServlet and
    // store it in session
    request
        .getPortletSession()
        .setAttribute("matchingBooks", request.getAttribute("matchingBooks"));
  }
  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);
        }
      }
    }
  }
  /**
   * @see de.ingrid.portal.portlets.admin.ContentPortlet#processAction(javax.portlet.ActionRequest,
   *     javax.portlet.ActionResponse)
   */
  public void processAction(ActionRequest request, ActionResponse response)
      throws PortletException, IOException {

    if (request.getParameter(PARAMV_ACTION_DB_DO_SAVE) != null) {
      AdminCMSForm f =
          (AdminCMSForm) Utils.getActionForm(request, AdminCMSForm.SESSION_KEY, AdminCMSForm.class);
      f.clear();
      f.clearMessages();
      // call sub method
      doActionSave(request);
      response.setRenderParameter(Settings.PARAM_ACTION, PARAMV_ACTION_DB_DO_SAVE);
      response.setRenderParameter("cmd", "action processed");
    } else if (request.getParameter(PARAMV_ACTION_DB_DO_UPDATE) != null) {
      AdminCMSForm f =
          (AdminCMSForm) Utils.getActionForm(request, AdminCMSForm.SESSION_KEY, AdminCMSForm.class);
      f.clear();
      f.clearMessages();
      // call sub method
      doActionUpdate(request);
      response.setRenderParameter(Settings.PARAM_ACTION, PARAMV_ACTION_DB_DO_UPDATE);
      response.setRenderParameter("cmd", "action processed");
    } else {
      super.processAction(request, response);
    }
  }
  /*
   * Process the "finished" action for the edit page. Set the "url" to the value specified in the
   * edit page.
   */
  private void processEditFinishedAction(ActionRequest request, ActionResponse response)
      throws PortletException {
    String nbPublis = request.getParameter(TEXTBOX_NB_ITEMS);
    String maxAge = request.getParameter(TEXTBOX_MAX_AGE);
    String displayDescription = request.getParameter("displayDescription");

    // Check if it is a number
    try {
      int nb = Integer.parseInt(nbPublis);
      Integer.parseInt(maxAge);
      if (nb < 0 || nb > 30) {
        throw new NumberFormatException();
      }
      // store preference
      PortletPreferences pref = request.getPreferences();
      try {
        pref.setValue("nbPublis", nbPublis);
        pref.setValue("maxAge", maxAge);
        pref.setValue("displayDescription", displayDescription);
        pref.store();
      } catch (ValidatorException ve) {
        log("could not set nbPublis", ve);
        throw new PortletException("IFramePortlet.processEditFinishedAction", ve);
      } catch (IOException ioe) {
        log("could not set nbPublis", ioe);
        throw new PortletException("IFramePortlet.prcoessEditFinishedAction", ioe);
      }
      response.setPortletMode(PortletMode.VIEW);

    } catch (NumberFormatException e) {
      response.setRenderParameter(ERROR_BAD_VALUE, "true");
      response.setPortletMode(PortletMode.EDIT);
    }
  }
  /**
   * Takes a submitted contact and adds it to the database if it passes validation.
   *
   * @param request
   * @param response
   */
  public void registerContact(ActionRequest request, ActionResponse response) throws Exception {

    _log.debug("registerContact");

    Contact contact = ActionUtil.contactFromRequest(request);
    ArrayList<String> errors = new ArrayList();
    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    String community = "";
    try {
      community = themeDisplay.getScopeGroupName();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    boolean regValid = ContactMeRegValidator.validateRegistration(contact, errors);

    if (regValid) {

      long userId = themeDisplay.getUserId();

      contact.setCreateDate(new Date(System.currentTimeMillis()));
      contact.setUserId(userId);
      contact.setStatus(Constants.CONTACT_RECEIVED);
      contact.setCommunity(community);

      ContactLocalServiceUtil.addContact(contact);
      SessionMessages.add(request, "thank-you-message");

      PortletPreferences preferences = request.getPreferences();

      long companyId = PortalUtil.getCompanyId(request);

      Message message = new Message();

      message.put("from-name", preferences.getValue("fromName", ""));
      message.put("from-address", preferences.getValue("fromEMail", ""));
      message.put("subject", preferences.getValue("subject", ""));
      message.put("body", preferences.getValue("body", ""));
      message.put("signature", preferences.getValue("signature", ""));
      message.put("to-name", contact.getFullname());
      message.put("to-address", contact.getEmail());
      message.put("community", contact.getCommunity());
      message.put("companyId", companyId);

      MessageBusUtil.sendMessage("liferay/contactme", message);

      response.setRenderParameter("jspPage", viewThankYouJSP);

    } else {
      for (String error : errors) {
        SessionErrors.add(request, error);
      }
      SessionErrors.add(request, "error-saving-contact");
      response.setRenderParameter("jspPage", viewAddContactJSP);
      request.setAttribute("cmContact", contact);
    }
  }
Beispiel #11
0
  @Override
  protected void doProcessAction(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    PortletConfig portletConfig = getPortletConfig(actionRequest);

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

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

        throw new PortalException(uploadException.getCause());
      } else if (cmd.equals(Constants.ADD)) {
        addAttachment(actionRequest);
      } else if (cmd.equals(Constants.ADD_MULTIPLE)) {
        addMultipleFileEntries(portletConfig, actionRequest, actionResponse);
      } else if (cmd.equals(Constants.ADD_TEMP)) {
        addTempAttachment(actionRequest, actionResponse);
      } else if (cmd.equals(Constants.CHECK)) {
        JSONObject jsonObject = RestoreEntryUtil.checkEntry(actionRequest);

        JSONPortletResponseUtil.writeJSON(actionRequest, actionResponse, jsonObject);

        return;
      } else if (cmd.equals(Constants.DELETE)) {
        deleteAttachment(actionRequest, false);
      } else if (cmd.equals(Constants.DELETE_TEMP)) {
        deleteTempAttachment(actionRequest, actionResponse);
      } else if (cmd.equals(Constants.EMPTY_TRASH)) {
        emptyTrash(actionRequest);
      } else if (cmd.equals(Constants.MOVE_TO_TRASH)) {
        deleteAttachment(actionRequest, true);
      } else if (cmd.equals(Constants.RENAME)) {
        restoreRename(actionRequest);
      } else if (cmd.equals(Constants.RESTORE)) {
        restoreEntries(actionRequest);
      } else if (cmd.equals(Constants.OVERRIDE)) {
        restoreOverride(actionRequest);
      }

      if (cmd.equals(Constants.ADD_TEMP) || cmd.equals(Constants.DELETE_TEMP)) {

        actionResponse.setRenderParameter("mvcPath", "/null.jsp");
      }
    } catch (NoSuchNodeException | NoSuchPageException | PrincipalException e) {

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

      actionResponse.setRenderParameter("mvcPath", "/wiki/error.jsp");
    } catch (Exception e) {
      handleUploadException(portletConfig, actionRequest, actionResponse, cmd, e);
    }
  }
  /**
   * This method inserts new TerminationReason record into the database table
   *
   * @param actionRequest
   * @param actionResponse
   * @throws IOException
   * @throws PortletException
   * @throws SystemException
   */
  public void saveTerminationReasons(ActionRequest actionRequest, ActionResponse actionResponse)
      throws IOException, PortletException, SystemException {
    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
    try {
      TerminationReasons terminationReasons =
          TerminationReasonsLocalServiceUtil.createTerminationReasons(
              CounterLocalServiceUtil.increment());

      String id = ParamUtil.getString(actionRequest, "terminationreasonsId");
      String name = ParamUtil.getString(actionRequest, "terminationreasonsName");
      String terminationReason = name.trim();
      if (terminationReason.equals("") || terminationReason == null) {

        System.out.println("Empty value in TerminationReason...");
        SessionMessages.add(actionRequest.getPortletSession(), "termination-form-error");
        actionResponse.setRenderParameter("mvcPath", "/html/terminationreasons/add.jsp");
      } else {

        System.out.println("id == " + id + "Name = " + name);
        if (id == "" || id == null) {

          DynamicQuery dynamicQuery =
              DynamicQueryFactoryUtil.forClass(
                  TerminationReasons.class, PortalClassLoaderUtil.getClassLoader());

          dynamicQuery.add(RestrictionsFactoryUtil.eq("terminationreasonsName", name));
          List<TerminationReasons> list =
              TerminationReasonsLocalServiceUtil.dynamicQuery(dynamicQuery);

          if (list.size() > 0) {
            TerminationReasons terminationReasons2 = list.get(0);

            if (terminationReasons2 != null) {

              SessionMessages.add(
                  actionRequest.getPortletSession(), "termination-form-duplicate-error");
              actionResponse.setRenderParameter("mvcPath", "/html/terminationreasons/add.jsp");
            }
          } else {

            terminationReasons.setTerminationreasonsName(
                ParamUtil.getString(actionRequest, "terminationreasonsName"));
            terminationReasons.setCreateDate(date);
            terminationReasons.setModifiedDate(date);
            terminationReasons.setCompanyId(themeDisplay.getCompanyId());
            terminationReasons.setGroupId(themeDisplay.getCompanyGroupId());
            terminationReasons.setUserId(themeDisplay.getUserId());
            terminationReasons =
                TerminationReasonsLocalServiceUtil.addTerminationReasons(terminationReasons);
          }
        }
      }
    } catch (SystemException e) {

      e.printStackTrace();
    }
  }
  @Override
  public void sendRedirect(String location) throws IOException {
    if (!_include) {
      if (_lifecycle.equals(PortletRequest.ACTION_PHASE)) {
        ActionResponse actionResponse = _getActionResponse();

        actionResponse.sendRedirect(location);
      }
    }
  }
 protected void processTab(ActionResponse actionResponse, String tab)
     throws PortletException, IOException {
   if (tab.equals(PARAMV_TAB_GEOTHESAURUS)) {
     actionResponse.sendRedirect(actionResponse.encodeURL(PAGE_GEOTHESAURUS));
   } else if (tab.equals(PARAMV_TAB_MAP)) {
     actionResponse.sendRedirect(actionResponse.encodeURL(PAGE_MAP));
   } else {
     super.processTab(actionResponse, tab);
   }
 }
  private void doGo(ActionRequest request, ActionResponse response, StringBuffer message)
      throws ReadOnlyException, ValidatorException, IOException, PortletModeException {
    boolean save = true;
    // PortletPreferences prefs = request.getPreferences();
    String url = request.getParameter("url");
    if (!url.startsWith("http://")) {
      save = false;
      message.append("URLs must start with 'http://'<br/>");
      response.setRenderParameter("message", message.toString());
      response.setPortletMode(PortletMode.VIEW);
    }
    if (save) {
      request.getPortletSession().removeAttribute("highlights");
      // response.setRenderParameter("url", url.toLowerCase());
      // request.getPortletSession().setAttribute("current_url", url.toLowerCase());
      request.getPortletSession().setAttribute("current_url", url);
      this.sendEvent("loadedurl", url, response);
      response.setPortletMode(PortletMode.VIEW);
      request.getPortletSession().removeAttribute("highlights");
      // gestion de la consultation
      if (request.getPortletSession().getAttribute("consult_url")
          != null) // si une consultation a déjà commencé
      {
        if (!url.equalsIgnoreCase(
            (String)
                request
                    .getPortletSession()
                    .getAttribute("consult_url"))) // si on change de page à consulter
        {
          if (request.getPortletSession().getAttribute("user") != null) {
            // creates consultation
            // URI uri =
            // CREATOR_URI.createAndGetURI((String)request.getPortletSession().getAttribute("consult_url"));
            // CREATOR_CONSULTATION.createsConsultation((UserAccount)request.getPortletSession().getAttribute("user"), (Date)request.getPortletSession().getAttribute("start_consult") , new Date(), uri, "[PortletWebBrowse]");
            URI uri =
                daoResource.createAndGetURI(
                    (String) request.getPortletSession().getAttribute("consult_url"));
            daoConsultation.createsConsultation(
                (UserAccount) request.getPortletSession().getAttribute("user"),
                (Date) request.getPortletSession().getAttribute("start_consult"),
                new Date(),
                uri,
                "[PortletWebBrowse]");
          }
          request.getPortletSession().setAttribute("consult_url", url);
          request.getPortletSession().setAttribute("start_consult", new Date());
        }

      } else // si c'est la première consultation
      {
        request.getPortletSession().setAttribute("consult_url", url);
        request.getPortletSession().setAttribute("start_consult", new Date());
      }
    }
  }
  /**
   * Saves the values in the portletPreferences.xhtml Facelet composition as portlet preferences.
   */
  public void submit() {

    // The JSR 329 specification defines an EL variable named mutablePortletPreferencesValues that
    // is being used in
    // the portletPreferences.xhtml Facelet composition. This object is of type Map<String,
    // Preference> and is
    // designed to be a model managed-bean (in a sense) that contain preference values. However the
    // only way to
    // access this from a Java class is to evaluate an EL expression (effectively self-injecting)
    // the map into
    // this backing bean.
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    String elExpression = "mutablePortletPreferencesValues";
    ELResolver elResolver = facesContext.getApplication().getELResolver();
    @SuppressWarnings("unchecked")
    Map<String, Preference> mutablePreferenceMap =
        (Map<String, Preference>)
            elResolver.getValue(facesContext.getELContext(), null, elExpression);

    // Get a list of portlet preference names.
    PortletRequest portletRequest = (PortletRequest) externalContext.getRequest();
    PortletPreferences portletPreferences = portletRequest.getPreferences();
    Enumeration<String> preferenceNames = portletPreferences.getNames();

    try {

      // For each portlet preference name:
      while (preferenceNames.hasMoreElements()) {

        // Get the value specified by the user.
        String preferenceName = preferenceNames.nextElement();
        String preferenceValue = mutablePreferenceMap.get(preferenceName).getValue();

        // Prepare to save the value.
        if (!portletPreferences.isReadOnly(preferenceName)) {
          portletPreferences.setValue(preferenceName, preferenceValue);
        }
      }

      // Save the preference values.
      portletPreferences.store();

      // Switch the portlet mode back to VIEW.
      ActionResponse actionResponse = (ActionResponse) externalContext.getResponse();
      actionResponse.setPortletMode(PortletMode.VIEW);
      actionResponse.setWindowState(WindowState.NORMAL);

      // Report a successful message back to the user as feedback.
      FacesContextHelperUtil.addGlobalSuccessInfoMessage();
    } catch (Exception e) {
      FacesContextHelperUtil.addGlobalUnexpectedErrorMessage();
    }
  }
  @RequestMapping("EDIT")
  public void savePreferences(
      ActionRequest request,
      ActionResponse response,
      @RequestParam("topicsToUpdate") Integer topicsToUpdate)
      throws PortletException {

    List<TopicSubscription> newSubscription = new ArrayList<TopicSubscription>();

    for (int i = 0; i < topicsToUpdate; i++) {
      Long topicId = Long.valueOf(request.getParameter("topicId_" + i));

      // Will be numeric for existing, persisted TopicSubscription
      // instances;  blank (due to null id field) otherwise
      String topicSubId = request.getParameter("topicSubId_" + i).trim();

      Boolean subscribed = Boolean.valueOf(request.getParameter("subscribed_" + i));
      Topic topic = announcementService.getTopic(topicId);

      // Make sure that any pushed_forced topics weren't sneakingly removed (by tweaking the URL,
      // for example)
      if (topic.getSubscriptionMethod() == Topic.PUSHED_FORCED) {
        subscribed = new Boolean(true);
      }

      TopicSubscription ts = new TopicSubscription(request.getRemoteUser(), topic, subscribed);
      if (topicSubId.length() > 0) {
        // This TopicSubscription represents an existing, persisted entity
        try {
          ts.setId(Long.valueOf(topicSubId));
        } catch (NumberFormatException nfe) {
          logger.debug(nfe.getMessage(), nfe);
        }
      }

      newSubscription.add(ts);
    }

    if (newSubscription.size() > 0) {
      try {
        announcementService.addOrSaveTopicSubscription(newSubscription);
      } catch (Exception e) {
        logger.error(
            "ERROR saving TopicSubscriptions for user "
                + request.getRemoteUser()
                + ". Message: "
                + e.getMessage());
      }
    }

    response.setPortletMode(PortletMode.VIEW);
    response.setRenderParameter("action", "displayAnnouncements");
  }
  @Override
  public void processAction(
      PortletConfig portletConfig, ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    if (!_openId.isEnabled(themeDisplay.getCompanyId())) {
      throw new PrincipalException.MustBeEnabled(
          themeDisplay.getCompanyId(), OpenId.class.getName());
    }

    if (actionRequest.getRemoteUser() != null) {
      actionResponse.sendRedirect(themeDisplay.getPathMain());

      return;
    }

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

    try {
      if (cmd.equals(Constants.READ)) {
        String redirect = readOpenIdResponse(themeDisplay, actionRequest);

        if (Validator.isNull(redirect)) {
          redirect = themeDisplay.getURLSignIn();
        }

        redirect = PortalUtil.escapeRedirect(redirect);

        actionResponse.sendRedirect(redirect);
      } else {
        sendOpenIdRequest(themeDisplay, actionRequest, actionResponse);
      }
    } catch (Exception e) {
      if (e instanceof OpenIDException) {
        if (_log.isInfoEnabled()) {
          _log.info("Error communicating with OpenID provider: " + e.getMessage());
        }

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

        SessionErrors.add(actionRequest, e.getClass());
      } else {
        _log.error("Error processing the OpenID login", e);

        PortalUtil.sendError(e, actionRequest, actionResponse);
      }
    }
  }
  public void processAction(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse)
      throws Exception {

    Set<Long> messages = new HashSet<Long>();
    ThemeDisplay themedisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
    long userId = themedisplay.getUserId();
    String redirect = ParamUtil.getString(actionRequest, MessageConstants.REDIRECT);
    String[] msgs =
        ParamUtil.getString(actionRequest, MessageConstants.MOVE_MESSAGE_IDS, "").split(",");

    for (String s : msgs) {
      if (s.trim().length() == 0) continue;
      long messageId = Long.parseLong(s);
      Message m = MessageLocalServiceUtil.getMessage(messageId);
      if (!m.isArchived(userId)) {
        m.setArchived(userId);
      }
    }
    actionResponse.sendRedirect(redirect);
  }
  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);
  }
  public void EditPreferenceAction(ActionRequest req, ActionResponse res) {
    String cmd = ParamUtil.getString(req, Constants.CMD);

    if (!cmd.equals(Constants.UPDATE)) {
      return;
    }

    PortletPreferences prefs = req.getPreferences();
    int displayStyle = ParamUtil.getInteger(req, "displayStyle");
    // String styleSelected = ParamUtil.getString(req, "displayStyle","1");
    String[] selectCategories = req.getParameterValues("selectCategories");
    String defaultSize = ParamUtil.getString(req, "defaultSize");
    String widthSize = ParamUtil.getString(req, "widthSize");
    String heightSize = ParamUtil.getString(req, "heightSize");
    try {
      prefs.setValues("selectCategories", selectCategories);
      prefs.setValue("displayStyleExt", String.valueOf(displayStyle));
      prefs.setValue("defaultSize", defaultSize);
      prefs.setValue("widthSize", widthSize);
      prefs.setValue("heightSize", heightSize);

      prefs.store();
      res.setRenderParameter("jspPage", "/html/portlet/view_vclip/view.jsp");
    } catch (Exception e) {
      // TODO: handle exception
    }
  }
  @Override
  protected void doProcessAction(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    try {
      if (cmd.equals(Constants.ADD) || cmd.equals(Constants.UPDATE)) {
        updateFolder(actionRequest);
      } else if (cmd.equals(Constants.DELETE)) {
        deleteFolders(actionRequest, false);
      } else if (cmd.equals(Constants.MOVE_TO_TRASH)) {
        deleteFolders(actionRequest, true);
      } else if (cmd.equals(Constants.RESTORE)) {
        restoreTrashEntries(actionRequest);
      } else if (cmd.equals(Constants.SUBSCRIBE)) {
        subscribeFolder(actionRequest);
      } else if (cmd.equals(Constants.UNSUBSCRIBE)) {
        unsubscribeFolder(actionRequest);
      }
    } catch (Exception e) {
      if (e instanceof NoSuchFolderException || e instanceof PrincipalException) {

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

        actionResponse.setRenderParameter("mvcPath", "/bookmarks/error.jsp");
      } else if (e instanceof FolderNameException) {
        SessionErrors.add(actionRequest, e.getClass());
      } else {
        throw e;
      }
    }
  }
  @RequestMapping(params = "action=save")
  public void saveConfiguration(
      ActionRequest request,
      ActionResponse response,
      @ModelAttribute("form") SearchPortletConfigurationForm form)
      throws PortletModeException {

    PortletPreferences prefs = request.getPreferences();

    try {

      prefs.setValue("gsaEnabled", String.valueOf(form.isGsaEnabled()));
      prefs.setValue("gsaBaseUrl", form.getGsaBaseUrl());
      prefs.setValue("gsaSite", form.getGsaSite());
      prefs.setValue("directoryEnabled", String.valueOf(form.isDirectoryEnabled()));
      prefs.setValue("portletRegistryEnabled", String.valueOf(form.isPortletRegistryEnabled()));
      prefs.store();

    } catch (ValidatorException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ReadOnlyException e) {
      e.printStackTrace();
    }

    response.setPortletMode(PortletMode.VIEW);
  }
  protected void remoteProcessAction(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    OAuthRequest oAuthRequest = new OAuthRequest(Verb.POST, getServerPortletURL());

    setRequestParameters(actionRequest, actionResponse, oAuthRequest);

    addOAuthParameter(oAuthRequest, "p_p_lifecycle", "1");
    addOAuthParameter(oAuthRequest, "p_p_state", WindowState.NORMAL.toString());

    Response response = getResponse(themeDisplay.getUser(), oAuthRequest);

    if (response.getCode() == HttpServletResponse.SC_FOUND) {
      String redirectLocation = response.getHeader(HttpHeaders.LOCATION);

      actionResponse.sendRedirect(redirectLocation);
    } else {
      HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(actionResponse);

      httpServletResponse.setContentType(response.getHeader(HttpHeaders.CONTENT_TYPE));

      ServletResponseUtil.write(httpServletResponse, response.getStream());
    }
  }
  @Override
  public void processAction(
      ActionMapping actionMapping,
      ActionForm actionForm,
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse)
      throws Exception {

    try {
      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 {
        addFileEntry(actionRequest);
      }

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

      if (Validator.isNotNull(redirect)) {
        actionResponse.sendRedirect(redirect);
      }
    } catch (Exception e) {
      handleUploadException(actionRequest, actionResponse, e);
    }
  }
  @Override
  public void processAction(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse)
      throws Exception {

    try {
      moveCategory(actionRequest, actionResponse);

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

      if (Validator.isNotNull(redirect)) {
        actionResponse.sendRedirect(redirect);
      }
    } catch (Exception e) {
      if (e instanceof PrincipalException) {
        SessionErrors.add(actionRequest, e.getClass());
      } else {
        throw e;
      }
    }
  }
Beispiel #27
0
  private void _import(ActionRequest req, ActionResponse res) throws Exception {

    UploadPortletRequest uploadReq = PortalUtil.getUploadPortletRequest(req);

    String importerType = ParamUtil.get(uploadReq, "importer_type", ABUtil.IE_OUTLOOK);

    byte[] bytes = FileUtil.getBytes(uploadReq.getFile("import_file"));

    if (bytes == null || bytes.length == 0) {
      throw new UploadException();
    }

    Importer importer = null;

    if (importerType.equals(ABUtil.IE_OUTLOOK)) {
      importer = new OutlookImporter();
    } else if (importerType.equals(ABUtil.IE_YAHOO)) {
      importer = new OutlookImporter();
    }

    if (importer != null) {
      importer.setData(bytes);

      ABContactServiceUtil.addContacts(importer);
    }

    // Send redirect

    res.sendRedirect(ParamUtil.getString(req, "redirect"));
  }
  public void deleteLayout(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

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

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

    if (selPlid <= 0) {
      long groupId = ParamUtil.getLong(actionRequest, "groupId");
      boolean privateLayout = ParamUtil.getBoolean(actionRequest, "privateLayout");
      long layoutId = ParamUtil.getLong(actionRequest, "layoutId");

      Layout layout = layoutLocalService.getLayout(groupId, privateLayout, layoutId);

      selPlid = layout.getPlid();
    }

    Object[] returnValue = SitesUtil.deleteLayout(actionRequest, actionResponse);

    if (selPlid == themeDisplay.getRefererPlid()) {
      long newRefererPlid = (Long) returnValue[2];

      redirect = HttpUtil.setParameter(redirect, "refererPlid", newRefererPlid);
      redirect = HttpUtil.setParameter(redirect, actionResponse.getNamespace() + "selPlid", 0);
    }

    actionRequest.setAttribute(WebKeys.REDIRECT, redirect);
  }
 @ActionMapping("save")
 public void populatePersonne(
     @Valid @ModelAttribute("personne") PersonneViewModel personne,
     BindingResult result,
     SessionStatus status,
     Model model,
     ActionResponse response) {
   Personne personneDb;
   if (personne.getId() > 0) {
     personneDb =
         service.modifie(
             personne.getId(),
             personne.getNom(),
             personne.getPrenom(),
             personne.getHomme(),
             personne.getPrive(),
             personne.getPhotoUrl(),
             personne.getAnnotations());
   } else {
     personneDb =
         service.ajoute(
             personne.getNom(),
             personne.getPrenom(),
             personne.getHomme(),
             personne.getPrive(),
             personne.getPhotoUrl(),
             personne.getAnnotations());
   }
   personne.setId(personneDb.getId());
   personne.setEditMode(false);
   //		status.setComplete();
   response.setRenderParameter("action", "list");
 }
 /**
  * Clear all the render parameters from the {@link javax.portlet.ActionResponse}. This may not be
  * called when the action will call {@link ActionResponse#sendRedirect sendRedirect}.
  *
  * @param response the current action response
  * @see ActionResponse#setRenderParameters
  */
 public static void clearAllRenderParameters(ActionResponse response) {
   try {
     response.setRenderParameters(new HashMap<String, String[]>(0));
   } catch (IllegalStateException ex) {
     // Ignore in case sendRedirect was already set.
   }
 }