private void applyConfigurationFromAnnotation(Map<Class<? extends Annotation>, String> annotatedClassMap, Configuration configuration, SwaggerUIConfiguration swaggerUIConfiguration) { configuration.setActive(swaggerUIConfiguration.active()); configuration.setConfigurationFilename(swaggerUIConfiguration.configurationFilename()); if (isNotEmpty(swaggerUIConfiguration.systemPropertyForExternalConfigurationFilename())) { configuration.setSystemPropertyForExternalConfigurationFilename(swaggerUIConfiguration.systemPropertyForExternalConfigurationFilename()); } configuration.setHost(swaggerUIConfiguration.host()); ApplicationPath applicationPath = getAnnotationFrom(annotatedClassMap, ApplicationPath.class); if (applicationPath != null) { try { configuration.setRestApplicationClass(classLoader.loadClass(annotatedClassMap.get(ApplicationPath.class))); configuration.setRestApplicationPath(applicationPath.value()); configuration.setRestApplicationPackageAsRoot(swaggerUIConfiguration.restApplicationPackageAsRoot()); if (configuration.isRestApplicationPackageAsRoot()) { configuration.setRestApplicationPackage(configuration.getRestApplicationClass().getPackage().getName()); } else { configuration.setRestApplicationPackage(swaggerUIConfiguration.restApplicationPackage()); } } catch (ClassNotFoundException e) { configuration.setRestApplicationClass(null); } } configuration.setApiDocPath(swaggerUIConfiguration.apiDocPath()); configuration.setApiDocIndex(swaggerUIConfiguration.apiDocIndex()); }
@Override public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException { servletContext.setAttribute(OZARK_CONTROLLERS_FOUND, false); if (classes != null && !classes.isEmpty()) { LOG.log(Level.INFO, "Ozark version {0} started", getClass().getPackage().getImplementationVersion()); for (Class<?> clazz : classes) { final ApplicationPath ap = getAnnotation(clazz, ApplicationPath.class); if (ap != null) { if (servletContext.getAttribute(APP_PATH_CONTEXT_KEY) != null) { // must be a singleton throw new IllegalStateException("More than one JAX-RS ApplicationPath detected!"); } servletContext.setAttribute(APP_PATH_CONTEXT_KEY, ap.value()); } if (hasAnnotationOnClassOrMethod(clazz, Path.class) && hasAnnotationOnClassOrMethod(clazz, Controller.class)) { servletContext.setAttribute(OZARK_CONTROLLERS_FOUND, true); } if (servletContext.getAttribute(APP_PATH_CONTEXT_KEY) != null && (Boolean) servletContext.getAttribute(OZARK_CONTROLLERS_FOUND) == true) { break; // no need to loop further } } } }
public JaxRsJavaTypeMetadata(Class<?> javaType) { isTrue(javaType.isInterface(), "Your type must be a Java interface."); isTrue(javaType.getInterfaces().length <= 1, "Only single inheritance is supported."); this.javaType = javaType; this.parent = javaType.getInterfaces().length == 1 ? new JaxRsJavaTypeMetadata(javaType.getInterfaces()[0]) : null; this.applicationPath = javaType.getAnnotation(ApplicationPath.class); this.path = javaType.getAnnotation(Path.class); isFalse(applicationPath != null && path != null, "Invalid use of the @Path and @ApplicationPath annotations at the top of the interface. Use only one."); this.consumes = javaType.getAnnotation(Consumes.class); this.produces = javaType.getAnnotation(Produces.class); }
private String getURLMappingFromApplication(Class<?> appClass) { ApplicationPath apath = appClass.getAnnotation(ApplicationPath.class); if (apath != null) { String urlMapping = apath.value(); if (urlMapping == null || urlMapping.isEmpty() || urlMapping.equals("/")) { return ""; } if (urlMapping != null && !urlMapping.startsWith("/")) { urlMapping = "/" + urlMapping; } return urlMapping; } else { logger.finest("Didn't find @ApplicationPath in Application classs " + appClass.getName()); } return null; }
@Override public Optional<String> visitType(TypeElement element, Void aVoid) { String servletName = element.getAnnotation(ExposedApplication.class).servletName(); ApplicationPath applicationPath = element.getAnnotation(ApplicationPath.class); String applicationName = String.valueOf(element.getQualifiedName()); if (!(applicationPath != null ^ !servletName.isEmpty())) { messager.printMessage(ERROR, INCONSISTENT_APPLICATION_MAPPING.format(applicationName), element); return absent(); } if (applicationPath != null) { return Optional.of(applicationName); } return Optional.of(servletName); }
private ServletContextHandler createJerseyHandler(final HandlerCollection handlerCollection) { // http://nikgrozev.com/2014/10/16/rest-with-embedded-jetty-and-jersey-in-a-single-jar-step-by-step/ final Set<Class<?>> managedClasses = collectAnnotated(JAX_RS_MANAGED_CLASSES); final ServletContextHandler context = initContext("/rest", managedClasses); handlerCollection.addHandler(context); final ResourceConfig config = initConfig(managedClasses); annotationScanner.scanFor(ApplicationPath.class).forEach(appClass -> { final String path = appClass.getAnnotation(ApplicationPath.class).value(); final String pathSpec = (path.startsWith("/") ? "" : "/") + path + "/*"; LOG.debug("Mapping rest application {} to {}", appClass.getName(), pathSpec); context.addServlet(new ServletHolder(new JerseyServlet(config)), pathSpec); }); return context; }
private String getPathSpec(Class<? extends Application> appClass) { ApplicationPath applicationPath = appClass.getAnnotation(ApplicationPath.class); StringBuilder pathSpec = new StringBuilder(applicationPath.value()); if(pathSpec.length()==0 || pathSpec.charAt(pathSpec.length()-1)!='/') { pathSpec.append('/'); } pathSpec.append('*'); return pathSpec.toString(); }
/** * Register the routes. * * @param applicationClass * application class to get the root * @param router * router to apply the changes to * @param pathsProvider * provides a list of Path classes * @param jaxRsHandler * route handler */ public void register(final Class<? extends Application> applicationClass, final Router router, final PathsProvider pathsProvider, final Handler<RoutingContext> jaxRsHandler) { final String rootPath = Optional.ofNullable(applicationClass.getAnnotation(ApplicationPath.class)).map(ApplicationPath::value).orElse(""); final SortedSet<JaxRsPath> paths = new TreeSet<>(); pathsProvider.getPathAnnotatedClasses().forEach(clazz -> { final String classPath = Optional.ofNullable(clazz.getAnnotation(Path.class)).map(Path::value).orElse(""); stream(clazz.getMethods()).filter(m -> m.getAnnotation(GET.class) != null || m.getAnnotation(POST.class) != null || m.getAnnotation(PUT.class) != null || m.getAnnotation(DELETE.class) != null).forEach(m -> { final String path = Optional.ofNullable(m.getAnnotation(Path.class)).map(Path::value).orElse(""); final String[] consumes = Optional.ofNullable(m.getAnnotation(Consumes.class)).map(Consumes::value).orElse(new String[0]); final String[] produces = Optional.ofNullable(m.getAnnotation(Produces.class)).map(Produces::value).orElse(new String[0]); paths.add(new JaxRsPath(UriBuilder.fromPath(rootPath).path(classPath).path(path).toTemplate(), consumes, produces, getHttpMethod(m))); }); }); paths.forEach(p -> { p.apply(router, jaxRsHandler, failureHandler); LOG.debug("route={}", p); }); }
public SwaggerHandler( final Class<? extends Application> applicationClass) { final ApplicationPath annotation = applicationClass.getAnnotation(ApplicationPath.class); if (annotation != null) { baseUri = URI.create(annotation.value()).normalize(); } else { baseUri = URI.create("/"); } Application application; try { application = applicationClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new ExceptionInInitializerError(e); } swagger = new ClonableSwagger(); final Reader swaggerReader = new Reader(swagger); final Set<Class<?>> resourceClasses = application.getClasses(); if (resourceClasses.isEmpty()) { final String packageName = applicationClass.getPackage().getName(); final Reflections reflections = new Reflections(packageName); reflections.getTypesAnnotatedWith(Api.class).forEach(swaggerReader::read); reflections.getTypesAnnotatedWith(SwaggerDefinition.class).forEach(swaggerReader::read); } else { swaggerReader.read(applicationClass); resourceClasses.forEach(swaggerReader::read); } }
private void resolveApplicationPath() { if (StringUtils.hasLength(this.resteasy.getApplicationPath())) { this.path = parseApplicationPath(this.resteasy.getApplicationPath()); } else { this.path = findApplicationPath( AnnotationUtils.findAnnotation(this.config.getClass(), ApplicationPath.class)); } }
@Override protected Configuration readConfigurationFrom(Configuration configuration, ServletContext servletContext) { @SuppressWarnings("unchecked") Map<Class<? extends Annotation>, String> annotatedClassMap = new ByteCodeAnnotationScanner(servletContext, SwaggerUIConfiguration.class, ApplicationPath.class).get(); if (annotatedClassMap.size() > 0) { classLoader = getClassLoader(); return readConfiguration(annotatedClassMap, configuration); } return configuration; }
private String[] allApplicationPaths() { ArrayList<String> applicationPaths = new ArrayList<>(); Optional.ofNullable(parent) .map(p -> p.allApplicationPaths()) .ifPresent(array -> Collections.addAll(applicationPaths, array)); Optional.ofNullable(applicationPath).map(ApplicationPath::value) .ifPresent(p -> applicationPaths.add(p)); return applicationPaths.toArray(new String[0]); }
private void resolveApplicationPath() { if (StringUtils.hasLength(this.jersey.getApplicationPath())) { this.path = parseApplicationPath(this.jersey.getApplicationPath()); } else { this.path = findApplicationPath(AnnotationUtils .findAnnotation(this.config.getClass(), ApplicationPath.class)); } }
private static String findApplicationPath(ApplicationPath annotation) { // Jersey doesn't like to be the default servlet, so map to /* as a fallback if (annotation == null) { return "/*"; } return parseApplicationPath(annotation.value()); }
private static String getApplicationPath(Application applicationConfig) { if (applicationConfig == null) { return null; } ApplicationPath ap = applicationConfig.getClass().getAnnotation(ApplicationPath.class); if (ap == null) { return null; } String applicationPath = ap.value(); if (isBlank(applicationPath)) { return null; } while (applicationPath.startsWith("/")) { applicationPath = applicationPath.substring(1); } // support Servlet configs if (applicationPath.endsWith("/*")) { applicationPath = applicationPath.substring(0, applicationPath.length() - 2); } while (applicationPath.endsWith("/")) { applicationPath = applicationPath.substring(0, applicationPath.length() - 1); } if (isBlank(applicationPath)) { return null; } return applicationPath; }
@Test public void testApplicationPath() { Class clazz = MTApplication.getClass(); assertThat(clazz.isAnnotationPresent(ApplicationPath.class)).isTrue(); ApplicationPath annotation = (ApplicationPath) clazz.getAnnotation(ApplicationPath.class); assertThat(annotation.value()).isEqualTo("api"); }
public RestModule(String host, int port, String contextRoot, WebAnnotations webAnnotations) { try { InfoStore infoStore = webAnnotations.getInfoStore(); webAnnotations.openInfoStore(); // Ignore all complexities like @Parent annotations for the moment, // and also inheritance. AnnotationTargets_Targets annotationTargets = webAnnotations.getAnnotationTargets(); String applicationPath = ""; Set<String> classesWithApplicationPath = annotationTargets .getAnnotatedClasses(ApplicationPath.class.getName(), POLICY_SEED); if (classesWithApplicationPath.size() == 0) { System.err.println("The REST application path must be set using annotations. "); } else if (classesWithApplicationPath.size() > 1) { System.err.println("There should only be one REST application path per application."); } else { applicationPath = getValue(infoStore, ApplicationPath.class, classesWithApplicationPath.iterator().next()); } // Scan annotation for @Provider, @Path processAnnotations(host, port, contextRoot, infoStore, annotationTargets, Provider.class, applicationPath); processAnnotations(host, port, contextRoot, infoStore, annotationTargets, Path.class, applicationPath); } catch (Exception e) { e.printStackTrace(); } }
@PostConstruct public void path() { if (StringUtils.hasLength(this.jersey.getApplicationPath())) { this.path = parseApplicationPath(this.jersey.getApplicationPath()); } else { this.path = findApplicationPath(AnnotationUtils .findAnnotation(this.config.getClass(), ApplicationPath.class)); } }
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { logger.debug("Post process bean factory has been called"); findJaxrsApplications(beanFactory); // This is done by finding their related Spring beans findJaxrsResourcesAndProviderClasses(beanFactory); if (allResources.size() == 0) { logger.warn("No JAX-RS resource Spring beans have been found"); } if (applications.size() == 0) { logger.info("No JAX-RS Application classes have been found. A default, one mapped to '/', will be registered."); registerDefaultJaxrsApp(beanFactory); return; } BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; for (Class<? extends Application> applicationClass : applications) { ApplicationPath path = AnnotationUtils.findAnnotation(applicationClass, ApplicationPath.class); if (path == null) { logger.warn("JAX-RS Application class {} has no ApplicationPath annotation, so it will not be registered", applicationClass.getName()); continue; } logger.debug("registering JAX-RS application class " + applicationClass.getName()); GenericBeanDefinition applicationServletBean = createApplicationServlet(applicationClass, path.value()); registry.registerBeanDefinition(applicationClass.getName(), applicationServletBean); } }
public Result tryParse(SourceType<?> sourceType) { if (!(sourceType.type instanceof Class<?>)) { return null; } final Class<?> cls = (Class<?>) sourceType.type; // application if (Application.class.isAssignableFrom(cls)) { final ApplicationPath applicationPathAnnotation = cls.getAnnotation(ApplicationPath.class); if (applicationPathAnnotation != null) { model.setApplicationPath(applicationPathAnnotation.value()); } model.setApplicationName(cls.getSimpleName()); final List<SourceType<Type>> discoveredTypes = JaxrsApplicationScanner.scanJaxrsApplication(cls, isClassNameExcluded); return new Result(discoveredTypes); } // resource final Path path = cls.getAnnotation(Path.class); if (path != null) { System.out.println("Parsing JAX-RS resource: " + cls.getName()); final Result result = new Result(); parseResource(result, new ResourceContext(cls, path.value()), cls); return result; } return null; }
private static String getApplicationPath(Application application) { ApplicationPath applicationPath = application.getClass().getAnnotation(ApplicationPath.class); if (applicationPath == null) { throw new RuntimeException(application.getClass() + " must have an ApplicationPath annotation"); } return "/" + applicationPath.value(); }
@Produces public ServletDescriptor jerseyServlet() { String urlPattern = restServerConfiguration.getRestServletMapping(); if (!applicationInstance.isUnsatisfied() && !applicationInstance.isAmbiguous()) { ApplicationPath annotation = ClassUtils.getAnnotation(applicationInstance.get().getClass(), ApplicationPath.class); if(annotation != null) { String path = annotation.value(); urlPattern = path.endsWith("/") ? path + "*" : path + "/*"; } } return new ServletDescriptor(SERVLET_NAME, null, new String[] { urlPattern }, 1, null, true, ServletContainer.class); }
@Produces public ServletDescriptor resteasyServlet() { String path = restServerConfiguration.getRestServerUri(); if( !(applicationInstance.isUnsatisfied() || applicationInstance.isAmbiguous())) { ApplicationPath appPath = ClassUtils.getAnnotation(applicationInstance.get().getClass(), ApplicationPath.class); if(appPath != null) { path = appPath.value(); } } String pattern = path.endsWith("/") ? path + "*" : path + "/*"; WebInitParam param = new WebParam("resteasy.servlet.mapping.prefix", path); return new ServletDescriptor("ResteasyServlet",new String[]{pattern}, new String[]{pattern}, 1,new WebInitParam[]{param},true,HttpServlet30Dispatcher.class); }
@Test public void shouldFindApplicationPathAnnotatedClassInPackage() { ClassPathScanner scanner = new ClassPathScanner(PACKAGE_RESTAPIDOC_TEST); Set<Class<?>> classes = scanner.getClassesWithAnnotation(ApplicationPath.class); assertEquals(1, classes.size()); for (Class<?> clazz : classes) { ApplicationPath annotation = clazz.getAnnotation(ApplicationPath.class); System.out.println(clazz + " path: " + annotation.value()); } }
/** * Retrieve the context from the provided {@link Application}'s {@link ApplicationPath}. * * @param application with a {@link ApplicationPath} annotation. * @return String of the path. */ public static String getApplicationContext(Application application) { final Class<?> clazz = application.getClass(); final ApplicationPath applicationPath = clazz.getAnnotation(ApplicationPath.class); String path = (applicationPath == null) ? "/" : applicationPath.value(); if(path.length() < 1) { return "/"; } else { return path.charAt(0) == '/' ? path : "/" + path; } }
private static String findApplicationPath(ApplicationPath annotation) { if (annotation == null) { return "/*"; } return parseApplicationPath(annotation.value()); }
@Test public void UnitOfWork_StateUnderTest_ExpectedBehavior0() throws Exception { // TODO should change method name if (log.isTraceEnabled()) { log.trace(String.format("url=%s", url.toString())); } String applicationPath = Application.class.getAnnotation(ApplicationPath.class).value().trim().replaceFirst("^/", ""); if (log.isTraceEnabled()) { log.trace(String.format("applicationPath=%s", applicationPath)); } try { // 1st request. ClientBuilder.newClient() .target(this.url.toURI()) .path(applicationPath).path("samples") //.request(MediaType.APPLICATION_JSON) .request() .post(Entity.json( Json.createObjectBuilder() .add("id", 1L) //.add("version", 0L) .add("name", UUID.randomUUID().toString()) .build() )); JsonArray jsonArray1 = ClientBuilder.newClient() .target(this.url.toURI()) .path(applicationPath).path("samples") //.request(MediaType.APPLICATION_JSON) .request() .accept(MediaType.APPLICATION_JSON) .get(JsonArray.class); if (log.isTraceEnabled()) { log.trace(String.format("jsonArray1=%s", jsonArray1.toString())); } assertThat("", jsonArray1.size(), equalTo(1)); // 2nd request. ClientBuilder.newClient() .target(this.url.toURI()) .path(applicationPath).path("samples") //.request(MediaType.APPLICATION_JSON) .request() .post(Entity.json( Json.createObjectBuilder() .add("id", 2L) //.add("version", 0L) .add("name", UUID.randomUUID().toString()) .build() )); JsonArray jsonArray2 = ClientBuilder.newClient() .target(this.url.toURI()) .path(applicationPath).path("samples") //.request(MediaType.APPLICATION_JSON) .request() .accept(MediaType.APPLICATION_JSON) .get(JsonArray.class); if (log.isTraceEnabled()) { log.trace(String.format("jsonArray2=%s", jsonArray2.toString())); } assertThat("", jsonArray2.size(), equalTo(2)); } catch (URISyntaxException cause) { throw new RuntimeException(cause); } }
private boolean isJAXRSRootResource(String className) { final Class<?> clazz = JavaUtils.loadClassFromName(className); return clazz != null && (isAnnotationPresent(clazz, javax.ws.rs.Path.class) || isAnnotationPresent(clazz, ApplicationPath.class)); }
private static String appPrefix(final WebAppInfo info, final Class<?> appClazz) { StringBuilder builder = null; // no annotation, try servlets for (final ServletInfo s : info.servlets) { if (s.mappings.isEmpty()) { continue; } String mapping = null; final String name = appClazz.getName(); if (name.equals(s.servletClass) || name.equals(s.servletName) || "javax.ws.rs.core.Application ".equals(s.servletName)) { mapping = s.mappings.iterator().next(); } else { for (final ParamValueInfo pvi : s.initParams) { if ("javax.ws.rs.Application".equals(pvi.name) || Application.class.getName().equals(pvi.name)) { mapping = s.mappings.iterator().next(); break; } } } if (mapping != null) { if (mapping.endsWith("/*")) { mapping = mapping.substring(0, mapping.length() - 2); } if (mapping.startsWith("/")) { mapping = mapping.substring(1); } builder = new StringBuilder(); builder.append(mapping); break; } } if (builder != null) { // https://issues.apache.org/jira/browse/CXF-5702 return builder.toString(); } // annotation final ApplicationPath path = appClazz.getAnnotation(ApplicationPath.class); if (path != null) { String appPath = path.value(); if (appPath.endsWith("*")) { appPath = appPath.substring(0, appPath.length() - 1); } builder = new StringBuilder(); if (appPath.startsWith("/")) { builder.append(appPath.substring(1)); } else { builder.append(appPath); } } if (builder == null) { return null; } return builder.toString(); }