public void testListeners() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // Must have a real docBase - just use temp
    File docBase = new File(System.getProperty("java.io.tmpdir"));

    Context ctx = tomcat.addContext("", docBase.getAbsolutePath());

    TrackingServlet tracking = new TrackingServlet();
    Wrapper wrapper = Tomcat.addServlet(ctx, "tracking", tracking);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/stage1", "tracking");

    TimeoutServlet timeout = new TimeoutServlet(true, null);
    Wrapper wrapper2 = Tomcat.addServlet(ctx, "timeout", timeout);
    wrapper2.setAsyncSupported(true);
    ctx.addServletMapping("/stage2", "timeout");

    tomcat.start();

    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/stage1");

    ByteChunk res = getUrl(url.toString());

    assertEquals(
        "DispatchingServletGet-DispatchingServletGet-onStartAsync-"
            + "TimeoutServletGet-onStartAsync-onTimeout-onComplete-",
        res.toString());
  }
Esempio n. 2
0
  private static void addServlets(JBossWebMetaData jbwebMD, StandardContext context) {
    for (JBossServletMetaData smd : jbwebMD.getServlets()) {
      final String sc = smd.getServletClass();
      if (sc.equals(WSFServlet.class.getName())) {
        final String servletName = smd.getServletName();
        List<ParamValueMetaData> params = smd.getInitParam();
        List<String> urlPatterns = null;
        for (ServletMappingMetaData smmd : jbwebMD.getServletMappings()) {
          if (smmd.getServletName().equals(servletName)) {
            urlPatterns = smmd.getUrlPatterns();
            break;
          }
        }

        WSFServlet wsfs = new WSFServlet();
        Wrapper wsfsWrapper = context.createWrapper();
        wsfsWrapper.setName(servletName);
        wsfsWrapper.setServlet(wsfs);
        wsfsWrapper.setServletClass(WSFServlet.class.getName());
        for (ParamValueMetaData param : params) {
          wsfsWrapper.addInitParameter(param.getParamName(), param.getParamValue());
        }
        context.addChild(wsfsWrapper);
        for (String urlPattern : urlPatterns) {
          context.addServletMapping(urlPattern, servletName);
        }
      }
    }
  }
  public void testBug49567() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));

    Bug49567Servlet servlet = new Bug49567Servlet();

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/", "servlet");

    tomcat.start();

    // Call the servlet once
    ByteChunk bc = getUrl("http://localhost:" + getPort() + "/");
    assertEquals("OK", bc.toString());

    // Give the async thread a chance to finish (but not too long)
    int counter = 0;
    while (!servlet.isDone() && counter < 10) {
      Thread.sleep(1000);
      counter++;
    }

    assertEquals("1false2true3true4true5false", servlet.getResult());
  }
  @Test
  public void testFlagFailCtxIfServletStartFails() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File docBase = new File(System.getProperty("java.io.tmpdir"));
    StandardContext context = (StandardContext) tomcat.addContext("", docBase.getAbsolutePath());

    // first we test the flag itself, which can be set on the Host and
    // Context
    assertFalse(context.getComputedFailCtxIfServletStartFails());

    StandardHost host = (StandardHost) tomcat.getHost();
    host.setFailCtxIfServletStartFails(true);
    assertTrue(context.getComputedFailCtxIfServletStartFails());
    context.setFailCtxIfServletStartFails(Boolean.FALSE);
    assertFalse(
        "flag on Context should override Host config",
        context.getComputedFailCtxIfServletStartFails());

    // second, we test the actual effect of the flag on the startup
    Wrapper servlet = Tomcat.addServlet(context, "myservlet", new FailingStartupServlet());
    servlet.setLoadOnStartup(1);

    tomcat.start();
    assertTrue("flag false should not fail deployment", context.getState().isAvailable());

    tomcat.stop();
    assertFalse(context.getState().isAvailable());

    host.removeChild(context);
    context = (StandardContext) tomcat.addContext("", docBase.getAbsolutePath());
    servlet = Tomcat.addServlet(context, "myservlet", new FailingStartupServlet());
    servlet.setLoadOnStartup(1);
    tomcat.start();
    assertFalse("flag true should fail deployment", context.getState().isAvailable());
  }
  public void testAsyncStartNoComplete() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // Minimise pauses during test
    tomcat.getConnector().setAttribute("connectionTimeout", Integer.valueOf(3000));

    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));

    AsyncStartNoCompleteServlet servlet = new AsyncStartNoCompleteServlet();

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/", "servlet");

    tomcat.start();

    // Call the servlet the first time
    ByteChunk bc1 = getUrl("http://localhost:" + getPort() + "/?echo=run1");
    assertEquals("OK-run1", bc1.toString());

    // Call the servlet the second time with a request parameter
    ByteChunk bc2 = getUrl("http://localhost:" + getPort() + "/?echo=run2");
    assertEquals("OK-run2", bc2.toString());
  }
