org.apache.cxf.jaxrs.JAXRSServiceFactoryBean Java Examples

The following examples show how to use org.apache.cxf.jaxrs.JAXRSServiceFactoryBean. 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: CxfJaxrsServiceRegistrator.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
private ResourceContextProvider createResourceContextProvider(
    JAXRSServiceFactoryBean jaxrsServiceFactoryBean) {

    ComparableResourceComparator comparableResourceComparator =
        new ComparableResourceComparator();

    List<ClassResourceInfo> classResourceInfos =
        jaxrsServiceFactoryBean.getClassResourceInfo().stream().sorted(
            (cri1, cri2) -> comparableResourceComparator.compare(
                cri1, cri2, null)
        ).collect(
            Collectors.toList()
        );

    HashMap<Class, ResourceProvider> map = new HashMap<>();

    for (ClassResourceInfo classResourceInfo : classResourceInfos) {
        map.put(
            classResourceInfo.getResourceClass(),
            classResourceInfo.getResourceProvider());
    }

    return map::get;
}
 
Example #2
Source File: AbstractSwaggerFeature.java    From cxf with Apache License 2.0 6 votes vote down vote up
void calculateDefaultResourcePackage(Server server) {
    if (!StringUtils.isEmpty(getResourcePackage())) {
        return;
    }
    JAXRSServiceFactoryBean serviceFactoryBean =
            (JAXRSServiceFactoryBean)server.getEndpoint().get(JAXRSServiceFactoryBean.class.getName());
    List<ClassResourceInfo> resourceInfos = serviceFactoryBean.getClassResourceInfo();

    if (resourceInfos.size() == 1) {
        setResourcePackage(resourceInfos.get(0).getServiceClass().getPackage().getName());
    } else {
        List<Class<?>> serviceClasses = new ArrayList<>(resourceInfos.size());
        for (ClassResourceInfo cri : resourceInfos) {
            serviceClasses.add(cri.getServiceClass());
        }
        String sharedPackage = PackageUtils.getSharedPackageName(serviceClasses);
        if (!StringUtils.isEmpty(sharedPackage)) {
            setResourcePackage(sharedPackage);
        }
    }
}
 
Example #3
Source File: DefaultApplicationFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Detects the application (if present) or creates the default application (in case the scan is disabled).
 */
public static Application createApplicationOrDefault(final Server server, final ServerProviderFactory factory, 
        final JAXRSServiceFactoryBean sfb, final Bus bus, final Set<String> resourcePackages, 
            final boolean scan) {

    ApplicationInfo appInfo = null;
    if (!scan) {
        appInfo = factory.getApplicationProvider();
        
        if (appInfo == null) {
            appInfo = createApplicationInfo(sfb, resourcePackages, bus);
            server.getEndpoint().put(Application.class.getName(), appInfo);
        }
    }
    
    return (appInfo == null) ? null : appInfo.getProvider();
}
 
Example #4
Source File: DefaultApplicationFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Detects the application (if present) or creates the default application (in case the scan is disabled).
 */
public static ApplicationInfo createApplicationInfoOrDefault(final Server server, 
            final ServerProviderFactory factory, final JAXRSServiceFactoryBean sfb, final Bus bus, 
                final boolean scan) {
    
    ApplicationInfo appInfo = null;
    if (!scan) {
        appInfo = factory.getApplicationProvider();
        if (appInfo == null) {
            Set<Class<?>> serviceClasses = new HashSet<>();
            for (ClassResourceInfo cri : sfb.getClassResourceInfo()) {
                serviceClasses.add(cri.getServiceClass());
            }
            appInfo = createApplicationInfo(serviceClasses, bus);
            server.getEndpoint().put(Application.class.getName(), appInfo);
        }
    }
    
    return appInfo;
}
 
Example #5
Source File: CxfJaxrsServiceRegistrator.java    From aries-jax-rs-whiteboard with Apache License 2.0 5 votes vote down vote up
public Iterable<Class<?>> getStaticResourceClasses() {
    if (_jaxRsServerFactoryBean == null) {
        return Collections.emptyList();
    }

    JAXRSServiceFactoryBean serviceFactory =
        _jaxRsServerFactoryBean.getServiceFactory();

    List<ClassResourceInfo> classResourceInfo =
        serviceFactory.getClassResourceInfo();

    ArrayList<Class<?>> classes = new ArrayList<>();

    for (ClassResourceInfo resourceInfo : classResourceInfo) {
        if (resourceInfo == null) {
            continue;
        }

        ResourceProvider resourceProvider =
            resourceInfo.getResourceProvider();

        if (resourceProvider == null ||
            !ServiceReferenceResourceProvider.class.isAssignableFrom(
                resourceProvider.getClass())) {

            classes.add(resourceInfo.getResourceClass());
        }
    }

    return classes;
}
 
