Exemple #1
0
 @Override
 public void init(ServletConfig config) throws ServletException {
   HelperLoader.init();
   ServletContext servletContext = config.getServletContext();
   ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
   jspServlet.addMapping(ConfigHelper.getAppJspPath() + "*");
   ServletRegistration defaultServlet = servletContext.getServletRegistration("default");
   defaultServlet.addMapping(ConfigHelper.getAppAssetPath() + "*");
 }
 @Override
 public void init(ServletConfig servletConfig) throws ServletException {
   // 初始化 Helper 类
   HelperLoader.init();
   // 获取 ServletContext 对象(用于注册Servlet)
   ServletContext servletContext = servletConfig.getServletContext();
   // 注册处理 JSP 的 Servlet
   ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
   jspServlet.addMapping(ConfigHelper.getAppJspPath() + "*");
   // 注册处理静态资源的默认 Servlet
   ServletRegistration defaultServlet = servletContext.getServletRegistration("default");
   defaultServlet.addMapping(ConfigHelper.getAppAssetPath() + "*");
 }
 private List<EndpointInfo> getConsolidatedEndpoints(
     ServletContext context,
     List<EndpointInfo> ddEndpointList,
     Set<Class<?>> wsClassSet,
     List<Source> metadata) {
   List<EndpointInfo> consList = new ArrayList<>();
   for (Class<?> c : wsClassSet) {
     EndpointInfo endpointInfo = findEndpointInfo(ddEndpointList, c);
     endpointInfo.implType = c;
     if (endpointInfo.servletLink == null) {
       endpointInfo.servletLink = getDefaultServletLink(c);
     }
     ServletRegistration reg = context.getServletRegistration(endpointInfo.servletLink);
     if (reg != null) {
       Collection<String> mappings = reg.getMappings();
       if (mappings.isEmpty()) {
         endpointInfo.urlPattern = getDefaultUrlPattern(c);
       } else {
         endpointInfo.urlPattern = mappings.iterator().next();
       }
     } else {
       endpointInfo.urlPattern = getDefaultUrlPattern(c);
     }
     endpointInfo.features = new WebServiceFeature[0];
     endpointInfo.metadata = metadata;
     consList.add(endpointInfo);
   }
   return consList;
 }
  public void onStartup(Set<Class<?>> wsClassSet, ServletContext context) throws ServletException {
    LOGGER.info("WAR has webservice classes: " + wsClassSet);

    // TODO Check if metadata-complete is true in web.xml

    // Get the WSDL and schema documents in /WEB-INF/wsdl dir
    List<Source> metadata = new ArrayList<>();
    try {
      Set<URL> docs = new HashSet<>();
      collectDocs(docs, new ServletResourceLoader(context), JAXWS_WSDL_DD_DIR);
      for (URL url : docs) {
        Source source = new StreamSource(url.openStream(), url.toExternalForm());
        metadata.add(source);
      }
    } catch (IOException me) {
      throw new ServletException(me);
    }

    // Parse /WEB-INF/webservices.xml DD
    List<EndpointInfo> ddEndpointList = parseDD(context);

    // Consolidate endpoints from DD and annotations
    List<EndpointInfo> endpointInfoList =
        getConsolidatedEndpoints(context, ddEndpointList, wsClassSet, metadata);
    if (endpointInfoList.isEmpty()) {
      return; // No web service endpoints
    }

    EndpointAdapterFactory factory = new EndpointAdapterFactory();

    List<EndpointAdapter> adapters = new ArrayList<>();

    for (EndpointInfo endpointInfo : endpointInfoList) {
      ServletRegistration reg = context.getServletRegistration(endpointInfo.servletLink);
      if (reg == null) {
        reg = context.addServlet(endpointInfo.servletLink, WSServlet.class);
      } else {
        // NEED the following in servlet API to override <servlet-class>
        // reg.setClassName(endpointInfo.implType);
      }
      Collection<String> mappings = reg.getMappings();
      if (!mappings.contains(endpointInfo.urlPattern)) {
        reg.addMapping(endpointInfo.urlPattern);
      }
      EndpointAdapter adapter = factory.createAdapter(endpointInfo);
      adapters.add(adapter);
    }

    for (EndpointAdapter adapter : adapters) {
      adapter.publish();
    }

    context.setAttribute(WSServlet.JAXWS_RI_RUNTIME_INFO, adapters);
  }
  @Override
  public void onStartup(ServletContext container) throws ServletException {
    container.getServletRegistration("default").addMapping("/resources/*");

    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(RootContextConfiguration.class);
    container.addListener(new ContextLoaderListener(rootContext));

    AnnotationConfigWebApplicationContext servletContext =
        new AnnotationConfigWebApplicationContext();
    servletContext.register(ServletContextConfiguration.class);
    ServletRegistration.Dynamic dispatcher =
        container.addServlet("springDispatcher", new DispatcherServlet(servletContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
  }
 @Override
 public ServletRegistration getServletRegistration(String s) {
   return proxy.getServletRegistration(s);
 }
 @Override
 public ServletRegistration getServletRegistration(String servletName) {
   return sc.getServletRegistration(servletName);
 }
 public ServletRegistration getServletRegistration(String arg0) {
   return servletContext.getServletRegistration(arg0);
 }
  /**
   * Configures the {@link OfficeFloorServlet} implementation into the {@link ServletContext}.
   *
   * <p>This is expected to be called from a {@link ServletContextListener} as it will configure an
   * instance of the {@link OfficeFloorServlet} with appropriate URI mapping.
   *
   * @param servletInitiateInstance Implementing instance of the {@link OfficeFloorServlet}. This
   *     instance is only used used for registration and configuration. Its {@link Class} however is
   *     registered so that a new instance is instantiated and allows injection of necessary
   *     resources to occur.
   * @param servletContext {@link ServletContext}.
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  public static synchronized void configure(
      OfficeFloorServlet servletInitiateInstance, final ServletContext servletContext) {

    // Wirer to specify process scoping
    final ManagedObjectSourceWirer processScopeWirer =
        new ManagedObjectSourceWirer() {
          @Override
          public void wire(ManagedObjectSourceWirerContext context) {
            context.setManagedObjectScope(ManagedObjectScope.PROCESS);
          }
        };

    // Obtain the Servlet name
    String servletName = servletInitiateInstance.getServletName();

    // Obtain the implementing class of the OfficeFloorServlet
    Class servletClass = servletInitiateInstance.getClass();

    // Determine if Servlet already registered for name
    if (servletContext.getServletRegistration(servletName) != null) {
      // Not register as already registered
      servletContext.log(
          "Not registering "
              + OfficeFloorServlet.class.getSimpleName()
              + " "
              + servletName
              + " ("
              + servletClass.getName()
              + ") as "
              + Servlet.class.getSimpleName()
              + " already registered under name");
      return;
    }

    // Create the instance of the application
    ServletWebAutoWireApplication<?> source = new ServletWebAutoWireApplication();

    // Create the bridger for the Servlet container
    source.bridger =
        ServletBridgeManagedObjectSource.createServletServiceBridger(
            servletClass, source, HANDLER_SECTION_NAME, HANDLER_INPUT_NAME);

    // Provide default suffix for link mapping
    String templateUriSuffix = servletInitiateInstance.getTemplateUriSuffix();
    if (templateUriSuffix == null) {
      servletContext.log(
          "Failed to configure "
              + servletClass.getName()
              + " as it does not provide a template URI suffix. It will not be available.");
      return;
    }
    if (!(templateUriSuffix.startsWith("."))) {
      templateUriSuffix = "." + templateUriSuffix;
    }
    source.setDefaultHttpTemplateUriSuffix(templateUriSuffix);

    // Allow loading template content from ServletContext.
    // (Allows integration into the WAR structure)
    OfficeFloorCompiler compiler = source.getOfficeFloorCompiler();
    compiler.addResources(
        new ResourceSource() {
          @Override
          public InputStream sourceResource(String location) {

            // Ensure location is always absolute
            location = (location.startsWith("/") ? location : "/" + location);

            // Attempt to obtain resource
            InputStream resource = servletContext.getResourceAsStream(location);

            // Return resource (if obtained)
            return resource;
          }
        });

    // Configure Server HTTP connection
    source.addManagedObject(
        ServletServerHttpConnectionManagedObjectSource.class.getName(),
        processScopeWirer,
        new AutoWire(ServerHttpConnection.class));

    // Configure the HTTP session
    source.addManagedObject(
        ServletHttpSessionManagedObjectSource.class.getName(),
        processScopeWirer,
        new AutoWire(HttpSession.class));

    // Configure the HTTP Application and Request State
    source.addManagedObject(
        ServletHttpApplicationStateManagedObjectSource.class.getName(),
        processScopeWirer,
        new AutoWire(HttpApplicationState.class));
    source.addManagedObject(
        ServletHttpRequestStateManagedObjectSource.class.getName(),
        processScopeWirer,
        new AutoWire(HttpRequestState.class));

    // Provide dependencies of Servlet
    Class<?>[] dependencyTypes = source.bridger.getObjectTypes();
    for (Class<?> dependencyType : dependencyTypes) {
      // Add Servlet dependency for dependency injection
      AutoWireObject dependency =
          source.addManagedObject(
              ServletDependencyManagedObjectSource.class.getName(),
              processScopeWirer,
              new AutoWire(dependencyType));
      dependency.addProperty(
          ServletDependencyManagedObjectSource.PROPERTY_TYPE_NAME, dependencyType.getName());
    }

    // Process Context Team to ensure appropriate Thread for dependencies
    // (EJB's typically rely on ThreadLocal functionality)
    if (dependencyTypes.length > 0) {

      // Create the auto-wiring for dependency types
      AutoWire[] autoWiring = new AutoWire[dependencyTypes.length];
      for (int i = 0; i < autoWiring.length; i++) {
        autoWiring[i] = new AutoWire(dependencyTypes[i]);
      }

      // Assign the team
      source.assignTeam(ProcessContextTeamSource.class.getName(), autoWiring);
    }

    // Configure the context path
    String contextPath = servletContext.getContextPath();
    compiler.addProperty(
        HttpApplicationLocationManagedObjectSource.PROPERTY_CONTEXT_PATH, contextPath);

    // Configure the web application
    try {
      boolean isConfigure = servletInitiateInstance.configure(source, servletContext);
      if (!isConfigure) {
        // Flagged not to configure
        return;
      }
    } catch (Exception ex) {
      // Indicate failure and not configured
      servletContext.log(
          "Failed to configure " + servletClass.getName() + ". It will not be available.", ex);
      return; // not configure
    }

    // Configure the Servlet container resource section
    AutoWireSection servletContainerResource =
        source.addSection(
            "SERVLET_CONTAINER_RESOURCE",
            ServletContainerResourceSectionSource.class.getName(),
            "NOT_HANDLED");
    source.chainServicer(servletContainerResource, "NOT_HANDLED", null);

    // Link the Servlet Resources
    for (ServletResourceLink link : source.servletResourceLinks) {
      servletContainerResource.addProperty(link.requestDispatcherPath, link.requestDispatcherPath);
      source.link(
          link.section, link.outputName, servletContainerResource, link.requestDispatcherPath);
    }

    // Link the escalation handling by Servlet Resources
    for (ServletResourceEscalation handling : source.servletResourceEscalations) {
      servletContainerResource.addProperty(
          handling.requestDispatcherPath, handling.requestDispatcherPath);
      source.linkEscalation(
          handling.escalationType, servletContainerResource, handling.requestDispatcherPath);
    }

    // Register the source (for initiation into an application)
    int applicationIndex;
    synchronized (registeredApplications) {

      // Obtain the index for the application
      applicationIndex = nextApplicationIndex++;

      // Register the application
      registeredApplications.put(Integer.valueOf(applicationIndex), source);
    }

    // Load the handled URIs (being absolute to domain)
    // (+1 to handle link mappings)
    String[] rawUris = source.getURIs();
    String[] mappedUris = new String[rawUris.length + 1];
    for (int i = 0; i < rawUris.length; i++) {

      // Obtain the URI
      String uri = rawUris[i];
      uri = (uri.startsWith("/") ? uri : "/" + uri);

      // Provide mapping of URIs
      mappedUris[i] = uri;

      // Prefix with context for handling
      if ((contextPath != null) && (!("/".equals(contextPath)))) {
        uri = contextPath + uri;
      }
    }

    // Include link mapping
    mappedUris[mappedUris.length - 1] = "*" + templateUriSuffix;

    // Provide Servlet and its configuration
    Dynamic servlet = servletContext.addServlet(servletName, servletClass);
    servlet.setAsyncSupported(true);
    servlet.setInitParameter(INIT_PROPERTY_APPLICATION_INDEX, String.valueOf(applicationIndex));
    servlet.addMapping(mappedUris);
    servlet.setLoadOnStartup(1);

    // Provide Filter to override DefaultServlet of Server
    javax.servlet.FilterRegistration.Dynamic filter =
        servletContext.addFilter(servletName, servletClass);
    filter.setAsyncSupported(true);
    filter.setInitParameter(INIT_PROPERTY_APPLICATION_INDEX, String.valueOf(applicationIndex));
    filter.addMappingForUrlPatterns(null, false, mappedUris);

    // Log that configured so that know if occurred
    StringBuilder logMessage = new StringBuilder();
    logMessage.append(
        servletName + " Servlet/Filter (" + servletClass.getName() + ") loaded to service ");
    boolean isFirst = true;
    for (String mappedUri : mappedUris) {
      if (!isFirst) {
        logMessage.append(", ");
      }
      isFirst = false;
      logMessage.append(mappedUri);
    }
    servletContext.log(logMessage.toString());
  }