Package org.emrys.webosgi.core.jeewrappers

Examples of org.emrys.webosgi.core.jeewrappers.BundledHttpServletRequestWrapper


   * @throws IOException
   * @throws ServletException
   */
  private void service(ServletRequest request, ServletResponse response,
      boolean isInclude) throws ServletException, IOException {
    BundledHttpServletRequestWrapper topRequest = (BundledHttpServletRequestWrapper) webContainer
        .getReqThreadVariants().get(OSGiWebContainer.THREAD_V_REQUEST);

    // Try to wrapper the given request and response.
    BundledHttpServletRequestWrapper reqWrapper = BundledHttpServletRequestWrapper
        .getHttpServletRequestWrapper(request, topRequest.getBundle());
    HttpServletResponseWrapper respWrapper = HttpServletResponseWrapper
        .getHttpServletResponseWrapper(response);

    // Buffer the former state and revert them at last.
    boolean oIsDispatched = reqWrapper.isDispatched();
    boolean oIsInclude = reqWrapper.isInclude();
    String oServletPath = reqWrapper.getServletPath();
    String oPathInfo = reqWrapper.getPathInfo();

    try {
      // Skip on system root path mark.
      if (targetPath.startsWith(IFwkConstants.SYS_PATH_PREFIX)) {
        targetPath = targetPath.substring(IFwkConstants.SYS_PATH_PREFIX
            .length());
      } else {
        if (!targetPath.startsWith("/")) {
          // Relative path not allowed, regard it as absolute.
          targetPath = "/" + targetPath;
        }

        if (this.webCtxPath != null && this.webCtxPath.length() != 0
            && !targetPath.startsWith("/" + this.webCtxPath + "/")) {
          targetPath = this.webCtxPath + targetPath;
        }
      }

      // Take the URI and query string together as targetURL, and later
      // set into request.
      String targetURL = targetPath;

      int index = targetPath.indexOf('?');
      if (index != -1) {
        String queryStr = targetPath.substring(index + 1);
        targetPath = targetPath.substring(0, index);
        reqWrapper.parseNewParameters(queryStr);
      }

      // set new path to dispatch to.
      reqWrapper.setServletPath(targetPath);
      // According to the tomcat's behavior, if forward, the request's URI
      // should be reset.
      if (!isInclude) {
        String oReqURL = reqWrapper.getRequestURL().toString();
        String ctxPath = reqWrapper.getContextPath();
        // Get the external top context path.
        int i = ctxPath.lastIndexOf('/');
        if (i > 0)
          ctxPath = ctxPath.substring(0, i);
        String newReqURI = ctxPath + targetPath;
        reqWrapper.setRequestURI(newReqURI);
        i = oReqURL.indexOf(ctxPath);
        if (i > -1) {
          String urlPrefix = oReqURL.substring(0, i
              + ctxPath.length());
          String newReqURL = urlPrefix + targetURL;
          reqWrapper.setRequestURL(newReqURL);
        }
      }

      reqWrapper.setPathInfo(null);

      // If need do filter, not set dispatching ad include mark.
      if (!doInternalFilter) {
        // If forward, we just reset the response's output buffer, not
        // reset the headers and status. So we invoke resetBuffer(), not
        // reset(); Notice, before dispatch this request, some filter or
        // servlet may add some cookie or set status. Tomcat remain them
        // after dispatch.
        if (!isInclude)
          respWrapper.resetBuffer(); // reset();
        // set the dispatching mark.
        reqWrapper.setDispatched(true);
        reqWrapper.setInclude(isInclude);
        // set include in response wrapper as well.
        respWrapper.setInclude(isInclude);

        // FIXME: If the original Request paths should not be modified
        // and just set several include_xxx attributes???
        if (isInclude && request instanceof HttpServletRequest) {
          // Store original include attribute.
          include_context_path = request
              .getAttribute("javax.servlet.include.context_path");
          include_servlet_path = request
              .getAttribute("javax.servlet.include.servlet_path");
          include_path_info = request
              .getAttribute("javax.servlet.include.path_info");
          include_request_uri = request
              .getAttribute("javax.servlet.include.request_uri");
          include_query_string = request
              .getAttribute("javax.servlet.include.query_string");

          request.setAttribute("javax.servlet.include.context_path",
              ((HttpServletRequest) request).getSession()
                  .getServletContext().getContextPath());
          request.setAttribute("javax.servlet.include.servlet_path",
              ((HttpServletRequest) request).getServletPath());
          request.setAttribute("javax.servlet.include.path_info",
              ((HttpServletRequest) request).getPathInfo());

          request.setAttribute("javax.servlet.include.request_uri",
              ((HttpServletRequest) request).getRequestURI());
          request.setAttribute("javax.servlet.include.query_string",
              ((HttpServletRequest) request).getQueryString());

        }
      }

      // rewire to JEE Container.
      webContainer.service(reqWrapper, respWrapper);
    } finally {
      // reset the include attributes at last.
      if (!doInternalFilter && isInclude
          && request instanceof HttpServletRequest) {
        // Store original include attribute.
        request.setAttribute("javax.servlet.include.context_path",
            include_context_path);
        request.setAttribute("javax.servlet.include.servlet_path",
            include_servlet_path);
        request.setAttribute("javax.servlet.include.path_info",
            include_path_info);
        request.setAttribute("javax.servlet.include.request_uri",
            include_request_uri);
        request.setAttribute("javax.servlet.include.query_string",
            include_query_string);
      }

      // revert the buffered state.
      reqWrapper.setServletPath(oServletPath);
      reqWrapper.setPathInfo(oPathInfo);
      reqWrapper.setDispatched(oIsDispatched);
      reqWrapper.setInclude(oIsInclude);
      respWrapper.setInclude(oIsInclude);
    }
  }