Example #6
Source File: OpenApiFeature.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Collection<String> scanResourcePackages(JAXRSServiceFactoryBean sfb) {
    return sfb
            .getClassResourceInfo()
            .stream()
            .map(cri -> cri.getServiceClass().getPackage().getName())
            .collect(Collectors.toSet());
}
 
Example #7
Source File: OpenApiFeature.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void registerOpenApiResources(
        final JAXRSServiceFactoryBean sfb,
        final Set<String> packages,
        final OpenAPIConfiguration config) {

    if (customizer != null) {
        customizer.setClassResourceInfos(sfb.getClassResourceInfo());
    }

    sfb.setResourceClassesFromBeans(Arrays.asList(
            createOpenApiResource()
                    .openApiConfiguration(config)
                    .configLocation(configLocation)
                    .resourcePackages(packages)));
}
 
Example #8
Source File: OpenApiFeature.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void registerSwaggerUiResources(JAXRSServiceFactoryBean sfb, Properties properties,
                                          ServerProviderFactory factory, Bus bus) {

    final Registration swaggerUiRegistration = getSwaggerUi(bus, properties, isRunAsFilter());

    if (!isRunAsFilter()) {
        sfb.setResourceClassesFromBeans(swaggerUiRegistration.getResources());
    }

    factory.setUserProviders(swaggerUiRegistration.getProviders());
}
 
Example #9
Source File: OpenApiFeature.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Collection<String> scanResourcePackages(JAXRSServiceFactoryBean sfb) {
    return sfb
            .getClassResourceInfo()
            .stream()
            .map(cri -> cri.getServiceClass().getPackage().getName())
            .collect(Collectors.toSet());
}
 
Example #10
Source File: Base.java    From iaf with Apache License 2.0 4 votes vote down vote up
protected JAXRSServiceFactoryBean getJAXRSService() {
	return serviceFactory;
}
 
Example #11
Source File: Swagger2Feature.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
protected void addSwaggerResource(Server server, Bus bus) {
    JAXRSServiceFactoryBean sfb =
            (JAXRSServiceFactoryBean) server.getEndpoint().get(JAXRSServiceFactoryBean.class.getName());

    ServerProviderFactory factory =
            (ServerProviderFactory)server.getEndpoint().get(ServerProviderFactory.class.getName());
    final ApplicationInfo appInfo = DefaultApplicationFactory.createApplicationInfoOrDefault(server,
            factory, sfb, bus, isScan());

    List<Object> swaggerResources = new LinkedList<>();

    if (customizer == null) {
        customizer = new Swagger2Customizer();
    }
    ApiListingResource apiListingResource = new Swagger2ApiListingResource(customizer);
    swaggerResources.add(apiListingResource);

    List<Object> providers = new ArrayList<>();
    providers.add(new SwaggerSerializers());

    if (isRunAsFilter()) {
        providers.add(new SwaggerContainerRequestFilter(appInfo == null ? null : appInfo.getProvider(),
                customizer));
    }

    final Properties swaggerProps = getSwaggerProperties(propertiesLocation, bus);
    final Registration swaggerUiRegistration = getSwaggerUi(bus, swaggerProps, isRunAsFilter());

    if (!isRunAsFilter()) {
        swaggerResources.addAll(swaggerUiRegistration.getResources());
    }

    providers.addAll(swaggerUiRegistration.getProviders());
    sfb.setResourceClassesFromBeans(swaggerResources);

    List<ClassResourceInfo> cris = sfb.getClassResourceInfo();
    if (!isRunAsFilter()) {
        for (ClassResourceInfo cri : cris) {
            if (ApiListingResource.class.isAssignableFrom(cri.getResourceClass())) {
                InjectionUtils.injectContextProxies(cri, apiListingResource);
            }
        }
    }
    customizer.setClassResourceInfos(cris);
    customizer.setDynamicBasePath(dynamicBasePath);

    BeanConfig beanConfig = appInfo == null
            ? new BeanConfig()
            : new ApplicationBeanConfig(appInfo.getProvider());
    initBeanConfig(beanConfig, swaggerProps);

    Swagger swagger = beanConfig.getSwagger();
    if (swagger != null && securityDefinitions != null) {
        swagger.setSecurityDefinitions(securityDefinitions);
    }
    customizer.setBeanConfig(beanConfig);

    providers.add(new ReaderConfigFilter());

    if (beanConfig.isUsePathBasedConfig()) {
        providers.add(new ServletConfigProvider());
    }

    factory.setUserProviders(providers);
}
 
