Search in sources :

Example 6 with OpenEJBException

use of org.apache.openejb.OpenEJBException 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 7 with OpenEJBException

use of org.apache.openejb.OpenEJBException in project tomee by apache.

the class Assembler method postConstructResources.

private void postConstructResources(final Set<String> resourceIds, final ClassLoader classLoader, final Context containerSystemContext, final AppContext appContext) throws NamingException, OpenEJBException {
    final Thread thread = Thread.currentThread();
    final ClassLoader oldCl = thread.getContextClassLoader();
    try {
        thread.setContextClassLoader(classLoader);
        final List<ResourceInfo> resourceList = config.facilities.resources;
        for (final ResourceInfo resourceInfo : resourceList) {
            if (!resourceIds.contains(resourceInfo.id)) {
                continue;
            }
            if (isTemplatizedResource(resourceInfo)) {
                continue;
            }
            try {
                Class<?> clazz;
                try {
                    clazz = classLoader.loadClass(resourceInfo.className);
                } catch (final ClassNotFoundException cnfe) {
                    // custom classpath
                    clazz = containerSystemContext.lookup(OPENEJB_RESOURCE_JNDI_PREFIX + resourceInfo.id).getClass();
                }
                final boolean initialize = "true".equalsIgnoreCase(String.valueOf(resourceInfo.properties.remove("InitializeAfterDeployment")));
                final AnnotationFinder finder = Proxy.isProxyClass(clazz) ? null : new AnnotationFinder(new ClassesArchive(ancestors(clazz)));
                final List<Method> postConstructs = finder == null ? Collections.<Method>emptyList() : finder.findAnnotatedMethods(PostConstruct.class);
                final List<Method> preDestroys = finder == null ? Collections.<Method>emptyList() : finder.findAnnotatedMethods(PreDestroy.class);
                resourceInfo.postConstructMethods = new ArrayList<>();
                resourceInfo.preDestroyMethods = new ArrayList<>();
                addMethodsToResourceInfo(resourceInfo.postConstructMethods, PostConstruct.class, postConstructs);
                addMethodsToResourceInfo(resourceInfo.preDestroyMethods, PreDestroy.class, preDestroys);
                CreationalContext<?> creationalContext = null;
                Object originalResource = null;
                if (!postConstructs.isEmpty() || initialize) {
                    originalResource = containerSystemContext.lookup(OPENEJB_RESOURCE_JNDI_PREFIX + resourceInfo.id);
                    Object resource = originalResource;
                    if (resource instanceof Reference) {
                        resource = unwrapReference(resource);
                        this.bindResource(resourceInfo.id, resource, true);
                    }
                    try {
                        // wire up CDI
                        if (appContext != null && appContext.getWebBeansContext() != null) {
                            final BeanManagerImpl beanManager = appContext.getWebBeansContext().getBeanManagerImpl();
                            if (beanManager.isInUse()) {
                                creationalContext = beanManager.createCreationalContext(null);
                                OWBInjector.inject(beanManager, resource, creationalContext);
                            }
                        }
                        if (!"none".equals(resourceInfo.postConstruct)) {
                            if (resourceInfo.postConstruct != null) {
                                final Method p = clazz.getDeclaredMethod(resourceInfo.postConstruct);
                                if (!p.isAccessible()) {
                                    SetAccessible.on(p);
                                }
                                p.invoke(resource);
                            }
                            for (final Method m : postConstructs) {
                                if (!m.isAccessible()) {
                                    SetAccessible.on(m);
                                }
                                m.invoke(resource);
                            }
                        }
                    } catch (final Exception e) {
                        logger.fatal("Error calling @PostConstruct method on " + resource.getClass().getName());
                        throw new OpenEJBException(e);
                    }
                }
                if (!"none".equals(resourceInfo.preDestroy)) {
                    if (resourceInfo.preDestroy != null) {
                        final Method p = clazz.getDeclaredMethod(resourceInfo.preDestroy);
                        if (!p.isAccessible()) {
                            SetAccessible.on(p);
                        }
                        preDestroys.add(p);
                    }
                    if (!preDestroys.isEmpty() || creationalContext != null) {
                        final String name = OPENEJB_RESOURCE_JNDI_PREFIX + resourceInfo.id;
                        if (originalResource == null) {
                            originalResource = containerSystemContext.lookup(name);
                        }
                        this.bindResource(resourceInfo.id, new ResourceInstance(name, originalResource, preDestroys, creationalContext), true);
                    }
                }
                // log unused now for these resources now we built the resource completely and @PostConstruct can have used injected properties
                if (resourceInfo.unsetProperties != null && !isPassthroughType(resourceInfo)) {
                    final Set<String> unsetKeys = resourceInfo.unsetProperties.stringPropertyNames();
                    for (final String key : unsetKeys) {
                        // don't use keySet to auto filter txMgr for instance and not real properties!
                        unusedProperty(resourceInfo.id, logger, key);
                    }
                }
            } catch (final Exception e) {
                logger.fatal("Error calling PostConstruct method on " + resourceInfo.id);
                logger.fatal("Resource " + resourceInfo.id + " could not be initialized. Application will be undeployed.");
                throw new OpenEJBException(e);
            }
        }
    } finally {
        thread.setContextClassLoader(oldCl);
    }
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) ConnectorReference(org.apache.openejb.core.ConnectorReference) ContextualJndiReference(org.apache.openejb.core.ivm.naming.ContextualJndiReference) JndiUrlReference(org.apache.openejb.core.ivm.naming.JndiUrlReference) Reference(org.apache.openejb.core.ivm.naming.Reference) ResourceReference(org.apache.webbeans.spi.api.ResourceReference) LazyObjectReference(org.apache.openejb.core.ivm.naming.LazyObjectReference) AtomicReference(java.util.concurrent.atomic.AtomicReference) Method(java.lang.reflect.Method) InvalidObjectException(java.io.InvalidObjectException) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ObjectStreamException(java.io.ObjectStreamException) ResourceAdapterInternalException(javax.resource.spi.ResourceAdapterInternalException) URISyntaxException(java.net.URISyntaxException) UndeployException(org.apache.openejb.UndeployException) DefinitionException(javax.enterprise.inject.spi.DefinitionException) ConstructionException(org.apache.xbean.recipe.ConstructionException) MBeanRegistrationException(javax.management.MBeanRegistrationException) InstanceNotFoundException(javax.management.InstanceNotFoundException) ValidationException(javax.validation.ValidationException) MalformedObjectNameException(javax.management.MalformedObjectNameException) DuplicateDeploymentIdException(org.apache.openejb.DuplicateDeploymentIdException) TimeoutException(java.util.concurrent.TimeoutException) NamingException(javax.naming.NamingException) OpenEJBException(org.apache.openejb.OpenEJBException) DeploymentException(javax.enterprise.inject.spi.DeploymentException) NoSuchApplicationException(org.apache.openejb.NoSuchApplicationException) MalformedURLException(java.net.MalformedURLException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl) ClassesArchive(org.apache.xbean.finder.archive.ClassesArchive) ContainerSystemPreDestroy(org.apache.openejb.assembler.classic.event.ContainerSystemPreDestroy) PreDestroy(javax.annotation.PreDestroy) PostConstruct(javax.annotation.PostConstruct) AnnotationFinder(org.apache.xbean.finder.AnnotationFinder)

