/*
   * (non-Javadoc)
   *
   * @see org.exoplatform.services.document.DocumentReader#getContentAsText(java.
   *      io.InputStream)
   */
  public String getContentAsText(InputStream is) throws IOException, DocumentReadException {
    if (is == null) {
      throw new IllegalArgumentException("InputStream is null.");
    }
    try {

      ZipInputStream zis = new ZipInputStream(is);
      try {
        ZipEntry ze = zis.getNextEntry();

        if (ze == null) {
          return "";
        }

        while (!ze.getName().equals("content.xml")) {
          ze = zis.getNextEntry();
        }

        OpenOfficeContentHandler contentHandler = new OpenOfficeContentHandler();
        XMLReader xmlReader = SAXHelper.newXMLReader();
        xmlReader.setFeature("http://xml.org/sax/features/validation", false);

        xmlReader.setFeature(
            "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        xmlReader.setContentHandler(contentHandler);
        xmlReader.parse(new InputSource(zis));
        return contentHandler.getContent();
      } finally {
        try {
          zis.close();
        } catch (IOException e) {
          if (LOG.isTraceEnabled()) {
            LOG.trace("An exception occurred: " + e.getMessage());
          }
        }
      }
    } catch (ParserConfigurationException e) {
      throw new DocumentReadException(e.getMessage(), e);
    } catch (SAXException e) {
      throw new DocumentReadException(e.getMessage(), e);
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        if (LOG.isTraceEnabled()) {
          LOG.trace("An exception occurred: " + e.getMessage());
        }
      }
    }
  }
  /** {@inheritDoc} */
  public List<Identity> getIdentitiesByFirstCharacterOfName(
      final String providerId,
      final ProfileFilter profileFilter,
      final long offset,
      final long limit,
      final boolean forceLoadOrReloadProfile)
      throws IdentityStorageException {

    //
    IdentityFilterKey key = new IdentityFilterKey(providerId, profileFilter);
    ListIdentitiesKey listKey = new ListIdentitiesKey(key, offset, limit);

    //
    ListIdentitiesData keys =
        identitiesCache.get(
            new ServiceContext<ListIdentitiesData>() {
              public ListIdentitiesData execute() {
                List<Identity> got =
                    storage.getIdentitiesByFirstCharacterOfName(
                        providerId, profileFilter, offset, limit, forceLoadOrReloadProfile);
                return buildIds(got);
              }
            },
            listKey);

    //
    LOG.trace("getIdentitiesByFirstCharacterOfName:: return " + keys.getIds().size());
    return buildIdentities(keys);
  }
