@Override
  public int doEndTag() throws JspException {
    // From portlet:defineObjects
    final RenderRequest renderRequest =
        (RenderRequest) this.pageContext.getAttribute("renderRequest");
    final RenderResponse renderResponse =
        (RenderResponse) this.pageContext.getAttribute("renderResponse");

    final PortletDelegationLocator portletDelegationLocator =
        (PortletDelegationLocator)
            renderRequest.getAttribute(PortletDelegationLocator.PORTLET_DELECATION_LOCATOR_ATTR);

    final String sessionKey = this.sessionKeyPrefix + this.fname;

    final PortletSession portletSession = renderRequest.getPortletSession();
    IPortletWindowId portletWindowId = (IPortletWindowId) portletSession.getAttribute(sessionKey);

    final PortletDelegationDispatcher portletDelegationDispatcher;
    final DelegateState delegateState;
    // No id in session, create a new dispatcher
    if (portletWindowId == null) {
      portletDelegationDispatcher =
          portletDelegationLocator.createRequestDispatcher(renderRequest, this.fname);
      portletWindowId = portletDelegationDispatcher.getPortletWindowId();
      portletSession.setAttribute(sessionKey, portletWindowId);

      final PortletMode portletMode = PortletUtils.getPortletMode(this.portletMode);
      final WindowState windowState = PortletUtils.getWindowState(this.windowState);

      delegateState = new DelegateState(portletMode, windowState);
    }
    // id in session, get the old dispatcher
    else {
      portletDelegationDispatcher =
          portletDelegationLocator.getRequestDispatcher(renderRequest, portletWindowId);
      delegateState = null;
    }

    final DelegationRequest delegationRequest = new DelegationRequest();
    delegationRequest.setDelegateState(delegateState);

    // Setup base for portlet URLs
    delegationRequest.setParentPortletMode(this.parentUrlMode);
    delegationRequest.setParentWindowState(this.parentUrlState);
    delegationRequest.setParentParameters(this.parentUrlParameters);

    final JspWriter out = this.pageContext.getOut();
    try {
      portletDelegationDispatcher.doRender(
          renderRequest,
          renderResponse,
          delegationRequest,
          new JspWriterPortletOutputHandler(out, renderResponse));
    } catch (IOException e) {
      throw new JspException(
          "Failed to execute delegate render on portlet '" + this.fname + "'", e);
    }

    return Tag.EVAL_PAGE;
  }
 private void sendAlert(RenderRequest request, Context context) {
   PortletSession pSession = request.getPortletSession(true);
   String str = (String) pSession.getAttribute(ALERT_MESSAGE);
   pSession.removeAttribute(ALERT_MESSAGE);
   if (str != null && str.length() > 0)
     context.put("alertMessage", validator.escapeHtml(str, false));
 }
  /**
   * Sets the "javax.portlet.faces.viewIdHistory.<code>portletMode</code>" session attribute
   * according to the requirements in Section 5.4.3 of the Bridge Spec. There is no corresponding
   * getter method, because the value is meant to be retrieved by developers via an EL expression.
   *
   * @param viewId The current Faces viewId.
   */
  protected void setViewHistory(String viewId) {

    String attributeName =
        Bridge.VIEWID_HISTORY.concat(".").concat(renderRequest.getPortletMode().toString());
    PortletSession portletSession = renderRequest.getPortletSession();
    portletSession.setAttribute(attributeName, viewId);
  }
  @Override
  public void doView(RenderRequest request, RenderResponse response)
      throws PortletException, IOException {
    PortletSession session = request.getPortletSession();
    MainSessionController mainSessionController =
        (MainSessionController)
            session.getAttribute(
                MainSessionController.MAIN_SESSION_CONTROLLER_ATT,
                PortletSession.APPLICATION_SCOPE);

    String spaceId =
        (String)
            session.getAttribute("Silverpeas_Portlet_SpaceId", PortletSession.APPLICATION_SCOPE);

    PortletPreferences pref = request.getPreferences();
    int nbPublis = 5;
    if (StringUtil.isInteger(pref.getValue("nbPublis", "5"))) {
      nbPublis = Integer.parseInt(pref.getValue("nbPublis", "5"));
    }
    int maxAge = 0;
    if (StringUtil.isInteger(pref.getValue("maxAge", "0"))) {
      maxAge = Integer.parseInt(pref.getValue("maxAge", "0"));
    }
    KmeliaTransversal kmeliaTransversal = new KmeliaTransversal(mainSessionController);
    List<PublicationDetail> publications =
        kmeliaTransversal.getUpdatedPublications(spaceId, maxAge, nbPublis);
    if (StringUtil.isDefined(spaceId)) {
      String rssUrl = getRSSUrl(mainSessionController, spaceId);
      request.setAttribute("rssUrl", rssUrl);
    }
    request.setAttribute("Publications", publications);
    include(request, response, "portlet.jsp");
  }
 private void showPrintableCatalog(RenderRequest request, RenderResponse response)
     throws PortletException, IOException {
   PortletRequestDispatcher dispatcher =
       request
           .getPortletSession()
           .getPortletContext()
           .getRequestDispatcher(response.encodeURL("/myservlet/bookServlet"));
   dispatcher.include(request, response);
 }
 private void showPrefsInfo(RenderRequest request, RenderResponse response)
     throws PortletException, IOException {
   PortletRequestDispatcher dispatcher =
       request
           .getPortletSession()
           .getPortletContext()
           .getRequestDispatcher(response.encodeURL("/WEB-INF/jsp/preferences.jsp"));
   dispatcher.include(request, response);
 }
  /**
   * Sets the "javax.portlet.faces.viewIdHistory.<code>portletMode</code>" session attribute
   * according to the requirements in Section 5.4.3 of the Bridge Spec. There is no corresponding
   * getter method, because the value is meant to be retrieved by developers via an EL expression.
   *
   * @param viewId The current Faces viewId.
   */
  protected void setViewHistory(String viewId) {
    StringBuilder buf = new StringBuilder();
    buf.append(Bridge.VIEWID_HISTORY);
    buf.append(StringPool.PERIOD);
    buf.append(renderRequest.getPortletMode());

    String attributeName = buf.toString();
    PortletSession portletSession = renderRequest.getPortletSession();
    portletSession.setAttribute(attributeName, viewId);
  }
  /**
   * @see
   *     org.apache.portals.bridges.velocity.GenericVelocityPortlet#doView(javax.portlet.RenderRequest,
   *     javax.portlet.RenderResponse)
   */
  public void doView(RenderRequest request, RenderResponse response)
      throws PortletException, IOException {
    Context context = getContext(request);

    IngridResourceBundle messages =
        new IngridResourceBundle(
            getPortletConfig().getResourceBundle(request.getLocale()), request.getLocale());
    context.put("MESSAGES", messages);

    PortletPreferences prefs = request.getPreferences();
    String titleKey = prefs.getValue("titleKey", "searchSettings.title.rankingAndGrouping");
    response.setTitle(messages.getString(titleKey));

    UtilsSearch.doViewForPartnerPortlet(request, context);

    Principal principal = request.getUserPrincipal();
    String partnerStr =
        (String)
            IngridPersistencePrefs.getPref(
                principal.getName(), IngridPersistencePrefs.SEARCH_PARTNER);

    if (partnerStr != null) {

      PortletSession session = request.getPortletSession();
      DisplayTreeNode partnerRoot = (DisplayTreeNode) session.getAttribute("partnerRoot");
      Iterator it = partnerRoot.getChildren().iterator();
      while (it.hasNext()) {
        DisplayTreeNode partnerNode = (DisplayTreeNode) it.next();
        if (partnerStr.indexOf(Settings.QFIELD_PARTNER.concat(":").concat(partnerNode.getId()))
                != -1
            || partnerNode.get("checked") != null) {
          partnerNode.put("checked", "true");
        } else {
          partnerNode.remove("checked");
        }
        Iterator it2 = partnerNode.getChildren().iterator();
        while (it2.hasNext()) {
          DisplayTreeNode providerNode = (DisplayTreeNode) it2.next();
          if (partnerStr.indexOf(Settings.QFIELD_PROVIDER.concat(":").concat(providerNode.getId()))
              != -1) {
            providerNode.put("checked", "true");
            partnerNode.setOpen(true);
          } else {
            providerNode.remove("checked");
          }
        }
      }
    }
    super.doView(request, response);
  }
  public static void init(RenderRequest request, RenderResponse response) {
    String outputEncoding = response.getCharacterEncoding();
    //        if (FacesResponseUtil.isMyFacesFacesContext(request)) {
    // for MyFaces
    // MyFaces needs this workaround code because of the implementation
    // issue..
    PortletSession session = request.getPortletSession(true);
    // FacesContext facesContext = FacesContext.getCurrentInstance();
    FacesContext facesContext = FacesResponseUtil.getMyFacesFacesContext(request);
    boolean existResonseWriter = true;
    if (facesContext == null) {
      existResonseWriter = false;
    } else {
      if (facesContext.getResponseWriter() == null) {
        existResonseWriter = false;
      }
    }

    Object oldBufferedResonseStream =
        session.getAttribute(FacesResponseConstants.BUFFERED_RESPONSE_STREAM);
    if (existResonseWriter && oldBufferedResonseStream != null) {
      ((BufferedResponseStream) oldBufferedResonseStream).recycle();
    } else {
      BufferedResponseStream bufferedResponseStream = new BufferedResponseStream(outputEncoding);
      session.setAttribute(FacesResponseConstants.BUFFERED_RESPONSE_STREAM, bufferedResponseStream);
    }
    //        } else {
    //            // for JSF implementation whice does not pass FacesContext from
    //            // processAction to render
    //            BufferedResponseStream bufferedResponseStream = new BufferedResponseStream(
    //                    outputEncoding);
    //            request.setAttribute(
    //                    FacesResponseConstants.BUFFERED_RESPONSE_STREAM,
    //                    bufferedResponseStream);
    //        }
  }
