org.junit.platform.commons.support.AnnotationSupport Java Examples
The following examples show how to use
org.junit.platform.commons.support.AnnotationSupport.
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: FlowableExtension.java From flowable-engine with Apache License 2.0 | 6 votes |
@Override public void beforeEach(ExtensionContext context) throws Exception { FlowableTestHelper flowableTestHelper = getTestHelper(context); FlowableMockSupport mockSupport = flowableTestHelper.getMockSupport(); if (mockSupport != null) { AnnotationSupport.findRepeatableAnnotations(context.getRequiredTestClass(), MockServiceTask.class) .forEach(mockServiceTask -> TestHelper.handleMockServiceTaskAnnotation(mockSupport, mockServiceTask)); AnnotationSupport.findRepeatableAnnotations(context.getRequiredTestMethod(), MockServiceTask.class) .forEach(mockServiceTask -> TestHelper.handleMockServiceTaskAnnotation(mockSupport, mockServiceTask)); AnnotationSupport.findAnnotation(context.getRequiredTestMethod(), NoOpServiceTasks.class) .ifPresent(noOpServiceTasks -> TestHelper.handleNoOpServiceTasksAnnotation(mockSupport, noOpServiceTasks)); } AnnotationSupport.findAnnotation(context.getTestMethod(), Deployment.class) .ifPresent(deployment -> { String deploymentIdFromDeploymentAnnotation = TestHelper .annotationDeploymentSetUp(flowableTestHelper.getProcessEngine(), context.getRequiredTestClass(), context.getRequiredTestMethod(), deployment); flowableTestHelper.setDeploymentIdFromDeploymentAnnotation(deploymentIdFromDeploymentAnnotation); }); }
Example #2
Source File: DisabledOnEnvironmentCondition.java From tutorials with MIT License | 6 votes |
@Override public ConditionEvaluationResult evaluate(TestExtensionContext context) { Properties props = new Properties(); String env = ""; try { props.load(ConnectionUtil.class.getResourceAsStream("/application.properties")); env = props.getProperty("env"); } catch (IOException e) { e.printStackTrace(); } Optional<DisabledOnEnvironment> disabled = AnnotationSupport.findAnnotation(context.getElement().get(), DisabledOnEnvironment.class); if (disabled.isPresent()) { String[] envs = disabled.get().value(); if (Arrays.asList(envs).contains(env)) { return ConditionEvaluationResult.disabled("Disabled on environment " + env); } } return ConditionEvaluationResult.enabled("Enabled on environment "+env); }
Example #3
Source File: TestGuiceyAppExtension.java From dropwizard-guicey with MIT License | 6 votes |
@Override protected DropwizardTestSupport<?> prepareTestSupport(final ExtensionContext context) { if (config == null) { // Configure from annotation // Note that it is impossible to have both manually build config and annotation because annotation // will be processed first and manual registration will be simply ignored final TestGuiceyApp ann = AnnotationSupport // also search annotation inside other annotations (meta) .findAnnotation(context.getElement(), TestGuiceyApp.class).orElse(null); // catch incorrect usage by direct @ExtendWith(...) Preconditions.checkNotNull(ann, "%s annotation not declared: can't work without configuration, " + "so either use annotation or extension with @%s for manual configuration", TestGuiceyApp.class.getSimpleName(), RegisterExtension.class.getSimpleName()); config = Config.parse(ann); } HooksUtil.register(config.hooks); // config overrides work through system properties so it is important to have unique prefixes final String configPrefix = ConfigOverrideUtils.createPrefix(context.getRequiredTestClass()); return create(context, config.app, config.configPath, configPrefix, config.configOverrides); }
Example #4
Source File: BQTestExtension.java From bootique with Apache License 2.0 | 6 votes |
protected Predicate<Field> isRunnable() { return f -> { // provide diagnostics for misapplied or missing annotations // TODO: will it be actually more useful to throw instead of print a warning? if (AnnotationSupport.isAnnotated(f, BQApp.class)) { if (!BQRuntime.class.isAssignableFrom(f.getType())) { logger.warn(() -> "Field '" + f.getName() + "' is annotated with @BQRun but is not a BQRuntime. Ignoring..."); return false; } if (!ReflectionUtils.isStatic(f)) { logger.warn(() -> "BQRuntime field '" + f.getName() + "' is annotated with @BQRun but is not static. Ignoring..."); return false; } return true; } return false; }; }
Example #5
Source File: FlowableEventExtension.java From flowable-engine with Apache License 2.0 | 6 votes |
@Override public void beforeEach(ExtensionContext context) { Optional<EventDeploymentAnnotation> optionalEventDeploymentAnnotation = AnnotationSupport.findAnnotation( context.getTestMethod(), EventDeploymentAnnotation.class); Optional<ChannelDeploymentAnnotation> optionalChannelDeploymentAnnotation = AnnotationSupport.findAnnotation( context.getTestMethod(), ChannelDeploymentAnnotation.class); if (optionalEventDeploymentAnnotation.isPresent() || optionalChannelDeploymentAnnotation.isPresent()) { EventDeploymentAnnotation eventDeploymentAnnotation = null; if (optionalEventDeploymentAnnotation.isPresent()) { eventDeploymentAnnotation = optionalEventDeploymentAnnotation.get(); } ChannelDeploymentAnnotation channelDeploymentAnnotation = null; if (optionalChannelDeploymentAnnotation.isPresent()) { channelDeploymentAnnotation = optionalChannelDeploymentAnnotation.get(); } FlowableEventTestHelper testHelper = getTestHelper(context); String deploymentIdFromDeploymentAnnotation = EventTestHelper .annotationDeploymentSetUp(testHelper.getEventRepositoryService(), context.getRequiredTestClass(), context.getRequiredTestMethod(), eventDeploymentAnnotation, channelDeploymentAnnotation); testHelper.setDeploymentIdFromDeploymentAnnotation(deploymentIdFromDeploymentAnnotation); } }
Example #6
Source File: InternalFlowableFormExtension.java From flowable-engine with Apache License 2.0 | 6 votes |
protected void doFinally(ExtensionContext context, TestInstance.Lifecycle lifecycleForClean) { FormEngine formEngine = getFormEngine(context); FormEngineConfiguration formEngineConfiguration = formEngine.getFormEngineConfiguration(); try { String annotationDeploymentKey = context.getUniqueId() + ANNOTATION_DEPLOYMENT_ID_KEY; String deploymentIdFromDeploymentAnnotation = getStore(context).get(annotationDeploymentKey, String.class); if (deploymentIdFromDeploymentAnnotation != null) { FormTestHelper.annotationDeploymentTearDown(formEngine, deploymentIdFromDeploymentAnnotation, context.getRequiredTestClass(), context.getRequiredTestMethod().getName()); getStore(context).remove(annotationDeploymentKey); } AnnotationSupport.findAnnotation(context.getTestMethod(), CleanTest.class) .ifPresent(cleanTest -> removeDeployments(formEngine.getFormRepositoryService())); if (context.getTestInstanceLifecycle().orElse(TestInstance.Lifecycle.PER_METHOD) == lifecycleForClean) { cleanTestAndAssertAndEnsureCleanDb(context, formEngine); } } finally { formEngineConfiguration.getClock().reset(); } }
Example #7
Source File: ContainerGroup.java From microshed-testing with Apache License 2.0 | 6 votes |
private Set<GenericContainer<?>> discoverContainers(Class<?> clazz) { Set<GenericContainer<?>> discoveredContainers = new HashSet<>(); for (Field containerField : AnnotationSupport.findAnnotatedFields(clazz, Container.class)) { if (!Modifier.isPublic(containerField.getModifiers())) throw new ExtensionConfigurationException("@Container annotated fields must be public visibility"); if (!Modifier.isStatic(containerField.getModifiers())) throw new ExtensionConfigurationException("@Container annotated fields must be static"); boolean isStartable = GenericContainer.class.isAssignableFrom(containerField.getType()); if (!isStartable) throw new ExtensionConfigurationException("@Container annotated fields must be a subclass of " + GenericContainer.class); try { GenericContainer<?> startableContainer = (GenericContainer<?>) containerField.get(null); discoveredContainers.add(startableContainer); } catch (IllegalArgumentException | IllegalAccessException e) { LOG.warn("Unable to access field " + containerField, e); } } return discoveredContainers; }
Example #8
Source File: MicroProfileTestExtension.java From microprofile-sandbox with Apache License 2.0 | 6 votes |
private static void injectRestClients(Class<?> clazz, TestcontainersConfiguration config) throws Exception { List<Field> restClientFields = AnnotationSupport.findAnnotatedFields(clazz, Inject.class); if (restClientFields.size() == 0) return; String mpAppURL = config.getApplicationURL(); for (Field restClientField : restClientFields) { if (!Modifier.isPublic(restClientField.getModifiers()) || !Modifier.isStatic(restClientField.getModifiers()) || Modifier.isFinal(restClientField.getModifiers())) { throw new ExtensionConfigurationException("REST-client field must be public, static, and non-final: " + restClientField.getName()); } String jwt = createJwtIfNeeded(restClientField); Object restClient = JAXRSUtilities.createRestClient(restClientField.getType(), mpAppURL, jwt); //Object restClient = JAXRSUtilities.createRestClient(restClientField.getType(), mpAppURL); restClientField.set(null, restClient); LOGGER.debug("Injecting rest client for " + restClientField); } }
Example #9
Source File: TestcontainersConfiguration.java From microprofile-sandbox with Apache License 2.0 | 6 votes |
private Set<GenericContainer<?>> discoverContainers(Class<?> clazz) { Set<GenericContainer<?>> discoveredContainers = new HashSet<>(); for (Field containerField : AnnotationSupport.findAnnotatedFields(clazz, Container.class)) { if (!Modifier.isPublic(containerField.getModifiers())) throw new ExtensionConfigurationException("@Container annotated fields must be public visibility"); if (!Modifier.isStatic(containerField.getModifiers())) throw new ExtensionConfigurationException("@Container annotated fields must be static"); boolean isStartable = GenericContainer.class.isAssignableFrom(containerField.getType()); if (!isStartable) throw new ExtensionConfigurationException("@Container annotated fields must be a subclass of " + GenericContainer.class); try { GenericContainer<?> startableContainer = (GenericContainer<?>) containerField.get(null); discoveredContainers.add(startableContainer); } catch (IllegalArgumentException | IllegalAccessException e) { LOG.warn("Unable to access field " + containerField, e); } } return discoveredContainers; }
Example #10
Source File: PluggableFlowableExtension.java From flowable-engine with Apache License 2.0 | 5 votes |
@Override public void afterEach(ExtensionContext context) throws Exception { try { super.afterEach(context); } finally { if (AnnotationSupport.isAnnotated(context.getRequiredTestClass(), EnableVerboseExecutionTreeLogging.class)) { swapCommandInvoker(getProcessEngine(context), false); } } }
Example #11
Source File: LoggingTestExtension.java From ogham with Apache License 2.0 | 5 votes |
@Override public void beforeAll(ExtensionContext context) throws InstantiationException, IllegalAccessException { if (logger != null) { return; } LogTestInformation annotation = AnnotationSupport.findAnnotation(context.getElement(), LogTestInformation.class).orElse(null); if (annotation == null) { logger = new TestInformationLogger(); } else { logger = new TestInformationLogger(annotation.maxLength(), annotation.marker(), annotation.printer().newInstance()); } }
Example #12
Source File: FlowableFormExtension.java From flowable-engine with Apache License 2.0 | 5 votes |
@Override public void beforeEach(ExtensionContext context) { AnnotationSupport.findAnnotation(context.getTestMethod(), FormDeploymentAnnotation.class) .ifPresent(deployment -> { FlowableFormTestHelper testHelper = getTestHelper(context); String deploymentIdFromDeploymentAnnotation = FormTestHelper .annotationDeploymentSetUp(testHelper.getFormEngine(), context.getRequiredTestClass(), context.getRequiredTestMethod(), deployment); testHelper.setDeploymentIdFromDeploymentAnnotation(deploymentIdFromDeploymentAnnotation); }); }
Example #13
Source File: TestcontainersConfiguration.java From microprofile-sandbox with Apache License 2.0 | 5 votes |
private MicroProfileApplication<?> autoDiscoverMPApp(Class<?> clazz, boolean errorIfNone) { // First check for any MicroProfileApplicaiton directly present on the test class List<Field> mpApps = AnnotationSupport.findAnnotatedFields(clazz, Container.class, f -> Modifier.isStatic(f.getModifiers()) && Modifier.isPublic(f.getModifiers()) && MicroProfileApplication.class.isAssignableFrom(f.getType()), HierarchyTraversalMode.TOP_DOWN); if (mpApps.size() == 1) try { return (MicroProfileApplication<?>) mpApps.get(0).get(null); } catch (IllegalArgumentException | IllegalAccessException e) { // This should never happen because we only look for fields that are public+static e.printStackTrace(); } if (mpApps.size() > 1) throw new ExtensionConfigurationException("Should be no more than 1 public static MicroProfileApplication field on " + clazz); // If none found, check any SharedContainerConfig String sharedConfigMsg = ""; if (sharedConfigClass != null) { MicroProfileApplication<?> mpApp = autoDiscoverMPApp(sharedConfigClass, false); if (mpApp != null) return mpApp; sharedConfigMsg = " or " + sharedConfigClass; } if (errorIfNone) throw new ExtensionConfigurationException("No public static MicroProfileApplication fields annotated with @Container were located " + "on " + clazz + sharedConfigMsg + " to auto-connect with REST-client fields."); return null; }
Example #14
Source File: TestParametersSupport.java From dropwizard-guicey with MIT License | 5 votes |
@Override @SuppressWarnings("checkstyle:ReturnCount") public boolean supportsParameter(final ParameterContext parameterContext, final ExtensionContext extensionContext) throws ParameterResolutionException { final Parameter parameter = parameterContext.getParameter(); if (parameter.getAnnotations().length > 0) { if (AnnotationSupport.isAnnotated(parameter, Jit.class)) { return true; } else if (!isQualifierAnnotation(parameter.getAnnotations())) { // if any other annotation declared on the parameter - skip it (possibly other extension's parameter) return false; } } final Class<?> type = parameter.getType(); if (Application.class.isAssignableFrom(type) || Configuration.class.isAssignableFrom(type)) { // special case when exact app or configuration class used return true; } else { for (Class<?> cls : supportedClasses) { if (type.equals(cls)) { return true; } } } // declared guice binding (by class only) return getInjector(extensionContext) .map(it -> it.getExistingBinding(getKey(parameter)) != null) .orElse(false); }
Example #15
Source File: InternalFlowableFormExtension.java From flowable-engine with Apache License 2.0 | 5 votes |
@Override public void beforeEach(ExtensionContext context) { FormEngine formEngine = getFormEngine(context); AnnotationSupport.findAnnotation(context.getTestMethod(), FormDeploymentAnnotation.class) .ifPresent(deployment -> { String deploymentIdFromDeploymentAnnotation = FormTestHelper .annotationDeploymentSetUp(formEngine, context.getRequiredTestClass(), context.getRequiredTestMethod(), deployment); getStore(context).put(context.getUniqueId() + ANNOTATION_DEPLOYMENT_ID_KEY, deploymentIdFromDeploymentAnnotation); }); }
Example #16
Source File: MicronautJunit5Extension.java From micronaut-test with Apache License 2.0 | 5 votes |
@Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext extensionContext) { final Optional<Object> testInstance = extensionContext.getTestInstance(); if (testInstance.isPresent()) { final Class<?> requiredTestClass = extensionContext.getRequiredTestClass(); if (applicationContext.containsBean(requiredTestClass)) { return ConditionEvaluationResult.enabled("Test bean active"); } else { final boolean hasBeanDefinition = isTestSuiteBeanPresent(requiredTestClass); if (!hasBeanDefinition) { throw new TestInstantiationException(MISCONFIGURED_MESSAGE); } else { return ConditionEvaluationResult.disabled(DISABLED_MESSAGE); } } } else { final Class<?> testClass = extensionContext.getRequiredTestClass(); if (AnnotationSupport.isAnnotated(testClass, MicronautTest.class)) { return ConditionEvaluationResult.enabled("Test bean active"); } else { return ConditionEvaluationResult.disabled(DISABLED_MESSAGE); } } }
Example #17
Source File: WireMockExtension.java From wiremock-extension with MIT License | 5 votes |
private static <A extends Annotation> Optional<A> retrieveAnnotation(final ExtensionContext context, final Class<A> annotationType) { Optional<ExtensionContext> currentContext = Optional.of(context); Optional<A> annotation = Optional.empty(); while (currentContext.isPresent() && !annotation.isPresent()) { annotation = AnnotationSupport.findAnnotation(currentContext.get().getElement(), annotationType); currentContext = currentContext.get().getParent(); } return annotation; }
Example #18
Source File: TestParametersSupport.java From dropwizard-guicey with MIT License | 5 votes |
private Key<?> getKey(final Parameter parameter) { final Key<?> key; if (parameter.getAnnotations().length > 0 && !AnnotationSupport.isAnnotated(parameter, Jit.class)) { // qualified bean key = Key.get(parameter.getParameterizedType(), parameter.getAnnotations()[0]); } else { key = Key.get(parameter.getParameterizedType()); } return key; }
Example #19
Source File: TestcontainersExtension.java From testcontainers-java with MIT License | 5 votes |
private static Predicate<Field> isContainer() { return field -> { boolean isAnnotatedWithContainer = AnnotationSupport.isAnnotated(field, Container.class); if (isAnnotatedWithContainer) { boolean isStartable = Startable.class.isAssignableFrom(field.getType()); if (!isStartable) { throw new ExtensionConfigurationException(String.format("FieldName: %s does not implement Startable", field.getName())); } return true; } return false; }; }
Example #20
Source File: InternalFlowableExtension.java From flowable-engine with Apache License 2.0 | 5 votes |
@Override public void beforeEach(ExtensionContext context) { ProcessEngine processEngine = getProcessEngine(context); AnnotationSupport.findAnnotation(context.getTestMethod(), Deployment.class) .ifPresent(deployment -> { String deploymentIdFromDeploymentAnnotation = TestHelper .annotationDeploymentSetUp(processEngine, context.getRequiredTestClass(), context.getRequiredTestMethod(), deployment); getStore(context).put(context.getUniqueId() + ANNOTATION_DEPLOYMENT_ID_KEY, deploymentIdFromDeploymentAnnotation); }); }
Example #21
Source File: PluggableFlowableExtension.java From flowable-engine with Apache License 2.0 | 5 votes |
@Override protected ProcessEngine getProcessEngine(ExtensionContext context) { ProcessEngine processEngine = getStore(context).getOrComputeIfAbsent(PROCESS_ENGINE, key -> initializeProcessEngine(), ProcessEngine.class); // Enable verbose execution tree debugging if needed Class<?> testClass = context.getRequiredTestClass(); if (AnnotationSupport.isAnnotated(testClass, EnableVerboseExecutionTreeLogging.class)) { swapCommandInvoker(processEngine, true); } return processEngine; }
Example #22
Source File: GuiceyExtensionsSupport.java From dropwizard-guicey with MIT License | 5 votes |
@SuppressWarnings({"unchecked", "checkstyle:Indentation"}) private void activateFieldHooks(final Class<?> testClass) { final List<Field> fields = AnnotationSupport.findAnnotatedFields(testClass, EnableHook.class); HooksUtil.validateFieldHooks(fields); if (!fields.isEmpty()) { HooksUtil.register((List<GuiceyConfigurationHook>) (List) ReflectionUtils.readFieldValues(fields, null)); } }
Example #23
Source File: FlowableCmmnExtension.java From flowable-engine with Apache License 2.0 | 5 votes |
@Override public void beforeEach(ExtensionContext context) { FlowableCmmnTestHelper flowableTestHelper = getTestHelper(context); AnnotationSupport.findAnnotation(context.getTestMethod(), CmmnDeployment.class) .ifPresent(deployment -> { String deploymentIdFromDeploymentAnnotation = CmmnTestHelper .annotationDeploymentSetUp(flowableTestHelper.getCmmnEngine(), context.getRequiredTestClass(), context.getRequiredTestMethod(), deployment); flowableTestHelper.setDeploymentIdFromDeploymentAnnotation(deploymentIdFromDeploymentAnnotation); }); }
Example #24
Source File: TestDropwizardAppExtension.java From dropwizard-guicey with MIT License | 5 votes |
@Override @SuppressWarnings("unchecked") protected DropwizardTestSupport<?> prepareTestSupport(final ExtensionContext context) { if (config == null) { // Configure from annotation // Note that it is impossible to have both manually build config and annotation because annotation // will be processed first and manual registration will be simply ignored final TestDropwizardApp ann = AnnotationSupport // also search annotation inside other annotations (meta) .findAnnotation(context.getElement(), TestDropwizardApp.class).orElse(null); // catch incorrect usage by direct @ExtendWith(...) Preconditions.checkNotNull(ann, "%s annotation not declared: can't work without configuration, " + "so either use annotation or extension with @%s for manual configuration", TestDropwizardApp.class.getSimpleName(), RegisterExtension.class.getSimpleName()); config = Config.parse(ann); } HooksUtil.register(config.hooks); // config overrides work through system properties so it is important to have unique prefixes final String configPrefix = ConfigOverrideUtils.createPrefix(context.getRequiredTestClass()); final DropwizardTestSupport support = new DropwizardTestSupport(config.app, config.configPath, configPrefix, buildConfigOverrides(configPrefix)); if (config.randomPorts) { support.addListener(new RandomPortsListener()); } return support; }
Example #25
Source File: RequiresNetworkExtension.java From calcite with Apache License 2.0 | 5 votes |
@Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { return context.getElement() .flatMap(element -> AnnotationSupport.findAnnotation(element, RequiresNetwork.class)) .map(net -> { try (Socket ignored = new Socket(net.host(), net.port())) { return enabled(net.host() + ":" + net.port() + " is reachable"); } catch (Exception e) { return disabled(net.host() + ":" + net.port() + " is unreachable: " + e.getMessage()); } }) .orElseGet(() -> enabled("@RequiresNetwork is not found")); }
Example #26
Source File: SqlValidatorTestCase.java From calcite with Apache License 2.0 | 5 votes |
@Override public void beforeEach(ExtensionContext context) { context.getElement() .flatMap(element -> AnnotationSupport.findAnnotation(element, WithLex.class)) .ifPresent(lex -> { SqlValidatorTestCase tc = (SqlValidatorTestCase) context.getTestInstance().get(); SqlTester tester = tc.tester; tester = tester.withLex(lex.value()); tc.tester = tester; }); }
Example #27
Source File: AbstractArchUnitTestDescriptor.java From ArchUnit with Apache License 2.0 | 5 votes |
AbstractArchUnitTestDescriptor(UniqueId uniqueId, String displayName, TestSource source, AnnotatedElement... elements) { super(uniqueId, displayName, source); tags = Arrays.stream(elements).map(this::findTagsOn).flatMap(Collection::stream).collect(toSet()); skipResult = Arrays.stream(elements) .map(e -> AnnotationSupport.findAnnotation(e, ArchIgnore.class)) .filter(Optional::isPresent) .map(Optional::get) .findFirst() .map(ignore -> SkipResult.skip(ignore.reason())) .orElse(SkipResult.doNotSkip()); }
Example #28
Source File: MicronautJunit5Extension.java From micronaut-test with Apache License 2.0 | 5 votes |
@Override public void beforeAll(ExtensionContext extensionContext) throws Exception { final Class<?> testClass = extensionContext.getRequiredTestClass(); final MicronautTest micronautTest = AnnotationSupport.findAnnotation(testClass, MicronautTest.class).orElse(null); beforeClass(extensionContext, testClass, micronautTest); getStore(extensionContext).put(ApplicationContext.class, applicationContext); if (specDefinition != null) { TestInstance ti = AnnotationSupport.findAnnotation(testClass, TestInstance.class).orElse(null); if (ti != null && ti.value() == TestInstance.Lifecycle.PER_CLASS) { Object testInstance = extensionContext.getRequiredTestInstance(); applicationContext.inject(testInstance); } } beforeTestClass(buildContext(extensionContext)); }
Example #29
Source File: JaasExtension.java From taskana with Apache License 2.0 | 5 votes |
@Override public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts( ExtensionContext context) { List<WithAccessId> accessIds = AnnotationSupport.findRepeatableAnnotations(context.getElement(), WithAccessId.class); Store store = getStore(context); return accessIds.stream() .peek(a -> store.put(ACCESS_IDS_STORE_KEY, a)) .map(JaasExtensionInvocationContext::new); }
Example #30
Source File: JAXRSUtilities.java From microprofile-sandbox with Apache License 2.0 | 5 votes |
public static <T> T createRestClient(Class<T> clazz, String appContextRoot, String jwt) { String resourcePackage = clazz.getPackage().getName(); // First check for a javax.ws.rs.core.Application in the same package as the resource List<Class<?>> appClasses = ReflectionSupport.findAllClassesInPackage(resourcePackage, c -> Application.class.isAssignableFrom(c) && AnnotationSupport.isAnnotated(c, ApplicationPath.class), n -> true); if (appClasses.size() == 0) { // If not found, check under the 3rd package, so com.foo.bar.* // Classpath scanning can be expensive, so we jump straight to the 3rd package from root instead // of recursing up one package at a time and scanning the entire CP for each step String[] pkgs = resourcePackage.split("(.*)\\.(.*)\\.(.*)\\.", 2); if (pkgs.length > 0 && !pkgs[0].isEmpty() && !pkgs[0].equals(resourcePackage)) { appClasses = ReflectionSupport.findAllClassesInPackage(pkgs[0], c -> Application.class.isAssignableFrom(c) && AnnotationSupport.isAnnotated(c, ApplicationPath.class), n -> true); } } if (appClasses.size() == 0) { LOGGER.info("No classes implementing 'javax.ws.rs.core.Application' found on classpath to set as context root for " + clazz + ". Defaulting context root to '/'"); return createRestClient(clazz, appContextRoot, "", jwt); } Class<?> selectedClass = appClasses.get(0); if (appClasses.size() > 1) { appClasses.sort((c1, c2) -> c1.getCanonicalName().compareTo(c2.getCanonicalName())); LOGGER.warn("Found multiple classes implementing 'javax.ws.rs.core.Application' on classpath: " + appClasses + ". Setting context root to the first class discovered (" + selectedClass.getCanonicalName() + ")"); } ApplicationPath appPath = AnnotationSupport.findAnnotation(selectedClass, ApplicationPath.class).get(); return createRestClient(clazz, appContextRoot, appPath.value(), jwt); }