Example #3
0
  private static void saveCookies() {
    if (cookie_jar != null
        && (!cookie_jar.exists() || cookie_jar.isFile() && cookie_jar.canWrite())) {
      Hashtable cookie_list = new Hashtable();
      Enumeration en =
          Util.getList(cookie_cntxt_list, HTTPConnection.getDefaultContext()).elements();

      // discard cookies which are not to be kept across sessions

      while (en.hasMoreElements()) {
        Cookie cookie = (Cookie) en.nextElement();
        if (!cookie.discard()) cookie_list.put(cookie, cookie);
      }

      // save any remaining cookies in jar
      if (cookie_list.size() > 0) {
        try {
          ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(cookie_jar));
          oos.writeObject(cookie_list);
          oos.close();
        } catch (IOException t) {
          if (LOG.isTraceEnabled()) {
            LOG.trace("An exception occurred: " + t.getMessage());
          }
        }
      }
    }
  }
    public void execute(Event<UIPortlet> event) throws Exception {
      UIPortlet uiPortlet = event.getSource();

      String portletMode = null;

      Object changePortletModeAttribute =
          event.getRequestContext().getAttribute(CHANGE_PORTLET_MODE_EVENT);
      if (changePortletModeAttribute != null && changePortletModeAttribute instanceof String) {
        portletMode = (String) changePortletModeAttribute;
      }

      if (portletMode == null) {
        portletMode = event.getRequestContext().getRequestParameter(Constants.PORTAL_PORTLET_MODE);
      }
      if (portletMode == null) {
        portletMode = event.getRequestContext().getRequestParameter(UIComponent.OBJECTID);
      }
      if (portletMode == null) {
        portletMode = uiPortlet.getCurrentPortletMode().toString();
      }

      log.trace(
          "Change portlet mode of " + uiPortlet.getPortletContext().getId() + " to " + portletMode);
      if (portletMode.equals(PortletMode.HELP.toString())) {
        uiPortlet.setCurrentPortletMode(PortletMode.HELP);
      } else if (portletMode.equals(PortletMode.EDIT.toString())) {
        uiPortlet.setCurrentPortletMode(PortletMode.EDIT);
      } else if (portletMode.equals(PortletMode.VIEW.toString())) {
        uiPortlet.setCurrentPortletMode(PortletMode.VIEW);
      } else {
        PortletMode customMode = new PortletMode(portletMode);
        uiPortlet.setCurrentPortletMode(customMode);
      }
      event.getRequestContext().addUIComponentToUpdateByAjax(uiPortlet);
    }
 @Override
 public void onEvent(Event<PortalContainer, HttpSessionEvent> event) throws Exception {
   if (LOG.isTraceEnabled()) {
     LOG.trace("Adding the key: " + event.getData().getSession().getId());
   }
   try {
     SessionManager sessionManager =
         (SessionManager) RootContainer.getComponent(SessionManager.class);
     sessionManager.addSessionContainer(
         event.getData().getSession().getId(), event.getSource().getName());
   } catch (Exception e) {
     LOG.warn("Can't add the key: " + event.getData().getSession().getId(), e);
   }
   if (LOG.isTraceEnabled()) {
     LOG.trace("Added the key: " + event.getData().getSession().getId());
   }
 }
    public void execute(Event<UIPortlet> event) throws Exception {
      UIPortlet uiPortlet = event.getSource();
      PortalRequestContext context = (PortalRequestContext) event.getRequestContext();
      List<UIPortlet> portletInstancesInPage = new ArrayList<UIPortlet>();
      //      UIPortalApplication uiPortal = uiPortlet.getAncestorOfType(UIPortalApplication.class);
      UIPortalApplication uiPortal = (UIPortalApplication) context.getUIApplication();
      uiPortal.findComponentOfType(portletInstancesInPage, UIPortlet.class);
      EventsWrapper eventsWrapper =
          (EventsWrapper) event.getRequestContext().getAttribute(PORTLET_EVENTS);
      List<javax.portlet.Event> events = eventsWrapper.getEvents();

      /*
       * Iterate over all the events that the processAction
       * has generated. Check among all the portlet instances deployed in the
       * page (usual layout or webos) which instance can be targeted by the
       * event and then process the event on the associated UIPortlet component
       */
      while (events.size() > 0) {
        javax.portlet.Event nativeEvent = events.remove(0);
        QName eventName = nativeEvent.getQName();
        for (Iterator<UIPortlet> iterator = portletInstancesInPage.iterator();
            iterator.hasNext(); ) {
          UIPortlet uiPortletInPage = iterator.next();
          if (uiPortletInPage.supportsProcessingEvent(eventName)
              && !eventsWrapper.isInvokedTooManyTimes(uiPortletInPage)) {
            List<javax.portlet.Event> newEvents = processEvent(uiPortletInPage, nativeEvent);
            eventsWrapper.increaseCounter(uiPortletInPage);
            if (context.useAjax()) {
              log.info(
                  "Events were generated inside the scope of an AJAX call, hence will only refresh the targeted portlets");
              event.getRequestContext().addUIComponentToUpdateByAjax(uiPortletInPage);
            } else {
              log.info(
                  "Events were generated outside the scope of an AJAX call, hence will make a full render of the page");
              context.ignoreAJAXUpdateOnPortlets(true);
            }
            if (newEvents != null && !newEvents.isEmpty()) {
              log.trace(
                  "The portlet: "
                      + uiPortletInPage.getPortletContext().getId()
                      + " processEvent() method has generated new events itself");
              events.addAll(newEvents);
            }
          }
        }
      }
    }
