Search in sources :

Example 56 with Application

use of javax.ws.rs.core.Application in project cxf by apache.

the class DefaultApplicationFactory method createApplicationInfoOrDefault.

/**
 * 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;
}
Also used : ApplicationInfo(org.apache.cxf.jaxrs.model.ApplicationInfo) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) Application(javax.ws.rs.core.Application) HashSet(java.util.HashSet)

Example 57 with Application

use of javax.ws.rs.core.Application in project cxf by apache.

the class JaxrsServletContainerInitializer method onStartup.

@Override
public void onStartup(final Set<Class<?>> classes, final ServletContext ctx) throws ServletException {
    Application app = null;
    String servletName = null;
    String servletMapping = null;
    final Class<?> appClass = findCandidate(classes);
    if (appClass != null) {
        // Custom servlets using non-standard mechanisms to create Application will not be detected
        if (isApplicationServletAvailable(ctx, appClass)) {
            return;
        }
        try {
            app = (Application) appClass.newInstance();
        } catch (Throwable t) {
            throw new ServletException(t);
        }
        // Servlet name is the application class name
        servletName = appClass.getName();
        ApplicationPath appPath = ResourceUtils.locateApplicationPath(appClass);
        // a servlet registration with an application implementation class name
        if (appPath != null) {
            servletMapping = appPath.value() + "/*";
        } else {
            servletMapping = getServletMapping(ctx, servletName);
        }
    }
    // resource and provider classes
    if (app == null || (app.getClasses().isEmpty() && app.getSingletons().isEmpty())) {
        // Custom servlets using non-standard mechanisms to create Application will not be detected
        if (isCxfServletAvailable(ctx)) {
            return;
        }
        final Map<Class<? extends Annotation>, Collection<Class<?>>> providersAndResources = groupByAnnotations(classes);
        if (!providersAndResources.get(Path.class).isEmpty() || !providersAndResources.get(Provider.class).isEmpty()) {
            if (app == null) {
                // Servlet name is a JAX-RS Application class name
                servletName = JAXRS_APPLICATION_SERVLET_NAME;
                // Servlet mapping is obtained from a servlet registration
                // with a JAX-RS Application class name
                servletMapping = getServletMapping(ctx, servletName);
            }
            final Map<String, Object> appProperties = app != null ? app.getProperties() : Collections.emptyMap();
            app = new Application() {

                @Override
                public Set<Class<?>> getClasses() {
                    Set<Class<?>> set = new HashSet<>();
                    set.addAll(providersAndResources.get(Path.class));
                    set.addAll(providersAndResources.get(Provider.class));
                    return set;
                }

                @Override
                public Map<String, Object> getProperties() {
                    return appProperties;
                }
            };
        }
    }
    if (app == null) {
        return;
    }
    CXFNonSpringJaxrsServlet cxfServlet = new CXFNonSpringJaxrsServlet(app);
    final Dynamic servlet = ctx.addServlet(servletName, cxfServlet);
    servlet.addMapping(servletMapping);
}
Also used : Path(javax.ws.rs.Path) ApplicationPath(javax.ws.rs.ApplicationPath) Dynamic(javax.servlet.ServletRegistration.Dynamic) Set(java.util.Set) HashSet(java.util.HashSet) ApplicationPath(javax.ws.rs.ApplicationPath) Annotation(java.lang.annotation.Annotation) Provider(javax.ws.rs.ext.Provider) CXFNonSpringJaxrsServlet(org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet) ServletException(javax.servlet.ServletException) Collection(java.util.Collection) Application(javax.ws.rs.core.Application) HashMap(java.util.HashMap) Map(java.util.Map)

Example 58 with Application

use of javax.ws.rs.core.Application in project cxf by apache.

the class BookServer20 method createServer.

@Override
protected Server createServer(Bus bus) throws Exception {
    JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
    sf.setResourceClasses(BookStore.class);
    List<Object> providers = new ArrayList<>();
    providers.add(new PreMatchContainerRequestFilter2());
    providers.add(new PreMatchContainerRequestFilter());
    providers.add(new PostMatchContainerResponseFilter());
    providers.add((Feature) context -> {
        context.register(new PostMatchContainerResponseFilter3());
        return true;
    });
    providers.add(new PostMatchContainerResponseFilter2());
    providers.add(new CustomReaderBoundInterceptor());
    providers.add(new CustomReaderInterceptor());
    providers.add(new CustomWriterInterceptor());
    providers.add(new CustomDynamicFeature());
    providers.add(new PostMatchContainerRequestFilter());
    providers.add(new FaultyContainerRequestFilter());
    providers.add(new PreMatchReplaceStreamOrAddress());
    providers.add(new ServerTestFeature());
    providers.add(new JacksonJaxbJsonProvider());
    providers.add(new IOExceptionMapper());
    providers.add(new GregorianCalendarMessageBodyWriter());
    sf.setApplication(new Application());
    sf.setProviders(providers);
    sf.setResourceProvider(BookStore.class, new SingletonResourceProvider(new BookStore(), true));
    sf.setAddress("http://localhost:" + PORT + "/");
    return sf.create();
}
Also used : Arrays(java.util.Arrays) Provider(javax.ws.rs.ext.Provider) StringUtils(org.apache.cxf.common.util.StringUtils) ExceptionMapper(javax.ws.rs.ext.ExceptionMapper) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) Application(javax.ws.rs.core.Application) ContainerRequestFilter(javax.ws.rs.container.ContainerRequestFilter) ContainerResponseFilter(javax.ws.rs.container.ContainerResponseFilter) ContainerRequestContext(javax.ws.rs.container.ContainerRequestContext) MediaType(javax.ws.rs.core.MediaType) ByteArrayInputStream(java.io.ByteArrayInputStream) ReaderInterceptor(javax.ws.rs.ext.ReaderInterceptor) Map(java.util.Map) URI(java.net.URI) Method(java.lang.reflect.Method) Server(org.apache.cxf.endpoint.Server) Context(javax.ws.rs.core.Context) GregorianCalendar(java.util.GregorianCalendar) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) Collectors(java.util.stream.Collectors) JacksonJaxbJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider) PreMatching(javax.ws.rs.container.PreMatching) Priority(javax.annotation.Priority) DynamicFeature(javax.ws.rs.container.DynamicFeature) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) WriterInterceptorContext(javax.ws.rs.ext.WriterInterceptorContext) Response(javax.ws.rs.core.Response) Type(java.lang.reflect.Type) Annotation(java.lang.annotation.Annotation) WebApplicationException(javax.ws.rs.WebApplicationException) UriInfo(javax.ws.rs.core.UriInfo) ContainerResponseContext(javax.ws.rs.container.ContainerResponseContext) Bus(org.apache.cxf.Bus) SingletonResourceProvider(org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider) Feature(javax.ws.rs.core.Feature) SimpleDateFormat(java.text.SimpleDateFormat) ReaderInterceptorContext(javax.ws.rs.ext.ReaderInterceptorContext) HashMap(java.util.HashMap) Retention(java.lang.annotation.Retention) ArrayList(java.util.ArrayList) HttpServletRequest(javax.servlet.http.HttpServletRequest) FeatureContext(javax.ws.rs.core.FeatureContext) ResourceInfo(javax.ws.rs.container.ResourceInfo) WriterInterceptor(javax.ws.rs.ext.WriterInterceptor) AbstractServerTestServerBase(org.apache.cxf.testutil.common.AbstractServerTestServerBase) OutputStream(java.io.OutputStream) JAXRSServerFactoryBean(org.apache.cxf.jaxrs.JAXRSServerFactoryBean) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOUtils(org.apache.cxf.helpers.IOUtils) IOException(java.io.IOException) Target(java.lang.annotation.Target) ElementType(java.lang.annotation.ElementType) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) NameBinding(javax.ws.rs.NameBinding) InjectionUtils(org.apache.cxf.jaxrs.utils.InjectionUtils) InputStream(java.io.InputStream) RetentionPolicy(java.lang.annotation.RetentionPolicy) JAXRSServerFactoryBean(org.apache.cxf.jaxrs.JAXRSServerFactoryBean) ArrayList(java.util.ArrayList) SingletonResourceProvider(org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider) JacksonJaxbJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider) Application(javax.ws.rs.core.Application)

Example 59 with Application

use of javax.ws.rs.core.Application in project openremote by openremote.

the class AbstractHTTPServerProtocol method doStart.

@Override
public void doStart(Container container) throws Exception {
    this.container = container;
    this.devMode = container.isDevMode();
    identityService = container.hasService(IdentityService.class) ? container.getService(IdentityService.class) : null;
    webService = container.getService(WebService.class);
    if (defaultResteasyExceptionMapper == null) {
        defaultResteasyExceptionMapper = new WebServiceExceptions.DefaultResteasyExceptionMapper(devMode);
        forbiddenResteasyExceptionMapper = new WebServiceExceptions.ForbiddenResteasyExceptionMapper(devMode);
        undertowExceptionHandler = new WebServiceExceptions.ServletUndertowExceptionHandler(devMode);
        jacksonConfig = new JacksonConfig();
        alreadyGzippedWriterInterceptor = new AlreadyGzippedWriterInterceptor();
        clientErrorExceptionHandler = new ClientErrorExceptionHandler();
    }
    Application application = createApplication();
    ResteasyDeployment deployment = createDeployment(application);
    DeploymentInfo deploymentInfo = createDeploymentInfo(deployment);
    configureDeploymentInfo(deploymentInfo);
    deploy(deploymentInfo);
}
Also used : JacksonConfig(org.openremote.container.json.JacksonConfig) ResteasyDeployment(org.jboss.resteasy.spi.ResteasyDeployment) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) Application(javax.ws.rs.core.Application)

Example 60 with Application

use of javax.ws.rs.core.Application in project wildfly by wildfly.

the class JaxrsIntegrationProcessor method deploy.

@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    if (!JaxrsDeploymentMarker.isJaxrsDeployment(deploymentUnit)) {
        return;
    }
    if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) {
        return;
    }
    final DeploymentUnit parent = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent();
    final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
    final JBossWebMetaData webdata = warMetaData.getMergedJBossWebMetaData();
    setConfigParameters(phaseContext, webdata);
    final ResteasyDeploymentData resteasy = deploymentUnit.getAttachment(JaxrsAttachments.RESTEASY_DEPLOYMENT_DATA);
    if (resteasy == null)
        return;
    deploymentUnit.getDeploymentSubsystemModel(JaxrsExtension.SUBSYSTEM_NAME);
    final List<ParamValueMetaData> params = webdata.getContextParams();
    boolean entityExpandEnabled = false;
    if (params != null) {
        Iterator<ParamValueMetaData> it = params.iterator();
        while (it.hasNext()) {
            final ParamValueMetaData param = it.next();
            if (param.getParamName().equals(ResteasyContextParameters.RESTEASY_EXPAND_ENTITY_REFERENCES)) {
                entityExpandEnabled = true;
            }
        }
    }
    // don't expand entity references by default
    if (!entityExpandEnabled) {
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_EXPAND_ENTITY_REFERENCES, "false");
    }
    final Map<ModuleIdentifier, ResteasyDeploymentData> attachmentMap = parent.getAttachment(JaxrsAttachments.ADDITIONAL_RESTEASY_DEPLOYMENT_DATA);
    final List<ResteasyDeploymentData> additionalData = new ArrayList<ResteasyDeploymentData>();
    final ModuleSpecification moduleSpec = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
    if (moduleSpec != null && attachmentMap != null) {
        final Set<ModuleIdentifier> identifiers = new HashSet<ModuleIdentifier>();
        for (ModuleDependency dep : moduleSpec.getAllDependencies()) {
            // make sure we don't double up
            if (!identifiers.contains(dep.getIdentifier())) {
                identifiers.add(dep.getIdentifier());
                if (attachmentMap.containsKey(dep.getIdentifier())) {
                    additionalData.add(attachmentMap.get(dep.getIdentifier()));
                }
            }
        }
        resteasy.merge(additionalData);
    }
    if (!resteasy.getScannedResourceClasses().isEmpty()) {
        StringBuilder buf = null;
        for (String resource : resteasy.getScannedResourceClasses()) {
            if (buf == null) {
                buf = new StringBuilder();
                buf.append(resource);
            } else {
                buf.append(",").append(resource);
            }
        }
        String resources = buf.toString();
        JAXRS_LOGGER.debugf("Adding Jakarta RESTful Web Services resource classes: %s", resources);
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_SCANNED_RESOURCES, resources);
    }
    if (!resteasy.getScannedProviderClasses().isEmpty()) {
        StringBuilder buf = null;
        for (String provider : resteasy.getScannedProviderClasses()) {
            if (buf == null) {
                buf = new StringBuilder();
                buf.append(provider);
            } else {
                buf.append(",").append(provider);
            }
        }
        String providers = buf.toString();
        JAXRS_LOGGER.debugf("Adding Jakarta RESTful Web Services provider classes: %s", providers);
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_SCANNED_PROVIDERS, providers);
    }
    if (!resteasy.getScannedJndiComponentResources().isEmpty()) {
        StringBuilder buf = null;
        for (String resource : resteasy.getScannedJndiComponentResources()) {
            if (buf == null) {
                buf = new StringBuilder();
                buf.append(resource);
            } else {
                buf.append(",").append(resource);
            }
        }
        String providers = buf.toString();
        JAXRS_LOGGER.debugf("Adding Jakarta RESTful Web Services jndi component resource classes: %s", providers);
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_SCANNED_JNDI_RESOURCES, providers);
    }
    if (!resteasy.isUnwrappedExceptionsParameterSet()) {
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_UNWRAPPED_EXCEPTIONS, "javax.ejb.EJBException");
    }
    if (findContextParam(webdata, ResteasyContextParameters.RESTEASY_PREFER_JACKSON_OVER_JSONB) == null) {
        final String prop = WildFlySecurityManager.getPropertyPrivileged(ResteasyContextParameters.RESTEASY_PREFER_JACKSON_OVER_JSONB, null);
        if (prop != null) {
            setContextParameter(webdata, ResteasyContextParameters.RESTEASY_PREFER_JACKSON_OVER_JSONB, prop);
        } else {
            setContextParameter(webdata, ResteasyContextParameters.RESTEASY_PREFER_JACKSON_OVER_JSONB, Boolean.toString(hasJacksonAnnotations(deploymentUnit)));
        }
    }
    boolean managementAdded = false;
    if (!resteasy.getScannedApplicationClasses().isEmpty() || resteasy.hasBootClasses() || resteasy.isDispatcherCreated()) {
        addManagement(deploymentUnit, resteasy);
        managementAdded = true;
    }
    if (resteasy.hasBootClasses() || resteasy.isDispatcherCreated())
        return;
    // ignore any non-annotated Application class that doesn't have a servlet mapping
    Set<Class<? extends Application>> applicationClassSet = new HashSet<>();
    for (Class<? extends Application> clazz : resteasy.getScannedApplicationClasses()) {
        if (clazz.isAnnotationPresent(ApplicationPath.class) || servletMappingsExist(webdata, clazz.getName())) {
            applicationClassSet.add(clazz);
        }
    }
    // add default servlet
    if (applicationClassSet.isEmpty()) {
        JBossServletMetaData servlet = new JBossServletMetaData();
        servlet.setName(JAX_RS_SERVLET_NAME);
        servlet.setServletClass(HttpServlet30Dispatcher.class.getName());
        servlet.setAsyncSupported(true);
        addServlet(webdata, servlet);
        setServletMappingPrefix(webdata, JAX_RS_SERVLET_NAME, servlet);
    } else {
        for (Class<? extends Application> applicationClass : applicationClassSet) {
            String servletName = null;
            servletName = applicationClass.getName();
            JBossServletMetaData servlet = new JBossServletMetaData();
            // must load on startup for services like JSAPI to work
            servlet.setLoadOnStartup("" + 0);
            servlet.setName(servletName);
            servlet.setServletClass(HttpServlet30Dispatcher.class.getName());
            servlet.setAsyncSupported(true);
            setServletInitParam(servlet, SERVLET_INIT_PARAM, applicationClass.getName());
            addServlet(webdata, servlet);
            if (!servletMappingsExist(webdata, servletName)) {
                try {
                    // no mappings, add our own
                    List<String> patterns = new ArrayList<String>();
                    // for some reason the spec requires this to be decoded
                    String pathValue = URLDecoder.decode(applicationClass.getAnnotation(ApplicationPath.class).value().trim(), "UTF-8");
                    if (!pathValue.startsWith("/")) {
                        pathValue = "/" + pathValue;
                    }
                    String prefix = pathValue;
                    if (pathValue.endsWith("/")) {
                        pathValue += "*";
                    } else {
                        pathValue += "/*";
                    }
                    patterns.add(pathValue);
                    setServletInitParam(servlet, "resteasy.servlet.mapping.prefix", prefix);
                    ServletMappingMetaData mapping = new ServletMappingMetaData();
                    mapping.setServletName(servletName);
                    mapping.setUrlPatterns(patterns);
                    if (webdata.getServletMappings() == null) {
                        webdata.setServletMappings(new ArrayList<ServletMappingMetaData>());
                    }
                    webdata.getServletMappings().add(mapping);
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            } else {
                setServletMappingPrefix(webdata, servletName, servlet);
            }
        }
    }
    if (!managementAdded && webdata.getServletMappings() != null) {
        for (ServletMappingMetaData servletMapMeta : webdata.getServletMappings()) {
            if (JAX_RS_SERVLET_NAME.equals(servletMapMeta.getServletName())) {
                addManagement(deploymentUnit, resteasy);
                break;
            }
        }
    }
    // suppress warning for EAR deployments, as we can't easily tell here the app is properly declared
    if (deploymentUnit.getParent() == null && (webdata.getServletMappings() == null || webdata.getServletMappings().isEmpty())) {
        JAXRS_LOGGER.noServletDeclaration(deploymentUnit.getName());
    }
}
Also used : JBossWebMetaData(org.jboss.metadata.web.jboss.JBossWebMetaData) ModuleDependency(org.jboss.as.server.deployment.module.ModuleDependency) JBossServletMetaData(org.jboss.metadata.web.jboss.JBossServletMetaData) WarMetaData(org.jboss.as.web.common.WarMetaData) ArrayList(java.util.ArrayList) ApplicationPath(javax.ws.rs.ApplicationPath) ModuleIdentifier(org.jboss.modules.ModuleIdentifier) HashSet(java.util.HashSet) ParamValueMetaData(org.jboss.metadata.javaee.spec.ParamValueMetaData) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ServletMappingMetaData(org.jboss.metadata.web.spec.ServletMappingMetaData) HttpServlet30Dispatcher(org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher) ModuleSpecification(org.jboss.as.server.deployment.module.ModuleSpecification) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit) Application(javax.ws.rs.core.Application)

Aggregations

Application (javax.ws.rs.core.Application)63 HashSet (java.util.HashSet)14 HashMap (java.util.HashMap)12 ApplicationInfo (org.apache.cxf.jaxrs.model.ApplicationInfo)12 JAXRSServerFactoryBean (org.apache.cxf.jaxrs.JAXRSServerFactoryBean)9 Test (org.junit.Test)9 ArrayList (java.util.ArrayList)8 IOException (java.io.IOException)7 Set (java.util.Set)7 ServletException (javax.servlet.ServletException)7 Annotation (java.lang.annotation.Annotation)5 List (java.util.List)5 Map (java.util.Map)5 ApplicationPath (javax.ws.rs.ApplicationPath)4 WebApplicationException (javax.ws.rs.WebApplicationException)4 ClassResourceInfo (org.apache.cxf.jaxrs.model.ClassResourceInfo)4 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)3 Method (java.lang.reflect.Method)3 Type (java.lang.reflect.Type)3 Collection (java.util.Collection)3