javax.servlet.annotation.WebServlet Java Examples

The following examples show how to use javax.servlet.annotation.WebServlet. 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
Source File: ThorntailWebAnnotationGenerator.java    From dekorate with Apache License 2.0 6 votes vote down vote up
@Override
default void add(Element element) {
  // JAX-RS
  ApplicationPath applicationPath = element.getAnnotation(ApplicationPath.class);
  if (applicationPath != null) {
    HashMap<String, Object> map = new HashMap<>();
    map.put(ApplicationPath.class.getName(), new HashMap<String, String>() {{
      put("value", applicationPath.value());
    }});
    addAnnotationConfiguration(map);
  }

  if (element.getAnnotation(Path.class) != null) {
    addAnnotationConfiguration(Collections.emptyMap());
  }

  // servlet
  if (element.getAnnotation(WebServlet.class) != null) {
    addAnnotationConfiguration(Collections.emptyMap());
  }
}
 
Example #2
Source File: WebServletInstaller.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
private void configure(final ServletEnvironment environment, final HttpServlet servlet,
                       final Class<? extends HttpServlet> type, final String name, final WebServlet annotation) {
    final ServletRegistration.Dynamic mapping = environment.addServlet(name, servlet);
    final Set<String> clash = mapping
            .addMapping(annotation.urlPatterns().length > 0 ? annotation.urlPatterns() : annotation.value());
    if (clash != null && !clash.isEmpty()) {
        final String msg = String.format(
                "Servlet registration %s clash with already installed servlets on paths: %s",
                type.getSimpleName(), Joiner.on(',').join(clash));
        if (option(DenyServletRegistrationWithClash)) {
            throw new IllegalStateException(msg);
        } else {
            logger.warn(msg);
        }
    }
    if (annotation.initParams().length > 0) {
        for (WebInitParam param : annotation.initParams()) {
            mapping.setInitParameter(param.name(), param.value());
        }
    }
    mapping.setAsyncSupported(annotation.asyncSupported());
}
 
Example #3
Source File: WebServletInstaller.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
@Override
public void install(final Environment environment, final HttpServlet instance) {
    final Class<? extends HttpServlet> extType = FeatureUtils.getInstanceClass(instance);
    final WebServlet annotation = FeatureUtils.getAnnotation(extType, WebServlet.class);
    final String[] patterns = annotation.urlPatterns().length > 0 ? annotation.urlPatterns() : annotation.value();
    Preconditions.checkArgument(patterns.length > 0,
            "Servlet %s not specified url pattern for mapping", extType.getName());
    final AdminContext context = FeatureUtils.getAnnotation(extType, AdminContext.class);
    final String name = WebUtils.getServletName(annotation, extType);
    reporter.line("%-25s %-8s %-4s %s   %s", Joiner.on(",").join(patterns),
            WebUtils.getAsyncMarker(annotation), WebUtils.getContextMarkers(context),
            RenderUtils.renderClassLine(extType), name);

    if (WebUtils.isForMain(context)) {
        configure(environment.servlets(), instance, extType, name, annotation);
    }
    if (WebUtils.isForAdmin(context)) {
        configure(environment.admin(), instance, extType, name, annotation);
    }
}
 
Example #4
Source File: ServerCmdlet.java    From HongsCORE with MIT License 5 votes vote down vote up
private void addServlet(ServletContextHandler context, Class clso, WebServlet anno) {
    ServletHolder hd = new ServletHolder(clso );
    hd.setName          (anno./****/name(    ));
    hd.setAsyncSupported(anno.asyncSupported());

    for(WebInitParam nv : anno.initParams ()) {
        hd.setInitParameter(nv.name( ), nv.value());
    }

    for(String       ur : anno.urlPatterns()) {
        context.addServlet(hd, ur/**/);
    }
}
 