Example #7
0
  private static String getCookieJarName() {
    String file = null;

    try {
      file = PrivilegedSystemHelper.getProperty("HTTPClient.cookies.jar");
    } catch (Exception e) {
      if (LOG.isTraceEnabled()) {
        LOG.trace("An exception occurred: " + e.getMessage());
      }
    }

    if (file == null) {
      // default to something reasonable

      String os = PrivilegedSystemHelper.getProperty("os.name");
      if (os.equalsIgnoreCase("Windows 95")
          || os.equalsIgnoreCase("16-bit Windows")
          || os.equalsIgnoreCase("Windows")) {
        file =
            PrivilegedSystemHelper.getProperty("java.home")
                + File.separator
                + ".httpclient_cookies";
      } else if (os.equalsIgnoreCase("Windows NT")) {
        file =
            PrivilegedSystemHelper.getProperty("user.home")
                + File.separator
                + ".httpclient_cookies";
      } else if (os.equalsIgnoreCase("OS/2")) {
        file =
            PrivilegedSystemHelper.getProperty("user.home")
                + File.separator
                + ".httpclient_cookies";
      } else if (os.equalsIgnoreCase("Mac OS") || os.equalsIgnoreCase("MacOS")) {
        file =
            "System Folder" + File.separator + "Preferences" + File.separator + "HTTPClientCookies";
      } else
      // it's probably U*IX or VMS
      {
        file =
            PrivilegedSystemHelper.getProperty("user.home")
                + File.separator
                + ".httpclient_cookies";
      }
    }

    return file;
  }
Example #8
0
  /**
   * Update the permanent redirection list.
   *
   * @param the original request
   * @param the new location
   */
  private static void update_perm_redir_list(RoRequest req, URI new_loc) {
    HTTPConnection con = req.getConnection();
    URI cur_loc = null;
    try {
      cur_loc =
          new URI(
              new URI(con.getProtocol(), con.getHost(), con.getPort(), null), req.getRequestURI());
    } catch (ParseException pe) {
      if (LOG.isTraceEnabled()) {
        LOG.trace("An exception occurred: " + pe.getMessage());
      }
    }

    if (cur_loc != null && !cur_loc.equals(new_loc)) {
      Hashtable perm_redir_list = Util.getList(perm_redir_cntxt_list, con.getContext());
      perm_redir_list.put(cur_loc, new_loc);
    }
  }
