Search in sources :

Example 1 with ManagedBean

use of javax.annotation.ManagedBean in project tomee by apache.

the class JndiEncBuilder method buildMap.

public Map<String, Object> buildMap(final JndiScope scope) throws OpenEJBException {
    // let it be sorted for real binding
    final Map<String, Object> bindings = new TreeMap<>();
    // get JtaEntityManagerRegistry
    final JtaEntityManagerRegistry jtaEntityManagerRegistry = SystemInstance.get().getComponent(JtaEntityManagerRegistry.class);
    for (final EjbReferenceInfo referenceInfo : jndiEnc.ejbReferences) {
        final Reference reference;
        if (referenceInfo.location != null) {
            reference = buildReferenceLocation(referenceInfo.location);
        } else if (referenceInfo.ejbDeploymentId == null) {
            reference = new LazyEjbReference(new Ref(referenceInfo), moduleUri, useCrossClassLoaderRef);
        } else {
            final String jndiName = "openejb/Deployment/" + JndiBuilder.format(referenceInfo.ejbDeploymentId, referenceInfo.interfaceClassName, referenceInfo.localbean ? InterfaceType.LOCALBEAN : InterfaceType.BUSINESS_REMOTE);
            if (useCrossClassLoaderRef && referenceInfo.externalReference) {
                reference = new CrossClassLoaderJndiReference(jndiName);
            } else {
                reference = new IntraVmJndiReference(jndiName);
            }
        }
        bindings.put(normalize(referenceInfo.referenceName), reference);
    }
    for (final EjbReferenceInfo referenceInfo : jndiEnc.ejbLocalReferences) {
        final Reference reference;
        if (referenceInfo.location != null) {
            reference = buildReferenceLocation(referenceInfo.location);
        } else if (referenceInfo.ejbDeploymentId == null) {
            reference = new LazyEjbReference(new Ref(referenceInfo), moduleUri, false);
        } else {
            final String jndiName = "openejb/Deployment/" + JndiBuilder.format(referenceInfo.ejbDeploymentId, referenceInfo.interfaceClassName, referenceInfo.localbean ? InterfaceType.LOCALBEAN : InterfaceType.BUSINESS_LOCAL);
            reference = new IntraVmJndiReference(jndiName);
        }
        bindings.put(normalize(referenceInfo.referenceName), reference);
    }
    for (final EnvEntryInfo entry : jndiEnc.envEntries) {
        if (entry.location != null) {
            final Reference reference = buildReferenceLocation(entry.location);
            bindings.put(normalize(entry.referenceName), reference);
            continue;
        }
        // It is possible that the value and location are both null, as it is allowed to use @Resource(name="java:global/env/abc") with no value is specified in DD
        if (entry.value == null) {
            continue;
        }
        try {
            final Class type = Classes.deprimitivize(getType(entry.type, entry));
            final Object obj;
            if (type == String.class) {
                obj = new String(entry.value);
            } else if (type == Double.class) {
                obj = new Double(entry.value);
            } else if (type == Integer.class) {
                obj = new Integer(entry.value);
            } else if (type == Long.class) {
                obj = new Long(entry.value);
            } else if (type == Float.class) {
                obj = new Float(entry.value);
            } else if (type == Short.class) {
                obj = new Short(entry.value);
            } else if (type == Boolean.class) {
                obj = Boolean.valueOf(entry.value);
            } else if (type == Byte.class) {
                obj = new Byte(entry.value);
            } else if (type == Character.class) {
                final StringBuilder sb = new StringBuilder(entry.value + " ");
                obj = sb.charAt(0);
            } else if (type == URL.class) {
                obj = new URL(entry.value);
            } else if (type == Class.class) {
                obj = new ClassReference(entry.value.trim());
            } else if (type.isEnum()) {
                obj = Enum.valueOf(type, entry.value.trim());
            } else {
                throw new IllegalArgumentException("Invalid env-entry-type " + type);
            }
            bindings.put(normalize(entry.referenceName), obj);
        } catch (final NumberFormatException e) {
            throw new IllegalArgumentException("The env-entry-value for entry " + entry.referenceName + " was not recognizable as type " + entry.type + ". Received Message: " + e.getLocalizedMessage(), e);
        } catch (final MalformedURLException e) {
            throw new IllegalArgumentException("URL for reference " + entry.referenceName + " was not a valid URL: " + entry.value, e);
        }
    }
    for (final ResourceReferenceInfo referenceInfo : jndiEnc.resourceRefs) {
        if (!(referenceInfo instanceof ContextReferenceInfo)) {
            if (referenceInfo.location != null) {
                final Reference reference = buildReferenceLocation(referenceInfo.location);
                bindings.put(normalize(referenceInfo.referenceName), reference);
                continue;
            }
            final Class<?> type = getType(referenceInfo.referenceType, referenceInfo);
            final Object reference;
            if (URL.class.equals(type)) {
                reference = new URLReference(referenceInfo.resourceID);
            } else if (type.isAnnotationPresent(ManagedBean.class)) {
                final ManagedBean managed = type.getAnnotation(ManagedBean.class);
                final String name = managed.value().length() == 0 ? type.getSimpleName() : managed.value();
                reference = new LinkRef("module/" + name);
            } else if (referenceInfo.resourceID != null) {
                final String jndiName = "openejb/Resource/" + referenceInfo.resourceID;
                reference = new IntraVmJndiReference(jndiName);
            } else {
                final String jndiName = "openejb/Resource/" + referenceInfo.referenceName;
                reference = new IntraVmJndiReference(jndiName);
            }
            bindings.put(normalize(referenceInfo.referenceName), reference);
        } else {
            final Class<?> type = getType(referenceInfo.referenceType, referenceInfo);
            final Object reference;
            if (Request.class.equals(type)) {
                reference = new ObjectReference(ThreadLocalContextManager.REQUEST);
            } else if (HttpServletRequest.class.equals(type)) {
                reference = new ObjectReference(ThreadLocalContextManager.HTTP_SERVLET_REQUEST);
            } else if (ServletRequest.class.equals(type)) {
                reference = new ObjectReference(ThreadLocalContextManager.SERVLET_REQUEST);
            } else if (UriInfo.class.equals(type)) {
                reference = new ObjectReference(ThreadLocalContextManager.URI_INFO);
            } else if (HttpHeaders.class.equals(type)) {
                reference = new ObjectReference(ThreadLocalContextManager.HTTP_HEADERS);
            } else if (SecurityContext.class.equals(type)) {
                reference = new ObjectReference(ThreadLocalContextManager.SECURITY_CONTEXT);
            } else if (ContextResolver.class.equals(type)) {
                reference = new ObjectReference(ThreadLocalContextManager.CONTEXT_RESOLVER);
            } else if (Providers.class.equals(type)) {
                reference = new ObjectReference(ThreadLocalContextManager.PROVIDERS);
            } else if (ServletConfig.class.equals(type)) {
                reference = new ObjectReference(ThreadLocalContextManager.SERVLET_CONFIG);
            } else if (ServletContext.class.equals(type)) {
                reference = new ObjectReference(ThreadLocalContextManager.SERVLET_CONTEXT);
            } else if (HttpServletResponse.class.equals(type)) {
                reference = new ObjectReference(ThreadLocalContextManager.HTTP_SERVLET_RESPONSE);
            } else if (javax.ws.rs.container.ResourceInfo.class.equals(type)) {
                reference = new ObjectReference(ThreadLocalContextManager.RESOURCE_INFO);
            } else if (ResourceContext.class.equals(type)) {
                reference = new ObjectReference(ThreadLocalContextManager.RESOURCE_CONTEXT);
            } else if (Configuration.class.equals(type)) {
                reference = new ObjectReference(ThreadLocalContextManager.CONFIGURATION);
            } else if (Application.class.equals(type)) {
                reference = new ObjectReference(ThreadLocalContextManager.APPLICATION);
            } else {
                reference = new MapObjectReference(ThreadLocalContextManager.OTHERS, referenceInfo.referenceType);
            }
            bindings.put(normalize(referenceInfo.referenceName), reference);
        }
    }
    for (final ResourceEnvReferenceInfo referenceInfo : jndiEnc.resourceEnvRefs) {
        if (referenceInfo.location != null) {
            final Reference reference = buildReferenceLocation(referenceInfo.location);
            bindings.put(normalize(referenceInfo.referenceName), reference);
            continue;
        }
        final Class<?> type = getType(referenceInfo.resourceEnvRefType, referenceInfo);
        final Object reference;
        if (EJBContext.class.isAssignableFrom(type)) {
            final String jndiName = "comp/EJBContext";
            reference = new LinkRef(jndiName);
            // Let the container bind this into JNDI
            if (jndiName.equals(referenceInfo.referenceName)) {
                continue;
            }
        } else if (Validator.class.equals(type)) {
            final String jndiName = "comp/Validator";
            reference = new LinkRef(jndiName);
        } else if (ValidatorFactory.class.equals(type)) {
            final String jndiName = "comp/ValidatorFactory";
            reference = new LinkRef(jndiName);
        } else if (WebServiceContext.class.equals(type)) {
            final String jndiName = "comp/WebServiceContext";
            reference = new LinkRef(jndiName);
        } else if (TimerService.class.equals(type)) {
            final String jndiName = "comp/TimerService";
            reference = new LinkRef(jndiName);
        } else if (BeanManager.class.equals(type)) {
            reference = new LazyObjectReference<>(new BeanManagerLazyReference());
        } else if (UserTransaction.class.equals(type)) {
            reference = new IntraVmJndiReference("comp/UserTransaction");
        } else if (referenceInfo.resourceID != null) {
            final String jndiName = "openejb/Resource/" + referenceInfo.resourceID;
            reference = new IntraVmJndiReference(jndiName);
        } else {
            final String jndiName = "openejb/Resource/" + referenceInfo.referenceName;
            reference = new IntraVmJndiReference(jndiName);
        }
        bindings.put(normalize(referenceInfo.referenceName), reference);
    }
    for (final PersistenceUnitReferenceInfo referenceInfo : jndiEnc.persistenceUnitRefs) {
        if (referenceInfo.location != null) {
            final Reference reference = buildReferenceLocation(referenceInfo.location);
            bindings.put(normalize(referenceInfo.referenceName), reference);
            continue;
        }
        final String jndiName = PersistenceBuilder.getOpenEJBJndiName(referenceInfo.unitId);
        final Reference reference = new IntraVmJndiReference(jndiName);
        bindings.put(normalize(referenceInfo.referenceName), reference);
    }
    for (final PersistenceContextReferenceInfo contextInfo : jndiEnc.persistenceContextRefs) {
        if (contextInfo.location != null) {
            final Reference reference = buildReferenceLocation(contextInfo.location);
            bindings.put(normalize(contextInfo.referenceName), reference);
            continue;
        }
        final Context context = SystemInstance.get().getComponent(ContainerSystem.class).getJNDIContext();
        final EntityManagerFactory factory;
        try {
            final String jndiName = PersistenceBuilder.getOpenEJBJndiName(contextInfo.unitId);
            factory = (EntityManagerFactory) context.lookup(jndiName);
        } catch (final NamingException e) {
            throw new OpenEJBException("PersistenceUnit '" + contextInfo.unitId + "' not found for EXTENDED ref '" + contextInfo.referenceName + "'");
        }
        final JtaEntityManager jtaEntityManager = new JtaEntityManager(contextInfo.persistenceUnitName, jtaEntityManagerRegistry, factory, contextInfo.properties, contextInfo.extended, contextInfo.synchronizationType);
        final Reference reference = new PersistenceContextReference(jtaEntityManager);
        bindings.put(normalize(contextInfo.referenceName), reference);
    }
    for (final ServiceReferenceInfo referenceInfo : jndiEnc.serviceRefs) {
        if (referenceInfo.location != null) {
            final Reference reference = buildReferenceLocation(referenceInfo.location);
            bindings.put(normalize(referenceInfo.referenceName), reference);
            continue;
        }
        // load service class which is used to construct the port
        Class<? extends Service> serviceClass = Service.class;
        if (referenceInfo.serviceType != null) {
            try {
                serviceClass = classLoader.loadClass(referenceInfo.serviceType).asSubclass(Service.class);
            } catch (final Exception e) {
                throw new OpenEJBException("Could not load service type class " + referenceInfo.serviceType, e);
            }
        }
        // load the reference class which is the ultimate type of the port
        Class<?> referenceClass = null;
        if (referenceInfo.referenceType != null) {
            try {
                referenceClass = classLoader.loadClass(referenceInfo.referenceType);
            } catch (final Exception e) {
                throw new OpenEJBException("Could not load reference type class " + referenceInfo.referenceType, e);
            }
        }
        // if ref class is a subclass of Service, use it for the service class
        if (referenceClass != null && Service.class.isAssignableFrom(referenceClass)) {
            serviceClass = referenceClass.asSubclass(Service.class);
        }
        // determine the location of the wsdl file
        URL wsdlUrl = null;
        if (referenceInfo.wsdlFile != null) {
            try {
                wsdlUrl = new URL(referenceInfo.wsdlFile);
            } catch (final MalformedURLException e) {
                wsdlUrl = classLoader.getResource(referenceInfo.wsdlFile);
                if (wsdlUrl == null) {
                    logger.warning("Error obtaining WSDL: " + referenceInfo.wsdlFile, e);
                }
            }
        }
        // port refs
        final List<PortRefData> portRefs = new ArrayList<>(referenceInfo.portRefs.size());
        for (final PortRefInfo portRefInfo : referenceInfo.portRefs) {
            final PortRefData portRef = new PortRefData();
            portRef.setQName(portRefInfo.qname);
            portRef.setServiceEndpointInterface(portRefInfo.serviceEndpointInterface);
            portRef.setEnableMtom(portRefInfo.enableMtom);
            portRef.getProperties().putAll(portRefInfo.properties);
            portRefs.add(portRef);
        }
        // create the handle chains
        List<HandlerChainData> handlerChains = null;
        if (!referenceInfo.handlerChains.isEmpty()) {
            handlerChains = WsBuilder.toHandlerChainData(referenceInfo.handlerChains, classLoader);
        }
        if (!client) {
            final Reference reference = new JaxWsServiceReference(referenceInfo.id, referenceInfo.serviceQName, serviceClass, referenceInfo.portQName, referenceClass, wsdlUrl, portRefs, handlerChains, injections, properties);
            bindings.put(normalize(referenceInfo.referenceName), reference);
        } else {
            final ServiceRefData serviceRefData = new ServiceRefData(referenceInfo.id, referenceInfo.serviceQName, serviceClass, referenceInfo.portQName, referenceClass, wsdlUrl, handlerChains, portRefs);
            bindings.put(normalize(referenceInfo.referenceName), serviceRefData);
        }
    }
    final OpenEjbConfiguration config = SystemInstance.get().getComponent(OpenEjbConfiguration.class);
    if (config != null) {
        for (final ResourceInfo resource : config.facilities.resources) {
            final String jndiName = resource.jndiName;
            if (jndiName != null && !jndiName.isEmpty() && isNotGobalOrIsHoldByThisApp(resource, scope)) {
                final String refName = "openejb/Resource/" + resource.id;
                final Object reference = new IntraVmJndiReference(refName);
                final String boundName = normalize(jndiName);
                bindings.put(boundName, reference);
            }
        }
    }
    return bindings;
}
Also used : ContainerSystem(org.apache.openejb.spi.ContainerSystem) OpenEJBException(org.apache.openejb.OpenEJBException) HandlerChainData(org.apache.openejb.core.webservices.HandlerChainData) MalformedURLException(java.net.MalformedURLException) Configuration(javax.ws.rs.core.Configuration) ArrayList(java.util.ArrayList) CrossClassLoaderJndiReference(org.apache.openejb.core.ivm.naming.CrossClassLoaderJndiReference) HttpServletRequest(javax.servlet.http.HttpServletRequest) JaxWsServiceReference(org.apache.openejb.core.ivm.naming.JaxWsServiceReference) IntraVmJndiReference(org.apache.openejb.core.ivm.naming.IntraVmJndiReference) JtaEntityManagerRegistry(org.apache.openejb.persistence.JtaEntityManagerRegistry) NamingException(javax.naming.NamingException) InjectableBeanManager(org.apache.webbeans.container.InjectableBeanManager) BeanManager(javax.enterprise.inject.spi.BeanManager) PersistenceContextReference(org.apache.openejb.core.ivm.naming.PersistenceContextReference) LazyObjectReference(org.apache.openejb.core.ivm.naming.LazyObjectReference) JtaEntityManager(org.apache.openejb.persistence.JtaEntityManager) EntityManagerFactory(javax.persistence.EntityManagerFactory) ManagedBean(javax.annotation.ManagedBean) Providers(javax.ws.rs.ext.Providers) HttpHeaders(javax.ws.rs.core.HttpHeaders) Providers(javax.ws.rs.ext.Providers) WebServiceContext(javax.xml.ws.WebServiceContext) URL(java.net.URL) ObjectReference(org.apache.openejb.core.ivm.naming.ObjectReference) MapObjectReference(org.apache.openejb.core.ivm.naming.MapObjectReference) LazyObjectReference(org.apache.openejb.core.ivm.naming.LazyObjectReference) ServletContext(javax.servlet.ServletContext) PortRefData(org.apache.openejb.core.webservices.PortRefData) LinkRef(javax.naming.LinkRef) SecurityContext(javax.ws.rs.core.SecurityContext) WebServiceContext(javax.xml.ws.WebServiceContext) WebBeansContext(org.apache.webbeans.config.WebBeansContext) Context(javax.naming.Context) EJBContext(javax.ejb.EJBContext) ResourceContext(javax.ws.rs.container.ResourceContext) ServletContext(javax.servlet.ServletContext) URLReference(org.apache.openejb.core.ivm.naming.URLReference) ObjectReference(org.apache.openejb.core.ivm.naming.ObjectReference) MapObjectReference(org.apache.openejb.core.ivm.naming.MapObjectReference) JndiReference(org.apache.openejb.core.ivm.naming.JndiReference) PersistenceContextReference(org.apache.openejb.core.ivm.naming.PersistenceContextReference) Reference(org.apache.openejb.core.ivm.naming.Reference) IntraVmJndiReference(org.apache.openejb.core.ivm.naming.IntraVmJndiReference) URLReference(org.apache.openejb.core.ivm.naming.URLReference) ClassReference(org.apache.openejb.core.ivm.naming.ClassReference) CrossClassLoaderJndiReference(org.apache.openejb.core.ivm.naming.CrossClassLoaderJndiReference) SystemComponentReference(org.apache.openejb.core.ivm.naming.SystemComponentReference) LazyObjectReference(org.apache.openejb.core.ivm.naming.LazyObjectReference) JndiUrlReference(org.apache.openejb.core.ivm.naming.JndiUrlReference) JaxWsServiceReference(org.apache.openejb.core.ivm.naming.JaxWsServiceReference) Service(javax.xml.ws.Service) TimerService(javax.ejb.TimerService) ServiceRefData(org.apache.openejb.core.webservices.ServiceRefData) TreeMap(java.util.TreeMap) NamingException(javax.naming.NamingException) OpenEJBException(org.apache.openejb.OpenEJBException) SystemException(org.apache.openejb.SystemException) MalformedURLException(java.net.MalformedURLException) LinkRef(javax.naming.LinkRef) SecurityContext(javax.ws.rs.core.SecurityContext) MapObjectReference(org.apache.openejb.core.ivm.naming.MapObjectReference) ClassReference(org.apache.openejb.core.ivm.naming.ClassReference) UriInfo(javax.ws.rs.core.UriInfo) Validator(javax.validation.Validator)