Example 8 with OpenEJBException

use of org.apache.openejb.OpenEJBException in project tomee by apache.

the class EnterpriseBeanBuilder method build.

public BeanContext build() throws OpenEJBException {
    Class ejbClass = loadClass(bean.ejbClass, "classNotFound.ejbClass");
    if (DynamicSubclass.isDynamic(ejbClass)) {
        ejbClass = DynamicSubclass.createSubclass(ejbClass, moduleContext.getClassLoader());
    }
    Class home = null;
    Class remote = null;
    if (bean.home != null) {
        home = loadClass(bean.home, "classNotFound.home");
        remote = loadClass(bean.remote, "classNotFound.remote");
    }
    Class<?> proxy = null;
    if (bean.proxy != null) {
        proxy = loadClass(bean.proxy, "classNotFound.proxy");
    }
    Class<?> localhome = null;
    Class<?> local = null;
    if (bean.localHome != null) {
        localhome = loadClass(bean.localHome, "classNotFound.localHome");
        local = loadClass(bean.local, "classNotFound.local");
    }
    final List<Class> businessLocals = new ArrayList<>();
    for (final String businessLocal : bean.businessLocal) {
        businessLocals.add(loadClass(businessLocal, "classNotFound.businessLocal"));
    }
    final List<Class> businessRemotes = new ArrayList<>();
    for (final String businessRemote : bean.businessRemote) {
        businessRemotes.add(loadClass(businessRemote, "classNotFound.businessRemote"));
    }
    Class serviceEndpoint = null;
    if (BeanType.STATELESS == ejbType || BeanType.SINGLETON == ejbType) {
        if (bean.serviceEndpoint != null) {
            serviceEndpoint = loadClass(bean.serviceEndpoint, "classNotFound.sei");
        }
    }
    Class primaryKey = null;
    if (ejbType.isEntity() && ((EntityBeanInfo) bean).primKeyClass != null) {
        final String className = ((EntityBeanInfo) bean).primKeyClass;
        primaryKey = loadClass(className, "classNotFound.primaryKey");
    }
    final String transactionType = bean.transactionType;
    // determine the injections
    final InjectionBuilder injectionBuilder = new InjectionBuilder(moduleContext.getClassLoader());
    final List<Injection> injections = injectionBuilder.buildInjections(bean.jndiEnc);
    final Set<Class<?>> relevantClasses = new HashSet<>();
    Class c = ejbClass;
    do {
        relevantClasses.add(c);
        c = c.getSuperclass();
    } while (c != null && c != Object.class);
    for (final Injection injection : moduleInjections) {
        if (relevantClasses.contains(injection.getTarget())) {
            injections.add(injection);
        }
    }
    // build the enc
    final JndiEncBuilder jndiEncBuilder = new JndiEncBuilder(bean.jndiEnc, injections, transactionType, moduleContext.getId(), null, moduleContext.getUniqueId(), moduleContext.getClassLoader(), moduleContext.getAppContext() == null ? moduleContext.getProperties() : moduleContext.getAppContext().getProperties());
    final Context compJndiContext = jndiEncBuilder.build(JndiEncBuilder.JndiScope.comp);
    bind(compJndiContext, "module", moduleContext.getModuleJndiContext());
    bind(compJndiContext, "app", moduleContext.getAppContext().getAppJndiContext());
    bind(compJndiContext, "global", moduleContext.getAppContext().getGlobalJndiContext());
    final BeanContext deployment;
    if (BeanType.MESSAGE_DRIVEN != ejbType) {
        deployment = new BeanContext(bean.ejbDeploymentId, compJndiContext, moduleContext, ejbClass, home, remote, localhome, local, proxy, serviceEndpoint, businessLocals, businessRemotes, primaryKey, ejbType, bean.localbean && ejbType.isSession(), bean.passivable);
        if (bean instanceof ManagedBeanInfo) {
            deployment.setHidden(((ManagedBeanInfo) bean).hidden);
        }
    } else {
        final MessageDrivenBeanInfo messageDrivenBeanInfo = (MessageDrivenBeanInfo) bean;
        final Class mdbInterface = loadClass(messageDrivenBeanInfo.mdbInterface, "classNotFound.mdbInterface");
        deployment = new BeanContext(bean.ejbDeploymentId, compJndiContext, moduleContext, ejbClass, mdbInterface, messageDrivenBeanInfo.activationProperties);
        deployment.setDestinationId(messageDrivenBeanInfo.destinationId);
    }
    deployment.getProperties().putAll(bean.properties);
    deployment.setEjbName(bean.ejbName);
    deployment.setRunAs(bean.runAs);
    deployment.setRunAsUser(bean.runAsUser);
    deployment.getInjections().addAll(injections);
    // ejbTimeout
    deployment.setEjbTimeout(getTimeout(ejbClass, bean.timeoutMethod));
    if (bean.statefulTimeout != null) {
        deployment.setStatefulTimeout(new Duration(bean.statefulTimeout.time, TimeUnit.valueOf(bean.statefulTimeout.unit)));
    }
    if (bean instanceof StatefulBeanInfo) {
        final StatefulBeanInfo statefulBeanInfo = (StatefulBeanInfo) bean;
        for (final InitMethodInfo init : statefulBeanInfo.initMethods) {
            final Method beanMethod = MethodInfoUtil.toMethod(ejbClass, init.beanMethod);
            final List<Method> methods = new ArrayList<>();
            if (home != null) {
                methods.addAll(Arrays.asList(home.getMethods()));
            }
            if (localhome != null) {
                methods.addAll(Arrays.asList(localhome.getMethods()));
            }
            for (final Method homeMethod : methods) {
                if (init.createMethod != null && !init.createMethod.methodName.equals(homeMethod.getName())) {
                    continue;
                }
                if (!homeMethod.getName().startsWith("create")) {
                    continue;
                }
                if (paramsMatch(beanMethod, homeMethod)) {
                    deployment.mapMethods(homeMethod, beanMethod);
                }
            }
        }
        for (final RemoveMethodInfo removeMethod : statefulBeanInfo.removeMethods) {
            if (removeMethod.beanMethod.methodParams == null) {
                final MethodInfo methodInfo = new MethodInfo();
                methodInfo.methodName = removeMethod.beanMethod.methodName;
                methodInfo.methodParams = removeMethod.beanMethod.methodParams;
                methodInfo.className = removeMethod.beanMethod.className;
                final List<Method> methods = MethodInfoUtil.matchingMethods(methodInfo, ejbClass);
                for (final Method method : methods) {
                    deployment.getRemoveMethods().add(method);
                    deployment.setRetainIfExeption(method, removeMethod.retainIfException);
                }
            } else {
                final Method method = MethodInfoUtil.toMethod(ejbClass, removeMethod.beanMethod);
                deployment.getRemoveMethods().add(method);
                deployment.setRetainIfExeption(method, removeMethod.retainIfException);
            }
        }
        final Map<EntityManagerFactory, BeanContext.EntityManagerConfiguration> extendedEntityManagerFactories = new HashMap<>();
        for (final PersistenceContextReferenceInfo info : statefulBeanInfo.jndiEnc.persistenceContextRefs) {
            if (info.extended) {
                try {
                    final ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class);
                    final Object o = containerSystem.getJNDIContext().lookup(PersistenceBuilder.getOpenEJBJndiName(info.unitId));
                    final EntityManagerFactory emf = EntityManagerFactory.class.cast(o);
                    extendedEntityManagerFactories.put(emf, new BeanContext.EntityManagerConfiguration(info.properties, JtaEntityManager.isJPA21(emf) && info.synchronizationType != null ? SynchronizationType.valueOf(info.synchronizationType) : null));
                } catch (final NamingException e) {
                    throw new OpenEJBException("PersistenceUnit '" + info.unitId + "' not found for EXTENDED ref '" + info.referenceName + "'");
                }
            }
        }
        deployment.setExtendedEntityManagerFactories(new Index<>(extendedEntityManagerFactories));
    }
    if (ejbType.isSession() || ejbType.isMessageDriven()) {
        deployment.setBeanManagedTransaction("Bean".equalsIgnoreCase(bean.transactionType));
    }
    if (ejbType.isSession()) {
        // Allow dependsOn to work for all session beans
        deployment.getDependsOn().addAll(bean.dependsOn);
    }
    if (ejbType == BeanType.SINGLETON) {
        deployment.setBeanManagedConcurrency("Bean".equalsIgnoreCase(bean.concurrencyType));
        deployment.setLoadOnStartup(bean.loadOnStartup);
    }
    if (ejbType.isEntity()) {
        final EntityBeanInfo entity = (EntityBeanInfo) bean;
        deployment.setCmp2(entity.cmpVersion == 2);
        deployment.setIsReentrant(entity.reentrant.equalsIgnoreCase("true"));
        if (ejbType == BeanType.CMP_ENTITY) {
            Class cmpImplClass = null;
            final String cmpImplClassName = CmpUtil.getCmpImplClassName(entity.abstractSchemaName, entity.ejbClass);
            cmpImplClass = loadClass(cmpImplClassName, "classNotFound.cmpImplClass");
            deployment.setCmpImplClass(cmpImplClass);
            deployment.setAbstractSchemaName(entity.abstractSchemaName);
            for (final QueryInfo query : entity.queries) {
                if (query.remoteResultType) {
                    final StringBuilder methodSignature = new StringBuilder();
                    methodSignature.append(query.method.methodName);
                    if (query.method.methodParams != null && !query.method.methodParams.isEmpty()) {
                        methodSignature.append('(');
                        boolean first = true;
                        for (final String methodParam : query.method.methodParams) {
                            if (!first) {
                                methodSignature.append(",");
                            }
                            methodSignature.append(methodParam);
                            first = false;
                        }
                        methodSignature.append(')');
                    }
                    deployment.setRemoteQueryResults(methodSignature.toString());
                }
            }
            if (entity.primKeyField != null) {
                deployment.setPrimaryKeyField(entity.primKeyField);
            }
        }
    }
    deployment.createMethodMap();
    // we could directly check the matching bean method.
    if (ejbType == BeanType.STATELESS || ejbType == BeanType.SINGLETON || ejbType == BeanType.STATEFUL) {
        for (final NamedMethodInfo methodInfo : bean.asynchronous) {
            final Method method = MethodInfoUtil.toMethod(ejbClass, methodInfo);
            deployment.getMethodContext(deployment.getMatchingBeanMethod(method)).setAsynchronous(true);
        }
        for (final String className : bean.asynchronousClasses) {
            deployment.getAsynchronousClasses().add(loadClass(className, "classNotFound.ejbClass"));
        }
        deployment.createAsynchronousMethodSet();
    }
    for (final SecurityRoleReferenceInfo securityRoleReference : bean.securityRoleReferences) {
        deployment.addSecurityRoleReference(securityRoleReference.roleName, securityRoleReference.roleLink);
    }
    return deployment;
}
Also used : ContainerSystem(org.apache.openejb.spi.ContainerSystem) OpenEJBException(org.apache.openejb.OpenEJBException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) NamingException(javax.naming.NamingException) HashSet(java.util.HashSet) BeanContext(org.apache.openejb.BeanContext) ModuleContext(org.apache.openejb.ModuleContext) Context(javax.naming.Context) Duration(org.apache.openejb.util.Duration) Injection(org.apache.openejb.Injection) Method(java.lang.reflect.Method) BeanContext(org.apache.openejb.BeanContext) EntityManagerFactory(javax.persistence.EntityManagerFactory) TimedObject(javax.ejb.TimedObject)

