示例#1
0
  public void invoke(Request request, Response response) throws IOException, ServletException {

    String servletName = ((HttpServletRequest) request).getRequestURI();
    servletName = servletName.substring(servletName.lastIndexOf("/") + 1);
    URLClassLoader loader = null;
    try {
      URL[] urls = new URL[1];
      URLStreamHandler streamHandler = null;
      File classPath = new File(WEB_ROOT);
      String repository =
          (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString();
      urls[0] = new URL(null, repository, streamHandler);
      loader = new URLClassLoader(urls);
    } catch (IOException e) {
      System.out.println(e.toString());
    }
    Class myClass = null;
    try {
      myClass = loader.loadClass(servletName);
    } catch (ClassNotFoundException e) {
      System.out.println(e.toString());
    }

    Servlet servlet = null;

    try {
      servlet = (Servlet) myClass.newInstance();
      servlet.service((HttpServletRequest) request, (HttpServletResponse) response);
    } catch (Exception e) {
      System.out.println(e.toString());
    } catch (Throwable e) {
      System.out.println(e.toString());
    }
  }
示例#2
0
 /**
  * Make and initialize a new ruby Servlet within the ScriptingContainer. The ruby class and other
  * options are taken from {@code servletConfig}.
  */
 public Servlet makeServlet(ServletConfig servletConfig) throws ServletException {
   final RubyConfig config = new RubyConfig(servletConfig);
   final Servlet servlet = newInstance(config.getServletClass(), Servlet.class);
   servlet.init(servletConfig);
   logger.info("initialized servlet: {}", servlet);
   return servlet;
 }
  public void process(Request request, Response response) {

    String uri = request.getUri();
    String servletName = uri.substring(uri.lastIndexOf("/") + 1);
    URLClassLoader loader = null;

    try {
      // create a URLClassLoader
      URL[] urls = new URL[1];
      URLStreamHandler streamHandler = null;
      File classPath = new File(Constants.WEB_ROOT);
      // the forming of repository is taken from the createClassLoader method in
      // org.apache.catalina.startup.ClassLoaderFactory
      String repository =
          (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString();
      // the code for forming the URL is taken from the addRepository method in
      // org.apache.catalina.loader.StandardClassLoader class.
      urls[0] = new URL(null, repository, streamHandler);
      loader = new URLClassLoader(urls);
    } catch (IOException e) {
      System.out.println(e.toString());
    }
    Class myClass = null;
    try {
      myClass = loader.loadClass(servletName);
    } catch (ClassNotFoundException e) {
      System.out.println(e.toString());
    }

    Servlet servlet = null;

    try {
      servlet = (Servlet) myClass.newInstance();
      servlet.service((ServletRequest) request, (ServletResponse) response);
    } catch (Exception e) {
      System.out.println(e.toString());
    } catch (Throwable e) {
      System.out.println(e.toString());
    }
    // this is  to run application1 by another way
    /*
    	 *  URL myUrl[]={new URL("file:///D:/github/Toy-Tomcat/Tomcat/TOMCAT/src/")};
    	  URLClassLoader x = new URLClassLoader(myUrl);
    	    Class myClass = x.loadClass("test.PrimitiveServlet");
        Servlet servlet = null;

        try {
          servlet = (Servlet) myClass.newInstance();
          servlet.service((ServletRequest) request, (ServletResponse) response);
        }
        catch (Exception e) {
          System.out.println(e.toString());
        }
        catch (Throwable e) {
          System.out.println(e.toString());
        }
    */
  }
示例#4
0
 @Override
 protected void doProcess(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   if (sgtServlet == null) {
     sgtServlet = new SGTServlet();
     sgtServlet.init(new FilterServletConfig(filterConfig));
   }
   sgtServlet.service(request, response);
 }
示例#5
0
 public void service(ServletRequest request, ServletResponse response)
     throws ServletException, IOException {
   if (servlet instanceof SingleThreadModel) {
     synchronized (this) {
       servlet.service(request, response);
     }
   } else {
     servlet.service(request, response);
   }
 }
示例#6
0
  @Test
  @WrapInMockProbeExecution
  public void testServlet() throws ServletException, IOException {

    Servlet servlet = new MockServlet();
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.service(request, response);

    ServletProbeExecution servletProbeExecution = getRootServletProbeExecution();
    assertEquals(MockServlet.class, servletProbeExecution.getClazz());
    assertNotNull(servletProbeExecution.getRequestURI());
  }
示例#7
0
 /**
  * Servlet等のモックを作成する。
  *
  * @return
  * @throws Exception
  */
 private void setMockContext(S2Container container) throws Exception {
   MockServletContext servletContext = new MockServletContextImpl("s2-example");
   MockHttpServletRequest request = servletContext.createRequest("/hello.html");
   MockHttpServletResponse response = new MockHttpServletResponseImpl(request);
   MockServletConfig servletConfig = new MockServletConfigImpl();
   servletConfig.setServletContext(servletContext);
   Servlet servlet = new S2ContainerServlet();
   servlet.init(servletConfig);
   container.register(servletConfig);
   container.register(servletContext);
   container.register(servlet);
   container.register(request);
   container.register(response);
 }
  public Servlet getServlet() throws ServletException, IOException, FileNotFoundException {
    if (reload) {
      synchronized (this) {
        // Synchronizing on jsw enables simultaneous loading
        // of different pages, but not the same page.
        if (reload) {
          // This is to maintain the original protocol.
          destroy();

          try {
            servletClass = ctxt.load();
            theServlet = (Servlet) servletClass.newInstance();
          } catch (IllegalAccessException ex1) {
            throw new JasperException(ex1);
          } catch (InstantiationException ex) {
            throw new JasperException(ex);
          }

          theServlet.init(config);
          firstTime = false;
          reload = false;
        }
      }
    }
    return theServlet;
  }
示例#9
0
  public void stop() throws LifecycleException {
    System.out.println("Stopping wrapper " + name);
    // Shut down our servlet instance (if it has been initialized)
    try {
      instance.destroy();
    } catch (Throwable t) {
    }
    instance = null;
    if (!started) throw new LifecycleException("Wrapper " + name + " not started");
    // Notify our interested LifecycleListeners
    lifecycle.fireLifecycleEvent(BEFORE_STOP_EVENT, null);

    // Notify our interested LifecycleListeners
    lifecycle.fireLifecycleEvent(STOP_EVENT, null);
    started = false;

    // Stop the Valves in our pipeline (including the basic), if any
    if (pipeline instanceof Lifecycle) {
      ((Lifecycle) pipeline).stop();
    }

    // Stop our subordinate components, if any
    if ((loader != null) && (loader instanceof Lifecycle)) {
      ((Lifecycle) loader).stop();
    }

    // Notify our interested LifecycleListeners
    lifecycle.fireLifecycleEvent(AFTER_STOP_EVENT, null);
  }
示例#10
0
  public void destroy() {
    if (servlet != null) {
      servlet.destroy();
    }

    this.alias = null;
    this.servlet = null;
  }
示例#11
0
 public void service(ServletRequest servletRequest, ServletResponse servletResponse)
     throws ServletException, IOException {
   if (errorCode > 0) {
     ((HttpServletResponse) servletResponse).sendError(errorCode, errorMessage);
   } else {
     servletRequest.setCharacterEncoding("UTF-8");
     proxiedServlet.service(servletRequest, servletResponse);
   }
 }
示例#12
0
  @Test
  @ConfigureAgentEnabled(false)
  @ConfigureServletProbeUsernameSessionAttribute("username")
  @WrapInMockProbeExecution
  public void testUsernameSessionAttributeCaptureUnderDisabledAgent()
      throws ServletException, IOException {

    Servlet servlet = new MockServlet();
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.service(request, response);

    MockHttpSession session = new MockHttpSession();
    session.setAttribute("username", "abc");

    // perform assertions
    OperationSafeImpl operation = Agent.getInstance().getCurrentOperation();
    assertNull(operation);
  }
  protected void registerServlet(String servletName, String... urlPatterns)
      throws NamespaceException, ServletException {

    mockBundleWiring();

    when(_servlet.getServletConfig()).thenReturn(new MockServletConfig(servletName));

    _bundleServletContext.registerServlet(
        servletName, Arrays.asList(urlPatterns), _servlet, null, _httpContext);

    Servlet servlet = _bundleServletContext.getServlet(servletName);

    Assert.assertNotNull(servlet);

    Assert.assertEquals(servletName, servlet.getServletConfig().getServletName());

    Mockito.verify(_servlet).getServletConfig();

    verifyBundleWiring();
  }
  protected void updateFileLastModified(String path, Servlet servlet) {
    ServletConfig servletConfig = servlet.getServletConfig();

    ServletContext servletContext = servletConfig.getServletContext();

    String rootPath = servletContext.getRealPath(StringPool.BLANK);

    File file = new File(rootPath, path);

    file.setLastModified(System.currentTimeMillis());
  }
  /**
   * Perform the actual request. {@inheritDoc}
   *
   * @see
   *     org.apache.sling.api.servlets.SlingSafeMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest,
   *     org.apache.sling.api.SlingHttpServletResponse)
   */
  protected void doGet(SlingHttpServletRequest req, SlingHttpServletResponse resp)
      throws IOException {

    Servlet servlet = ((SlingHttpServletRequest) req).getResource().adaptTo(Servlet.class);
    if (servlet != null) {
      try {
        servlet.service((ServletRequest) req, (ServletResponse) resp);
      } catch (ServletException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    } else {
      // send error
      PrintWriter p = resp.getWriter();
      p.print("Failed miserably");
      p.flush();
    }

    return;
  }
示例#16
0
 @Override
 public synchronized Servlet loadServlet() throws ServletException {
   if (singleThreadModel) {
     Servlet instance;
     try {
       instance = existing.getClass().newInstance();
     } catch (InstantiationException e) {
       throw new ServletException(e);
     } catch (IllegalAccessException e) {
       throw new ServletException(e);
     }
     instance.init(facade);
     return instance;
   } else {
     if (!instanceInitialized) {
       existing.init(facade);
       instanceInitialized = true;
     }
     return existing;
   }
 }
示例#17
0
 public void destroy() {
   if (theServlet != null) {
     theServlet.destroy();
     InstanceManager instanceManager = InstanceManagerFactory.getInstanceManager(config);
     try {
       instanceManager.destroyInstance(theServlet);
     } catch (Exception e) {
       // Log any exception, since it can't be passed along
       log.error(Localizer.getMessage("jsp.error.file.not.found", e.getMessage()), e);
     }
   }
 }
示例#18
0
  public Servlet loadServlet() throws ServletException {
    if (instance != null) return instance;

    Servlet servlet = null;
    String actualClass = servletClass;
    if (actualClass == null) {
      throw new ServletException("servlet class has not been specified");
    }

    Loader loader = getLoader();
    // Acquire an instance of the class loader to be used
    if (loader == null) {
      throw new ServletException("No loader.");
    }
    ClassLoader classLoader = loader.getClassLoader();

    // Load the specified servlet class from the appropriate class loader
    Class classClass = null;
    try {
      if (classLoader != null) {
        classClass = classLoader.loadClass(actualClass);
      }
    } catch (ClassNotFoundException e) {
      throw new ServletException("Servlet class not found");
    }
    // Instantiate and initialize an instance of the servlet class itself
    try {
      servlet = (Servlet) classClass.newInstance();
    } catch (Throwable e) {
      throw new ServletException("Failed to instantiate servlet");
    }

    // Call the initialization method of this servlet
    try {
      servlet.init(null);
    } catch (Throwable f) {
      throw new ServletException("Failed initialize servlet.");
    }
    return servlet;
  }
示例#19
0
  public Servlet getServlet() throws ServletException {
    // DCL on 'reload' requires that 'reload' be volatile
    // (this also forces a read memory barrier, ensuring the
    // new servlet object is read consistently)
    if (reload) {
      synchronized (this) {
        // Synchronizing on jsw enables simultaneous loading
        // of different pages, but not the same page.
        if (reload) {
          // This is to maintain the original protocol.
          destroy();

          final Servlet servlet;

          try {
            InstanceManager instanceManager = InstanceManagerFactory.getInstanceManager(config);
            servlet = (Servlet) instanceManager.newInstance(ctxt.getFQCN(), ctxt.getJspLoader());
          } catch (IllegalAccessException e) {
            throw new JasperException(e);
          } catch (InstantiationException e) {
            throw new JasperException(e);
          } catch (Exception e) {
            throw new JasperException(e);
          }

          servlet.init(config);

          if (!firstTime) {
            ctxt.getRuntimeContext().incrementJspReloadCount();
          }

          theServlet = servlet;
          reload = false;
          // Volatile 'reload' forces in order write of 'theServlet' and new servlet object
        }
      }
    }
    return theServlet;
  }
示例#20
0
 @Override
 public ServletRegistration.Dynamic addServlet(final String servletName, final Servlet servlet) {
   ensureNotProgramaticListener();
   ensureNotInitialized();
   if (deploymentInfo.getServlets().containsKey(servletName)) {
     return null;
   }
   ServletInfo s =
       new ServletInfo(
           servletName, servlet.getClass(), new ImmediateInstanceFactory<Servlet>(servlet));
   deploymentInfo.addServlet(s);
   deployment.getServlets().addServlet(s);
   return new ServletRegistrationImpl(s, deployment);
 }
 public void setServletConfig(ServletConfig servletConfig) {
   try {
     shadowCxfServlet = (Servlet) servletClass.newInstance();
   } catch (InstantiationException e) {
     throw new RuntimeException(e);
   } catch (IllegalAccessException e) {
     throw new RuntimeException(e);
   }
   try {
     shadowCxfServlet.init(servletConfig);
   } catch (ServletException ex) {
     throw new RuntimeException(ex.getMessage(), ex);
   }
 }
 public void destroy() {
   if (theServlet != null) {
     theServlet.destroy();
     InstanceManager instanceManager = InstanceManagerFactory.getInstanceManager(config);
     try {
       instanceManager.destroyInstance(theServlet);
     } catch (Exception e) {
       Throwable t = ExceptionUtils.unwrapInvocationTargetException(e);
       ExceptionUtils.handleThrowable(t);
       // Log any exception, since it can't be passed along
       log.error(Localizer.getMessage("jsp.error.file.not.found", e.getMessage()), t);
     }
   }
 }
  public void invoke(Request request, Response response, ValveContext valveContext)
      throws IOException, ServletException {

    SimpleWrapper wrapper = (SimpleWrapper) getContainer();
    ServletRequest sreq = request.getRequest();
    ServletResponse sres = response.getResponse();
    Servlet servlet = null;
    HttpServletRequest hreq = null;
    if (sreq instanceof HttpServletRequest) hreq = (HttpServletRequest) sreq;
    HttpServletResponse hres = null;
    if (sres instanceof HttpServletResponse) hres = (HttpServletResponse) sres;

    // Allocate a servlet instance to process this request
    try {
      servlet = wrapper.allocate();
      if (hres != null && hreq != null) {
        servlet.service(hreq, hres);
      } else {
        servlet.service(sreq, sres);
      }
    } catch (ServletException e) {
    }
  }
示例#24
0
 @Override
 public void process(HttpServletRequest request, HttpServletResponse response) {
   String uri = request.getRequestURI();
   String servletName = uri.substring(uri.lastIndexOf('/') + 1);
   servletName = "com.tojaoomy.tomcat.server.servlet." + servletName;
   URLClassLoader classLoader = null;
   URLStreamHandler streamHandler = null;
   URL[] urls = new URL[1];
   File classPath = new File(Constants.WEB_ROOT);
   String repository;
   Class<?> clazz;
   try {
     System.out.println(
         getClass()
             .getResource("/com/tojaoomy/tomcat/server/servlet/PrimitiveServlet.class")
             .getPath());
     repository = new URL("file", null, classPath.getCanonicalPath() + File.separator).toString();
     URL url = new URL(null, repository, streamHandler);
     urls[0] = url;
     classLoader = new URLClassLoader(urls);
     clazz = classLoader.loadClass(servletName);
     Servlet servlet = (Servlet) clazz.newInstance();
     servlet.service(request, response);
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (ClassNotFoundException e) {
     e.printStackTrace();
   } catch (InstantiationException e) {
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   } catch (ServletException e) {
     e.printStackTrace();
   }
 }
  private void _initialize(
      Servlet servlet,
      ServletRequest request,
      ServletResponse response,
      String errorPageURL,
      boolean needsSession,
      int bufferSize,
      boolean autoFlush) {

    // initialize state
    this.servlet = servlet;
    this.config = servlet.getServletConfig();
    this.context = config.getServletContext();
    this.errorPageURL = errorPageURL;
    this.request = request;
    this.response = response;

    // initialize application context
    this.applicationContext = JspApplicationContextImpl.getInstance(context);

    // Setup session (if required)
    if (request instanceof HttpServletRequest && needsSession)
      this.session = ((HttpServletRequest) request).getSession();
    if (needsSession && session == null)
      throw new IllegalStateException("Page needs a session and none is available");

    // initialize the initial out ...
    depth = -1;
    if (this.baseOut == null) {
      this.baseOut = new JspWriterImpl(response, bufferSize, autoFlush);
    } else {
      this.baseOut.init(response, bufferSize, autoFlush);
    }
    this.out = baseOut;

    // register names/values as per spec
    setAttribute(OUT, this.out);
    setAttribute(REQUEST, request);
    setAttribute(RESPONSE, response);

    if (session != null) setAttribute(SESSION, session);

    setAttribute(PAGE, servlet);
    setAttribute(CONFIG, config);
    setAttribute(PAGECONTEXT, this);
    setAttribute(APPLICATION, context);

    isIncluded = request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH) != null;
  }
  protected long getFileLastModified(String path, Servlet servlet) {
    ServletConfig servletConfig = servlet.getServletConfig();

    ServletContext servletContext = servletConfig.getServletContext();

    String rootPath = servletContext.getRealPath(StringPool.BLANK);

    File file = new File(rootPath, path);

    if (file.exists()) {
      return file.lastModified();
    }

    return -1;
  }
    private static HttpServer create(
        URI u,
        Servlet servlet,
        Map<String, String> initParams,
        Map<String, String> contextParams,
        List<String> listeners,
        List<String> urlMappings)
        throws IOException {
      if (u == null) {
        throw new IllegalArgumentException("The URI must not be null");
      }

      String path = u.getPath();

      WebappContext context = new WebappContext("GrizzlyContext", path);

      for (String listener : listeners) {
        context.addListener(listener);
      }

      ServletRegistration registration = context.addServlet(servlet.getClass().getName(), servlet);

      for (String mapping : urlMappings) {
        registration.addMapping(mapping);
      }

      if (contextParams != null) {
        for (Map.Entry<String, String> e : contextParams.entrySet()) {
          context.setInitParameter(e.getKey(), e.getValue());
        }
      }

      if (initParams != null) {
        registration.setInitParameters(initParams);
      }

      HttpServer server = GrizzlyHttpServerFactory.createHttpServer(u);
      context.deploy(server);

      return server;
    }
示例#28
0
 public void destroy() {
   proxiedServlet.destroy();
 }
示例#29
0
 public String getServletInfo() {
   return proxiedServlet.getServletInfo();
 }
示例#30
0
 public ServletConfig getServletConfig() {
   return proxiedServlet.getServletConfig();
 }