Exemplo n.º 10
0
  protected void doView(RenderRequest request, RenderResponse response)
      throws PortletException, java.io.IOException {
    String page = request.getParameter("pageId");
    if (page == null || page.trim().length() < 1) page = "1";
    int pageId = Integer.parseInt(page);
    if (request.getPortletSession().getAttribute("mails", PortletSession.PORTLET_SCOPE) == null
        || request.getParameter("refresh") != null
        || request.getParameter("newPage") != null) {
      PortletPreferences portletPreferences = request.getPreferences();
      UserProfile userProfile =
          this.getUserService(request).getUserProfileById(this.getUser(request).getId());
      String name = null;
      if (userProfile != null) name = userProfile.getName();
      if ((name == null || name.length() <= 0) && this.getUser(request) != null)
        name = this.getUser(request).getDisplayName();
      String fullName = portletPreferences.getValue("fullName", name);
      String incomingType = portletPreferences.getValue("incomingType", null);
      String incoming = portletPreferences.getValue("incoming", null);
      String incomingPort = portletPreferences.getValue("incomingPort", null);
      String incomingSSL = portletPreferences.getValue("incomingSSL", null);
      String outgoing = portletPreferences.getValue("outgoing", null);
      String outgoingPort = portletPreferences.getValue("outgoingPort", null);
      String outgoingSSL = portletPreferences.getValue("outgoingSSL", null);
      String email = portletPreferences.getValue("email", null);
      String password = portletPreferences.getValue("password", null);
      String number = portletPreferences.getValue("number", "10");
      if (incoming == null || outgoing == null || email == null || password == null) {
        request.setAttribute("incomingPort", "110");
        request.setAttribute("outgoingPort", "25");
        request.setAttribute("number", number);
        this.getPortletContext()
            .getRequestDispatcher(_PORTLET_JSP_PATH + "/email/emailPortletConfig.jsp")
            .include(request, response);
      } else {
        int row = Integer.parseInt(number);
        if (request.getParameter("refresh") != null) pageId = 1;
        List<MailBean> mails = null;
        EmailClient client =
            new EmailClient(
                email,
                password,
                incomingType,
                incoming,
                incomingPort,
                incomingSSL,
                outgoing,
                outgoingPort,
                outgoingPort);
        try {
          mails = client.getMessage(EmailClient.SHOW_MESSAGES, pageId, row);
        } catch (Exception e) {
          request.setAttribute("error", e.getMessage());
        }
        int count = 0;
        int unread = 0;
        if (mails != null && mails.size() > 0) {
          count = mails.get(0).getTotal();
          unread = mails.get(0).getUnreadCount();
        }
        int pages = count / row;
        if (count % row != 0) pages++;

        request.getPortletSession().setAttribute("mails", mails, PortletSession.PORTLET_SCOPE);
        request.getPortletSession().setAttribute("totalCount", count, PortletSession.PORTLET_SCOPE);
        request
            .getPortletSession()
            .setAttribute("unreadCount", unread, PortletSession.PORTLET_SCOPE);
        request.getPortletSession().setAttribute("pages", pages, PortletSession.PORTLET_SCOPE);
        request.getPortletSession().setAttribute("row", row, PortletSession.PORTLET_SCOPE);
        request.setAttribute("pageId", pageId);
        request.setAttribute("totalCount", count);
        request.setAttribute("unreadCount", unread);
        request.setAttribute("pages", pages);
        request.setAttribute("row", row);
        request.setAttribute("mails", mails);
        if (request.getWindowState().equals(WindowState.MAXIMIZED))
          this.getPortletContext()
              .getRequestDispatcher(_PORTLET_JSP_PATH + "/email/emailPortletMaxView.jsp")
              .include(request, response);
        else
          this.getPortletContext()
              .getRequestDispatcher(_PORTLET_JSP_PATH + "/email/emailPortletView.jsp")
              .include(request, response);
      }
    } else {
      if (request.getParameter("mailId") != null) {
        int index = Integer.parseInt(request.getParameter("mailId"));
        List<MailBean> mails =
            (List<MailBean>)
                request.getPortletSession().getAttribute("mails", PortletSession.PORTLET_SCOPE);
        MailBean mail = mails.get(index);
        if (mail.getContent() == null) {
          PortletPreferences portletPreferences = request.getPreferences();
          String incomingType = portletPreferences.getValue("incomingType", null);
          String incoming = portletPreferences.getValue("incoming", null);
          String incomingPort = portletPreferences.getValue("incomingPort", null);
          String incomingSSL = portletPreferences.getValue("incomingSSL", null);
          String outgoing = portletPreferences.getValue("outgoing", null);
          String outgoingPort = portletPreferences.getValue("outgoingPort", null);
          String outgoingSSL = portletPreferences.getValue("outgoingSSL", null);
          String email = portletPreferences.getValue("email", null);
          String password = portletPreferences.getValue("password", null);
          EmailClient client =
              new EmailClient(
                  email,
                  password,
                  incomingType,
                  incoming,
                  incomingPort,
                  incomingSSL,
                  outgoing,
                  outgoingPort,
                  outgoingPort);
          try {
            mail = client.getMessageDetail(mails.get(index).getMsg());
            int unread =
                (Integer)
                    request
                        .getPortletSession()
                        .getAttribute("unreadCount", PortletSession.PORTLET_SCOPE);
            if (mails.get(index).getFlag() == 1) unread--;
            if (unread < 0) unread = 0;
            request
                .getPortletSession()
                .setAttribute("unreadCount", unread, PortletSession.PORTLET_SCOPE);
            // request.getPortletSession().removeAttribute("mails",PortletSession.PORTLET_SCOPE);
          } catch (Exception e) {
            request.setAttribute("error", e.getMessage());
          }
          mails.set(index, mail);
        }
        request.setAttribute("currentMail", mail);
        request.setAttribute("pageId", pageId);
      } else {

        List<MailBean> mails =
            (List<MailBean>)
                request.getPortletSession().getAttribute("mails", PortletSession.PORTLET_SCOPE);
        int row =
            (Integer) request.getPortletSession().getAttribute("row", PortletSession.PORTLET_SCOPE);
        int count =
            (Integer)
                request
                    .getPortletSession()
                    .getAttribute("totalCount", PortletSession.PORTLET_SCOPE);
        int unread =
            (Integer)
                request
                    .getPortletSession()
                    .getAttribute("unreadCount", PortletSession.PORTLET_SCOPE);
        int pages =
            (Integer)
                request.getPortletSession().getAttribute("pages", PortletSession.PORTLET_SCOPE);
        List<MailBean> pageMails = new ArrayList<MailBean>();
        request.setAttribute("pageId", pageId);
        request.setAttribute("totalCount", count);
        request.setAttribute("unreadCount", unread);
        request.setAttribute("pages", pages);
        request.setAttribute("row", row);
        request.setAttribute("mails", mails);
      }
      if (request.getWindowState().equals(WindowState.MAXIMIZED))
        this.getPortletContext()
            .getRequestDispatcher(_PORTLET_JSP_PATH + "/email/emailPortletMaxView.jsp")
            .include(request, response);
      else
        this.getPortletContext()
            .getRequestDispatcher(_PORTLET_JSP_PATH + "/email/emailPortletView.jsp")
            .include(request, response);
    }
  }
  @Override
  public void render(RenderRequest portletReq, RenderResponse portletResp)
      throws PortletException, IOException {
    LOGGER.entering(LOG_CLASS, "main portlet render entry");

    long tid = Thread.currentThread().getId();
    portletReq.setAttribute(THREADID_ATTR, tid);

    PrintWriter writer = portletResp.getWriter();

    PortletSession ps = portletReq.getPortletSession();
    String msg =
        (String)
            ps.getAttribute(
                RESULT_ATTR_PREFIX + "DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse",
                APPLICATION_SCOPE);
    if (msg != null) {
      writer.write("<p>" + msg + "</p><br/>\n");
      ps.removeAttribute(
          RESULT_ATTR_PREFIX + "DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse",
          APPLICATION_SCOPE);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_containsHeader */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.containsHeader must return false"         */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_containsHeader", aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_encodeRedirectURL1 */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.encodeRedirectURL must return null"       */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_encodeRedirectURL1",
              aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_encodeRedirectUrl */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.encodeRedirectUrl must return null"       */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_encodeRedirectUrl",
              aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_encodeURL1 */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.encodeURL must provide the same           */
    /* functionality as ActionResponse.encodeURL"                           */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_encodeURL1", aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_encodeUrl */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.encodeUrl must provide the same           */
    /* functionality as ActionResponse.encodeURL"                           */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_encodeUrl", aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_getBufferSize */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.getBufferSize must return 0"              */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_getBufferSize", aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_getCharacterEncoding */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.getCharacterEncoding must return null"    */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_getCharacterEncoding",
              aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_getContentType */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.getContentType must return null"          */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_getContentType", aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_getLocale */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.getLocale must return null"               */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_getLocale", aurl);
      tb.writeTo(writer);
    }

    /* TestCase: V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_isCommitted */
    /* Details: "In a target jsp of a include in the Action phase, the      */
    /* method HttpServletResponse.isCommitted must return true"             */
    {
      PortletURL aurl = portletResp.createActionURL();
      aurl.setParameters(portletReq.getPrivateParameterMap());
      TestButton tb =
          new TestButton(
              "V2DispatcherReqRespTests3_SPEC2_19_IncludeJSPActionResponse_isCommitted", aurl);
      tb.writeTo(writer);
    }
  }
  /**
   * @param request the render request being processed
   * @param response the render response to be returned
   * @param preferences portlet preferences
   * @param model model for rendering
   * @return the view name or view content for the content
   * @throws any exceptions that occur
   */
  @RenderMapping
  public String doRenderDelegationDefaultView(
      RenderRequest request, RenderResponse response, PortletPreferences preferences, Model model)
      throws Exception {
    LogHelper log = new LogHelper(request);
    RequestMessages rqm = RequestMessages.getRequestMessages(request);
    String viewName = Consts.DELEGATEUSERACCESSTOSERVICECREDITSDELEGATIONDEFAULTVIEWVIEWNAME;
    try {
      log.startTimer("doRenderDelegationDefaultView");
      TTT t = new TTT();
      PortletSession session = request.getPortletSession();
      session.setAttribute("x", t);
      String test = (String) session.getAttribute("ActionMode", PortletSession.PORTLET_SCOPE);
      boolean action = (test != null && "action".equals(test));
      if (action) session.removeAttribute("ActionMode");
      model.addAttribute("Consts", new Consts());
      BannerPortletData data =
          (BannerPortletData)
              session.getAttribute("BannerPortletData", PortletSession.APPLICATION_SCOPE);
      if (data == null) {
        data = new BannerPortletData();
        data.loadFromRequest(request);
        data.loadFromPreferences(request, rqm);
      }
      // ProtectBlock renderDelegationDefaultViewBody
      // TODO Fill In Render Body
      logger.debug("In the default render method of the ServiceCrerditsDelegationView Controller");

      logger.info(
          "Logged in user id in default render method: "
              + Utility.isLoggedInUserInDelegateMode(request)
              + "--->>"
              + Utility.retrieveDelegateUserProfileMapFromRequest(request));
      logger.info(
          "Subject user id in default render method: "
              + Utility.isLoggedInUserInDelegateMode(request)
              + "===>>"
              + Utility.retrieveUserId(request)
              + Utility.retrieveUserEmail(request));
      // logger.info("In the doRenderDefault,Sessin clean up triggred in previous action method. "
      // +session.getAttributeMap(PortletSession.APPLICATION_SCOPE).keySet());
      viewName = "FindCustomerUser";
      if (session.getAttribute("showOverlayFlag", PortletSession.APPLICATION_SCOPE) != null) {
        boolean showOverlayFlag =
            (Boolean) session.getAttribute("showOverlayFlag", PortletSession.APPLICATION_SCOPE);
        if (showOverlayFlag) {
          model.addAttribute("display_modal_overlay", "true");
          session.removeAttribute("showOverlayFlag", PortletSession.APPLICATION_SCOPE);
        }
      } else {
        model.addAttribute("display_modal_overlay", "false");
      }
      if (Utility.isLoggedInUserInDelegateMode(request)) {
        logger.debug(
            "Changing view to DelegationView as the Delegate has still not signed out of the delegation mode");
        logger.info(
            "Changing view to DelegationView as the Delegate has still not signed out of the delegation mode");
        // ExternalUserProfile userProfile =
        // (ExternalUserProfile)session.getAttribute(Consts.TEMP_SUBJECT_USER_MAP_KEY_IN_SESSION,
        // PortletSession.APPLICATION_SCOPE);
        Map<String, Object> userProfile =
            (Map<String, Object>)
                session.getAttribute(
                    Consts.SESSION_SUBJECT_USER_MAP, PortletSession.APPLICATION_SCOPE);

        if (userProfile == null) {
          logger.info("The user profile returned in the Do-render-Delegate view was null");
          viewName = "FindCustomerUser";
          return viewName;
        } else {
          logger.debug(
              "Adding a few attribute fo the subject user in to the model like the name,company name and email-id");
          logger.info(
              "Setting the attribute of the subject user to model :"
                  + (String) userProfile.get(Consts.KEY_FIRST_NAME)
                  + " "
                  + (String) userProfile.get(Consts.KEY_LAST_NAME));
          model.addAttribute("company_Name", (String) userProfile.get("Company"));
          model.addAttribute("user_ID", (String) userProfile.get(Consts.KEY_USER_NAME));
          model.addAttribute("last_Name", (String) userProfile.get(Consts.KEY_LAST_NAME));
          model.addAttribute("first_Name", (String) userProfile.get(Consts.KEY_FIRST_NAME));
          model.addAttribute("email_Address", (String) userProfile.get(Consts.KEY_EMAIL));
        }
        viewName = "DelegationView";
      }
      logger.debug("End of default render method of the ServiceCrerditsDelegationView Controller");
      // ProtectBlock End
      data.saveToModel(model, rqm);
      session.setAttribute("BannerPortletData", data, PortletSession.APPLICATION_SCOPE);
    } catch (Exception ex) {
      log.endTimer("doRenderDelegationDefaultView");
      throw ex;
    } finally {
      rqm.release();
      log.endTimer("doRenderDelegationDefaultView");
    }
    return viewName;
  }
  /**
   * @param request the render request being processed
   * @param response the render response to be returned
   * @param preferences portlet preferences
   * @param model model for rendering
   * @return the view name or view content for the content
   * @throws any exceptions that occur
   */
  @RenderMapping(params = Consts.ACTION_SEARCHRESULTVIEW)
  public String doRenderSearchResultView(
      RenderRequest request, RenderResponse response, PortletPreferences preferences, Model model)
      throws Exception {
    LogHelper log = new LogHelper(request);
    RequestMessages rqm = RequestMessages.getRequestMessages(request);
    String viewName = Consts.DELEGATEUSERACCESSTOSERVICECREDITSSEARCHRESULTVIEWVIEWNAME;
    try {
      log.startTimer("doRenderSearchResultView");
      PortletSession session = request.getPortletSession();
      String test = (String) session.getAttribute("ActionMode", PortletSession.PORTLET_SCOPE);
      boolean action = (test != null && "action".equals(test));
      if (action) session.removeAttribute("ActionMode");
      model.addAttribute("Consts", new Consts());
      BannerPortletData data =
          (BannerPortletData)
              session.getAttribute("BannerPortletData", PortletSession.APPLICATION_SCOPE);
      if (data == null) {
        data = new BannerPortletData();
        data.loadFromRequest(request);
        data.loadFromPreferences(request, rqm);
      }
      // ProtectBlock renderSearchResultViewBody
      logger.debug("In the render result view of the ServiceCreditsDelegationView Controller");
      logger.debug("setting modal overlay display flag to true");

      // logger.info("In the doRenderSearchResult,Sessin clean up triggred in previous action
      // method. " +session.getAttributeMap(PortletSession.APPLICATION_SCOPE).keySet());
      if (session.getAttribute("showOverlayFlag", PortletSession.APPLICATION_SCOPE) != null) {
        boolean showOverlayFlag =
            (Boolean) session.getAttribute("showOverlayFlag", PortletSession.APPLICATION_SCOPE);
        if (showOverlayFlag) {
          model.addAttribute("display_modal_overlay", "true");
          session.removeAttribute("showOverlayFlag", PortletSession.APPLICATION_SCOPE);
        }
      } else {
        model.addAttribute("display_modal_overlay", "false");
      }
      logger.debug("Setting the attribute of the subject user to model");
      ExternalUserProfile user_profile =
          (ExternalUserProfile)
              session.getAttribute(
                  Consts.TEMP_SUBJECT_USER_MAP_KEY_IN_SESSION, PortletSession.APPLICATION_SCOPE);
      model.addAttribute("company_Name", user_profile.getBusCompanyName());
      model.addAttribute("user_ID", user_profile.getHppUserId());
      model.addAttribute("last_Name", user_profile.getFamilyName());
      model.addAttribute("first_Name", user_profile.getGivenName());
      model.addAttribute("email_Address", user_profile.getEmail());
      viewName = "FindCustomerUser";
      logger.debug("End of render result view of ServiceCreditsDelegationView Controller");
      // TODO Fill In Render Body
      // ProtectBlock End
      data.saveToModel(model, rqm);
      session.setAttribute("BannerPortletData", data, PortletSession.APPLICATION_SCOPE);
    } catch (Exception ex) {
      log.endTimer("doRenderSearchResultView");
      throw ex;
    } finally {
      rqm.release();
      log.endTimer("doRenderSearchResultView");
    }
    return viewName;
  }
  protected void doView(RenderRequest request, RenderResponse response)
      throws PortletException, java.io.IOException {
    String input = request.getParameter("input");
    String keyword = request.getParameter("keyword");
    String type = request.getParameter("type");
    String sort = request.getParameter("sort");
    String show = request.getParameter("show");
    if ("0".equals(input)) keyword = null;
    SearchCriteria criteria =
        (SearchCriteria)
            request.getPortletSession().getAttribute("criteria", PortletSession.APPLICATION_SCOPE);
    if (criteria == null)
      criteria = new SearchCriteria(OrganizationThreadLocal.getOrganizationId());
    if (!StringUtil.isEmpty(show))
      try {
        criteria.setRowPerPage(Integer.parseInt(show));
      } catch (Exception e) {
      }
    int page = 1;
    int number = 0;
    boolean pageChange = false;
    if (request.getParameter("page") != null) {
      try {
        page = Integer.parseInt(request.getParameter("page"));
        number = page * criteria.getRowPerPage();
        pageChange = true;
      } catch (Exception e) {
      }
    } else if (request.getParameter("number") != null) {
      try {
        number = Integer.parseInt(request.getParameter("number"));
        page = number / criteria.getRowPerPage();
        pageChange = true;
      } catch (Exception e) {
      }
    }
    criteria.setPage(page);
    if (!pageChange) {
      criteria.setKeyword(keyword);
      if (sort != null) criteria.setSort(sort);
    }
    SearchResult result = null;
    if (type == null) type = getDefaultType();
    try {
      if (type != null && !type.equals("all"))
        result = this.getSearcher(request).search(Class.forName(type), criteria);
      else result = this.getSearcher(request).search(criteria);
      request
          .getPortletSession()
          .setAttribute("criteria", criteria, PortletSession.APPLICATION_SCOPE);
    } catch (Exception e) {
      e.printStackTrace();
    }
    int total = result.getTotal();
    int rowPerPage = criteria.getRowPerPage();
    int pages = (total % rowPerPage == 0) ? total / rowPerPage : total / rowPerPage + 1;
    int start = (page - 1) * rowPerPage;
    int end = (page * rowPerPage < total) ? page * rowPerPage : total;

    JSONObject json = new JSONObject();
    try {
      json.put("view", "globalSearch.view");
      json.put("type", type);
      json.put("sort", criteria.getSort());
      json.put("show", criteria.getRowPerPage());
      json.put("keyword", StringUtil.isEmpty(criteria.getKeyword()) ? "" : criteria.getKeyword());
      json.put("items", getSearchResultsJSON(result.getItems()));
      json.put("total", total);
      json.put("pages", pages);
      json.put("page", page);
      json.put("start", start);
      json.put("end", end);
      int begin = page;
      if (begin - 5 > 0) begin -= 5;
      else begin = 1;
      int finish = pages;
      if (finish >= begin + 10) finish = begin + 9;
      JSONArray jArray = new JSONArray();
      for (int i = begin; i <= finish; i++) jArray.put(i);
      json.put("pageNumbers", jArray);
    } catch (Exception e) {
    }
    response.getWriter().write(json.toString());
  }
  @SuppressWarnings("unchecked")
  @RenderMode(name = "VIEW")
  public void showBooks(RenderRequest request, RenderResponse response)
      throws IOException, PortletException {
    logger.info("Entering showBooks method");
    PortalContext context = request.getPortalContext();
    printSupportedPortletModes(context);
    printSupportedWindowStates(context);

    // --get user attributes user.name.given and user.name.family
    Map<String, Object> userAttributeMap =
        (Map<String, Object>) request.getAttribute(PortletRequest.USER_INFO);
    String firstName = "";
    String lastName = "";
    if (userAttributeMap != null) {
      firstName = (String) userAttributeMap.get("user.name.given");
      lastName = (String) userAttributeMap.get("user.name.family");
      request.setAttribute("firstName", firstName);
      request.setAttribute("lastName", lastName);
    }

    String portalInfo = context.getPortalInfo();
    request.setAttribute("portalInfo", portalInfo);

    // --generate all the URLs that will be used by the portlet
    generateUrls(request, response);

    String myaction = request.getParameter("myaction");
    if (myaction != null) {
      logger.info("myaction parameter is not null. Value is " + myaction);
      request.getPortletSession().setAttribute("myaction", myaction, PortletSession.PORTLET_SCOPE);
    } else {
      // -- if myaction is NULL then show the home page of Book
      // catalog
      // page
      request
          .getPortletSession()
          .setAttribute("myaction", "showCatalog", PortletSession.PORTLET_SCOPE);
    }

    // -- send myaction as a request attribute to the BookServlet.
    request.setAttribute("myaction", request.getPortletSession().getAttribute("myaction"));

    // --dynamically obtain the title for the portlet, based on myaction
    String titleKey =
        "portlet.title." + (String) request.getPortletSession().getAttribute("myaction");
    response.setTitle(getResourceBundle(request.getLocale()).getString(titleKey));

    // --if the action is uploadTocForm then store the ISBN number of
    // the
    // --book for which the TOC is being uploaded. The upload action
    // will use the ISBN number to create file name -- refer home.jsp
    // page
    if (((String) request.getAttribute("myaction")).equalsIgnoreCase("uploadTocForm")) {
      request.getPortletSession().setAttribute("isbnNumber", request.getParameter("isbnNumber"));
    }

    if (((String) request.getPortletSession().getAttribute("myaction"))
        .equalsIgnoreCase("showSearchResults")) {
      request.setAttribute(
          "matchingBooks", request.getPortletSession().getAttribute("matchingBooks"));
    }

    // its important to encode URLs
    PortletRequestDispatcher dispatcher =
        request
            .getPortletSession()
            .getPortletContext()
            .getRequestDispatcher(response.encodeURL("/myservlet/bookServlet"));
    dispatcher.include(request, response);
  }