Esempio n. 6
0
  @Test
  public void testBug56042() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    Bug56042Servlet bug56042Servlet = new Bug56042Servlet();
    Wrapper wrapper = Tomcat.addServlet(ctx, "bug56042Servlet", bug56042Servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/bug56042Servlet", "bug56042Servlet");

    tomcat.start();

    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/bug56042Servlet");

    ByteChunk res = new ByteChunk();
    int rc = getUrl(url.toString(), res, null);

    Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, rc);
  }
Esempio n. 7
0
  /**
   * Static version of {@link #addServlet(String, String, Servlet)}.
   *
   * @param ctx Context to add Servlet to
   * @param servletName Servlet name (used in mappings)
   * @param servlet The Servlet to add
   * @return The wrapper for the servlet
   */
  public static Wrapper addServlet(Context ctx, String servletName, Servlet servlet) {
    // will do class for name and set init params
    Wrapper sw = new ExistingStandardWrapper(servlet);
    sw.setName(servletName);
    ctx.addChild(sw);

    return sw;
  }
Esempio n. 8
0
  /**
   * Static version of {@link #addServlet(String, String, String)}
   *
   * @param ctx Context to add Servlet to
   * @param servletName Servlet name (used in mappings)
   * @param servletClass The class to be used for the Servlet
   * @return The wrapper for the servlet
   */
  public static Wrapper addServlet(Context ctx, String servletName, String servletClass) {
    // will do class for name and set init params
    Wrapper sw = ctx.createWrapper();
    sw.setServletClass(servletClass);
    sw.setName(servletName);
    ctx.addChild(sw);

    return sw;
  }
 private void addJspServlet(Context context) {
   Wrapper jspServlet = context.createWrapper();
   jspServlet.setName("jsp");
   jspServlet.setServletClass(getJspServletClassName());
   jspServlet.addInitParameter("fork", "false");
   jspServlet.setLoadOnStartup(3);
   context.addChild(jspServlet);
   context.addServletMapping("*.jsp", "jsp");
   context.addServletMapping("*.jspx", "jsp");
 }
Esempio n. 10
0
 /** Set the error flag. */
 public boolean setError() {
   boolean result = errorState.compareAndSet(0, 1);
   if (result) {
     Wrapper wrapper = getRequest().getWrapper();
     if (wrapper != null) {
       wrapper.incrementErrorCount();
     }
   }
   return result;
 }
 private void addInitParameters(final Wrapper wrapper, final Map<String, String> initParameters) {
   NullArgumentException.validateNotNull(initParameters, "initParameters");
   NullArgumentException.validateNotNull(wrapper, "wrapper");
   for (final Map.Entry<String, String> initParam : initParameters.entrySet()) {
     wrapper.addInitParameter(initParam.getKey(), initParam.getValue());
   }
 }
