public MappedServlet toMappedServlet(Servlet servlet) { WebServlet wsAnnotation = servlet.getClass().getAnnotation(WebServlet.class); if (wsAnnotation == null) { throw new IllegalArgumentException( "Servlet contains no @WebServlet annotation and can not be mapped directly. Wrap it in a MappedServlet instead."); } String name = wsAnnotation.name() != null && wsAnnotation.name().length() > 0 ? wsAnnotation.name() : null; Set<String> urlPatterns = new HashSet<>(asList(wsAnnotation.urlPatterns())); Map<String, String> initParams = new HashMap<>(); WebInitParam[] paramsArray = wsAnnotation.initParams(); if (paramsArray != null) { asList(paramsArray).forEach(p -> initParams.put(p.name(), p.value())); } return new MappedServlet(servlet, urlPatterns, name, initParams); }
private void registerJeeComponents(ConfigurableListableBeanFactory beanFactory, ClassLoader cl, Set<BeanDefinition> candiates) { for (BeanDefinition bd : candiates) { try { Class<?> beanClass = ClassUtils.forName(bd.getBeanClassName(), cl); WebServlet webServlet = beanClass.getDeclaredAnnotation(WebServlet.class); WebFilter webFilter = beanClass.getDeclaredAnnotation(WebFilter.class); WebListener webListener = beanClass.getDeclaredAnnotation(WebListener.class); DefaultListableBeanFactory targetBeanFactory = (DefaultListableBeanFactory) beanFactory; if (webServlet != null) { createAndRegisterServletBean(targetBeanFactory, bd, beanClass, webServlet); } else if (webFilter != null) { createAndRegisterServletFilterBean(targetBeanFactory, bd, beanClass, webFilter); } else if (webListener != null) { createAndRegisterWebListenerBean(targetBeanFactory, bd, beanClass, webListener); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
public String getBasePath() { WebServlet webServlet = this.servlet.getClass().getAnnotation(WebServlet.class); String path = null; if (webServlet.value().length > 0 ) { path = webServlet.value()[0]; } if(webServlet.urlPatterns().length>0){ path = webServlet.urlPatterns()[0]; } if(null == path) { return null; } if (!path.endsWith("/*")) { return ""; } else { return path.substring(0, path.length() - 2); } }
@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("%-15s %-5s %-2s (%s) %s", Joiner.on(",").join(patterns), WebUtils.getAsyncMarker(annotation), WebUtils.getContextMarkers(context), extType.getName(), name); if (WebUtils.isForMain(context)) { configure(environment.servlets(), instance, extType, name, annotation); } if (WebUtils.isForAdmin(context)) { configure(environment.admin(), instance, extType, name, annotation); } }
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()); }
protected void printServletInfo() { Class<?> clazz = this.getClass(); WebServlet servlet = clazz.getAnnotation(WebServlet.class); if (servlet == null) { return; } String name = servlet.name(); String uri = StringUtils.arrayToDelimitedString(servlet.urlPatterns(), ","); System.err.println("WebServlet name:" + name + "\turi:" + uri + "\tclass:" + clazz.getName()); }
private List<Class<?>> findServletTypes() { ReflectionsHelper.registerUrlTypes(); Reflections reflections = new Reflections(scanPkgNames.toArray()); Set<Class<?>> types = reflections.getTypesAnnotatedWith(WebServlet.class); List<Class<?>> result = new ArrayList<>(); for(Class<?> type : types) { if(Servlet.class.isAssignableFrom(type)) { result.add(type); } } return result; }
@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); } }
private void createAndRegisterServletBean(DefaultListableBeanFactory defaultListeableBeanFactory, BeanDefinition bd, Class<?> beanClass, WebServlet webServlet) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ServletRegistrationBean.class); builder.addPropertyValue("servlet", bd); builder.addPropertyValue("urlMappings", new LinkedHashSet<>(Arrays.asList(webServlet.urlPatterns()))); String beanName = webServlet.name().isEmpty() ? StringUtils.uncapitalize(beanClass.getSimpleName()) : webServlet .name(); defaultListeableBeanFactory.registerBeanDefinition(beanName, builder.getBeanDefinition()); }
@EvoSuiteAssertionOnly @Override public boolean isAsyncSupported() { Servlet sut = EvoServletState.getServlet(); WebServlet annotation = sut.getClass().getAnnotation(WebServlet.class); if(annotation == null){ return false; //TODO: unsure if really correct. need more investigation } return annotation.asyncSupported(); }
private String addServlet(Servlet servlet) { Class<?> clz = servlet.getClass(); WebServlet ann = clz.getAnnotation(WebServlet.class); if (ann == null) { return null; } String name = ann.name(); DynamicSRegistration reg = addServlet(name, servlet); if (reg == null) { return null; } doParameters(reg, ann.initParams()); reg.addMapping(ann.urlPatterns()); return name; }
@PostConstruct public void init() { logger.info("Starting undertow w/ resteasy support."); WebServlet resteasyServlet = new WebServletLiteral("RestEasy",new String[]{"/"}, new WebInitParam[]{},true,1); Map<String,Object> servletContextParams = new HashMap<>(); servletContextParams.put(ResteasyDeployment.class.getName(), createDeployment()); undertowComponent = new UndertowComponent(httpListenPort,httpListenAddress,contextRoot,deploymentName) .addServlet(resteasyServlet,HttpServlet30Dispatcher.class) .setWebSocketEndpoint(CourseServer.class) .addListener(RequestScopedServletRequestListener.class) .start(servletContextParams); logger.info("Container up and running on port "+httpListenPort); }
public void startUndertow(@Observes ApplicationStartupEvent applicationStartupEvent) { WebServlet resteasyServlet = new WebServletLiteral("RestEasy",new String[]{"/"}, new WebInitParam[]{},true,1); Map<String,Object> servletContextParams = new HashMap<>(); servletContextParams.put(ResteasyDeployment.class.getName(), createDeployment()); undertowComponent = new UndertowComponent(undertowBindPort,undertowBindAddress,contextRoot,deploymentName) .addServlet(resteasyServlet,HttpServlet30Dispatcher.class) .addListener(RequestScopedServletRequestListener.class) .start(servletContextParams); }
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); }
WebServletHandler() { super(WebServlet.class); }
@Override public boolean matches(final Class<?> type) { return FeatureUtils.is(type, HttpServlet.class) && FeatureUtils.hasAnnotation(type, WebServlet.class); }
public UndertowComponent addServlet(WebServlet webServlet, Class<? extends Servlet> clazz) { servlets.put(webServlet,clazz); return this; }
public void startUndertow(@Observes ApplicationStartupEvent applicationStartupEvent) { WebServlet webServlet = GreeterServlet.class.getAnnotation(WebServlet.class); undertowComponent = new UndertowComponent(undertowBindPort,undertowBindAddress,contextRoot,deploymentName) .addServlet(webServlet,GreeterServlet.class).start(); }
public void findServlets(@Observes @WithAnnotations({WebServlet.class}) ProcessAnnotatedType<? extends HttpServlet> pat) { servlets.add(pat.getAnnotatedType().getJavaClass()); }
@Override public void run() { try { Server jettyServer = new Server(HTTP_SERVER_PORT); ContextHandlerCollection contexts = new ContextHandlerCollection(); jettyServer.setHandler(contexts); ServletContextHandler ctxRest = new ServletContextHandler(contexts, "/rest", ServletContextHandler.SESSIONS); ServletContainer container = new ServletContainer(); ServletHolder restHolder = new ServletHolder(); Map<String, String> inits = new HashMap<String, String>(); inits.put(APPLICATION_PARAM_NAME, RestConfig.class.getName()); restHolder.setInitParameters(inits); restHolder.setInitOrder(1); restHolder.setServlet(container); ctxRest.addServlet(restHolder, "/*"); WebServlet webServlet = DeployManager.class.getAnnotation(WebServlet.class); String deployManagerName = CollectionUtils.getFirst(webServlet.value()); ServletContextHandler ctxManager = new ServletContextHandler(contexts, deployManagerName, ServletContextHandler.SESSIONS); DeployManager deploy = new DeployManager(); ServletHolder managerHolder = new ServletHolder(); managerHolder.setServlet(deploy); ctxManager.addServlet(managerHolder, "/*"); ServletContextHandler ctxPerson = new ServletContextHandler(contexts, "/persons", ServletContextHandler.SESSIONS); ctxPerson.addEventListener(new LoaderListener()); PersonManager manager = new PersonManager(); ServletHolder personHolder = new ServletHolder(); personHolder.setServlet(manager); ctxPerson.addServlet(personHolder, "/*"); contexts.setHandlers(new Handler[] { ctxRest, ctxManager, ctxPerson }); jettyServer.start(); jettyServer.join(); } catch (Exception ex) { LOG.error("Error while starting jetty server", ex); } }
/** * 获取Api的路径 * * @param apiClass XController的class对象 * @return api的路径 */ public static String apiPath(Class<? extends XController<?>> apiClass) { return apiClass.getAnnotation(WebServlet.class).urlPatterns()[0]; }
/** * Pageの拡張子を取得します。 * <pre> * Servletアノテーションの先頭のURLパターンから、拡張子を取得します。 * </pre> * @return Pageの拡張子。 */ public String getPageExt() { WebServlet an = this.getClass().getAnnotation(WebServlet.class); String[] uplist = an.urlPatterns(); return uplist[0].substring(2); }
/** * @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"); }
/** * @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()); }