Example #12
Source File: JAXRSClientFactoryBean.java    From cxf with Apache License 2.0 4 votes vote down vote up
public JAXRSClientFactoryBean(JAXRSServiceFactoryBean serviceFactory) {
    super(serviceFactory);
    serviceFactory.setEnableStaticResolution(true);

}
 
Example #13
Source File: JAXRSClientFactoryBean.java    From cxf with Apache License 2.0 4 votes vote down vote up
public JAXRSClientFactoryBean() {
    this(new JAXRSServiceFactoryBean());
}
 
Example #14
Source File: OpenApiFeature.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(Server server, Bus bus) {
    final JAXRSServiceFactoryBean sfb = (JAXRSServiceFactoryBean)server
            .getEndpoint()
            .get(JAXRSServiceFactoryBean.class.getName());

    final ServerProviderFactory factory = (ServerProviderFactory)server
            .getEndpoint()
            .get(ServerProviderFactory.class.getName());

    final Set<String> packages = new HashSet<>();
    if (resourcePackages != null) {
        packages.addAll(resourcePackages);
    }

    // Generate random Context ID for Swagger
    if (useContextBasedConfig) {
        ctxId = UUID.randomUUID().toString();
    }

    Properties swaggerProps = null;
    GenericOpenApiContextBuilder<?> openApiConfiguration;
    final Application application = DefaultApplicationFactory.createApplicationOrDefault(server, factory,
            sfb, bus, resourcePackages, isScan());

    String defaultConfigLocation = getConfigLocation();
    if (scanKnownConfigLocations && StringUtils.isEmpty(defaultConfigLocation)) {
        defaultConfigLocation = OpenApiDefaultConfigurationScanner.locateDefaultConfiguration().orElse(null);
    }

    if (StringUtils.isEmpty(defaultConfigLocation)) {
        swaggerProps = getSwaggerProperties(propertiesLocation, bus);

        if (isScan()) {
            packages.addAll(scanResourcePackages(sfb));
        }

        final OpenAPI oas = new OpenAPI().info(getInfo(swaggerProps));
        registerComponents(securityDefinitions).ifPresent(oas::setComponents);

        final SwaggerConfiguration config = new SwaggerConfiguration()
                .openAPI(oas)
                .prettyPrint(getOrFallback(isPrettyPrint(), swaggerProps, PRETTY_PRINT_PROPERTY))
                .readAllResources(isReadAllResources())
                .ignoredRoutes(getIgnoredRoutes())
                .filterClass(getOrFallback(getFilterClass(), swaggerProps, FILTER_CLASS_PROPERTY))
                .resourceClasses(getResourceClasses())
                .resourcePackages(getOrFallback(packages, swaggerProps, RESOURCE_PACKAGE_PROPERTY));
        
        if (!StringUtils.isEmpty(getScannerClass())) {
            config.setScannerClass(getScannerClass());
        }

        openApiConfiguration = new JaxrsOpenApiContextBuilder<>()
                .application(application)
                .openApiConfiguration(config)
                .ctxId(ctxId); /* will be null if not used */
    } else {
        openApiConfiguration = new JaxrsOpenApiContextBuilder<>()
                .application(application)
                .configLocation(defaultConfigLocation)
                .ctxId(ctxId); /* will be null if not used */
    }

    try {
        final OpenApiContext context = openApiConfiguration.buildContext(true);
        final Properties userProperties = getUserProperties(
                context
                        .getOpenApiConfiguration()
                        .getUserDefinedOptions());
        registerOpenApiResources(sfb, packages, context.getOpenApiConfiguration());
        registerSwaggerUiResources(sfb, combine(swaggerProps, userProperties), factory, bus);
        registerSwaggerContainerRequestFilter(factory, application);

        if (useContextBasedConfig) {
            registerServletConfigProvider(factory);
        }

        if (customizer != null) {
            customizer.setApplicationInfo(factory.getApplicationProvider());
        }

        bus.setProperty("openapi.service.description.available", "true");
    } catch (OpenApiConfigurationException ex) {
        throw new RuntimeException("Unable to initialize OpenAPI context", ex);
    }
}
 
Example #15
Source File: OpenApiFeature.java    From cxf with Apache License 2.0 4 votes vote down vote up
public Collection<String> scanResourcePackages(JAXRSServiceFactoryBean sfb) {
    return delegate.scanResourcePackages(sfb);
}
 