Example 2 with ManagedBean

use of javax.annotation.ManagedBean in project Payara by payara.

the class ManagedBeanHandler method processAnnotation.

@Override
public HandlerProcessingResult processAnnotation(AnnotationInfo element) throws AnnotationProcessorException {
    AnnotatedElementHandler aeHandler = element.getProcessingContext().getHandler();
    if (aeHandler instanceof ManagedBeanContext) {
        // Ignore @ManagedBean processing during ManagedBean class processing itself
        return getDefaultProcessedResult();
    }
    ManagedBeanDescriptor managedBeanDesc = new ManagedBeanDescriptor();
    ManagedBean resourceAn = (ManagedBean) element.getAnnotation();
    // name() is optional
    String logicalName = resourceAn.value();
    if (!logicalName.equals("")) {
        managedBeanDesc.setName(logicalName);
    }
    Class managedBeanClass = (Class) element.getAnnotatedElement();
    managedBeanDesc.setBeanClassName(managedBeanClass.getName());
    Class[] classInterceptors = null;
    Map<AccessibleObject, Class[]> methodLevelInterceptors = new HashMap<>();
    Map<String, InterceptorDescriptor> interceptorDescs = new HashMap<>();
    // For now, just process the javax.interceptor related annotations directly instead
    // of relying on the annotation framework.   All the existing javax.interceptor
    // handlers are very tightly coupled to ejb so it would be more work to abstract those
    // than to just process the annotations directly.  Also, do javax.interceptor
    // annotation processing reflectively to avoid dependency on javax.interceptor from
    // DOL module.
    // TODO refactor javax.interceptor annotation handlers to support both ejb and non-ejb
    // related interceptors
    Annotation interceptorsAnn = getClassAnnotation(managedBeanClass, "javax.interceptor.Interceptors");
    if (interceptorsAnn != null) {
        try {
            Method m = interceptorsAnn.annotationType().getDeclaredMethod("value");
            classInterceptors = (Class[]) m.invoke(interceptorsAnn);
        } catch (Exception e) {
            AnnotationProcessorException ape = new AnnotationProcessorException(e.getMessage(), element);
            ape.initCause(e);
            throw ape;
        }
    }
    Class nextIntClass = managedBeanClass;
    while (nextIntClass != Object.class) {
        Method managedBeanAroundInvoke = getMethodForMethodAnnotation(nextIntClass, "javax.interceptor.AroundInvoke");
        if ((managedBeanAroundInvoke != null) && !(methodOverridden(managedBeanAroundInvoke, nextIntClass, managedBeanClass))) {
            LifecycleCallbackDescriptor desc = new LifecycleCallbackDescriptor();
            desc.setLifecycleCallbackClass(nextIntClass.getName());
            desc.setLifecycleCallbackMethod(managedBeanAroundInvoke.getName());
            managedBeanDesc.addAroundInvokeDescriptor(desc);
        }
        nextIntClass = nextIntClass.getSuperclass();
    }
    for (Method m : managedBeanClass.getMethods()) {
        processForAnnotations(element, m, methodLevelInterceptors, managedBeanDesc, managedBeanClass);
    }
    for (Constructor c : managedBeanClass.getDeclaredConstructors()) {
        processForAnnotations(element, c, methodLevelInterceptors, managedBeanDesc, managedBeanClass);
    }
    if (aeHandler instanceof ResourceContainerContext) {
        ((ResourceContainerContext) aeHandler).addManagedBean(managedBeanDesc);
        // process managed bean class annotations
        ManagedBeanContext managedBeanContext = new ManagedBeanContext(managedBeanDesc);
        ProcessingContext procContext = element.getProcessingContext();
        procContext.pushHandler(managedBeanContext);
        procContext.getProcessor().process(procContext, new Class[] { managedBeanClass });
        List<InterceptorDescriptor> classInterceptorChain = new LinkedList<>();
        if (classInterceptors != null) {
            for (Class i : classInterceptors) {
                InterceptorDescriptor nextInterceptor = processInterceptor(i, managedBeanContext, procContext);
                // Add interceptor to class-level chain
                classInterceptorChain.add(nextInterceptor);
                interceptorDescs.put(i.getName(), nextInterceptor);
            }
            managedBeanDesc.setClassInterceptorChain(classInterceptorChain);
        }
        for (Map.Entry<AccessibleObject, Class[]> next : methodLevelInterceptors.entrySet()) {
            AccessibleObject o = next.getKey();
            Class[] interceptors = next.getValue();
            boolean excludeClassInterceptors = (getMethodAnnotation(o, "javax.interceptor.ExcludeClassInterceptors") != null);
            List<InterceptorDescriptor> methodInterceptorChain = excludeClassInterceptors ? new LinkedList<>() : new LinkedList<>(classInterceptorChain);
            for (Class nextInterceptor : interceptors) {
                InterceptorDescriptor interceptorDesc = interceptorDescs.get(nextInterceptor.getName());
                if (interceptorDesc == null) {
                    interceptorDesc = processInterceptor(nextInterceptor, managedBeanContext, procContext);
                    interceptorDescs.put(nextInterceptor.getName(), interceptorDesc);
                }
                methodInterceptorChain.add(interceptorDesc);
            }
            MethodDescriptor mDesc = getMethodDescriptor(o, managedBeanClass);
            if (mDesc != null) {
                managedBeanDesc.setMethodLevelInterceptorChain(mDesc, methodInterceptorChain);
            }
        }
    }
    return getDefaultProcessedResult();
}
Also used : HashMap(java.util.HashMap) ManagedBeanContext(com.sun.enterprise.deployment.annotation.context.ManagedBeanContext) AccessibleObject(java.lang.reflect.AccessibleObject) ResourceContainerContext(com.sun.enterprise.deployment.annotation.context.ResourceContainerContext) Constructor(java.lang.reflect.Constructor) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) LinkedList(java.util.LinkedList) ManagedBean(javax.annotation.ManagedBean) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with ManagedBean

