Search in sources :

Example 16 with Application

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

the class JaxrsScanningProcessor method scan.

protected void scan(final DeploymentUnit du, final ClassLoader classLoader, final ResteasyDeploymentData resteasyDeploymentData) throws DeploymentUnitProcessingException, ModuleLoadException {
    final CompositeIndex index = du.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
    if (!resteasyDeploymentData.shouldScan()) {
        return;
    }
    if (!resteasyDeploymentData.isDispatcherCreated()) {
        final Set<ClassInfo> applicationClasses = index.getAllKnownSubclasses(APPLICATION);
        try {
            for (ClassInfo c : applicationClasses) {
                if (Modifier.isAbstract(c.flags()))
                    continue;
                @SuppressWarnings("unchecked") Class<? extends Application> scanned = (Class<? extends Application>) classLoader.loadClass(c.name().toString());
                resteasyDeploymentData.getScannedApplicationClasses().add(scanned);
            }
        } catch (ClassNotFoundException e) {
            throw JaxrsLogger.JAXRS_LOGGER.cannotLoadApplicationClass(e);
        }
    }
    List<AnnotationInstance> resources = null;
    List<AnnotationInstance> providers = null;
    if (resteasyDeploymentData.isScanResources()) {
        resources = index.getAnnotations(JaxrsAnnotations.PATH.getDotName());
    }
    if (resteasyDeploymentData.isScanProviders()) {
        providers = index.getAnnotations(JaxrsAnnotations.PROVIDER.getDotName());
    }
    if ((resources == null || resources.isEmpty()) && (providers == null || providers.isEmpty()))
        return;
    final Set<ClassInfo> pathInterfaces = new HashSet<ClassInfo>();
    if (resources != null) {
        for (AnnotationInstance e : resources) {
            final ClassInfo info;
            if (e.target() instanceof ClassInfo) {
                info = (ClassInfo) e.target();
            } else if (e.target() instanceof MethodInfo) {
                //ignore
                continue;
            } else {
                JAXRS_LOGGER.classOrMethodAnnotationNotFound("@Path", e.target());
                continue;
            }
            if (info.annotations().containsKey(DECORATOR)) {
                //we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
                continue;
            }
            if (!Modifier.isInterface(info.flags())) {
                resteasyDeploymentData.getScannedResourceClasses().add(info.name().toString());
            } else {
                pathInterfaces.add(info);
            }
        }
    }
    if (providers != null) {
        for (AnnotationInstance e : providers) {
            if (e.target() instanceof ClassInfo) {
                ClassInfo info = (ClassInfo) e.target();
                if (info.annotations().containsKey(DECORATOR)) {
                    //we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
                    continue;
                }
                if (!Modifier.isInterface(info.flags())) {
                    resteasyDeploymentData.getScannedProviderClasses().add(info.name().toString());
                }
            } else {
                JAXRS_LOGGER.classAnnotationNotFound("@Provider", e.target());
            }
        }
    }
    // look for all implementations of interfaces annotated @Path
    for (final ClassInfo iface : pathInterfaces) {
        final Set<ClassInfo> implementors = index.getAllKnownImplementors(iface.name());
        for (final ClassInfo implementor : implementors) {
            if (implementor.annotations().containsKey(DECORATOR)) {
                //we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
                continue;
            }
            resteasyDeploymentData.getScannedResourceClasses().add(implementor.name().toString());
        }
    }
}
Also used : CompositeIndex(org.jboss.as.server.deployment.annotation.CompositeIndex) MethodInfo(org.jboss.jandex.MethodInfo) Application(javax.ws.rs.core.Application) AnnotationInstance(org.jboss.jandex.AnnotationInstance) ClassInfo(org.jboss.jandex.ClassInfo) HashSet(java.util.HashSet)