Exemplo n.º 16
0
  @RequestMapping
  public String ver(
      RenderRequest request,
      RenderResponse response,
      @RequestParam(required = false) Integer dias,
      Model model) {
    log.debug("Viendo el versiculo");
    TimeZone tz = null;
    DateTimeZone zone = null;
    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
    try {
      tz = themeDisplay.getTimeZone();
      zone = DateTimeZone.forID(tz.getID());
    } catch (IllegalArgumentException e) {
      zone = DateTimeZone.forID(ZonaHorariaUtil.getConvertedId(tz.getID()));
    }
    try {
      long scopeGroupId = themeDisplay.getScopeGroupId();

      AssetEntryQuery assetEntryQuery = new AssetEntryQuery();

      DateTime hoy =
          (DateTime)
              request.getPortletSession().getAttribute("hoy", PortletSession.APPLICATION_SCOPE);
      if (hoy == null) {
        hoy = new DateTime(zone);
        log.debug("Subiendo atributo hoy({}) a la sesion", hoy);
        request.getPortletSession().setAttribute("hoy", hoy, PortletSession.APPLICATION_SCOPE);
      }

      // Busca el contenido del dia
      String[] tags = TagsUtil.getTags(new String[4], hoy);
      tags[3] = "versiculo";

      long[] assetTagIds = AssetTagLocalServiceUtil.getTagIds(scopeGroupId, tags);

      assetEntryQuery.setAllTagIds(assetTagIds);

      List<AssetEntry> results = AssetEntryServiceUtil.getEntries(assetEntryQuery);

      log.debug("Buscando el versiculo de la semana {}", hoy);
      for (AssetEntry asset : results) {
        if (asset.getClassName().equals(JournalArticle.class.getName())) {
          JournalArticle ja = JournalArticleLocalServiceUtil.getLatestArticle(asset.getClassPK());
          String contenido =
              JournalArticleLocalServiceUtil.getArticleContent(
                  ja.getGroupId(),
                  ja.getArticleId(),
                  "view",
                  "" + themeDisplay.getLocale(),
                  themeDisplay);
          model.addAttribute("contenido", contenido);
        }
      }

    } catch (Exception e) {
      log.error("No se pudo cargar el contenido", e);
      throw new RuntimeException("No se pudo cargar el contenido", e);
    }

    return "versiculo/ver";
  }