Example #9
0
  /**
   * Gets the node view.
   *
   * @param node the node
   * @return the node view
   * @throws Exception the exception
   */
  private Node getViewableContent(Node node, HashMap<String, String> filters) throws Exception {
    Node viewNode = null;
    if (trashService == null) {
      trashService = WCMCoreUtils.getService(TrashService.class);
    }
    try {
      node = getTargetNode(node);
    } catch (AccessDeniedException ade) {
      return null;
    }

    if (node != null && trashService.isInTrash(node)) {
      return null;
    }

    String languageFilter = filters.get(FILTER_LANGUAGE);
    if (languageFilter != null) {
      addUsedLanguage(languageFilter);
      Node lnode = null;
      try {
        lnode = multiLanguageService.getLanguage(node, languageFilter);
      } catch (AccessDeniedException e) {
        if (LOG.isTraceEnabled())
          LOG.trace("AccessDenied on " + languageFilter + " translation for " + node.getPath());
      }
      if (lnode != null) {

        viewNode = getPublishedContent(lnode, filters);
        if (viewNode != null) {
          return viewNode;
        }
        return null;
      }
    }

    if (node != null) {
      viewNode = getPublishedContent(node, filters);
    }

    return viewNode;
  }
  /*
   * (non-Javadoc)
   *
   * @see org.exoplatform.services.document.DocumentReader#getProperties(java.io.
   *      InputStream)
   */
  public Properties getProperties(InputStream is) throws IOException, DocumentReadException {
    try {

      ZipInputStream zis = new ZipInputStream(is);
      try {
        ZipEntry ze = zis.getNextEntry();
        while (!ze.getName().equals("meta.xml")) {
          ze = zis.getNextEntry();
        }

        OpenOfficeMetaHandler metaHandler = new OpenOfficeMetaHandler();
        XMLReader xmlReader = SAXHelper.newXMLReader();

        xmlReader.setFeature("http://xml.org/sax/features/validation", false);
        xmlReader.setFeature(
            "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        xmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
        xmlReader.setContentHandler(metaHandler);
        xmlReader.parse(new InputSource(zis));
        return metaHandler.getProperties();
      } finally {
        zis.close();
      }
    } catch (ParserConfigurationException e) {
      throw new DocumentReadException(e.getMessage(), e);
    } catch (SAXException e) {
      throw new DocumentReadException(e.getMessage(), e);
    } finally {
      if (is != null)
        try {
          is.close();
        } catch (IOException e) {
          if (LOG.isTraceEnabled()) {
            LOG.trace("An exception occurred: " + e.getMessage());
          }
        }
    }
  }
Example #11
0
 private void trace(String message) {
   log.trace(message + " [" + Thread.currentThread().getName() + "]");
 }
Example #12
0
  /** Invoked by the HTTPClient. */
  public int requestHandler(Request req, Response[] resp) {
    HTTPConnection con = req.getConnection();
    URI new_loc, cur_loc;

    // check for retries

    HttpOutputStream out = req.getStream();
    if (out != null && deferred_redir_list.get(out) != null) {
      copyFrom((RedirectionModule) deferred_redir_list.remove(out));
      req.copyFrom(saved_req);

      if (new_con) return REQ_NEWCON_RST;
      else return REQ_RESTART;
    }

    // handle permanent redirections

    try {
      cur_loc =
          new URI(
              new URI(con.getProtocol(), con.getHost(), con.getPort(), null), req.getRequestURI());
    } catch (ParseException pe) {
      throw new Error("HTTPClient Internal Error: unexpected exception '" + pe + "'", pe);
    }

    // handle permanent redirections

    Hashtable perm_redir_list =
        Util.getList(perm_redir_cntxt_list, req.getConnection().getContext());
    if ((new_loc = (URI) perm_redir_list.get(cur_loc)) != null) {
      /*
       * copy query if present in old url but not in new url. This isn't
       * strictly conforming, but some scripts fail to properly propagate the
       * query string to the Location header. Unfortunately it looks like we're
       * f****d either way: some scripts fail if you don't propagate the query
       * string, some fail if you do... God, don't you just love it when people
       * can't read a spec? Anway, since we can't get it right for all scripts
       * we opt to follow the spec. String nres = new_loc.getPathAndQuery(),
       * oquery = Util.getQuery(req.getRequestURI()), nquery =
       * Util.getQuery(nres); if (nquery == null && oquery != null) nres += "?"
       * + oquery;
       */
      String nres = new_loc.getPathAndQuery();
      req.setRequestURI(nres);

      try {
        lastURI = new URI(new_loc, nres);
      } catch (ParseException pe) {
        if (LOG.isTraceEnabled()) {
          LOG.trace("An exception occurred: " + pe.getMessage());
        }
      }

      if (LOG.isDebugEnabled())
        LOG.debug(
            "Matched request in permanent redirection list - redoing request to "
                + lastURI.toExternalForm());

      if (!con.isCompatibleWith(new_loc)) {
        try {
          con = new HTTPConnection(new_loc);
        } catch (ProtocolNotSuppException e) {
          throw new Error("HTTPClient Internal Error: unexpected " + "exception '" + e + "'", e);
        }

        con.setContext(req.getConnection().getContext());
        req.setConnection(con);
        return REQ_NEWCON_RST;
      } else {
        return REQ_RESTART;
      }
    }

    return REQ_CONTINUE;
  }
Example #13
0
  /** Invoked by the HTTPClient. */
  public int responsePhase2Handler(Response resp, Request req) throws IOException {
    /* handle various response status codes until satisfied */

    int sts = resp.getStatusCode();
    switch (sts) {
      case 302: // General (temporary) Redirection (handle like 303)

        /*
         * Note we only do this munging for POST and PUT. For GET it's not
         * necessary; for HEAD we probably want to do another HEAD. For all
         * others (i.e. methods from WebDAV, IPP, etc) it's somewhat unclear -
         * servers supporting those should really return a 307 or 303, but some
         * don't (guess who...), so we just don't touch those.
         */
        if (req.getMethod().equals("POST") || req.getMethod().equals("PUT")) {
          if (LOG.isDebugEnabled())
            LOG.debug(
                "Received status: " + sts + " " + resp.getReasonLine() + " - treating as 303");

          sts = 303;
        }

      case 301: // Moved Permanently
      case 303: // See Other (use GET)
      case 307: // Moved Temporarily (we mean it!)
        if (LOG.isDebugEnabled()) LOG.debug("Handling status: " + sts + " " + resp.getReasonLine());

        // the spec says automatic redirection may only be done if
        // the second request is a HEAD or GET.
        if (!req.getMethod().equals("GET") && !req.getMethod().equals("HEAD") && sts != 303) {
          if (LOG.isDebugEnabled())
            LOG.debug("Not redirected because method is neither HEAD nor GET");

          if (sts == 301 && resp.getHeader("Location") != null)
            update_perm_redir_list(req, resLocHdr(resp.getHeader("Location"), req));

          resp.setEffectiveURI(lastURI);
          return RSP_CONTINUE;
        }

      case 305: // Use Proxy
      case 306: // Switch Proxy
        if (sts == 305 || sts == 306) {
          if (LOG.isDebugEnabled())
            LOG.debug("Handling status: " + sts + " " + resp.getReasonLine());
        }

        // Don't accept 305 from a proxy
        if (sts == 305 && req.getConnection().getProxyHost() != null) {
          if (LOG.isDebugEnabled()) LOG.debug("305 ignored because a proxy is already in use");

          resp.setEffectiveURI(lastURI);
          return RSP_CONTINUE;
        }

        /*
         * the level is a primitive way of preventing infinite redirections.
         * RFC-2068 set the max to 5, but RFC-2616 has loosened this. Since some
         * sites (notably M$) need more levels, this is now set to the
         * (arbitrary) value of 15 (god only knows why they need to do even 5
         * redirections...).
         */
        if (level >= 15 || resp.getHeader("Location") == null) {
          if (LOG.isDebugEnabled()) {
            if (level >= 15) LOG.debug("Not redirected because of too many levels of redirection");
            else LOG.debug("Not redirected because no Location header was present");
          }

          resp.setEffectiveURI(lastURI);
          return RSP_CONTINUE;
        }
        level++;

        URI loc = resLocHdr(resp.getHeader("Location"), req);

        HTTPConnection mvd;
        String nres;
        new_con = false;

        if (sts == 305) {
          mvd =
              new HTTPConnection(
                  req.getConnection().getProtocol(),
                  req.getConnection().getHost(),
                  req.getConnection().getPort());
          mvd.setCurrentProxy(loc.getHost(), loc.getPort());
          mvd.setContext(req.getConnection().getContext());
          new_con = true;

          nres = req.getRequestURI();

          /*
           * There was some discussion about this, and especially Foteos
           * Macrides (Lynx) said a 305 should also imply a change to GET (for
           * security reasons) - see the thread starting at
           * http://www.ics.uci.edu/pub/ietf/http/hypermail/1997q4/0351.html
           * However, this is not in the latest draft, but since I agree with
           * Foteos we do it anyway...
           */
          req.setMethod("GET");
          req.setData(null);
          req.setStream(null);
        } else if (sts == 306) {
          // We'll have to wait for Josh to create a new spec here.
          return RSP_CONTINUE;
        } else {
          if (req.getConnection().isCompatibleWith(loc)) {
            mvd = req.getConnection();
            nres = loc.getPathAndQuery();
          } else {
            try {
              mvd = new HTTPConnection(loc);
              nres = loc.getPathAndQuery();
            } catch (ProtocolNotSuppException e) {
              if (req.getConnection().getProxyHost() == null
                  || !loc.getScheme().equalsIgnoreCase("ftp")) return RSP_CONTINUE;

              // We're using a proxy and the protocol is ftp -
              // maybe the proxy will also proxy ftp...
              mvd =
                  new HTTPConnection(
                      "http",
                      req.getConnection().getProxyHost(),
                      req.getConnection().getProxyPort());
              mvd.setCurrentProxy(null, 0);
              nres = loc.toExternalForm();
            }

            mvd.setContext(req.getConnection().getContext());
            new_con = true;
          }

          /*
           * copy query if present in old url but not in new url. This isn't
           * strictly conforming, but some scripts fail to propagate the query
           * properly to the Location header. See comment on line 126. String
           * oquery = Util.getQuery(req.getRequestURI()), nquery =
           * Util.getQuery(nres); if (nquery == null && oquery != null) nres +=
           * "?" + oquery;
           */

          if (sts == 303) {
            // 303 means "use GET"

            if (!req.getMethod().equals("HEAD")) req.setMethod("GET");
            req.setData(null);
            req.setStream(null);
          } else {
            // If they used an output stream then they'll have
            // to do the resend themselves
            if (req.getStream() != null) {
              if (!HTTPConnection.deferStreamed) {
                if (LOG.isDebugEnabled())
                  LOG.debug("Status " + sts + " not handled - request has an output stream");

                return RSP_CONTINUE;
              }

              saved_req = (Request) req.clone();
              deferred_redir_list.put(req.getStream(), this);
              req.getStream().reset();
              resp.setRetryRequest(true);
            }

            if (sts == 301) {
              // update permanent redirection list
              try {
                update_perm_redir_list(req, new URI(loc, nres));
              } catch (ParseException pe) {
                throw new Error(
                    "HTTPClient Internal Error: " + "unexpected exception '" + pe + "'", pe);
              }
            }
          }

          // Adjust Referer, if present
          NVPair[] hdrs = req.getHeaders();
          for (int idx = 0; idx < hdrs.length; idx++)
            if (hdrs[idx].getName().equalsIgnoreCase("Referer")) {
              HTTPConnection con = req.getConnection();
              hdrs[idx] = new NVPair("Referer", con + req.getRequestURI());
              break;
            }
        }

        req.setConnection(mvd);
        req.setRequestURI(nres);

        try {
          resp.getInputStream().close();
        } catch (IOException ioe) {
          if (LOG.isTraceEnabled()) {
            LOG.trace("An exception occurred: " + ioe.getMessage());
          }
        }

        if (sts != 305 && sts != 306) {
          try {
            lastURI = new URI(loc, nres);
          } catch (ParseException pe) {
            if (LOG.isTraceEnabled()) {
              LOG.trace("An exception occurred: " + pe.getMessage());
            }
          }

          if (LOG.isDebugEnabled())
            LOG.debug(
                "Request redirected to "
                    + lastURI.toExternalForm()
                    + " using method "
                    + req.getMethod());
        } else {
          if (LOG.isDebugEnabled())
            LOG.debug(
                "Resending request using "
                    + "proxy "
                    + mvd.getProxyHost()
                    + ":"
                    + mvd.getProxyPort());
        }

        if (req.getStream() != null) return RSP_CONTINUE;
        else if (new_con) return RSP_NEWCON_REQ;
        else return RSP_REQUEST;

      default:
        return RSP_CONTINUE;
    }
  }
  /**
   * This method is called when the javax.portlet.Event is supported by the current portlet stored
   * in the Portlet Caontainer
   *
   * <p>The processEvent() method can also generates IPC events and hence the portal itself will
   * call the ProcessEventsActionListener once again
   */
  public static <S, C extends Serializable, I> List<javax.portlet.Event> processEvent(
      UIPortlet<S, C> uiPortlet, javax.portlet.Event event) {
    log.trace("Process Event: " + event.getName() + " for portlet: " + uiPortlet.getState());
    try {
      PortalRequestContext context =
          (PortalRequestContext) WebuiRequestContext.getCurrentInstance();

      //
      EventInvocation eventInvocation = uiPortlet.create(EventInvocation.class, context);

      //
      eventInvocation.setName(event.getQName());
      eventInvocation.setPayload(event.getValue());

      //
      PortletInvocationResponse piResponse = uiPortlet.invoke(eventInvocation);

      //
      ExoPortletInstanceContext instanceCtx =
          (ExoPortletInstanceContext) eventInvocation.getInstanceContext();
      if (instanceCtx.getModifiedContext() != null) {
        StatefulPortletContext<C> updatedCtx =
            (StatefulPortletContext<C>) instanceCtx.getModifiedContext();
        C portletState = updatedCtx.getState();
        uiPortlet.update(portletState);
      }

      // todo: handle the error response better than this.
      if (!(piResponse instanceof UpdateNavigationalStateResponse)) {
        if (piResponse instanceof ErrorResponse) {
          ErrorResponse errorResponse = (ErrorResponse) piResponse;
          throw (Exception) errorResponse.getCause();
        } else {
          throw new Exception(
              "Unexpected response type ["
                  + piResponse
                  + "]. Expected a UpdateNavigationResponse or an ErrorResponse.");
        }
      }

      UpdateNavigationalStateResponse navResponse = (UpdateNavigationalStateResponse) piResponse;

      //

      /*
       * Update the portlet window state according to the action output
       * information
       *
       * If the current node is displaying a usual layout page, also tells the
       * page which portlet to render or not when the state is maximized
       */
      WindowState state = new WindowState(getWindowStateOrDefault(navResponse));
      setNextState(uiPortlet, state);

      // update the portlet with the next mode to display
      PortletMode mode = new PortletMode(getPortletModeOrDefault(navResponse));
      setNextMode(uiPortlet, mode);

      StateString navState = navResponse.getNavigationalState();
      if (navState != null) {
        uiPortlet.setNavigationalState(navResponse.getNavigationalState());
      }
      setupPublicRenderParams(uiPortlet, navResponse.getPublicNavigationalStateUpdates());

      // TODO: (mwringe) add this to the UpdateNavigationStateResponse.Event class instead of here
      class PortletEvent implements javax.portlet.Event {
        QName qName;

        Serializable value;

        public PortletEvent(QName qName, Serializable value) {
          this.qName = qName;
          this.value = value;
        }

        public String getName() {
          return qName.getLocalPart();
        }

        public QName getQName() {
          return qName;
        }

        public Serializable getValue() {
          return value;
        }
      }

      List<UpdateNavigationalStateResponse.Event> nsEvents = navResponse.getEvents();
      List<javax.portlet.Event> events = new ArrayList<javax.portlet.Event>(nsEvents.size());
      if (nsEvents != null && !nsEvents.isEmpty()) {
        for (UpdateNavigationalStateResponse.Event nsEvent : nsEvents) {
          javax.portlet.Event portletEvent =
              new PortletEvent(nsEvent.getName(), nsEvent.getPayload());
          events.add(portletEvent);
        }
      }

      return events;
    } catch (Exception e) {
      log.error("Problem while processesing event for the portlet: " + uiPortlet.getState(), e);
    }
    return null;
  }
    public void execute(Event<UIPortlet<S, C>> event) throws Exception {
      UIPortlet<S, C> uiPortlet = event.getSource();
      log.trace("Serve Resource for portlet: " + uiPortlet.getPortletContext());
      String resourceId = null;

      //
      PortalRequestContext context = (PortalRequestContext) event.getRequestContext();
      HttpServletResponse response = context.getResponse();

      //
      try {
        // Set the NavigationalState
        String navState =
            context.getRequestParameter(ExoPortletInvocationContext.NAVIGATIONAL_STATE_PARAM_NAME);
        if (navState != null) {
          uiPortlet.setNavigationalState(ParametersStateString.create(navState));
        }

        //
        ResourceInvocation resourceInvocation = uiPortlet.create(ResourceInvocation.class, context);

        // set the resourceId to be used in case of a problem
        resourceId = resourceInvocation.getResourceId();

        //
        PortletInvocationResponse portletResponse = uiPortlet.invoke(resourceInvocation);

        //
        int statusCode;
        MultiValuedPropertyMap<String> transportHeaders;
        String contentType;
        String charset;
        Object content;
        if (!(portletResponse instanceof ContentResponse)) {
          if (portletResponse instanceof ErrorResponse) {
            ErrorResponse errorResponse = (ErrorResponse) portletResponse;
            Throwable cause = errorResponse.getCause();
            if (cause != null) {
              log.trace("Got error response from portlet", cause);
            } else if (errorResponse.getMessage() != null) {
              log.trace("Got error response from portlet:" + errorResponse.getMessage());
            } else {
              log.trace("Got error response from portlet");
            }
          } else {
            log.trace(
                "Unexpected response type ["
                    + portletResponse
                    + "]. Expected a ContentResponse or an ErrorResponse.");
          }
          statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
          contentType = null;
          charset = null;
          transportHeaders = null;
          content = null;
        } else {
          //
          ContentResponse piResponse = (ContentResponse) portletResponse;
          ResponseProperties properties = piResponse.getProperties();
          transportHeaders = properties != null ? properties.getTransportHeaders() : null;

          // Look at status code if there is one and honour it
          String status =
              transportHeaders != null
                  ? transportHeaders.getValue(ResourceResponse.HTTP_STATUS_CODE)
                  : null;
          if (status != null) {
            try {
              statusCode = Integer.parseInt(status);
            } catch (NumberFormatException e) {
              statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
            }
          } else {
            statusCode = HttpServletResponse.SC_OK;
          }

          //
          contentType = piResponse.getContentType();
          charset = piResponse.getEncoding();

          //
          log.trace(
              "Try to get a resource of type: "
                  + contentType
                  + " for the portlet: "
                  + uiPortlet.getPortletContext());
          if (piResponse.getChars() != null) {
            content = piResponse.getChars();
          } else if (piResponse.getBytes() != null) {
            content = piResponse.getBytes();
          } else {
            content = null;
          }
        }

        //
        response.setStatus(statusCode);

        // Set content type if any
        if (contentType != null) {
          response.setContentType(contentType);
        }

        // Set encoding
        if (charset != null) {
          response.setCharacterEncoding(charset);
        }

        // Send headers if any
        if (transportHeaders != null) {
          sendHeaders(transportHeaders, context);
        }

        // Send body if any
        if (content instanceof String) {
          context.getWriter().write((String) content);
        } else if (content instanceof byte[]) {
          byte[] bytes = (byte[]) content;
          response.setContentLength(bytes.length);
          OutputStream stream = response.getOutputStream();
          try {
            stream.write(bytes);
          } finally {
            Safe.close(stream);
          }
        }

        //
        response.flushBuffer();
      } catch (Exception e) {
        if (!e.getClass().toString().contains("ClientAbortException")) {
          log.error(
              "Problem while serving resource "
                  + (resourceId != null ? resourceId : "")
                  + " for the portlet: "
                  + uiPortlet.getPortletContext().getId(),
              e);
        }
      } finally {
        /** The resource method does not need to go through the render phase */
        event.getRequestContext().setResponseComplete(true);
      }
    }