View Full Code Here


            && lastWabCtxPath != null
            && !thisFilterServletPath.startsWith(lastWabCtxPath)) {
          // Use old bundle not change the bundle context.
          request = BundledHttpServletRequestWrapper
              .getHttpServletRequestWrapper(request, oldBundle);
          BundledHttpServletRequestWrapper bundledReqWrapper = ((BundledHttpServletRequestWrapper) request);
          thisFilterServletPath = lastWabCtxPath
              + thisFilterServletPath;
          bundledReqWrapper.setServletPath(thisFilterServletPath);
        }

        if (isReqPathSysRootBased) {
          // If last filter switched the request path to system root
          // based, wrapper the req again and remove the system root
          // prefix.
          request = BundledHttpServletRequestWrapper
              .getHttpServletRequestWrapper(request, oldBundle);
          BundledHttpServletRequestWrapper bundledReqWrapper = ((BundledHttpServletRequestWrapper) request);
          thisFilterServletPath = thisFilterServletPath
              .substring(IFwkConstants.SYS_PATH_PREFIX.length());
          bundledReqWrapper.setServletPath(thisFilterServletPath);
        }

        lastWabCtxPath = null;
        // Record this filter's servlet path for next use.
        lastFilterServletPath = thisFilterServletPath;

        // If filter chain empty, do servlet invoke if needed.
        if (!it.hasNext()) {
          // The customize's Filter may wrapper our Req or Response
          // again, here wrapper back if any need.
          BundledHttpServletRequestWrapper httpReqWrapper = BundledHttpServletRequestWrapper
              .getHttpServletRequestWrapper(request, oldBundle);
          HttpServletResponseWrapper httpRespWrapper = HttpServletResponseWrapper
              .getHttpServletResponseWrapper(response);
          handlerChain.handle(httpReqWrapper, httpRespWrapper);
          return;
        }

        // Iterate to do filter matching the current request servlet
        // path. Remove bundle's web prefix from servlet path
        // temporarily before filter invoke.
        ClonedExecutableServletObject<FilterDelegate> clonedFilterInstance = it
            .next();
        FilterDelegate filterDelegate = clonedFilterInstance
            .getOriginalObj();
        String urlPattern = filterDelegate.getURLPatterns()[clonedFilterInstance
            .getId()];

        // Notes: decide the url pattern according to the dispatchers
        // set if any. If dispatcher type check failed, a null url
        // pattern returned. So do the next while iterate.
        urlPattern = decideUrlPattern(req, urlPattern);

        while (clonedFilterInstance != null
            && (clonedFilterInstance.isExecuted() || !(!StringUtils
                .isEmpty(urlPattern) && fwkContainerHelper
                .checkNeedFilter((HttpServletRequest) request,
                    urlPattern)))) {
          if (it.hasNext()) {
            clonedFilterInstance = it.next();
            filterDelegate = clonedFilterInstance.getOriginalObj();
            urlPattern = filterDelegate.getURLPatterns()[clonedFilterInstance
                .getId()];
            urlPattern = decideUrlPattern(req, urlPattern);
          } else {
            clonedFilterInstance = null;
          }
        }

        // If any filter matched in the chain, do it.
        if (clonedFilterInstance != null) {
          try {
            // Switch request's current bundle to the filter's
            // bundle. And modify the servlet path of the request
            // delivering to the filter.
            fwkContainerHelper
                .switchReqBundleContext(filterDelegate
                    .getBundleContext().getBundle());
            switchReqPath(filterDelegate.getBundleContext());
            // set the executed mark early.
            clonedFilterInstance.setExecuted();
            filterDelegate.doFilter(request, response, this);
          } finally {
            // revert to the former bundle.
            clonedFilterInstance.refresh();
            // revertReqPath(); // no need to revert req path at
            // last for it is not be used later.
            fwkContainerHelper.switchReqBundleContext(oldBundle);
          }
        } else if (!it.hasNext()) {
          BundledHttpServletRequestWrapper httpReqWrapper = BundledHttpServletRequestWrapper
              .getHttpServletRequestWrapper(request, oldBundle);
          HttpServletResponseWrapper httpRespWrapper = HttpServletResponseWrapper
              .getHttpServletResponseWrapper(response);
          handlerChain.handle(httpReqWrapper, httpRespWrapper);
        }