Example #16
Source File: OpenApiFeature.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void registerSwaggerUiResources(JAXRSServiceFactoryBean sfb, Properties properties,
                                       ServerProviderFactory factory, Bus bus) {
    delegate.registerSwaggerUiResources(sfb, properties, factory, bus);
}
 
Example #17
Source File: OpenApiFeature.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void registerOpenApiResources(JAXRSServiceFactoryBean sfb, Set<String> packages,
                                     OpenAPIConfiguration config) {
    delegate.registerOpenApiResources(sfb, packages, config);
}
 
Example #18
Source File: DefaultApplicationFactory.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static ApplicationInfo createApplicationInfo(final JAXRSServiceFactoryBean sfb, 
        final Set<String> resourcePackages, final Bus bus) {
    return new ApplicationInfo(createApplication(sfb.getClassResourceInfo(), resourcePackages), bus);
}
 
Example #19
Source File: OpenApiFeature.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void registerOpenApiResources(
        final JAXRSServiceFactoryBean sfb,
        final OpenAPI openApiDefinition) {

    sfb.setResourceClassesFromBeans(Collections.singletonList(new OpenApiEndpoint(openApiDefinition)));
}
 
Example #20
Source File: OpenApiFeature.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(Server server, Bus bus) {
    final JAXRSServiceFactoryBean sfb = (JAXRSServiceFactoryBean)server
            .getEndpoint()
            .get(JAXRSServiceFactoryBean.class.getName());

    final ServerProviderFactory factory = (ServerProviderFactory)server
            .getEndpoint()
            .get(ServerProviderFactory.class.getName());

    final Set<String> packages = new HashSet<>();
    if (resourcePackages != null) {
        packages.addAll(resourcePackages);
    }

    final Application application = DefaultApplicationFactory.createApplicationOrDefault(server, factory,
            sfb, bus, resourcePackages, isScan());

    final AnnotationProcessor processor = new AnnotationProcessor(GeronimoOpenAPIConfig.create(),
            new NamingStrategy.Http(), null /* default JsonReaderFactory */);

    final OpenAPIImpl api = new OpenAPIImpl();

    if (isScan()) {
        packages.addAll(scanResourcePackages(sfb));
    }

    final Set<Class<?>> resources = new HashSet<>();
    if (application != null) {
        processor.processApplication(api, new ClassElement(application.getClass()));
        LOG.fine("Processed application " + application);

        if (application.getClasses() != null) {
            resources.addAll(application.getClasses());
        }
    }

    resources.addAll(sfb
            .getClassResourceInfo()
            .stream()
            .map(AbstractResourceInfo::getServiceClass)
            .filter(cls -> filterByPackage(cls, packages))
            .filter(cls -> filterByClassName(cls, resourceClasses))
            .collect(Collectors.toSet()));

    if (!resources.isEmpty()) {
        final String binding = (application == null) ? ""
                : processor.getApplicationBinding(application.getClass());

        resources
                .stream()
                .peek(c -> LOG.info("Processing class " + c.getName()))
                .forEach(c -> processor.processClass(binding, api, new ClassElement(c),
                        Stream.of(c.getMethods()).map(MethodElement::new)));
    } else {
        LOG.warning("No resource classes registered, the OpenAPI will not contain any endpoints.");
    }

    Properties swaggerProps = getSwaggerProperties(propertiesLocation, bus);
    if (api.getInfo() == null) {
        api.setInfo(getInfo(swaggerProps));
    }

    registerOpenApiResources(sfb, api);
    registerSwaggerUiResources(sfb, swaggerProps, factory, bus);
}
 
Example #21
Source File: OpenApiFeature.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void registerSwaggerUiResources(JAXRSServiceFactoryBean sfb, Properties properties,
        ServerProviderFactory factory, Bus bus) {
    
    delegate.registerSwaggerUiResources(sfb, properties, factory, bus);
}
 
Example #22
Source File: OpenApiFeature.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void registerOpenApiResources(
        final JAXRSServiceFactoryBean sfb,
        final OpenAPI openApiDefinition) {

    delegate.registerOpenApiResources(sfb, openApiDefinition);
}
 
Example #23
Source File: JAXRSServerFactoryBeanDefinitionParser.java    From cxf with Apache License 2.0 4 votes vote down vote up
public BPJAXRSServerFactoryBean(JAXRSServiceFactoryBean fact) {
    super(fact);
}
 
Example #24
Source File: JAXRSServerFactoryBeanDefinitionParser.java    From cxf with Apache License 2.0 4 votes vote down vote up
public SpringJAXRSServerFactoryBean(JAXRSServiceFactoryBean sf) {
    super(sf);
}
 