Esempio n. 12
0
  @Override
  public void construct() {
    tomcat = new Tomcat();

    Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
    connector.setURIEncoding("UTF-8");
    connector.setPort(5000);
    tomcat.getService().addConnector(connector);
    tomcat.setConnector(connector);

    try {
      Context ctx;

      if (new File(Configuration.WEBROOT_PATH).exists()) {
        L.i("Static web client found.");

        ctx = tomcat.addContext("", Configuration.WEBROOT_PATH);
        ctx.addWelcomeFile("index.html");

        Wrapper wrapper = tomcat.addServlet(ctx, "DefaultServlet", new DefaultServlet());
        wrapper.setAsyncSupported(true);
        wrapper.addInitParameter("listings", "false");
        wrapper.addMapping("/");
        wrapper.setLoadOnStartup(1);
      } else {
        L.w("No static web client found, web interface will not be available.");
        ctx = tomcat.addContext("/", "/tmp");
      }

      configureMimeMappings(ctx);

      addSessionFilter(ctx);
      addCharacterEncodingFilter(ctx);

      Wrapper wrapper = tomcat.addServlet(ctx, "JerseyServlet", new ServletContainer());
      wrapper.setAsyncSupported(true);
      wrapper.addInitParameter("javax.ws.rs.Application", JerseyApplication.class.getName());
      wrapper.addMapping("/api/*");
      wrapper.setLoadOnStartup(1);

      tomcat.start();
    } catch (Exception e) {
      L.e("Failed to start RestApiModule.", e);
    }
  }
  /**
   * Handle the HTTP status code (and corresponding message) generated while processing the
   * specified Request to produce the specified Response. Any exceptions that occur during
   * generation of the error report are logged and swallowed.
   *
   * @param request The request being processed
   * @param response The response being generated
   */
  private void status(Request request, Response response) {

    int statusCode = response.getStatus();

    // Handle a custom error page for this status code
    Context context = request.getContext();
    if (context == null) return;

    /* Only look for error pages when isError() is set.
     * isError() is set when response.sendError() is invoked. This
     * allows custom error pages without relying on default from
     * web.xml.
     */
    if (!response.isError()) return;

    ErrorPage errorPage = context.findErrorPage(statusCode);
    if (errorPage == null) {
      // Look for a default error page
      errorPage = context.findErrorPage(0);
    }
    if (errorPage != null && response.setErrorReported()) {
      response.setAppCommitted(false);
      request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, Integer.valueOf(statusCode));

      String message = response.getMessage();
      if (message == null) message = "";
      request.setAttribute(RequestDispatcher.ERROR_MESSAGE, message);
      request.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, errorPage.getLocation());
      request.setAttribute(Globals.DISPATCHER_TYPE_ATTR, DispatcherType.ERROR);

      Wrapper wrapper = request.getWrapper();
      if (wrapper != null)
        request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, wrapper.getName());
      request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, request.getRequestURI());
      if (custom(request, response, errorPage)) {
        try {
          response.finishResponse();
        } catch (ClientAbortException e) {
          // Ignore
        } catch (IOException e) {
          container.getLogger().warn("Exception Processing " + errorPage, e);
        }
      }
    }
  }
  public void testAsyncStartWithComplete() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));

    AsyncStartWithCompleteServlet servlet = new AsyncStartWithCompleteServlet();

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/", "servlet");

    tomcat.start();

    // Call the servlet once
    ByteChunk bc = getUrl("http://localhost:" + getPort() + "/");
    assertEquals("OK", bc.toString());
  }
  private void doTestDispatchError(int iter, boolean useThread, boolean completeOnError)
      throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // Must have a real docBase - just use temp
    File docBase = new File(System.getProperty("java.io.tmpdir"));

    Context ctx = tomcat.addContext("", docBase.getAbsolutePath());

    DispatchingServlet dispatch = new DispatchingServlet(true, completeOnError);
    Wrapper wrapper = Tomcat.addServlet(ctx, "dispatch", dispatch);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/stage1", "dispatch");

    ErrorServlet error = new ErrorServlet();
    Tomcat.addServlet(ctx, "error", error);
    ctx.addServletMapping("/stage2", "error");

    tomcat.start();

    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/stage1?iter=");
    url.append(iter);
    if (useThread) {
      url.append("&useThread=y");
    }
    ByteChunk res = getUrl(url.toString());

    StringBuilder expected = new StringBuilder();
    int loop = iter;
    while (loop > 0) {
      expected.append("DispatchingServletGet-");
      if (loop != iter) {
        expected.append("onStartAsync-");
      }
      loop--;
    }
    expected.append("ErrorServletGet-onError-onComplete-");
    assertEquals(expected.toString(), res.toString());
  }