Example 9 with OpenEJBException

use of org.apache.openejb.OpenEJBException in project tomee by apache.

the class ReloadableEntityManagerFactory method register.

public void register() throws OpenEJBException {
    if (!LocalMBeanServer.isJMXActive()) {
        return;
    }
    final MBeanServer server = LocalMBeanServer.get();
    try {
        generateObjectName();
        if (server.isRegistered(objectName)) {
            server.unregisterMBean(objectName);
        }
        server.registerMBean(mBeanify(), objectName);
    } catch (final Exception e) {
        throw new OpenEJBException("can't register the mbean for the entity manager factory " + getPUname(), e);
    } catch (final NoClassDefFoundError ncdfe) {
        objectName = null;
        LOGGER.error("can't register the mbean for the entity manager factory {0}", getPUname());
    }
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) NamingException(javax.naming.NamingException) InvalidObjectException(java.io.InvalidObjectException) OpenEJBException(org.apache.openejb.OpenEJBException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ObjectStreamException(java.io.ObjectStreamException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) MBeanServer(javax.management.MBeanServer) LocalMBeanServer(org.apache.openejb.monitoring.LocalMBeanServer)

Example 10 with OpenEJBException

use of org.apache.openejb.OpenEJBException in project tomee by apache.

the class JaccPermissionsBuilder method install.

public void install(final PolicyContext policyContext) throws OpenEJBException {
    if (SystemInstance.get().hasProperty("openejb.geronimo")) {
        return;
    }
    final String contextID = policyContext.getContextID();
    try {
        final PolicyConfigurationFactory factory = PolicyConfigurationFactory.getPolicyConfigurationFactory();
        // final boolean needsCommit = factory.inService(contextID);
        final PolicyConfiguration policy = factory.getPolicyConfiguration(contextID, false);
        policy.addToExcludedPolicy(policyContext.getExcludedPermissions());
        policy.addToUncheckedPolicy(policyContext.getUncheckedPermissions());
        for (final Map.Entry<String, PermissionCollection> entry : policyContext.getRolePermissions().entrySet()) {
            policy.addToRole(entry.getKey(), entry.getValue());
        }
        // not sure if this is required or not
        // if (needsCommit) {
        policy.commit();
    // }
    } catch (final ClassNotFoundException e) {
        throw new OpenEJBException("PolicyConfigurationFactory class not found", e);
    } catch (final PolicyContextException e) {
        throw new OpenEJBException("JACC PolicyConfiguration failed: ContextId=" + contextID, e);
    }
}
Also used : PermissionCollection(java.security.PermissionCollection) OpenEJBException(org.apache.openejb.OpenEJBException) PolicyConfiguration(javax.security.jacc.PolicyConfiguration) PolicyContextException(javax.security.jacc.PolicyContextException) PolicyConfigurationFactory(javax.security.jacc.PolicyConfigurationFactory) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

OpenEJBException (org.apache.openejb.OpenEJBException)192 IOException (java.io.IOException)54 NamingException (javax.naming.NamingException)35 URL (java.net.URL)31 MalformedURLException (java.net.MalformedURLException)30 BeanContext (org.apache.openejb.BeanContext)30 ApplicationException (org.apache.openejb.ApplicationException)29 ArrayList (java.util.ArrayList)28 File (java.io.File)27 OpenEJBRuntimeException (org.apache.openejb.OpenEJBRuntimeException)24 Method (java.lang.reflect.Method)22 SystemException (org.apache.openejb.SystemException)22 HashMap (java.util.HashMap)18 ThreadContext (org.apache.openejb.core.ThreadContext)18 RemoteException (java.rmi.RemoteException)14 EJBException (javax.ejb.EJBException)14 EjbTransactionUtil.handleApplicationException (org.apache.openejb.core.transaction.EjbTransactionUtil.handleApplicationException)14 HashSet (java.util.HashSet)13 Properties (java.util.Properties)13 EJBAccessException (javax.ejb.EJBAccessException)13