Exemplo n.º 17
0
	/**
	 * Processes the actual dispatching to the handler for render requests.
	 * <p>The handler will be obtained by applying the portlet's HandlerMappings in order.
	 * The HandlerAdapter will be obtained by querying the portlet's installed
	 * HandlerAdapters to find the first that supports the handler class.
	 * @param request current portlet render request
	 * @param response current portlet render response
	 * @throws Exception in case of any kind of processing failure
	 */
	@Override
	protected void doRenderService(RenderRequest request, RenderResponse response) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received render request");
		}

		HandlerExecutionChain mappedHandler = null;
		int interceptorIndex = -1;

		try {
			ModelAndView mv;
			try {
				// Determine handler for the current request.
				mappedHandler = getHandler(request);
				if (mappedHandler == null || mappedHandler.getHandler() == null) {
					noHandlerFound(request, response);
					return;
				}

				// Apply preHandle methods of registered interceptors.
				HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
				if (interceptors != null) {
					for (int i = 0; i < interceptors.length; i++) {
						HandlerInterceptor interceptor = interceptors[i];
						if (!interceptor.preHandleRender(request, response, mappedHandler.getHandler())) {
							triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, null);
							return;
						}
						interceptorIndex = i;
					}
				}

				// Check for forwarded exception from the action phase
				PortletSession session = request.getPortletSession(false);
				if (session != null) {
					if (request.getParameter(ACTION_EXCEPTION_RENDER_PARAMETER) != null) {
						Exception ex = (Exception) session.getAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
						if (ex != null) {
							logger.debug("Render phase found exception caught during action phase - rethrowing it");
							throw ex;
						}
					}
					else {
						session.removeAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
					}
				}

				// Actually invoke the handler.
				HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
				mv = ha.handleRender(request, response, mappedHandler.getHandler());

				// Apply postHandle methods of registered interceptors.
				if (interceptors != null) {
					for (int i = interceptors.length - 1; i >= 0; i--) {
						HandlerInterceptor interceptor = interceptors[i];
						interceptor.postHandleRender(request, response, mappedHandler.getHandler(), mv);
					}
				}
			}
			catch (ModelAndViewDefiningException ex) {
				logger.debug("ModelAndViewDefiningException encountered", ex);
				mv = ex.getModelAndView();
			}
			catch (Exception ex) {
				Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
				mv = processHandlerException(request, response, handler, ex);
			}

			// Did the handler return a view to render?
			if (mv != null && !mv.isEmpty()) {
				render(mv, request, response);
			}
			else {
				if (logger.isDebugEnabled()) {
					logger.debug("Null ModelAndView returned to DispatcherPortlet with name '" +
							getPortletName() + "': assuming HandlerAdapter completed request handling");
				}
			}

			// Trigger after-completion for successful outcome.
			triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, null);
		}

		catch (Exception ex) {
			// Trigger after-completion for thrown exception.
			triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, ex);
			throw ex;
		}
		catch (Error err) {
			PortletException ex =
					new PortletException("Error occured during request processing: " + err.getMessage(), err);
			// Trigger after-completion for thrown exception.
			triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, ex);
			throw ex;
		}
	}
  @RequestMapping("EDIT")
  public ModelAndView renderEditView(RenderRequest request, RenderResponse response)
      throws Exception {

    ModelMap model = new ModelMap();
    final PortletPreferences prefs = request.getPreferences();
    String[] recupPrefDisplay_userTabs = prefs.getValues(WebController.PREF_TAB_USER, null);
    String[] recupPrefDisplay_managerTabs = prefs.getValues(WebController.PREF_TAB_MANAGER, null);
    String messageFile = prefs.getValue(WebController.PREF_MESSAGE_FILE, "_fr");
    String nbMaxTickets = prefs.getValue(WebController.PREF_MAX_TICKETS, "15");

    ArrayOfString managerFilters =
        domainService.getInvolvementFilters(
            (prefs.getValue(WebController.PREF_WSDL_LOCATION, null)), false);
    ArrayOfString userFilters =
        domainService.getInvolvementFilters(
            (prefs.getValue(WebController.PREF_WSDL_LOCATION, null)), true);

    ArrayList<String> userTabPrefs = new ArrayList<String>();
    ArrayList<String> managerTabPrefs = new ArrayList<String>();
    int i = 0;
    for (String userFilter : userFilters.getString()) {
      if (Arrays.asList(recupPrefDisplay_userTabs).contains(userFilter.toLowerCase())) {
        i++;
        userTabPrefs.add(String.valueOf(i).concat(".").concat(userFilter).toLowerCase());
      } else {
        userTabPrefs.add(userFilter.toLowerCase());
      }
    }
    Collections.sort(userTabPrefs);
    i = 0;
    for (String managerFilter : managerFilters.getString()) {
      if (Arrays.asList(recupPrefDisplay_managerTabs).contains(managerFilter.toLowerCase())) {
        i++;
        managerTabPrefs.add(String.valueOf(i).concat(".").concat(managerFilter).toLowerCase());
      } else {
        managerTabPrefs.add(managerFilter.toLowerCase());
      }
    }
    Collections.sort(managerTabPrefs);
    boolean userViewMode = true;
    boolean managerViewMode = false;
    boolean maxTicketsViewMode = false;
    String isManagerViewAble = "false";

    if (prefs.isReadOnly(WebController.PREF_TAB_USER)) {
      userViewMode = false;
    }
    PortletSession session = request.getPortletSession();
    if (session != null) {
      isManagerViewAble = session.getAttribute("isManagerViewAble").toString();
    }
    if ((isManagerViewAble.equalsIgnoreCase("true"))
        && (!prefs.isReadOnly(WebController.PREF_TAB_MANAGER))) {
      managerViewMode = true;
    }
    if (!prefs.isReadOnly(WebController.PREF_MAX_TICKETS)) {
      maxTicketsViewMode = true;
    }
    model.put("nbMaxTickets", nbMaxTickets);
    model.put("messageFile", messageFile);
    model.put("managerTabPrefs", managerTabPrefs);
    model.put("userTabPrefs", userTabPrefs);
    model.put("userViewMode", userViewMode);
    model.put("managerViewMode", managerViewMode);
    model.put("maxTicketsViewMode", maxTicketsViewMode);
    model.put("isManagerViewAble", isManagerViewAble);
    return new ModelAndView("edit-portlet", model);
  }
  @Override
  public void doView(RenderRequest request, RenderResponse response)
      throws PortletException, IOException {
    try {
      String view = VIEW_FORM_PAGE;
      String viewType = request.getParameter("viewType");
      if (viewType == null) {
        viewType = (String) request.getPortletSession().getAttribute("viewType");
      }
      // Set global preferences
      request.setAttribute(TITLE, request.getPreferences().getValue(PREF_TITLE, null));
      request.setAttribute(
          INTRODUCTION_MESSAGE, request.getPreferences().getValue(PREF_INTRODUCTION_MESSAGE, null));

      User user = PortalUtils.getUser(request);
      Project project = PortalUtils.getProject(request);

      Task task = (Task) request.getPortletSession().getAttribute("task");

      int projectId = project == null ? -1 : project.getId();
      String projectIdOfLists = request.getParameter(PROJECT_ID_OF_LISTS);
      int pidOfLists = projectIdOfLists == null ? -1 : Integer.parseInt(projectIdOfLists);

      LOG.debug("doView: pidOfLists -- " + pidOfLists);

      // Clean up session
      request.getPortletSession().removeAttribute(VIEW_TYPE);
      request.getPortletSession().removeAttribute(PROJECT_ID_OF_LISTS);

      if (SAVE_FAILURE.equals(viewType)) {
        // Prep the form to show errors...
        request.setAttribute(
            ACTION_ERROR, request.getPreferences().getValue(PREF_FAILURE_MESSAGE, null));
        // Show the form with any errors provided
        PortalUtils.processErrors(request, task.getErrors());
      } else if (SAVE_SUCCESS.equals(viewType)) {
        // Save Success
        request.setAttribute(
            SUCCESS_MESSAGE, request.getPreferences().getValue(PREF_SUCCESS_MESSAGE, null));
        view = VIEW_MESSAGE_PAGE;
      } else {
        if (!user.isLoggedIn()) {
          // If user is not logged in, redirect
          view = VIEW_MESSAGE_PAGE;
          request.setAttribute(ACTION_ERROR, "You need to be logged in to perform this action");
        } else if (projectId <= 0) {
          request.setAttribute(ACTION_ERROR, "No project was specified");
          view = VIEW_MESSAGE_PAGE;
        } else {
          view = VIEW_FORM_PAGE;
          try {
            Connection db = PortalUtils.useConnection(request);

            int userProfileId = user.getProfileProjectId();
            Project userProfile;
            if (userProfileId == -1) {
              view = VIEW_MESSAGE_PAGE;
              request.setAttribute(ACTION_ERROR, "No profile is available to bookmark.");
            } else {
              userProfile = ProjectUtils.loadProject(userProfileId);
              if (pidOfLists == -1) {
                pidOfLists = userProfile.getId();
              }
              // check the user has permissions to add/delete from lists for the project whose lists
              // are being modified
              // these will be used by the view to dynamically show/hide functionality
              request.setAttribute(
                  CAN_ADD_LIST, ProjectUtils.hasAccess(pidOfLists, user, "project-lists-add"));
              request.setAttribute(
                  CAN_DELETE_FROM_LIST,
                  ProjectUtils.hasAccess(pidOfLists, user, "project-lists-delete"));

              ProjectList projectList = findUserProjects(db, user);
              ProjectList availableProjects = new ProjectList();
              // Profile needs to appear on top so remove it from list and don't add twice
              availableProjects.add(userProfile);
              for (int i = 0; i != projectList.size(); i++) {
                Project p = projectList.get(i);
                if (p.getId() != userProfile.getId()) {
                  availableProjects.add(p);
                }
              }

              TaskCategoryList availableLists = getAvailableLists(db, pidOfLists);

              String errorMessage = (String) request.getPortletSession().getAttribute(ACTION_ERROR);
              if (StringUtils.hasText(errorMessage)) {
                request.setAttribute(ACTION_ERROR, errorMessage);
              }

              Map<Integer, TaskCategory> usedLists =
                  findExistingTaskCategorysForProjects(db, pidOfLists, project.getId());
              request.setAttribute(PROJECT_ID_OF_LISTS, pidOfLists);
              request.setAttribute(PROJECT, project);
              request.setAttribute(AVAILABLE_LISTS, availableLists);
              request.setAttribute(USER_PROFILE, userProfile);
              request.setAttribute(AVAILABLE_PROJECTS, availableProjects);
              request.setAttribute(USED_LIST_MAP, usedLists);
            }
          } catch (SQLException e) {
            e.printStackTrace();
            view = VIEW_MESSAGE_PAGE;
            request.setAttribute(
                ACTION_ERROR, "An error occurred processing your request. Please try again.");
          }
        }
      }
      // Clean up session
      request.getPortletSession().removeAttribute(ACTION_ERROR);
      PortletContext context = getPortletContext();
      PortletRequestDispatcher requestDispatcher = context.getRequestDispatcher(view);
      requestDispatcher.include(request, response);
    } catch (Exception e) {
      e.printStackTrace();
      throw new PortletException(e);
    }
  }