Example #5
Source File: ServerCmdlet.java    From HongsCORE with MIT License 5 votes vote down vote up
@Override
public void init(ServletContextHandler context) {
    String pkgx  = CoreConfig.getInstance("defines"   )
                             .getProperty("apply.serv");
    if  (  pkgx != null ) {
        String[]   pkgs = pkgx.split(";");
        for(String pkgn : pkgs) {
            pkgn = pkgn.trim  ( );
            if  (  pkgn.length( ) == 0  ) {
                continue;
            }

            Set<String> clss = getClss(pkgn);
            for(String  clsn : clss) {
                Class   clso = getClso(clsn);

                WebFilter   wf = (WebFilter  ) clso.getAnnotation(WebFilter.class  );
                if (null != wf) {
                    addFilter  (context, clso, wf);
                }

                WebServlet  wb = (WebServlet ) clso.getAnnotation(WebServlet.class );
                if (null != wb) {
                    addServlet (context, clso, wb);
                }

                WebListener wl = (WebListener) clso.getAnnotation(WebListener.class);
                if (null != wl) {
                    addListener(context, clso, wl);
                }
            }
        }
    }
}
 
Example #6
Source File: FrontAndChats_IntegrationTest.java    From live-chat-engine with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void addServletWithMapping(ServletHandler sh, Class type){
	WebServlet annotation = (WebServlet)type.getAnnotation(WebServlet.class);
	String[] paths = annotation.value();
	for (String path : paths) {
		sh.addServletWithMapping(type, path);			
	}
}
 
Example #7
Source File: UndertowDeployerHelper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void addAnnotatedServlets(DeploymentInfo di, Archive<?> archive) {
    Map<ArchivePath, Node> classNodes = archive.getContent((ArchivePath path) -> {

        String stringPath = path.get();
        return (stringPath.startsWith("/WEB-INF/classes") && stringPath.endsWith("class"));

    });

    for (Map.Entry<ArchivePath, Node> entry : classNodes.entrySet()) {
        Node n = entry.getValue();
        if (n.getAsset() instanceof ClassAsset) {
            ClassAsset classAsset = (ClassAsset) n.getAsset();
            Class<?> clazz = classAsset.getSource();

            WebServlet annotation = clazz.getAnnotation(WebServlet.class);
            if (annotation != null) {
                ServletInfo undertowServlet = new ServletInfo(clazz.getSimpleName(), (Class<? extends Servlet>) clazz);

                String[] mappings = annotation.value();
                if (mappings != null) {
                    for (String urlPattern : mappings) {
                        undertowServlet.addMapping(urlPattern);
                    }
                }

                di.addServlet(undertowServlet);
            }
        }
    }

}
 
Example #8
Source File: StartWebServer.java    From hammock with Apache License 2.0 5 votes vote down vote up
private void procesServlets() {
    Consumer<Class<? extends HttpServlet>> c = servlet -> {
        WebServlet webServlet = ClassUtils.getAnnotation(servlet, WebServlet.class);
        if(webServlet != null) {
            ServletDescriptor servletDescriptor = new ServletDescriptor(webServlet.name(),
                    webServlet.value(), mapUrls(webServlet.urlPatterns()), webServlet.loadOnStartup(),
                    webServlet.initParams(),webServlet.asyncSupported(),servlet);
            webServer.addServlet(servletDescriptor);
        }
    };
    extension.processServlets(c);
}
 
Example #9
Source File: AnnotationScanInitializer.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Is this a web annotation.
 *
 * @param annotation the annotation.
 * @return true if it is, false otherwise.
 */
private boolean isWebAnnotation(Annotation annotation) {
    return annotation instanceof WebServlet
            || annotation instanceof WebListener
            || annotation instanceof WebInitParam
            || annotation instanceof WebFilter
            || annotation instanceof ServletSecurity
            || annotation instanceof MultipartConfig;
}
 
Example #10
Source File: Tomcat.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private static boolean hasAsync(Servlet existing) {
    boolean result = false;
    Class<?> clazz = existing.getClass();
    WebServlet ws = clazz.getAnnotation(WebServlet.class);
    if (ws != null) {
        result = ws.asyncSupported();
    }
    return result;
}
 