Example #25
Source File: CxfCdiAutoSetup.java    From openwebbeans-meecrowave with Apache License 2.0 4 votes vote down vote up
private Function<ServletDestination, String> getServletDestinationPath(ServletConfig sc, LogFacade log)
{
    return sd -> {
        final Endpoint endpoint = ChainInitiationObserver.class.cast(sd.getMessageObserver()).getEndpoint();
        final ApplicationInfo app = ApplicationInfo.class.cast(endpoint.get(Application.class.getName()));
        final JAXRSServiceFactoryBean sfb = JAXRSServiceFactoryBean.class.cast(endpoint.get(JAXRSServiceFactoryBean.class.getName()));
        final String base = sd.getEndpointInfo().getAddress();

        if (sfb != null) {
            final List<Logs.LogResourceEndpointInfo> resourcesToLog = new ArrayList<>();
            int classSize = 0;
            int addressSize = 0;

            final List<ClassResourceInfo> resources = sfb.getClassResourceInfo();
            for (final ClassResourceInfo info : resources) {
                if (info.getResourceClass() == null) { // possible?
                    continue;
                }

                final String address = Logs.singleSlash(base, info.getURITemplate().getValue());

                final String clazz = uproxyName(info.getResourceClass().getName());
                classSize = Math.max(classSize, clazz.length());
                addressSize = Math.max(addressSize, address.length());

                int methodSize = 7;
                int methodStrSize = 0;

                final List<Logs.LogOperationEndpointInfo> toLog = new ArrayList<>();

                final MethodDispatcher md = info.getMethodDispatcher();
                for (final OperationResourceInfo ori : md.getOperationResourceInfos()) {
                    final String httpMethod = ori.getHttpMethod();
                    final String currentAddress = Logs.singleSlash(address, ori.getURITemplate().getValue());
                    final String methodToStr = Logs.toSimpleString(ori.getMethodToInvoke());
                    toLog.add(new Logs.LogOperationEndpointInfo(httpMethod, currentAddress, methodToStr));

                    if (httpMethod != null) {
                        methodSize = Math.max(methodSize, httpMethod.length());
                    }
                    addressSize = Math.max(addressSize, currentAddress.length());
                    methodStrSize = Math.max(methodStrSize, methodToStr.length());
                }

                Collections.sort(toLog);

                resourcesToLog.add(new Logs.LogResourceEndpointInfo(address, clazz, toLog, methodSize, methodStrSize));
            }

            // effective logging
            log.info("REST Application: " + endpoint.getEndpointInfo().getAddress() + " -> "
                    + ofNullable(app).map(ApplicationInfo::getResourceClass).map(Class::getName).map(CxfCdiAutoSetup::uproxyName).orElse(""));

            Collections.sort(resourcesToLog);
            final int fClassSize = classSize;
            final int fAddressSize = addressSize;
            resourcesToLog.forEach(resource -> {
                log.info("     Service URI: "
                        + Logs.forceLength(resource.address, fAddressSize, true) + " -> "
                        + Logs.forceLength(resource.classname, fClassSize, true));

                resource.operations.forEach(info -> {
                    log.info("          "
                            + Logs.forceLength(info.http, resource.methodSize, false) + " "
                            + Logs.forceLength(info.address, fAddressSize, true) + " ->      "
                            + Logs.forceLength(info.method, resource.methodStrSize, true));
                });
                resource.operations.clear();
            });
            resourcesToLog.clear();

            // log @Providers
            if (Configuration.class.cast(sc.getServletContext().getAttribute("meecrowave.configuration")).isJaxrsLogProviders()) {
                final ServerProviderFactory spf = ServerProviderFactory.class.cast(endpoint.get(ServerProviderFactory.class.getName()));
                dump(log, spf, "MessageBodyReaders", "messageReaders");
                dump(log, spf, "MessageBodyWriters", "messageWriters");
            }
        } else {
            final EndpointInfo endpointInfo = endpoint.getEndpointInfo();
            if (endpointInfo.getName() != null) {
                log.info("@WebService > " + endpointInfo.getName().toString() + " -> " + base);
            }
        }

        return base;
    };
}
 
Example #26
Source File: OpenApiFeature.java    From cxf with Apache License 2.0 3 votes vote down vote up
protected void registerSwaggerUiResources(JAXRSServiceFactoryBean sfb, Properties properties,
                                          ServerProviderFactory factory, Bus bus) {

    final Registration swaggerUiRegistration = getSwaggerUi(bus, properties, isRunAsFilter());

    if (!isRunAsFilter()) {
        sfb.setResourceClassesFromBeans(swaggerUiRegistration.getResources());
    }
    
    factory.setUserProviders(swaggerUiRegistration.getProviders());
               
}