use of javax.annotation.ManagedBean in project Payara by payara.

the class InjectionManagerImpl method createManagedObject.

/**
 * Create a managed object for the given class. The object will be injected and if invokePostConstruct is true,
 * any @PostConstruct methods on the instance's class(and super-classes) will be invoked after injection. The returned
 * object can be cast to the clazz type but is not necessarily a direct reference to the managed instance. All
 * invocations on the returned object should be on its public methods.
 *
 * It is the responsibility of the caller to destroy the returned object by calling destroyManagedObject(Object
 * managedObject).
 *
 * @param clazz
 *            Class to be instantiated
 * @param invokePostConstruct
 *            if true, invoke any @PostConstruct methods on the instance's class(and super-classes) after injection.
 * @return managed object
 * @throws InjectionException
 */
public <T> T createManagedObject(Class<T> clazz, boolean invokePostConstruct) throws InjectionException {
    T managedObject = null;
    try {
        ManagedBean managedBeanAnn = clazz.getAnnotation(ManagedBean.class);
        ManagedBeanManager managedBeanMgr = serviceLocator.getService(ManagedBeanManager.class);
        if (managedBeanAnn != null) {
            // EE style @ManagedBean
            // Create , inject, and call PostConstruct (if necessary) via managed bean manager
            managedObject = managedBeanMgr.createManagedBean(clazz, invokePostConstruct);
        } else {
            JCDIService jcdiService = serviceLocator.getService(JCDIService.class);
            if ((jcdiService != null) && jcdiService.isCurrentModuleJCDIEnabled()) {
                // Create , inject, and call PostConstruct (if necessary) via managed bean manager
                managedObject = managedBeanMgr.createManagedBean(clazz, invokePostConstruct);
            } else {
                // Not in a 299-enabled module and not annoated with @ManagedBean, so
                // just instantiate using new and perform injection
                Constructor<T> noArgCtor = clazz.getConstructor();
                managedObject = noArgCtor.newInstance();
                // Inject and call PostConstruct if necessary
                injectInstance(managedObject, invokePostConstruct);
            }
        }
    } catch (Exception e) {
        throw new InjectionException(localStrings.getLocalString("injection-manager.error-creating-managed-object", "Error creating managed object for class: {0}", clazz), e);
    }
    return managedObject;
}
Also used : InjectionException(com.sun.enterprise.container.common.spi.util.InjectionException) JCDIService(com.sun.enterprise.container.common.spi.JCDIService) ManagedBean(javax.annotation.ManagedBean) NamingException(javax.naming.NamingException) InjectionException(com.sun.enterprise.container.common.spi.util.InjectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ManagedBeanManager(com.sun.enterprise.container.common.spi.ManagedBeanManager)

Example 4 with ManagedBean

use of javax.annotation.ManagedBean in project Payara by payara.

the class InjectionManagerImpl method destroyManagedObject.

/**
 * Destroy a managed object that was created via createManagedObject. Any PreDestroy methods will be called.
 *
 * @param managedObject
 * @param validate
 *            if false, do nothing if the instance is not registered
 * @throws InjectionException
 */
public void destroyManagedObject(Object managedObject, boolean validate) throws InjectionException {
    Class managedObjectClass = managedObject.getClass();
    ManagedBean managedBeanAnn = (ManagedBean) managedObjectClass.getAnnotation(ManagedBean.class);
    ManagedBeanManager managedBeanMgr = serviceLocator.getService(ManagedBeanManager.class);
    JCDIService jcdiService = serviceLocator.getService(JCDIService.class);
    if ((jcdiService != null) && jcdiService.isCurrentModuleJCDIEnabled()) {
        // If 299-enabled always delegate to managed bean manager
        managedBeanMgr.destroyManagedBean(managedObject, validate);
    } else {
        // If the object's class has @ManagedBean it's a managed bean. Otherwise, ask
        // managed bean manager.
        boolean isManagedBean = (managedBeanAnn != null) || managedBeanMgr.isManagedBean(managedObject);
        if (isManagedBean) {
            managedBeanMgr.destroyManagedBean(managedObject, validate);
        } else {
            this.invokeInstancePreDestroy(managedObject, validate);
        }
    }
}
Also used : JCDIService(com.sun.enterprise.container.common.spi.JCDIService) ManagedBean(javax.annotation.ManagedBean) ManagedBeanManager(com.sun.enterprise.container.common.spi.ManagedBeanManager)

Example 5 with ManagedBean

use of javax.annotation.ManagedBean in project Payara by payara.

the class InjectionManagerImpl method createManagedObject.

/**
 * Create a managed object for the given class. The object will be injected and any PostConstruct methods will be
 * called. The returned object can be cast to the clazz type but is not necessarily a direct reference to the managed
 * instance. All invocations on the returned object should be on its public methods.
 *
 * It is the responsibility of the caller to destroy the returned object by calling destroyManagedObject(Object
 * managedObject).
 *
 * @param clazz
 *            Class to be instantiated
 * @return managed object
 * @throws InjectionException
 */
public <T> T createManagedObject(Class<T> clazz) throws InjectionException {
    T managedObject = null;
    try {
        ManagedBean managedBeanAnn = clazz.getAnnotation(ManagedBean.class);
        ManagedBeanManager managedBeanMgr = serviceLocator.getService(ManagedBeanManager.class);
        if (managedBeanAnn != null) {
            // EE style @ManagedBean
            // Create , inject, and call PostConstruct via managed bean manager
            managedObject = managedBeanMgr.createManagedBean(clazz);
        } else {
            JCDIService cdiService = serviceLocator.getService(JCDIService.class);
            if (cdiService != null && cdiService.isCurrentModuleJCDIEnabled()) {
                // Create , inject, and call PostConstruct via managed bean manager
                managedObject = managedBeanMgr.createManagedBean(clazz);
            } else {
                // Not in a 299-enabled module and not annoated with @ManagedBean, so
                // just instantiate using new and perform injection
                Constructor<T> noArgCtor = clazz.getConstructor();
                managedObject = noArgCtor.newInstance();
                // Inject and call PostConstruct
                injectInstance(managedObject);
            }
        }
    } catch (Exception e) {
        throw new InjectionException(localStrings.getLocalString("injection-manager.error-creating-managed-object", "Error creating managed object for class: {0}", clazz), e);
    }
    return managedObject;
}
Also used : InjectionException(com.sun.enterprise.container.common.spi.util.InjectionException) JCDIService(com.sun.enterprise.container.common.spi.JCDIService) ManagedBean(javax.annotation.ManagedBean) NamingException(javax.naming.NamingException) InjectionException(com.sun.enterprise.container.common.spi.util.InjectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ManagedBeanManager(com.sun.enterprise.container.common.spi.ManagedBeanManager)

Aggregations

ManagedBean (javax.annotation.ManagedBean)5 JCDIService (com.sun.enterprise.container.common.spi.JCDIService)3 ManagedBeanManager (com.sun.enterprise.container.common.spi.ManagedBeanManager)3 NamingException (javax.naming.NamingException)3 InjectionException (com.sun.enterprise.container.common.spi.util.InjectionException)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 ManagedBeanContext (com.sun.enterprise.deployment.annotation.context.ManagedBeanContext)1 ResourceContainerContext (com.sun.enterprise.deployment.annotation.context.ResourceContainerContext)1 Annotation (java.lang.annotation.Annotation)1 AccessibleObject (java.lang.reflect.AccessibleObject)1 Constructor (java.lang.reflect.Constructor)1 Method (java.lang.reflect.Method)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1 TreeMap (java.util.TreeMap)1 EJBContext (javax.ejb.EJBContext)1