Java Code Examples for javax.servlet.ServletContext#getServletRegistrations()

The following examples show how to use javax.servlet.ServletContext#getServletRegistrations() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void testSaveUrlPrefixNormal(@Mocked ServletContext servletContext,
    @Mocked ServletRegistration servletRegistration) {
  ClassLoaderScopeContext.clearClassLoaderScopeProperty();
  new Expectations() {
    {
      servletContext.getContextPath();
      result = "/root";
      servletRegistration.getClassName();
      result = RestServlet.class.getName();
      servletRegistration.getMappings();
      result = Arrays.asList("/rest/*");
      servletContext.getServletRegistrations();
      result = Collections.singletonMap("test", servletRegistration);
    }
  };

  ServletUtils.saveUrlPrefix(servletContext);

  Assert.assertThat(ClassLoaderScopeContext.getClassLoaderScopeProperty(DefinitionConst.URL_PREFIX),
      Matchers.is("/root/rest"));
  ClassLoaderScopeContext.clearClassLoaderScopeProperty();
}
 
Example 2
Source Project: flow   File: JSR356WebsocketInitializer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Initializes Atmosphere for use with Vaadin servlets found in the given
 * context.
 * <p>
 * For JSR 356 websockets to work properly, the initialization must be done
 * in the servlet context initialization phase.
 *
 * @param servletContext
 *            The servlet context
 */
public void init(ServletContext servletContext) {
    if (!atmosphereAvailable) {
        return;
    }
    getLogger().debug("Atmosphere available, initializing");

    Map<String, ? extends ServletRegistration> regs = servletContext
            .getServletRegistrations();
    for (Entry<String, ? extends ServletRegistration> entry : regs
            .entrySet()) {
        String servletName = entry.getKey();
        ServletRegistration servletRegistration = entry.getValue();

        getLogger().debug("Checking if {} is a Vaadin Servlet",
                servletRegistration.getName());

        if (isVaadinServlet(servletRegistration, servletContext)) {
            try {
                initAtmosphereForVaadinServlet(servletRegistration,
                        servletContext);
            } catch (Exception e) {
                getLogger().warn("Failed to initialize Atmosphere for {}",
                        servletName, e);
            }
        }
    }
}
 
Example 3
Source Project: tomee   File: TomEEWebConfigProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<ServletMapping> getFacesServletMappings(final ExternalContext externalContext) {
    final List<ServletMapping> facesServletMappings = super.getFacesServletMappings(externalContext);
    try { // getContext() is a runtime object where getServletRegistrations() is forbidden so unwrap
        final ServletContext sc = ServletContext.class.cast(Reflections.get(externalContext.getContext(), "sc"));
        if (sc != null && sc.getServletRegistrations() != null) {
            for (final Map.Entry<String, ? extends ServletRegistration> reg : sc.getServletRegistrations().entrySet()) {
                final ServletRegistration value = reg.getValue();
                if ("javax.faces.webapp.FacesServlet".equals(value.getClassName())) {
                    for (final String mapping : value.getMappings()) {
                        final Class<?> clazz = sc.getClassLoader().loadClass(value.getClassName());
                        final org.apache.myfaces.shared_impl.webapp.webxml.ServletMapping mappingImpl =
                                new org.apache.myfaces.shared_impl.webapp.webxml.ServletMapping(
                                    value.getName(), clazz, mapping);
                        facesServletMappings.add(new ServletMappingImpl(mappingImpl));
                    }
                }
            }
        } else {
            facesServletMappings.addAll(super.getFacesServletMappings(externalContext));
        }
    } catch (final Exception e) { // don't fail cause our cast failed
        facesServletMappings.clear();
        facesServletMappings.addAll(super.getFacesServletMappings(externalContext));
    }
    return facesServletMappings;
}
 
Example 4
public void init(@Observes @Initialized(ApplicationScoped.class) final ServletContext context) {
    final Map<String, ? extends ServletRegistration> servletRegistrations = context.getServletRegistrations();
    servletRegistrations.forEach((servletName, servletRegistration) -> {
        try {
            final Class<?> servletClass = Thread.currentThread().getContextClassLoader().loadClass(servletName);
            if (servletClass.isAnnotationPresent(BasicAuthenticationMechanismDefinition.class)) {
                servletAuthenticationMapper.put(servletName,
                                                CDI.current().select(BasicAuthenticationMechanism.class).get());
            }

            if (servletClass.isAnnotationPresent(FormAuthenticationMechanismDefinition.class)) {
                servletAuthenticationMapper.put(servletName,
                                                CDI.current().select(FormAuthenticationMechanism.class).get());
            }

        } catch (final ClassNotFoundException e) {
            // Ignore
        }
    });

    final Set<HttpAuthenticationMechanism> availableBeans =
            authenticationMechanisms.stream().collect(Collectors.toSet());
    availableBeans.removeAll(servletAuthenticationMapper.values());
    availableBeans.remove(defaultAuthenticationMechanism);

    if (availableBeans.size() == 1) {
        defaultAuthenticationMechanism.setDelegate(availableBeans.iterator().next());
    } else if (availableBeans.size() > 1) {
        throw new IllegalStateException(
                "Multiple HttpAuthenticationMechanism found " +
                availableBeans.stream()
                              .map(b -> substringBefore(b.getClass().getSimpleName(), "$$"))
                              .collect(toList()) + " " +
                "without a @WebServlet association. " +
                "Deploy a single one for the application, or associate it with a @WebServlet.");
    }
}
 
Example 5
@Test
public void setServletParameters_supportUpload(@Mocked ServletContext servletContext, @Mocked Dynamic d1,
    @Mocked ServletRegistration d2) throws IOException {
  Map<String, ServletRegistration> servletRegistrations = new HashMap<>();
  servletRegistrations.put("d1", d1);
  servletRegistrations.put("d2", d2);
  new Expectations() {
    {
      servletContext.getServletRegistrations();
      result = servletRegistrations;
      d1.getClassName();
      result = RestServlet.class.getName();
      d2.getClassName();
      result = HttpServlet.class.getName();
    }
  };

  List<MultipartConfigElement> multipartConfigs = new ArrayList<>();
  new MockUp<Dynamic>(d1) {
    @Mock
    void setMultipartConfig(MultipartConfigElement multipartConfig) {
      multipartConfigs.add(multipartConfig);
    }
  };

  File tempDir = Files.createTempDirectory("temp").toFile();
  File uploadDir = new File(tempDir, "upload");
  ArchaiusUtils.setProperty(RestConst.UPLOAD_DIR, uploadDir.getAbsolutePath());

  ServletUtils.setServletParameters(servletContext);

  Assert.assertEquals(1, multipartConfigs.size());

  MultipartConfigElement multipartConfigElement = multipartConfigs.get(0);
  Assert.assertEquals(uploadDir.getAbsolutePath(), multipartConfigElement.getLocation());
  Assert.assertEquals(-1, multipartConfigElement.getMaxFileSize());
  Assert.assertEquals(-1, multipartConfigElement.getMaxRequestSize());
  Assert.assertEquals(0, multipartConfigElement.getFileSizeThreshold());

  uploadDir.delete();
  tempDir.delete();
  Assert.assertFalse(tempDir.exists());
}