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);
        }
      }
    }
  }
Exemple #2
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;
  }
Exemple #3
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");
 }
Exemple #5
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");
 }
Exemple #6
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");
 }
  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();
    }
  }
  @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!");
    }
  }
  @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());
  }
Exemple #10
0
  public static void main(String[] args) {

    // invoke: http://localhost:8080/Modern or  http://localhost:8080/Primitive

    System.setProperty("catalina.base", System.getProperty("user.dir"));
    Connector 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 StandardContext();
    // StandardContext's start method adds a default mapper
    context.setPath("/myApp");
    context.setDocBase("myApp");
    LifecycleListener listener = new SimpleContextConfig();
    ((Lifecycle) context).addLifecycleListener(listener);

    context.addChild(wrapper1);
    context.addChild(wrapper2);
    // for simplicity, we don't add a valve, but you can add
    // valves to context or wrapper just as you did in Chapter 6

    Loader loader = new WebappLoader();
    context.setLoader(loader);
    // context.addServletMapping(pattern, name);
    context.addServletMapping("/Primitive", "Primitive");
    context.addServletMapping("/Modern", "Modern");
    // add ContextConfig. This listener is important because it configures
    // StandardContext (sets configured to true), otherwise StandardContext
    // won't start

    // add constraint
    SecurityCollection securityCollection = new SecurityCollection();
    securityCollection.addPattern("/");
    securityCollection.addMethod("GET");

    SecurityConstraint constraint = new SecurityConstraint();
    constraint.addCollection(securityCollection);
    constraint.addAuthRole("manager");
    LoginConfig loginConfig = new LoginConfig();
    loginConfig.setRealmName("Simple Realm");
    // add realm
    Realm realm = new SimpleRealm();

    context.setRealm(realm);
    context.addConstraint(constraint);
    context.setLoginConfig(loginConfig);

    connector.setContainer(context);

    try {
      connector.initialize();
      ((Lifecycle) connector).start();
      ((Lifecycle) context).start();

      // make the application wait until we press a key.
      System.in.read();
      ((Lifecycle) context).stop();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #11
0
  @Override
  public void start() {
    embedded = new Tomcat();
    AuthConfigFactory.setFactory(new AuthConfigFactoryImpl());

    Context context = embedded.addContext(getContextPath(), "/");
    context.addParameter("contextConfigLocation", getContextResource());
    context.addApplicationListener(ContextLoaderListener.class.getName());

    embedded.getHost().setAppBase("");

    // Each servlet should get an unique name, otherwise all servers will reuse
    // one and the same servlet instance.  Note that name clashes with servlets
    // created somewhere else are still possible.
    String servletName =
        getServletName() == null
            ? "ipf-servlet-" + SERVLET_COUNTER.getAndIncrement()
            : getServletName();

    wrapper = context.createWrapper();
    wrapper.setName(servletName);
    wrapper.setServletClass(getServlet().getClass().getName());

    for (Map.Entry<String, String> parameters : getInitParameters().entrySet()) {
      wrapper.addInitParameter(parameters.getKey(), parameters.getValue());
    }

    context.addChild(wrapper);
    context.addServletMapping(getServletPath(), servletName);

    /*
    VirtualWebappLoader loader = new VirtualWebappLoader(this.getClass().getClassLoader());
    loader.setVirtualClasspath(System.getProperty("java.class.path"));
    context.setLoader(loader);
    */
    Connector connector = embedded.getConnector();
    connector.setPort(getPort());
    if (isSecure()) {
      connector.setSecure(true);
      connector.setScheme("https");
      connector.setProperty("SSLEnabled", "true");
      connector.setProperty("sslProtocol", "TLS");
      connector.setProperty("keystoreFile", getKeystoreFile());
      connector.setProperty("keystorePass", getKeystorePass());
      connector.setProperty("truststoreFile", getTruststoreFile());
      connector.setProperty("truststorePass", getTruststorePass());
      if (getClientAuthType() == ClientAuthType.MUST) {
        connector.setProperty("clientAuth", "true");
      } else if (getClientAuthType() == ClientAuthType.WANT) {
        connector.setProperty("clientAuth", "want");
      }
    }

    try {
      embedded.start();
      wrapper.allocate();
      log.info("Started embedded Tomcat server");
    } catch (Exception e) {
      throw new AssertionError(e);
    }
  }
Exemple #12
0
  /**
   * Serve the specified request, creating the corresponding response. After the first time a
   * particular servlet class is requested, it will be served directly (like any registered servlet)
   * because it will have been registered and mapped in our associated Context.
   *
   * @param request The servlet request we are processing
   * @param response The servlet response we are creating
   * @exception IOException if an input/output error occurs
   * @exception ServletException if a servlet-specified error occurs
   */
  public void serveRequest(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    // Disallow calling this servlet via a named dispatcher
    if (request.getAttribute(Globals.NAMED_DISPATCHER_ATTR) != null)
      throw new ServletException(sm.getString("invokerServlet.notNamed"));

    // Identify the input parameters and our "included" state
    String inRequestURI = null;
    String inServletPath = null;
    String inPathInfo = null;
    boolean included = (request.getAttribute(Globals.REQUEST_URI_ATTR) != null);

    if (included) {
      inRequestURI = (String) request.getAttribute(Globals.REQUEST_URI_ATTR);
      inServletPath = (String) request.getAttribute(Globals.SERVLET_PATH_ATTR);
      inPathInfo = (String) request.getAttribute(Globals.PATH_INFO_ATTR);
    } else {
      inRequestURI = request.getRequestURI();
      inServletPath = request.getServletPath();
      inPathInfo = request.getPathInfo();
    }
    if (debug >= 1) {
      log("included='" + included + "', requestURI='" + inRequestURI + "'");
      log("  servletPath='" + inServletPath + "', pathInfo='" + inPathInfo + "'");
    }

    // Make sure a servlet name or class name was specified
    if (inPathInfo == null) {
      if (debug >= 1) log("Invalid pathInfo '" + inPathInfo + "'");
      if (included)
        throw new ServletException(sm.getString("invokerServlet.invalidPath", inRequestURI));
      else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, inRequestURI);
        return;
      }
    }

    // Identify the outgoing servlet name or class, and outgoing path info
    String pathInfo = inPathInfo;
    String servletClass = pathInfo.substring(1);
    int slash = servletClass.indexOf('/');
    //        if (debug >= 2)
    //            log("  Calculating with servletClass='" + servletClass +
    //                "', pathInfo='" + pathInfo + "', slash=" + slash);
    if (slash >= 0) {
      pathInfo = servletClass.substring(slash);
      servletClass = servletClass.substring(0, slash);
    } else {
      pathInfo = "";
    }

    if (servletClass.startsWith("org.apache.catalina")) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND, inRequestURI);
      return;
    }

    if (debug >= 1)
      log("Processing servlet '" + servletClass + "' with path info '" + pathInfo + "'");
    String name = "org.apache.catalina.INVOKER." + servletClass;
    String pattern = inServletPath + "/" + servletClass + "/*";
    Wrapper wrapper = null;

    // Synchronize to avoid race conditions when multiple requests
    // try to initialize the same servlet at the same time
    synchronized (this) {

      // Are we referencing an existing servlet class or name?
      wrapper = (Wrapper) context.findChild(servletClass);
      if (wrapper == null) wrapper = (Wrapper) context.findChild(name);
      if (wrapper != null) {
        if (debug >= 1)
          log(
              "Using wrapper for servlet '"
                  + wrapper.getName()
                  + "' with mapping '"
                  + pattern
                  + "'");
        context.addServletMapping(pattern, wrapper.getName());
      }

      // No, create a new wrapper for the specified servlet class
      else {

        if (debug >= 1)
          log("Creating wrapper for '" + servletClass + "' with mapping '" + pattern + "'");

        try {
          wrapper = context.createWrapper();
          wrapper.setName(name);
          wrapper.setLoadOnStartup(1);
          wrapper.setServletClass(servletClass);
          context.addChild(wrapper);
          context.addServletMapping(pattern, name);
        } catch (Throwable t) {
          log(sm.getString("invokerServlet.cannotCreate", inRequestURI), t);
          context.removeServletMapping(pattern);
          context.removeChild(wrapper);
          if (included)
            throw new ServletException(
                sm.getString("invokerServlet.cannotCreate", inRequestURI), t);
          else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, inRequestURI);
            return;
          }
        }
      }
    }

    // Create a request wrapper to pass on to the invoked servlet
    InvokerHttpRequest wrequest = new InvokerHttpRequest(request);
    wrequest.setRequestURI(inRequestURI);
    StringBuffer sb = new StringBuffer(inServletPath);
    sb.append("/");
    sb.append(servletClass);
    wrequest.setServletPath(sb.toString());
    if ((pathInfo == null) || (pathInfo.length() < 1)) {
      wrequest.setPathInfo(null);
      wrequest.setPathTranslated(null);
    } else {
      wrequest.setPathInfo(pathInfo);
      wrequest.setPathTranslated(getServletContext().getRealPath(pathInfo));
    }

    // Allocate a servlet instance to perform this request
    Servlet instance = null;
    try {
      //            if (debug >= 2)
      //                log("  Allocating servlet instance");
      instance = wrapper.allocate();
    } catch (ServletException e) {
      log(sm.getString("invokerServlet.allocate", inRequestURI), e);
      context.removeServletMapping(pattern);
      context.removeChild(wrapper);
      Throwable rootCause = e.getRootCause();
      if (rootCause == null) rootCause = e;
      if (rootCause instanceof ClassNotFoundException) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, inRequestURI);
        return;
      } else if (rootCause instanceof IOException) {
        throw (IOException) rootCause;
      } else if (rootCause instanceof RuntimeException) {
        throw (RuntimeException) rootCause;
      } else if (rootCause instanceof ServletException) {
        throw (ServletException) rootCause;
      } else {
        throw new ServletException(
            sm.getString("invokerServlet.allocate", inRequestURI), rootCause);
      }
    } catch (Throwable e) {
      log(sm.getString("invokerServlet.allocate", inRequestURI), e);
      context.removeServletMapping(pattern);
      context.removeChild(wrapper);
      throw new ServletException(sm.getString("invokerServlet.allocate", inRequestURI), e);
    }

    // After loading the wrapper, restore some of the fields when including
    if (included) {
      wrequest.setRequestURI(request.getRequestURI());
      wrequest.setPathInfo(request.getPathInfo());
      wrequest.setServletPath(request.getServletPath());
    }

    // Invoke the service() method of the allocated servlet
    try {
      String jspFile = wrapper.getJspFile();
      if (jspFile != null) request.setAttribute(Globals.JSP_FILE_ATTR, jspFile);
      else request.removeAttribute(Globals.JSP_FILE_ATTR);
      request.setAttribute(Globals.INVOKED_ATTR, request.getServletPath());
      //            if (debug >= 2)
      //                log("  Calling service() method, jspFile=" +
      //                    jspFile);
      instance.service(wrequest, response);
      request.removeAttribute(Globals.INVOKED_ATTR);
      request.removeAttribute(Globals.JSP_FILE_ATTR);
    } catch (IOException e) {
      //            if (debug >= 2)
      //                log("  service() method IOException", e);
      request.removeAttribute(Globals.INVOKED_ATTR);
      request.removeAttribute(Globals.JSP_FILE_ATTR);
      try {
        wrapper.deallocate(instance);
      } catch (Throwable f) {;
      }
      throw e;
    } catch (UnavailableException e) {
      //            if (debug >= 2)
      //                log("  service() method UnavailableException", e);
      context.removeServletMapping(pattern);
      request.removeAttribute(Globals.INVOKED_ATTR);
      request.removeAttribute(Globals.JSP_FILE_ATTR);
      try {
        wrapper.deallocate(instance);
      } catch (Throwable f) {;
      }
      throw e;
    } catch (ServletException e) {
      //            if (debug >= 2)
      //                log("  service() method ServletException", e);
      request.removeAttribute(Globals.INVOKED_ATTR);
      request.removeAttribute(Globals.JSP_FILE_ATTR);
      try {
        wrapper.deallocate(instance);
      } catch (Throwable f) {;
      }
      throw e;
    } catch (RuntimeException e) {
      //            if (debug >= 2)
      //                log("  service() method RuntimeException", e);
      request.removeAttribute(Globals.INVOKED_ATTR);
      request.removeAttribute(Globals.JSP_FILE_ATTR);
      try {
        wrapper.deallocate(instance);
      } catch (Throwable f) {;
      }
      throw e;
    } catch (Throwable e) {
      //            if (debug >= 2)
      //                log("  service() method Throwable", e);
      request.removeAttribute(Globals.INVOKED_ATTR);
      request.removeAttribute(Globals.JSP_FILE_ATTR);
      try {
        wrapper.deallocate(instance);
      } catch (Throwable f) {;
      }
      throw new ServletException("Invoker service() exception", e);
    }

    // Deallocate the allocated servlet instance
    try {
      //            if (debug >= 2)
      //                log("  deallocate servlet instance");
      wrapper.deallocate(instance);
    } catch (ServletException e) {
      log(sm.getString("invokerServlet.deallocate", inRequestURI), e);
      throw e;
    } catch (Throwable e) {
      log(sm.getString("invokerServlet.deallocate", inRequestURI), e);
      throw new ServletException(sm.getString("invokerServlet.deallocate", inRequestURI), e);
    }
  }
  public static void main(String[] args) {

    System.setProperty("catalina.base", System.getProperty("user.dir"));
    Connector connector = new HttpConnector();

    Wrapper wrapper1 = new StandardWrapper();
    wrapper1.setName("Primitive");
    wrapper1.setServletClass("PrimitiveServlet");
    Wrapper wrapper2 = new StandardWrapper();
    wrapper2.setName("Modern");
    wrapper2.setServletClass("ModernServlet");

    Context context = new StandardContext();
    // StandardContext's start method adds a default mapper
    context.setPath("/app1");
    context.setDocBase("app1");

    context.addChild(wrapper1);
    context.addChild(wrapper2);

    LifecycleListener listener = new SimpleContextConfig();
    ((Lifecycle) context).addLifecycleListener(listener);

    Host host = new StandardHost();
    host.addChild(context);
    host.setName("localhost");
    host.setAppBase("webapps");

    Loader loader = new WebappLoader();
    context.setLoader(loader);
    // context.addServletMapping(pattern, name);
    context.addServletMapping("/Primitive", "Primitive");
    context.addServletMapping("/Modern", "Modern");

    Engine engine = new StandardEngine();
    engine.addChild(host);
    engine.setDefaultHost("localhost");

    Service service = new StandardService();
    service.setName("Stand-alone Service");
    Server server = new StandardServer();
    server.addService(service);
    service.addConnector(connector);

    // StandardService class's setContainer will call all its connector's setContainer method
    service.setContainer(engine);

    // Start the new server
    if (server instanceof Lifecycle) {
      try {
        server.initialize();
        ((Lifecycle) server).start();
        server.await();
        // the program waits until the await method returns,
        // i.e. until a shutdown command is received.
      } catch (LifecycleException e) {
        e.printStackTrace(System.out);
      }
    }

    // Shut down the server
    if (server instanceof Lifecycle) {
      try {
        ((Lifecycle) server).stop();
      } catch (LifecycleException e) {
        e.printStackTrace(System.out);
      }
    }
  }