Exemplo n.º 20
0
 private void setRenderAttributes(RenderRequest request) {
   String currentURL = defaultURL;
   request
       .getPortletSession()
       .setAttribute("default_url", defaultURL, request.getPortletSession().APPLICATION_SCOPE);
   request.setAttribute("default_url", defaultURL);
   if (hide_url) request.setAttribute("hide_url", "");
   else request.removeAttribute("hide_url");
   if (hide_new_windows) request.setAttribute("hide_new_windows", "");
   else request.removeAttribute("hide_new_windows");
   if (request.getParameter("height") != null)
     request.setAttribute("height", request.getParameter("height"));
   else request.setAttribute("height", PortletWebBrowser.defaultHeight);
   if (request.getParameter("width") != null)
     request.setAttribute("width", request.getParameter("width"));
   else request.setAttribute("width", PortletWebBrowser.defaultWidth);
   if (request.getParameter("message") != null)
     request.setAttribute("message", request.getParameter("message"));
   else request.setAttribute("message", PortletWebBrowser.defaultMessage);
   if (request.getPortletSession().getAttribute("current_url") != null)
     currentURL = (String) request.getPortletSession().getAttribute("current_url");
   request.setAttribute("url", currentURL);
   // String _clean_html = HTMLmanager.getCleanHTML(currentURL);
   // //HTMLParser.toStringFromHTML(currentURL) ;
   HTMLPage toBrowse = new HTMLPage(currentURL);
   String html = toBrowse.getBody();
   // on set la liste de highlights
   ArrayList<HighlightSelectionHTML> _highlights;
   if (request.getPortletSession().getAttribute("highlights") != null)
     _highlights =
         ((ArrayList<HighlightSelectionHTML>)
             request.getPortletSession().getAttribute("highlights"));
   else _highlights = new ArrayList<HighlightSelectionHTML>();
   // String _html_to_load = HTMLmanager.colorHighlights(_clean_html, _highlights);
   for (HighlightSelectionHTML highlight : _highlights) {
     try {
       toBrowse.addAnnotationSpan(
           highlight.getSelection().getXpointerBegin(),
           highlight.getSelection().getXpointerEnd(),
           highlight.getStyle(),
           highlight.getInfo(),
           highlight.getId());
       if (toBrowse.getBody() != null) html = toBrowse.getBody();
       // System.out.println("[PortletBrowser.setRenderAttributes] html : " + html);
     } catch (ParserException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
       System.out.println(
           "[PortletWebBrowser.setRenderAttributes] unable to parse HTML and add annotations for URL : "
               + currentURL);
     }
   }
   // String _html_to_load = toBrowse.getBody();
   String _html_to_load = html;
   if (_html_to_load != null && _html_to_load.length() > 0)
     request.setAttribute("html", _html_to_load);
   // else request.setAttribute("html" , _clean_html);
   else
     request.setAttribute(
         "html",
         "Problem Parsing HTML, try to reload page without annotations or selections ... or just reload ^^");
   // Add Css
   request.setAttribute("css", toBrowse.getCss());
 }