Esempio n. 16
0
    private synchronized void init() throws Exception {
      if (init) return;

      Tomcat tomcat = getTomcatInstance();
      context = tomcat.addContext("", TEMP_DIR);
      Tomcat.addServlet(context, "regular", new Bug49711Servlet());
      Wrapper w = Tomcat.addServlet(context, "multipart", new Bug49711Servlet_multipart());

      // Tomcat.addServlet does not respect annotations, so we have
      // to set our own MultipartConfigElement.
      w.setMultipartConfigElement(new MultipartConfigElement(""));

      context.addServletMapping("/regular", "regular");
      context.addServletMapping("/multipart", "multipart");
      tomcat.start();

      setPort(tomcat.getConnector().getLocalPort());

      init = true;
    }
  private void doTestTimeout(boolean completeOnTimeout, String dispatchUrl) throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // Must have a real docBase - just use temp
    File docBase = new File(System.getProperty("java.io.tmpdir"));

    // Create the folder that will trigger the redirect
    File foo = new File(docBase, "async");
    if (!foo.exists() && !foo.mkdirs()) {
      fail("Unable to create async directory in docBase");
    }

    Context ctx = tomcat.addContext("", docBase.getAbsolutePath());

    TimeoutServlet timeout = new TimeoutServlet(completeOnTimeout, dispatchUrl);

    Wrapper wrapper = Tomcat.addServlet(ctx, "time", timeout);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/async", "time");

    if (dispatchUrl != null) {
      NonAsyncServlet nonAsync = new NonAsyncServlet();
      Tomcat.addServlet(ctx, "nonasync", nonAsync);
      ctx.addServletMapping(dispatchUrl, "nonasync");
    }

    tomcat.start();
    ByteChunk res = getUrl("http://localhost:" + getPort() + "/async");
    StringBuilder expected = new StringBuilder();
    expected.append("TimeoutServletGet-onTimeout-");
    if (!completeOnTimeout) {
      expected.append("onError-");
    }
    if (dispatchUrl == null) {
      expected.append("onComplete-");
    } else {
      expected.append("NonAsyncServletGet-");
    }
    assertEquals(expected.toString(), res.toString());
  }
Esempio n. 18
0
 @Override
 public void stop() {
   if (embedded != null) {
     try {
       wrapper.deallocate(getServlet());
       embedded.stop();
       log.info("Stopped embedded Tomcat server");
     } catch (Exception e) {
       throw new AssertionError(e);
     }
   }
 }
  @Override
  public synchronized void start() throws Exception {

    Host host = ServerUtil.getDefaultHost().getHost();
    _serverContext = (StandardContext) host.findChild("/" + _contextName);
    if (_serverContext == null) {
      _serverContext = new StandardContext();
      _serverContext.setPath("/" + _contextName);
      File docBase = new File(SERVER_TEMP_DIR, _contextName);
      if (!docBase.exists()) {
        if (!docBase.mkdirs()) {
          throw new RuntimeException("Unable to create temp directory " + docBase.getPath());
        }
      }
      _serverContext.setDocBase(docBase.getPath());
      _serverContext.addLifecycleListener(new ContextConfig());

      final Loader loader = new WebCtxLoader(Thread.currentThread().getContextClassLoader());
      loader.setContainer(host);
      _serverContext.setLoader(loader);
      _serverContext.setInstanceManager(new LocalInstanceManager());

      Wrapper wrapper = _serverContext.createWrapper();
      wrapper.setName(SERVLET_NAME);
      wrapper.setServletClass(SwitchYardRemotingServlet.class.getName());
      wrapper.setLoadOnStartup(1);
      _serverContext.addChild(wrapper);
      _serverContext.addServletMapping("/*", SERVLET_NAME);

      host.addChild(_serverContext);
      _serverContext.create();
      _serverContext.start();

      SwitchYardRemotingServlet remotingServlet = (SwitchYardRemotingServlet) wrapper.getServlet();
      remotingServlet.setEndpointPublisher(this);
      _log.info("Published Remote Service Endpoint " + _serverContext.getPath());
    } else {
      throw new RuntimeException("Context " + _contextName + " already exists!");
    }
  }
Esempio n. 20
0
  /**
   * Static version of {@link #initWebappDefaults(String)}
   *
   * @param ctx The context to set the defaults for
   */
  public static void initWebappDefaults(Context ctx) {
    // Default servlet
    Wrapper servlet = addServlet(ctx, "default", "org.apache.catalina.servlets.DefaultServlet");
    servlet.setLoadOnStartup(1);
    servlet.setOverridable(true);

    // JSP servlet (by class name - to avoid loading all deps)
    servlet = addServlet(ctx, "jsp", "org.apache.jasper.servlet.JspServlet");
    servlet.addInitParameter("fork", "false");
    servlet.setLoadOnStartup(3);
    servlet.setOverridable(true);

    // Servlet mappings
    ctx.addServletMapping("/", "default");
    ctx.addServletMapping("*.jsp", "jsp");
    ctx.addServletMapping("*.jspx", "jsp");

    // Sessions
    ctx.setSessionTimeout(30);

    // MIME mappings
    for (int i = 0; i < DEFAULT_MIME_MAPPINGS.length; ) {
      ctx.addMimeMapping(DEFAULT_MIME_MAPPINGS[i++], DEFAULT_MIME_MAPPINGS[i++]);
    }

    // Welcome files
    ctx.addWelcomeFile("index.html");
    ctx.addWelcomeFile("index.htm");
    ctx.addWelcomeFile("index.jsp");
  }