Example #11
Source File: WebServletPlugin.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private List<ServletDefinition> detectServlets(Collection<Class<?>> servletClasses) {
    List<ServletDefinition> servletDefinitions = new ArrayList<>();
    for (Class<?> candidate : servletClasses) {
        if (Servlet.class.isAssignableFrom(candidate)) {
            Class<? extends Servlet> servletClass = (Class<? extends Servlet>) candidate;
            WebServlet annotation = servletClass.getAnnotation(WebServlet.class);
            ServletDefinition servletDefinition = new ServletDefinition(
                    Strings.isNullOrEmpty(annotation.name()) ? servletClass.getCanonicalName() : annotation.name(),
                    servletClass
            );
            servletDefinition.setAsyncSupported(annotation.asyncSupported());
            if (annotation.value().length > 0) {
                servletDefinition.addMappings(annotation.value());
            }
            if (annotation.urlPatterns().length > 0) {
                servletDefinition.addMappings(annotation.urlPatterns());
            }
            servletDefinition.setLoadOnStartup(annotation.loadOnStartup());
            servletDefinition.addInitParameters(convert(annotation.initParams()));

            servletDefinitions.add(servletDefinition);
        }
    }

    return servletDefinitions;
}
 
Example #12
Source File: WebServletPlugin.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public Collection<ClasspathScanRequest> classpathScanRequests() {
    return classpathScanRequestBuilder()
            .annotationType(WebFilter.class)
            .annotationType(WebServlet.class)
            .annotationType(WebListener.class)
            .build();
}
 
Example #13
Source File: WebServletPlugin.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public InitState initialize(InitContext initContext) {
    if (servletContext != null) {
        listenerDefinitions.addAll(
                detectListeners(initContext.scannedClassesByAnnotationClass().get(WebListener.class)));
        filterDefinitions.addAll(detectFilters(initContext.scannedClassesByAnnotationClass().get(WebFilter.class)));
        servletDefinitions.addAll(
                detectServlets(initContext.scannedClassesByAnnotationClass().get(WebServlet.class)));
    }

    return InitState.INITIALIZED;
}
 
Example #14
Source File: WebContainerStartup.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void registerServlets(ServletHandler handler) {
  Class[] classes = new Class[]{RootUIServlet.class, UIIconServlet.class};

  for (Class aClass : classes) {
    Servlet servlet = (Servlet)ReflectionUtil.newInstance(aClass);

    ServletHolder servletHolder = new ServletHolder(servlet);

    WebServlet declaredAnnotation = (WebServlet)aClass.getDeclaredAnnotation(WebServlet.class);

    String[] urls = declaredAnnotation.urlPatterns();

    for (String url : urls) {
      handler.addServletWithMapping(servletHolder, url);
    }

    System.out.println(aClass.getName() + " registered to: " + Arrays.asList(urls));
  }
}
 
Example #15
Source File: WebServerExtension.java    From hammock with Apache License 2.0 4 votes vote down vote up
public void findServlets(@Observes @WithAnnotations({WebServlet.class})
                                  ProcessAnnotatedType<? extends HttpServlet> pat) {
    servlets.add(pat.getAnnotatedType().getJavaClass());
}
 
Example #16
Source File: WebServletInstaller.java    From dropwizard-guicey with MIT License 4 votes vote down vote up
@Override
public boolean matches(final Class<?> type) {
    return FeatureUtils.is(type, HttpServlet.class)
            && FeatureUtils.hasAnnotation(type, WebServlet.class);
}
 
Example #17
Source File: WebService.java    From HTTP-RPC with Apache License 2.0 4 votes vote down vote up
@Override
public void init() throws ServletException {
    root = new Resource();

    Method[] methods = getClass().getMethods();

    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];

        RequestMethod requestMethod = method.getAnnotation(RequestMethod.class);

        if (requestMethod != null) {
            Handler handler = new Handler(method);

            Resource resource = root;

            ResourcePath resourcePath = method.getAnnotation(ResourcePath.class);

            if (resourcePath != null) {
                String[] components = resourcePath.value().split("/");

                for (int j = 0; j < components.length; j++) {
                    String component = components[j];

                    if (component.length() == 0) {
                        continue;
                    }

                    if (component.startsWith(ResourcePath.PATH_VARIABLE_PREFIX)) {
                        int k = ResourcePath.PATH_VARIABLE_PREFIX.length();

                        String key;
                        if (component.length() > k) {
                            if (component.charAt(k++) != ':') {
                                throw new ServletException("Invalid path variable.");
                            }

                            key = component.substring(k);

                            component = ResourcePath.PATH_VARIABLE_PREFIX;
                        } else {
                            key = null;
                        }

                        handler.keys.add(key);
                    }

                    Resource child = resource.resources.get(component);

                    if (child == null) {
                        child = new Resource();

                        resource.resources.put(component, child);
                    }

                    resource = child;
                }
            }

            String verb = requestMethod.value().toLowerCase();

            LinkedList<Handler> handlerList = resource.handlerMap.get(verb);

            if (handlerList == null) {
                handlerList = new LinkedList<>();

                resource.handlerMap.put(verb, handlerList);
            }

            handlerList.add(handler);
        }
    }

    Class<? extends WebService> type = getClass();

    if (getClass().getAnnotation(WebServlet.class) != null) {
        services.put(type, this);
    }
}
 