View Full Code Here

      originalCtxClassLoader = Thread.currentThread()
          .getContextClassLoader();
      classLoader = ctx.getWabClassLoader();
    }

    BundledHttpServletRequestWrapper topReq = null;
    String originalServletPath = null;

    if (switchReqPath) {
      topReq = (BundledHttpServletRequestWrapper) jeeContainer
          .getReqThreadVariants().get(
              OSGiWebContainer.THREAD_V_REQUEST);
      originalServletPath = topReq.getServletPath();
      // String originalPathInfo = topReq.getPathInfo();
    }

    try {
      if (switchCtxCL) {
        Thread.currentThread().setContextClassLoader(classLoader);
      }
      if (switchReqPath) {
        String wabCtxPath = ctx.getWABContextPath();
        if (originalServletPath.startsWith(wabCtxPath))
          topReq.setServletPath(originalServletPath.replaceFirst(
              wabCtxPath, ""));
        // topReq.setPathInfo(originalPathInfo);
      }

      result = execute();
    } finally {
      if (switchReqPath) {
        topReq.setServletPath(originalServletPath);
        // topReq.setPathInfo(originalPathInfo);
      }
      if (switchReqPath) {
        Thread.currentThread().setContextClassLoader(
            originalCtxClassLoader);
View Full Code Here

   *      </li> <li>
   *      {@link #doServletService(BundledHttpServletRequestWrapper, HttpServletResponseWrapper)}
   *      </li>
   */
  public void switchReqBundleContext(Bundle bundle) {
    BundledHttpServletRequestWrapper req = (BundledHttpServletRequestWrapper) webContainer
        .getReqThreadVariants().get(OSGiWebContainer.THREAD_V_REQUEST);
    req.setBundle(bundle);
  }
View Full Code Here

          else {
            // Process JSP file.
            Bundle bundle = ctx.getBundle();
            JasperServletWrapper jspServlet = JspServletPool
                .getInstance(ctx);
            BundledHttpServletRequestWrapper wrapper = BundledHttpServletRequestWrapper
                .getHttpServletRequestWrapper(req, bundle);
            wrapper.setServletPath(jspFile);
            wrapper.setPathInfo(null);
            jspServlet.service(wrapper, resp);
          }
          return Status.OK_STATUS;
        } catch (Exception e) {
          // e.printStackTrace();
View Full Code Here

   */
  public void service(HttpServletRequestAdapter req,
      HttpServletResponseAdapter res) throws Exception {
    // Wrapper the original HttpServletRequest and HttpServletResponse and
    // buffer them in Thread Local variants.
    BundledHttpServletRequestWrapper topReq = BundledHttpServletRequestWrapper
        .getHttpServletRequestWrapper(req, null);
    HttpServletResponseWrapper topResp = HttpServletResponseWrapper
        .getHttpServletResponseWrapper(res);

    getReqThreadVariants().put(OSGiWebContainer.THREAD_V_REQUEST, topReq);
View Full Code Here

              "OSGiWebContainer: Service error", t);
      }
    } finally {
      HttpServletResponseWrapper topResp = (HttpServletResponseWrapper) this
          .getReqThreadVariants().get(THREAD_V_RESPONSE);
      BundledHttpServletRequestWrapper topReq = (BundledHttpServletRequestWrapper) this
          .getReqThreadVariants().get(THREAD_V_REQUEST);
      // If not any exception throwed and not dispatched, do flush buffer.
      if (!exceptionThrowed && !topReq.isDispatched()) {
        try {
          topResp.flushBufferInternal();
        } catch (Exception e) {
          String msg = e.getMessage();
          // If http socket reset by client, a IOException will be
View Full Code Here

  public void handle(BundledHttpServletRequestWrapper request,
      HttpServletResponseWrapper response, IFwkHandlerChain handlerChain)
      throws IOException, ServletException {
    // Record the old path before servlet invoke, and reset to the req at
    // last. Otherwise, the filter will not be matched to the modified path.
    BundledHttpServletRequestWrapper topRequest = request.getTopWrapper();
    // HttpServletResponseWrapper topResponse = response.getTopWrapper();
    String oldPathInfo = topRequest.getPathInfo();
    String oldServletPath = topRequest.getServletPath();

    try {
      // Because a servlet may have mutiple url pattern map. Here
      // create mutiple cloned copy of a servlet for each url
      // parttern. And then, sort these copys of many servlets
      // according to some regular into a wait queue. If one copy be
      // executed, others of the same servlet or filter won't execute.
      Collection<FilterDelegate> filters = getFwkContainerHelper()
          .getAllBufferedFilters(false);
      List<ClonedExecutableServletObject<ServletDelegate>> servletCopys = getFwkContainerHelper()
          .sortURLPatternsExeObjs(ServletDelegate.class, false);

      // Try to find the url matched servlet copy below.
      ClonedExecutableServletObject<ServletDelegate> servletDelegateCopy = null;
      try {
        servletDelegateCopy = getFwkContainerHelper()
            .chooseDelegateServlet(request, servletCopys);
      } catch (Exception e) {
        throw new ServletException(e);
      }

      if (servletDelegateCopy != null) {
        ServletDelegate servletDelegate = servletDelegateCopy
            .getOriginalObj();
        Object oldBundle = topRequest.getBundle();
        // Only need to set once, because the filter of same bundle
        // with the servlet can be called.
        getFwkContainerHelper().switchReqBundleContext(
            servletDelegate.getBundleContext().getBundle());
        try {
          doServletMapFilter(servletDelegate, request, response,
              filters);
        } finally {
          // Revert bundle of Top Req
          getFwkContainerHelper().switchReqBundleContext(
              (Bundle) oldBundle);
        }
      } else {
        // No matched servlet found, set NOT_FOUND status rather than
        // throw ServletException.
        /*throw new ServletException("No Service found for Request URI:"
            + request.getRequestURI());*/
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
      }
    } finally {
      // Reset the pathinfo and servlet path to the buffered request.
      // Because serlvet mapping will modify these two variants, and then
      // the web bundle's flters will not be maped after the servlet
      // invoked.
      topRequest.setPathInfo(oldPathInfo);
      topRequest.setServletPath(oldServletPath);
    }
  }
View Full Code Here

      // redirect the response.
      List<String> welcomePages = hostServletContext.getWelcomePages();
      for (Iterator<String> it = welcomePages.iterator(); it.hasNext();) {
        String welcomeFilePath = it.next();
        if (hostServletContext.getResource(welcomeFilePath) != null) {
          BundledHttpServletRequestWrapper req = (BundledHttpServletRequestWrapper) threadScope
              .get().get(RESPONSE_REQ);
          // oReqPath =
          // path.append(welcomeFilePath).toPortableString();
          // req.setPathInfo(oReqPath);
          HttpServletResponse resp = (HttpServletResponse) threadScope
              .get().get(RESPONSE_RESP);
          StringBuffer rawUrl = req.getRequestURL();
          if (rawUrl.charAt(rawUrl.length() - 1) == '/')
            rawUrl.deleteCharAt(rawUrl.length() - 1);

          resp.sendRedirect(rawUrl.append(
              new Path(welcomeFilePath).makeAbsolute()
View Full Code Here

    // ServletConfig newConfig = new
    // BundledServletConfig(targetBundle,getJspServletConfig(),
    // virtualPath);
    // jspServlet.init(newConfig);

    BundledHttpServletRequestWrapper topReq = (BundledHttpServletRequestWrapper) webContainer
        .getReqThreadVariants().get(OSGiWebContainer.THREAD_V_REQUEST);

    HttpServletRequest req = (HttpServletRequest) threadScope.get().get(
        RESPONSE_REQ);
    ServletResponse resp = (ServletResponse) threadScope.get().get(
        RESPONSE_RESP);

    BundledHttpServletRequestWrapper wrapper = BundledHttpServletRequestWrapper
        .getHttpServletRequestWrapper(req, targetBundle);

    Bundle oldBundle = topReq.getBundle();
    String oldServletPath = topReq.getServletPath();
    String oldPathInfo = topReq.getPathInfo();
    try {
      // Switch to another bundled servelt request.
      // No need to swith thread context class loader, coz Jsp Servlet's
      // class loader has been changed.
      topReq.setBundle(targetBundle);
      // wrapper.setBundle(targetBundle);
      wrapper.setServletPath(virtualPath);
      wrapper.setPathInfo(null);
      jspServlet.service(wrapper, resp);
      // jspServlet.destroy();
    } finally {
      if (topReq.equals(wrapper)) {
        topReq.setBundle(oldBundle);
View Full Code Here

TOP

Related Classes of org.emrys.webosgi.core.jeewrappers.BundledHttpServletRequestWrapper

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.