Esempio n. 21
0
  @BeforeClass(alwaysRun = true)
  public void setUpGlobal() throws Exception {

    port1 = findFreePort();
    embedded = new Embedded();
    String path = new File(".").getAbsolutePath();
    embedded.setCatalinaHome(path);

    Engine engine = embedded.createEngine();
    engine.setDefaultHost("127.0.0.1");

    Host host = embedded.createHost("127.0.0.1", path);
    engine.addChild(host);

    Context c = embedded.createContext("/", path);
    c.setReloadable(false);
    Wrapper w = c.createWrapper();
    w.addMapping("/*");
    w.setServletClass(org.apache.catalina.servlets.WebdavServlet.class.getName());
    w.addInitParameter("readonly", "false");
    w.addInitParameter("listings", "true");

    w.setLoadOnStartup(0);

    c.addChild(w);
    host.addChild(c);

    Connector connector =
        embedded.createConnector("127.0.0.1", port1, Http11NioProtocol.class.getName());
    connector.setContainer(host);
    embedded.addEngine(engine);
    embedded.addConnector(connector);
    embedded.start();
  }
Esempio n. 22
0
 private void addDefaultServlet(Context context) {
   Wrapper defaultServlet = context.createWrapper();
   defaultServlet.setName("default");
   defaultServlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
   defaultServlet.addInitParameter("debug", "0");
   defaultServlet.addInitParameter("listings", "false");
   defaultServlet.setLoadOnStartup(1);
   // Otherwise the default location of a Spring DispatcherServlet cannot be set
   defaultServlet.setOverridable(true);
   context.addChild(defaultServlet);
   context.addServletMapping("/", "default");
 }
 public static List getApplicationServletMaps(Context context) {
   String[] sms = context.findServletMappings();
   List servletMaps = new ArrayList(sms.length);
   for (String servletMapping : sms) {
     if (servletMapping != null) {
       String sn = context.findServletMapping(servletMapping);
       if (sn != null) {
         ServletMapping sm = new ServletMapping();
         sm.setApplicationName(context.getName().length() > 0 ? context.getName() : "/");
         sm.setUrl(servletMapping);
         sm.setServletName(sn);
         Container container = context.findChild(sn);
         if (container instanceof Wrapper) {
           Wrapper wrapper = (Wrapper) container;
           sm.setServletClass(wrapper.getServletClass());
           sm.setAvailable(!wrapper.isUnavailable());
         }
         servletMaps.add(sm);
       }
     }
   }
   return servletMaps;
 }
  public void testBug50352() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // Must have a real docBase - just use temp
    File docBase = new File(System.getProperty("java.io.tmpdir"));

    Context ctx = tomcat.addContext("", docBase.getAbsolutePath());

    AsyncStartRunnable servlet = new AsyncStartRunnable();
    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/", "servlet");

    ErrorServlet error = new ErrorServlet();
    Tomcat.addServlet(ctx, "error", error);
    ctx.addServletMapping("/stage2", "error");

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");

    assertEquals("Runnable-onComplete-", res.toString());
  }
  @Override
  public void addServlet(final ServletModel model) {
    LOG.debug("add servlet [{}]", model);
    final Context context = findOrCreateContext(model.getContextModel());
    final String servletName = model.getName();
    // Wrapper wrapper = Tomcat.addServlet( context, servletName,
    // model.getServlet() );

    Wrapper sw = null;

    if (model.getServlet() == null) {
      // will do class for name and set init params
      sw = context.createWrapper();
    } else {
      sw =
          new ExistingStandardWrapper(model.getServlet()) {

            @Override
            protected void initInternal() throws LifecycleException {
              super.initInternal();
              try {
                super.loadServlet();
              } catch (final ServletException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              }
            }
          };
    }

    sw.setName(servletName);
    context.addChild(sw);

    addServletMappings(context, servletName, model.getUrlPatterns());
    addInitParameters(sw, model.getInitParams());
  }
 public void setWrapper(Wrapper wrapper) {
   if (wrapper != null) {
     host = (Host) wrapper.getParent().getParent();
     try {
       deployerOName =
           new ObjectName(host.getParent().getName() + ":type=Deployer,host=" + host.getName());
     } catch (MalformedObjectNameException e) {
       // do nothing here
     }
     host.getPipeline().addValve(valve);
     mBeanServer = Registry.getRegistry(null, null).getMBeanServer();
   } else if (host != null) {
     host.getPipeline().removeValve(valve);
   }
 }