Example #18
Source File: MeecrowaveContextConfig.java    From openwebbeans-meecrowave with Apache License 2.0 4 votes vote down vote up
@Override
protected void webConfig() {
    if (context.getServletContext().getAttribute("meecrowave.configuration") == null) { // redeploy
        context.getServletContext().setAttribute("meecrowave.configuration",
                Meecrowave.Builder.class.isInstance(configuration) ? configuration : new Meecrowave.Builder(configuration));
        context.addServletContainerInitializer(intializer, emptySet());
    }

    if (!configuration.isTomcatScanning()) {
        super.webConfig();
        return;
    }

    // eagerly start CDI to scan only once and not twice (tomcat+CDI)
    final ClassLoader loader = context.getLoader().getClassLoader(); // should already be started at that point
    final Thread thread = Thread.currentThread();
    final ClassLoader old = thread.getContextClassLoader();
    thread.setContextClassLoader(loader);
    try {
        final OWBTomcatWebScannerService scannerService = OWBTomcatWebScannerService.class.cast(WebBeansContext.getInstance().getScannerService());
        scannerService.setFilter(ofNullable(context.getJarScanner()).map(JarScanner::getJarScanFilter).orElse(null), context.getServletContext());
        scannerService.setDocBase(context.getDocBase());
        scannerService.setShared(configuration.getSharedLibraries());
        if (configuration.getWatcherBouncing() > 0) { // note that caching should be disabled with this config in most of the times
            watcher = new ReloadOnChangeController(context, configuration.getWatcherBouncing());
            scannerService.setFileVisitor(f -> watcher.register(f));
        }
        scannerService.scan();
        finder = scannerService.getFinder();
        finder.link();
        final CdiArchive archive = CdiArchive.class.cast(finder.getArchive());
        Stream.of(WebServlet.class, WebFilter.class, WebListener.class)
                .forEach(marker -> finder.findAnnotatedClasses(marker).stream()
                        .filter(c -> !Modifier.isAbstract(c.getModifiers()) && Modifier.isPublic(c.getModifiers()))
                        .forEach(webComponent -> webClasses.computeIfAbsent(
                                archive.classesByUrl().entrySet().stream()
                                        .filter(e -> e.getValue().getClassNames().contains(webComponent.getName()))
                                        .findFirst().get().getKey(), k -> new HashSet<>())
                                .add(webComponent)));
    } finally {
        thread.setContextClassLoader(old);
    }
    try {
        super.webConfig();
    } finally {
        webClasses.clear();
        finder = null;
    }
}
 
Example #19
Source File: WebUtils.java    From dropwizard-guicey with MIT License 2 votes vote down vote up
/**
 * @param annotation servlet registration annotation
 * @return "async" string if servlet support async and empty string otherwise
 */
public static String getAsyncMarker(final WebServlet annotation) {
    return getAsyncMarker(annotation.asyncSupported());
}
 
Example #20
Source File: WebUtils.java    From dropwizard-guicey with MIT License 2 votes vote down vote up
/**
 * @param servlet servlet annotation
 * @param type    servlet type
 * @return servlet name or generated name if name not provided
 */
public static String getServletName(final WebServlet servlet, final Class<? extends HttpServlet> type) {
    final String name = Strings.emptyToNull(servlet.name());
    return name != null ? name : generateName(type, "servlet");
}