Example 17 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();
    final ResteasyDeploymentData resteasy = deploymentUnit.getAttachment(JaxrsAttachments.RESTEASY_DEPLOYMENT_DATA);
    if (resteasy == null)
        return;
    deploymentUnit.getDeploymentSubsystemModel(JaxrsExtension.SUBSYSTEM_NAME);
    //remove the resteasy.scan parameter
    //because it is not needed
    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(RESTEASY_SCAN)) {
                it.remove();
            } else if (param.getParamName().equals(RESTEASY_SCAN_RESOURCES)) {
                it.remove();
            } else if (param.getParamName().equals(RESTEASY_SCAN_PROVIDERS)) {
                it.remove();
            } else 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()) {
        StringBuffer buf = null;
        for (String resource : resteasy.getScannedResourceClasses()) {
            if (buf == null) {
                buf = new StringBuffer();
                buf.append(resource);
            } else {
                buf.append(",").append(resource);
            }
        }
        String resources = buf.toString();
        JAXRS_LOGGER.debugf("Adding JAX-RS resource classes: %s", resources);
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_SCANNED_RESOURCES, resources);
    }
    if (!resteasy.getScannedProviderClasses().isEmpty()) {
        StringBuffer buf = null;
        for (String provider : resteasy.getScannedProviderClasses()) {
            if (buf == null) {
                buf = new StringBuffer();
                buf.append(provider);
            } else {
                buf.append(",").append(provider);
            }
        }
        String providers = buf.toString();
        JAXRS_LOGGER.debugf("Adding JAX-RS provider classes: %s", providers);
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_SCANNED_PROVIDERS, providers);
    }
    if (!resteasy.getScannedJndiComponentResources().isEmpty()) {
        StringBuffer buf = null;
        for (String resource : resteasy.getScannedJndiComponentResources()) {
            if (buf == null) {
                buf = new StringBuffer();
                buf.append(resource);
            } else {
                buf.append(",").append(resource);
            }
        }
        String providers = buf.toString();
        JAXRS_LOGGER.debugf("Adding JAX-RS 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 (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.size() == 0) {
        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 (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)

Example 18 with Application

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

the class RESTService method deployApplication.

private void deployApplication(final AppInfo appInfo, final String contextRoot, final Map<String, EJBRestServiceInfo> restEjbs, final ClassLoader classLoader, final Collection<Injection> injections, final WebBeansContext owbCtx, final Context context, final Collection<Object> additionalProviders, final Collection<IdPropertiesInfo> pojoConfigurations, final Application application, final String prefix) {
    // get configuration
    Properties configuration;
    if (InternalApplication.class.equals(application.getClass())) {
        final Application original = InternalApplication.class.cast(application).getOriginal();
        if (original == null) {
            configuration = PojoUtil.findConfiguration(pojoConfigurations, "jaxrs-application");
        } else {
            configuration = PojoUtil.findConfiguration(pojoConfigurations, original.getClass().getName());
        }
    } else {
        configuration = PojoUtil.findConfiguration(pojoConfigurations, application.getClass().getName());
    }
    if (configuration == null) {
        // try a constant (common in half of cases)
        configuration = PojoUtil.findConfiguration(pojoConfigurations, "jaxrs-application");
    }
    if (configuration != null) {
        LOGGER.info("Registered JAX-RS Configuration: " + configuration);
    }
    final String base = getAddress(contextRoot);
    final String nopath;
    if (base.endsWith("/") && prefix.startsWith("/")) {
        nopath = base + prefix.substring(1);
    } else {
        nopath = base + prefix;
    }
    final RsHttpListener listener = createHttpListener();
    final String host = findHost(contextRoot, appInfo.webApps);
    final RsRegistry.AddressInfo address = rsRegistry.createRsHttpListener(appInfo.appId, contextRoot, listener, classLoader, nopath.substring(NOPATH_PREFIX.length() - 1), host, auth, realm);
    services.add(new DeployedService(address.complete, contextRoot, application.getClass().getName(), appInfo.appId));
    // app config
    listener.deployApplication(// app config
    application, // app config
    address.complete.substring(0, address.complete.length() - wildcard.length()), // app config
    nopath.substring(NOPATH_PREFIX.length(), nopath.length() - wildcard.length()), // app config
    additionalProviders, // app config
    restEjbs, // injection/webapp context
    classLoader, // injection/webapp context
    injections, // injection/webapp context
    context, // injection/webapp context
    owbCtx, // deployment config
    new ServiceConfiguration(configuration, appInfo.services));
}
Also used : ServiceConfiguration(org.apache.openejb.assembler.classic.util.ServiceConfiguration) Properties(java.util.Properties) Application(javax.ws.rs.core.Application)

Example 19 with Application

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

the class RESTService method afterApplicationCreated.

public void afterApplicationCreated(@Observes final AssemblerAfterApplicationCreated event) {
    if (!enabled)
        return;
    final AppInfo appInfo = event.getApp();
    if ("false".equalsIgnoreCase(appInfo.properties.getProperty("openejb.jaxrs.on", "true"))) {
        return;
    }
    quickCheckIfOldDeploymentShouldBeUsedFromEjbConfig(appInfo);
    if (deployedApplications.add(appInfo)) {
        if (appInfo.webApps.size() == 0) {
            final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
            final ClassLoader appClassLoader = getClassLoader(containerSystem.getAppContext(appInfo.appId).getClassLoader());
            Thread.currentThread().setContextClassLoader(appClassLoader);
            try {
                final Map<String, EJBRestServiceInfo> restEjbs = getRestEjbs(appInfo, null);
                if (restEjbs.isEmpty()) {
                    return;
                }
                final Collection<Object> providers;
                if (useDiscoveredProviders(appInfo)) {
                    providers = appProviders(appInfo.jaxRsProviders, appClassLoader);
                } else {
                    providers = new ArrayList<>();
                }
                if ("true".equalsIgnoreCase(appInfo.properties.getProperty(OPENEJB_USE_APPLICATION_PROPERTY, APPLICATION_DEPLOYMENT))) {
                    final Application application = new InternalApplication(null);
                    addEjbToApplication(application, restEjbs);
                    // merge configurations at app level since a single deployment is available
                    final List<IdPropertiesInfo> pojoConfigurations = new ArrayList<>();
                    BeanContext comp = null;
                    for (final EjbJarInfo ejbJar : appInfo.ejbJars) {
                        for (final EnterpriseBeanInfo bean : ejbJar.enterpriseBeans) {
                            if (comp != null) {
                                break;
                            }
                            if (bean.ejbClass.equals(BeanContext.Comp.class.getName())) {
                                comp = containerSystem.getBeanContext(bean.ejbDeploymentId);
                                break;
                            }
                        }
                        if (ejbJar.pojoConfigurations != null) {
                            pojoConfigurations.addAll(ejbJar.pojoConfigurations);
                        }
                    }
                    if (appInfo.pojoConfigurations != null) {
                        pojoConfigurations.addAll(appInfo.pojoConfigurations);
                    }
                    final Map.Entry<String, EJBRestServiceInfo> next = restEjbs.entrySet().iterator().next();
                    if (comp == null) {
                        comp = next.getValue().context;
                    }
                    deployApplication(appInfo, next.getValue().path, restEjbs, comp.getClassLoader(), comp.getInjections(), containerSystem.getAppContext(appInfo.appId).getWebBeansContext(), comp.getJndiContext(), providers, pojoConfigurations, application, wildcard);
                } else {
                    for (final Map.Entry<String, EJBRestServiceInfo> ejb : restEjbs.entrySet()) {
                        final BeanContext ctx = ejb.getValue().context;
                        if (BeanType.MANAGED.equals(ctx.getComponentType())) {
                            deployPojo(appInfo.appId, "", ejb.getValue().path, ctx.getBeanClass(), null, ctx.getClassLoader(), ctx.getInjections(), ctx.getJndiContext(), containerSystem.getAppContext(appInfo.appId).getWebBeansContext(), providers, new ServiceConfiguration(ctx.getProperties(), appInfo.services));
                        } else {
                            deployEJB(appInfo.appId, "", ejb.getValue().path, ctx, providers, appInfo.services);
                        }
                    }
                }
            } finally {
                Thread.currentThread().setContextClassLoader(oldLoader);
            }
        } else {
            for (final WebAppInfo webApp : appInfo.webApps) {
                afterApplicationCreated(appInfo, webApp);
            }
        }
    }
}
Also used : ArrayList(java.util.ArrayList) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) AppInfo(org.apache.openejb.assembler.classic.AppInfo) EnterpriseBeanInfo(org.apache.openejb.assembler.classic.EnterpriseBeanInfo) BeanContext(org.apache.openejb.BeanContext) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) ServiceConfiguration(org.apache.openejb.assembler.classic.util.ServiceConfiguration) IdPropertiesInfo(org.apache.openejb.assembler.classic.IdPropertiesInfo) Application(javax.ws.rs.core.Application) EjbJarInfo(org.apache.openejb.assembler.classic.EjbJarInfo) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

Application (javax.ws.rs.core.Application)19 HashSet (java.util.HashSet)9 Test (org.junit.Test)8 ArrayList (java.util.ArrayList)3 BeanContext (org.apache.openejb.BeanContext)3 IdPropertiesInfo (org.apache.openejb.assembler.classic.IdPropertiesInfo)3 ServiceConfiguration (org.apache.openejb.assembler.classic.util.ServiceConfiguration)3 IOException (java.io.IOException)2 MalformedURLException (java.net.MalformedURLException)2 URISyntaxException (java.net.URISyntaxException)2 Set (java.util.Set)2 ServiceException (org.apache.openejb.server.ServiceException)2 MetaAnnotatedClass (org.apache.xbean.finder.MetaAnnotatedClass)2 Function (com.google.common.base.Function)1 HttpHandler (com.sun.net.httpserver.HttpHandler)1 HttpServer (com.sun.net.httpserver.HttpServer)1 DefaultJaxrsScanner (io.swagger.jaxrs.config.DefaultJaxrsScanner)1 File (java.io.File)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 InetSocketAddress (java.net.InetSocketAddress)1