Esempio n. 27
0
 private void addJspServlet(Context context) {
   Wrapper jspServlet = context.createWrapper();
   jspServlet.setName("jsp");
   jspServlet.setServletClass(getJspServlet().getClassName());
   jspServlet.addInitParameter("fork", "false");
   for (Entry<String, String> initParameter : getJspServlet().getInitParameters().entrySet()) {
     jspServlet.addInitParameter(initParameter.getKey(), initParameter.getValue());
   }
   jspServlet.setLoadOnStartup(3);
   context.addChild(jspServlet);
   context.addServletMapping("*.jsp", "jsp");
   context.addServletMapping("*.jspx", "jsp");
 }
  /**
   * Return <code>true</code> if the specified Principal has the specified security role, within the
   * context of this Realm; otherwise return <code>false</code>. This method can be overridden by
   * Realm implementations, but the default is adequate when an instance of <code>GenericPrincipal
   * </code> is used to represent authenticated Principals from this Realm.
   *
   * @param principal Principal for whom the role is to be checked
   * @param role Security role to be checked
   */
  @Override
  public boolean hasRole(Wrapper wrapper, Principal principal, String role) {
    // Check for a role alias defined in a <security-role-ref> element
    if (wrapper != null) {
      String realRole = wrapper.findSecurityReference(role);
      if (realRole != null) role = realRole;
    }

    // Should be overridden in JAASRealm - to avoid pretty inefficient conversions
    if ((principal == null) || (role == null) || !(principal instanceof GenericPrincipal))
      return (false);

    GenericPrincipal gp = (GenericPrincipal) principal;
    boolean result = gp.hasRole(role);
    if (log.isDebugEnabled()) {
      String name = principal.getName();
      if (result) log.debug(sm.getString("realmBase.hasRoleSuccess", name, role));
      else log.debug(sm.getString("realmBase.hasRoleFailure", name, role));
    }
    return (result);
  }
 private static ServletInfo getServletInfo(Wrapper wrapper, String contextName) {
   ServletInfo si = new ServletInfo();
   si.setApplicationName(contextName.length() > 0 ? contextName : "/");
   si.setServletName(wrapper.getName());
   si.setServletClass(wrapper.getServletClass());
   si.setAvailable(!wrapper.isUnavailable());
   si.setLoadOnStartup(wrapper.getLoadOnStartup());
   si.setRunAs(wrapper.getRunAs());
   si.getMappings().addAll(Arrays.asList(wrapper.findMappings()));
   if (wrapper instanceof StandardWrapper) {
     StandardWrapper sw = (StandardWrapper) wrapper;
     si.setAllocationCount(sw.getCountAllocated());
     si.setErrorCount(sw.getErrorCount());
     si.setLoadTime(sw.getLoadTime());
     si.setMaxInstances(sw.getMaxInstances());
     si.setMaxTime(sw.getMaxTime());
     si.setMinTime(sw.getMinTime() == Long.MAX_VALUE ? 0 : sw.getMinTime());
     si.setProcessingTime(sw.getProcessingTime());
     si.setRequestCount(sw.getRequestCount());
     si.setSingleThreaded(sw.isSingleThreadModel());
   }
   return si;
 }
Esempio n. 30
0
  public static void main(String[] args) {
    HttpConnector connector = new HttpConnector();
    Wrapper wrapper1 = new SimpleWrapper();
    wrapper1.setName("Primitive");
    wrapper1.setServletClass("PrimitiveServlet");
    Wrapper wrapper2 = new SimpleWrapper();
    wrapper2.setName("Modern");
    wrapper2.setServletClass("ModernServlet");

    Context context = new SimpleContext();
    context.addChild(wrapper1);
    context.addChild(wrapper2);

    Valve valve1 = new HeaderLoggerValve();
    Valve valve2 = new ClientIPLoggerValve();
    ((Pipeline) context).addValve(valve1);
    ((Pipeline) context).addValve(valve2);

    Mapper mapper = new SimpleContextMapper();
    mapper.setProtocol("http");
    context.addMapper(mapper);
    Loader loader = new SimpleLoader();
    context.setLoader(loader);

    context.addServletMapping("/Primitive", "Primitive");
    context.addServletMapping("/Modern", "Modern");
    connector.setContainer(context);

    try {
      connector.initialize();
      connector.start();
      System.in.read();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }