use of org.apache.openejb.OpenEJBException in project tomee by apache.
the class OpenEJBEnricher method enrich.
public static void enrich(final Object testInstance, final AppContext appCtx) {
// don't rely on arquillian since this enrichment should absolutely be done before the following ones
new MockitoEnricher().enrich(testInstance);
AppContext ctx = appCtx;
if (ctx == null) {
ctx = AppFinder.findAppContextOrWeb(Thread.currentThread().getContextClassLoader(), AppFinder.AppContextTransformer.INSTANCE);
if (ctx == null) {
return;
}
}
final BeanContext context = SystemInstance.get().getComponent(ContainerSystem.class).getBeanContext(ctx.getId() + "_" + testInstance.getClass().getName());
final WebBeansContext appWBC = ctx.getWebBeansContext();
final BeanManagerImpl bm = appWBC == null ? null : appWBC.getBeanManagerImpl();
boolean ok = false;
for (final WebContext web : ctx.getWebContexts()) {
final WebBeansContext webBeansContext = web.getWebBeansContext();
if (webBeansContext == null) {
continue;
}
final BeanManagerImpl webAppBm = webBeansContext.getBeanManagerImpl();
if (webBeansContext != appWBC && webAppBm.isInUse()) {
try {
doInject(testInstance, context, webAppBm);
ok = true;
break;
} catch (final Exception e) {
// no-op, try next
}
}
}
if (bm != null && bm.isInUse() && !ok) {
try {
doInject(testInstance, context, bm);
} catch (final Exception e) {
LOGGER.log(Level.SEVERE, "Failed injection on: " + testInstance.getClass(), e);
if (RuntimeException.class.isInstance(e)) {
throw RuntimeException.class.cast(e);
}
throw new OpenEJBRuntimeException(e);
}
}
if (context != null) {
final ThreadContext callContext = new ThreadContext(context, null, Operation.INJECTION);
final ThreadContext oldContext = ThreadContext.enter(callContext);
try {
final InjectionProcessor processor = new InjectionProcessor<>(testInstance, context.getInjections(), context.getJndiContext());
processor.createInstance();
} catch (final OpenEJBException e) {
// ignored
} finally {
ThreadContext.exit(oldContext);
}
}
}
use of org.apache.openejb.OpenEJBException in project tomee by apache.
the class Assembler method doCreateResource.
private Object doCreateResource(final Collection<ServiceInfo> infos, final ResourceInfo serviceInfo) throws OpenEJBException {
// do it early otherwise we can loose it
final String skipPropertiesFallback = (String) serviceInfo.properties.remove("SkipPropertiesFallback");
final ObjectRecipe serviceRecipe = createRecipe(infos, serviceInfo);
final boolean properties = PropertiesFactory.class.getName().equals(serviceInfo.className);
if ("false".equalsIgnoreCase(serviceInfo.properties.getProperty("SkipImplicitAttributes", "false")) && !properties) {
serviceRecipe.setProperty("transactionManager", transactionManager);
serviceRecipe.setProperty("ServiceId", serviceInfo.id);
}
serviceInfo.properties.remove("SkipImplicitAttributes");
// if custom instance allow to skip properties fallback to avoid to set unexpectedly it - connectionProps of DBs
final AtomicReference<Properties> injectedProperties = new AtomicReference<>();
if (!"true".equalsIgnoreCase(skipPropertiesFallback)) {
serviceRecipe.setProperty("properties", new UnsetPropertiesRecipe() {
@Override
protected Object internalCreate(final Type expectedType, final boolean lazyRefAllowed) throws ConstructionException {
final Map<String, Object> original = serviceRecipe.getUnsetProperties();
final Properties properties = new SuperProperties() {
@Override
public Object remove(final Object key) {
// avoid to log them then
original.remove(key);
return super.remove(key);
}
}.caseInsensitive(// keep our nice case insensitive feature
true);
for (final Map.Entry<String, Object> entry : original.entrySet()) {
properties.put(entry.getKey(), entry.getValue());
}
injectedProperties.set(properties);
return properties;
}
});
} else {
// this is not the best fallback we have but since it is super limited it is acceptable
final Map<String, Object> unsetProperties = serviceRecipe.getUnsetProperties();
injectedProperties.set(new Properties() {
@Override
public String getProperty(final String key) {
final Object obj = unsetProperties.get(key);
return String.class.isInstance(obj) ? String.valueOf(obj) : null;
}
@Override
public Set<String> stringPropertyNames() {
return unsetProperties.keySet();
}
@Override
public Set<Object> keySet() {
// noinspection unchecked
return Set.class.cast(unsetProperties.keySet());
}
@Override
public synchronized boolean containsKey(final Object key) {
return getProperty(String.valueOf(key)) != null;
}
});
}
if (serviceInfo.types.contains("DataSource") || serviceInfo.types.contains(DataSource.class.getName())) {
final Properties props = PropertyPlaceHolderHelper.simpleHolds(serviceInfo.properties);
if (serviceInfo.properties.containsKey("Definition")) {
final Object encoding = serviceInfo.properties.remove("DefinitionEncoding");
try {
// we catch classcast etc..., if it fails it is not important
final InputStream is = new ByteArrayInputStream(serviceInfo.properties.getProperty("Definition").getBytes(encoding != null ? encoding.toString() : "ISO-8859-1"));
final Properties p = new SuperProperties();
IO.readProperties(is, p);
for (final Entry<Object, Object> entry : p.entrySet()) {
final String key = entry.getKey().toString();
if (!props.containsKey(key) && !(key.equalsIgnoreCase("url") && props.containsKey("JdbcUrl"))) {
// with @DataSource we can get both, see org.apache.openejb.config.ConvertDataSourceDefinitions.rawDefinition()
props.put(key, entry.getValue());
}
}
} catch (final Exception e) {
// ignored
}
}
serviceRecipe.setProperty("Definition", PropertiesHelper.propertiesToString(props));
}
// else: any other kind of resource relying on it? shouldnt be
replaceResourceAdapterProperty(serviceRecipe);
ClassLoader loader = Thread.currentThread().getContextClassLoader();
boolean customLoader = false;
try {
if (serviceInfo.classpath != null && serviceInfo.classpath.length > 0) {
final URL[] urls = new URL[serviceInfo.classpath.length];
for (int i = 0; i < serviceInfo.classpath.length; i++) {
urls[i] = serviceInfo.classpath[i].toURL();
}
loader = new URLClassLoaderFirst(urls, loader);
customLoader = true;
serviceRecipe.setProperty("OpenEJBResourceClasspath", "true");
}
} catch (final MalformedURLException e) {
throw new OpenEJBException("Unable to create a classloader for " + serviceInfo.id, e);
}
if (!customLoader && serviceInfo.classpathAPI != null) {
throw new IllegalArgumentException("custom-api provided but not classpath used for " + serviceInfo.id);
}
Object service = serviceRecipe.create(loader);
if (customLoader) {
final Collection<Class<?>> apis;
if (serviceInfo.classpathAPI == null) {
apis = new ArrayList<>(Arrays.asList(service.getClass().getInterfaces()));
} else {
final String[] split = serviceInfo.classpathAPI.split(" *, *");
apis = new ArrayList<>(split.length);
final ClassLoader apiLoader = Thread.currentThread().getContextClassLoader();
for (final String fqn : split) {
try {
apis.add(apiLoader.loadClass(fqn));
} catch (final ClassNotFoundException e) {
throw new IllegalArgumentException(fqn + " not usable as API for " + serviceInfo.id, e);
}
}
}
if (apis.size() - (apis.contains(Serializable.class) ? 1 : 0) - (apis.contains(Externalizable.class) ? 1 : 0) > 0) {
service = Proxy.newProxyInstance(loader, apis.toArray(new Class<?>[apis.size()]), new ClassLoaderAwareHandler(null, service, loader));
}
// else proxy would be useless
}
serviceInfo.unsetProperties = injectedProperties.get();
// Java Connector spec ResourceAdapters and ManagedConnectionFactories need special activation
if (service instanceof ResourceAdapter) {
final ResourceAdapter resourceAdapter = (ResourceAdapter) service;
// Create a thead pool for work manager
final int threadPoolSize = getIntProperty(serviceInfo.properties, "threadPoolSize", 30);
final Executor threadPool;
if (threadPoolSize <= 0) {
logger.warning("Thread pool for '" + serviceInfo.id + "' is (unbounded), consider setting a size using: " + serviceInfo.id + ".QueueSize=[size]");
threadPool = Executors.newCachedThreadPool(new DaemonThreadFactory(serviceInfo.id + "-worker-"));
} else {
threadPool = new ExecutorBuilder().size(threadPoolSize).prefix(serviceInfo.id).threadFactory(new DaemonThreadFactory(serviceInfo.id + "-worker-")).build(new Options(serviceInfo.properties, SystemInstance.get().getOptions()));
logger.info("Thread pool size for '" + serviceInfo.id + "' is (" + threadPoolSize + ")");
}
// WorkManager: the resource adapter can use this to dispatch messages or perform tasks
final WorkManager workManager;
if (GeronimoTransactionManager.class.isInstance(transactionManager)) {
final GeronimoTransactionManager geronimoTransactionManager = (GeronimoTransactionManager) transactionManager;
final TransactionContextHandler txWorkContextHandler = new TransactionContextHandler(geronimoTransactionManager);
// use id as default realm name if realm is not specified in service properties
final String securityRealmName = getStringProperty(serviceInfo.properties, "realm", serviceInfo.id);
final SecurityContextHandler securityContextHandler = new SecurityContextHandler(securityRealmName);
final HintsContextHandler hintsContextHandler = new HintsContextHandler();
final Collection<WorkContextHandler> workContextHandlers = new ArrayList<>();
workContextHandlers.add(txWorkContextHandler);
workContextHandlers.add(securityContextHandler);
workContextHandlers.add(hintsContextHandler);
workManager = new GeronimoWorkManager(threadPool, threadPool, threadPool, workContextHandlers);
} else {
workManager = new SimpleWorkManager(threadPool);
}
// BootstrapContext: wraps the WorkMananger and XATerminator
final BootstrapContext bootstrapContext;
if (transactionManager instanceof GeronimoTransactionManager) {
bootstrapContext = new GeronimoBootstrapContext(GeronimoWorkManager.class.cast(workManager), (GeronimoTransactionManager) transactionManager, (GeronimoTransactionManager) transactionManager);
} else if (transactionManager instanceof XATerminator) {
bootstrapContext = new SimpleBootstrapContext(workManager, (XATerminator) transactionManager);
} else {
bootstrapContext = new SimpleBootstrapContext(workManager);
}
// start the resource adapter
try {
logger.debug("createResource.startingResourceAdapter", serviceInfo.id, service.getClass().getName());
resourceAdapter.start(bootstrapContext);
} catch (final ResourceAdapterInternalException e) {
throw new OpenEJBException(e);
}
final Map<String, Object> unset = serviceRecipe.getUnsetProperties();
unset.remove("threadPoolSize");
logUnusedProperties(unset, serviceInfo);
registerAsMBean(serviceInfo.id, "ResourceAdapter", resourceAdapter);
service = new ResourceAdapterReference(resourceAdapter, threadPool, OPENEJB_RESOURCE_JNDI_PREFIX + serviceInfo.id);
} else if (service instanceof ManagedConnectionFactory) {
final ManagedConnectionFactory managedConnectionFactory = (ManagedConnectionFactory) service;
// connection manager is constructed via a recipe so we automatically expose all cmf properties
final ObjectRecipe connectionManagerRecipe = new ObjectRecipe(GeronimoConnectionManagerFactory.class, "create");
connectionManagerRecipe.allow(Option.CASE_INSENSITIVE_PROPERTIES);
connectionManagerRecipe.allow(Option.IGNORE_MISSING_PROPERTIES);
connectionManagerRecipe.setAllProperties(serviceInfo.properties);
connectionManagerRecipe.setProperty("name", serviceInfo.id);
connectionManagerRecipe.setProperty("mcf", managedConnectionFactory);
// standard properties
connectionManagerRecipe.setProperty("transactionManager", transactionManager);
ClassLoader classLoader = loader;
if (classLoader == null) {
classLoader = getClass().getClassLoader();
}
if (classLoader == null) {
classLoader = ClassLoader.getSystemClassLoader();
}
connectionManagerRecipe.setProperty("classLoader", classLoader);
logger.getChildLogger("service").info("createResource.createConnectionManager", serviceInfo.id, service.getClass().getName());
// create the connection manager
final ConnectionManager connectionManager = (ConnectionManager) connectionManagerRecipe.create();
String txSupport = "xa";
try {
txSupport = (String) connectionManagerRecipe.getProperty("transactionSupport");
} catch (Exception e) {
// ignore
}
if (txSupport == null || txSupport.trim().length() == 0) {
txSupport = "xa";
}
if (connectionManager == null) {
throw new OpenEJBRuntimeException(messages.format("assembler.invalidConnectionManager", serviceInfo.id));
}
final Map<String, Object> unsetA = serviceRecipe.getUnsetProperties();
final Map<String, Object> unsetB = connectionManagerRecipe.getUnsetProperties();
final Map<String, Object> unset = new HashMap<>();
for (final Entry<String, Object> entry : unsetA.entrySet()) {
if (unsetB.containsKey(entry.getKey())) {
unset.put(entry.getKey(), entry.getValue());
}
}
// service becomes a ConnectorReference which merges connection manager and mcf
service = new ConnectorReference(connectionManager, managedConnectionFactory);
// init cm if needed
final Object eagerInit = unset.remove("eagerInit");
if (eagerInit != null && eagerInit instanceof String && "true".equalsIgnoreCase((String) eagerInit) && connectionManager instanceof AbstractConnectionManager) {
try {
((AbstractConnectionManager) connectionManager).doStart();
try {
final Object cf = managedConnectionFactory.createConnectionFactory(connectionManager);
if (cf instanceof ConnectionFactory) {
final Connection connection = ((ConnectionFactory) cf).getConnection();
connection.getMetaData();
connection.close();
}
} catch (final Exception e) {
// no-op: just to force eager init of pool
}
} catch (final Exception e) {
logger.warning("Can't start connection manager", e);
}
}
logUnusedProperties(unset, serviceInfo);
} else if (service instanceof DataSource) {
ClassLoader classLoader = loader;
if (classLoader == null) {
classLoader = getClass().getClassLoader();
}
final ImportSql importer = new ImportSql(classLoader, serviceInfo.id, (DataSource) service);
if (importer.hasSomethingToImport()) {
importer.doImport();
}
final ObjectRecipe recipe = DataSourceFactory.forgetRecipe(service, serviceRecipe);
if (recipe != serviceRecipe || !serviceInfo.properties.containsKey("XaDataSource")) {
logUnusedProperties(recipe, serviceInfo);
}
// else logged on xadatasource itself
final Properties prop = serviceInfo.properties;
String url = prop.getProperty("JdbcUrl", prop.getProperty("url"));
if (url == null) {
url = prop.getProperty("jdbcUrl");
}
if (url == null) {
logger.debug("Unable to find url for " + serviceInfo.id + " will not monitor it");
} else {
final String host = extractHost(url);
if (host != null) {
remoteResourceMonitor.addHost(host);
remoteResourceMonitor.registerIfNot();
}
}
} else if (!Properties.class.isInstance(service)) {
if (serviceInfo.unsetProperties == null || isTemplatizedResource(serviceInfo)) {
logUnusedProperties(serviceRecipe, serviceInfo);
}
// else wait post construct
registerAsMBean(serviceInfo.id, "Resource", service);
}
final ResourceCreated event = new ResourceCreated(service, serviceInfo.id);
SystemInstance.get().fireEvent(event);
return event.getReplacement() == null ? service : event.getReplacement();
}
use of org.apache.openejb.OpenEJBException in project tomee by apache.
the class Assembler method createApplication.
private AppContext createApplication(final AppInfo appInfo, ClassLoader classLoader, final boolean start) throws OpenEJBException, IOException, NamingException {
try {
try {
mergeServices(appInfo);
} catch (final URISyntaxException e) {
logger.info("Can't merge resources.xml services and appInfo.properties");
}
// The path is used in the UrlCache, command line deployer, JNDI name templates, tomcat integration and a few other places
if (appInfo.appId == null) {
throw new IllegalArgumentException("AppInfo.appId cannot be null");
}
if (appInfo.path == null) {
appInfo.path = appInfo.appId;
}
Extensions.addExtensions(classLoader, appInfo.eventClassesNeedingAppClassloader);
logger.info("createApplication.start", appInfo.path);
final Context containerSystemContext = containerSystem.getJNDIContext();
// To start out, ensure we don't already have any beans deployed with duplicate IDs. This
// is a conflict we can't handle.
final List<String> used = getDuplicates(appInfo);
if (used.size() > 0) {
StringBuilder message = new StringBuilder(logger.error("createApplication.appFailedDuplicateIds", appInfo.path));
for (final String id : used) {
logger.error("createApplication.deploymentIdInUse", id);
message.append("\n ").append(id);
}
throw new DuplicateDeploymentIdException(message.toString());
}
final ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(classLoader);
for (final ContainerInfo container : appInfo.containers) {
createContainer(container);
}
} finally {
Thread.currentThread().setContextClassLoader(oldCl);
}
// Construct the global and app jndi contexts for this app
final InjectionBuilder injectionBuilder = new InjectionBuilder(classLoader);
final Set<Injection> injections = new HashSet<>();
injections.addAll(injectionBuilder.buildInjections(appInfo.globalJndiEnc));
injections.addAll(injectionBuilder.buildInjections(appInfo.appJndiEnc));
final JndiEncBuilder globalBuilder = new JndiEncBuilder(appInfo.globalJndiEnc, injections, appInfo.appId, null, GLOBAL_UNIQUE_ID, classLoader, appInfo.properties);
final Map<String, Object> globalBindings = globalBuilder.buildBindings(JndiEncBuilder.JndiScope.global);
final Context globalJndiContext = globalBuilder.build(globalBindings);
final JndiEncBuilder appBuilder = new JndiEncBuilder(appInfo.appJndiEnc, injections, appInfo.appId, null, appInfo.appId, classLoader, appInfo.properties);
final Map<String, Object> appBindings = appBuilder.buildBindings(JndiEncBuilder.JndiScope.app);
final Context appJndiContext = appBuilder.build(appBindings);
final boolean cdiActive = shouldStartCdi(appInfo);
try {
// Generate the cmp2/cmp1 concrete subclasses
final CmpJarBuilder cmpJarBuilder = new CmpJarBuilder(appInfo, classLoader);
final File generatedJar = cmpJarBuilder.getJarFile();
if (generatedJar != null) {
classLoader = ClassLoaderUtil.createClassLoader(appInfo.path, new URL[] { generatedJar.toURI().toURL() }, classLoader);
}
final AppContext appContext = new AppContext(appInfo.appId, SystemInstance.get(), classLoader, globalJndiContext, appJndiContext, appInfo.standaloneModule);
for (final Entry<Object, Object> entry : appInfo.properties.entrySet()) {
if (!Module.class.isInstance(entry.getValue())) {
appContext.getProperties().put(entry.getKey(), entry.getValue());
}
}
appContext.getInjections().addAll(injections);
appContext.getBindings().putAll(globalBindings);
appContext.getBindings().putAll(appBindings);
containerSystem.addAppContext(appContext);
appContext.set(AsynchronousPool.class, AsynchronousPool.create(appContext));
final Map<String, LazyValidatorFactory> lazyValidatorFactories = new HashMap<>();
final Map<String, LazyValidator> lazyValidators = new HashMap<>();
final boolean isGeronimo = SystemInstance.get().hasProperty("openejb.geronimo");
// try to not create N times the same validator for a single app
final Map<ComparableValidationConfig, ValidatorFactory> validatorFactoriesByConfig = new HashMap<>();
if (!isGeronimo) {
// Bean Validation
// ValidatorFactory needs to be put in the map sent to the entity manager factory
// so it has to be constructed before
final List<CommonInfoObject> vfs = listCommonInfoObjectsForAppInfo(appInfo);
final Map<String, ValidatorFactory> validatorFactories = new HashMap<>();
for (final CommonInfoObject info : vfs) {
if (info.validationInfo == null) {
continue;
}
final ComparableValidationConfig conf = new ComparableValidationConfig(info.validationInfo.providerClassName, info.validationInfo.messageInterpolatorClass, info.validationInfo.traversableResolverClass, info.validationInfo.constraintFactoryClass, info.validationInfo.parameterNameProviderClass, info.validationInfo.version, info.validationInfo.propertyTypes, info.validationInfo.constraintMappings, info.validationInfo.executableValidationEnabled, info.validationInfo.validatedTypes);
ValidatorFactory factory = validatorFactoriesByConfig.get(conf);
if (factory == null) {
try {
// lazy cause of CDI :(
final LazyValidatorFactory handler = new LazyValidatorFactory(classLoader, info.validationInfo);
factory = (ValidatorFactory) Proxy.newProxyInstance(appContext.getClassLoader(), VALIDATOR_FACTORY_INTERFACES, handler);
lazyValidatorFactories.put(info.uniqueId, handler);
} catch (final ValidationException ve) {
logger.warning("can't build the validation factory for module " + info.uniqueId, ve);
continue;
}
validatorFactoriesByConfig.put(conf, factory);
} else {
lazyValidatorFactories.put(info.uniqueId, LazyValidatorFactory.class.cast(Proxy.getInvocationHandler(factory)));
}
validatorFactories.put(info.uniqueId, factory);
}
// validators bindings
for (final Entry<String, ValidatorFactory> validatorFactory : validatorFactories.entrySet()) {
final String id = validatorFactory.getKey();
final ValidatorFactory factory = validatorFactory.getValue();
try {
containerSystemContext.bind(VALIDATOR_FACTORY_NAMING_CONTEXT + id, factory);
final Validator validator;
try {
final LazyValidator lazyValidator = new LazyValidator(factory);
validator = (Validator) Proxy.newProxyInstance(appContext.getClassLoader(), VALIDATOR_INTERFACES, lazyValidator);
lazyValidators.put(id, lazyValidator);
} catch (final Exception e) {
logger.error(e.getMessage(), e);
continue;
}
containerSystemContext.bind(VALIDATOR_NAMING_CONTEXT + id, validator);
} catch (final NameAlreadyBoundException e) {
throw new OpenEJBException("ValidatorFactory already exists for module " + id, e);
} catch (final Exception e) {
throw new OpenEJBException(e);
}
}
validatorFactories.clear();
}
// JPA - Persistence Units MUST be processed first since they will add ClassFileTransformers
// to the class loader which must be added before any classes are loaded
final Map<String, String> units = new HashMap<>();
final PersistenceBuilder persistenceBuilder = new PersistenceBuilder(persistenceClassLoaderHandler);
for (final PersistenceUnitInfo info : appInfo.persistenceUnits) {
final ReloadableEntityManagerFactory factory;
try {
factory = persistenceBuilder.createEntityManagerFactory(info, classLoader, validatorFactoriesByConfig, cdiActive);
containerSystem.getJNDIContext().bind(PERSISTENCE_UNIT_NAMING_CONTEXT + info.id, factory);
units.put(info.name, PERSISTENCE_UNIT_NAMING_CONTEXT + info.id);
} catch (final NameAlreadyBoundException e) {
throw new OpenEJBException("PersistenceUnit already deployed: " + info.persistenceUnitRootUrl);
} catch (final Exception e) {
throw new OpenEJBException(e);
}
factory.register();
}
logger.debug("Loaded persistence units: " + units);
// Connectors
for (final ConnectorInfo connector : appInfo.connectors) {
final ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try {
// todo add undeployment code for these
if (connector.resourceAdapter != null) {
createResource(null, connector.resourceAdapter);
}
for (final ResourceInfo outbound : connector.outbound) {
createResource(null, outbound);
// set it after as a marker but not as an attribute (no getOpenejb().setConnector(...))
outbound.properties.setProperty("openejb.connector", "true");
}
for (final MdbContainerInfo inbound : connector.inbound) {
createContainer(inbound);
}
for (final ResourceInfo adminObject : connector.adminObject) {
createResource(null, adminObject);
}
} finally {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
}
final List<BeanContext> allDeployments = initEjbs(classLoader, appInfo, appContext, injections, new ArrayList<>(), null);
if ("true".equalsIgnoreCase(SystemInstance.get().getProperty(PROPAGATE_APPLICATION_EXCEPTIONS, appInfo.properties.getProperty(PROPAGATE_APPLICATION_EXCEPTIONS, "false")))) {
propagateApplicationExceptions(appInfo, classLoader, allDeployments);
}
if (cdiActive) {
new CdiBuilder().build(appInfo, appContext, allDeployments);
ensureWebBeansContext(appContext);
appJndiContext.bind("app/BeanManager", appContext.getBeanManager());
appContext.getBindings().put("app/BeanManager", appContext.getBeanManager());
} else {
// ensure we can reuse it in tomcat to remove OWB filters
appInfo.properties.setProperty("openejb.cdi.activated", "false");
}
// now cdi is started we can try to bind real validator factory and validator
if (!isGeronimo) {
for (final Entry<String, LazyValidator> lazyValidator : lazyValidators.entrySet()) {
final String id = lazyValidator.getKey();
final ValidatorFactory factory = lazyValidatorFactories.get(lazyValidator.getKey()).getFactory();
try {
final String factoryName = VALIDATOR_FACTORY_NAMING_CONTEXT + id;
containerSystemContext.unbind(factoryName);
containerSystemContext.bind(factoryName, factory);
final String validatoryName = VALIDATOR_NAMING_CONTEXT + id;
try {
// do it after factory cause of TCKs which expects validator to be created later
final Validator val = lazyValidator.getValue().getValidator();
containerSystemContext.unbind(validatoryName);
containerSystemContext.bind(validatoryName, val);
} catch (final Exception e) {
logger.error(e.getMessage(), e);
}
} catch (final NameAlreadyBoundException e) {
throw new OpenEJBException("ValidatorFactory already exists for module " + id, e);
} catch (final Exception e) {
throw new OpenEJBException(e);
}
}
}
startEjbs(start, allDeployments);
// App Client
for (final ClientInfo clientInfo : appInfo.clients) {
// determine the injections
final List<Injection> clientInjections = injectionBuilder.buildInjections(clientInfo.jndiEnc);
// build the enc
final JndiEncBuilder jndiEncBuilder = new JndiEncBuilder(clientInfo.jndiEnc, clientInjections, "Bean", clientInfo.moduleId, null, clientInfo.uniqueId, classLoader, new Properties());
// then, we can set the client flag
if (clientInfo.remoteClients.size() > 0 || clientInfo.localClients.size() == 0) {
jndiEncBuilder.setClient(true);
}
jndiEncBuilder.setUseCrossClassLoaderRef(false);
final Context context = jndiEncBuilder.build(JndiEncBuilder.JndiScope.comp);
// Debug.printContext(context);
containerSystemContext.bind("openejb/client/" + clientInfo.moduleId, context);
if (clientInfo.path != null) {
context.bind("info/path", clientInfo.path);
}
if (clientInfo.mainClass != null) {
context.bind("info/mainClass", clientInfo.mainClass);
}
if (clientInfo.callbackHandler != null) {
context.bind("info/callbackHandler", clientInfo.callbackHandler);
}
context.bind("info/injections", clientInjections);
for (final String clientClassName : clientInfo.remoteClients) {
containerSystemContext.bind("openejb/client/" + clientClassName, clientInfo.moduleId);
}
for (final String clientClassName : clientInfo.localClients) {
containerSystemContext.bind("openejb/client/" + clientClassName, clientInfo.moduleId);
logger.getChildLogger("client").info("createApplication.createLocalClient", clientClassName, clientInfo.moduleId);
}
}
// WebApp
final SystemInstance systemInstance = SystemInstance.get();
final WebAppBuilder webAppBuilder = systemInstance.getComponent(WebAppBuilder.class);
if (webAppBuilder != null) {
webAppBuilder.deployWebApps(appInfo, classLoader);
}
if (start) {
final EjbResolver globalEjbResolver = systemInstance.getComponent(EjbResolver.class);
globalEjbResolver.addAll(appInfo.ejbJars);
}
// bind all global values on global context
bindGlobals(appContext.getBindings());
validateCdiResourceProducers(appContext, appInfo);
// deploy MBeans
for (final String mbean : appInfo.mbeans) {
deployMBean(appContext.getWebBeansContext(), classLoader, mbean, appInfo.jmx, appInfo.appId);
}
for (final EjbJarInfo ejbJarInfo : appInfo.ejbJars) {
for (final String mbean : ejbJarInfo.mbeans) {
deployMBean(appContext.getWebBeansContext(), classLoader, mbean, appInfo.jmx, ejbJarInfo.moduleName);
}
}
for (final ConnectorInfo connectorInfo : appInfo.connectors) {
for (final String mbean : connectorInfo.mbeans) {
deployMBean(appContext.getWebBeansContext(), classLoader, mbean, appInfo.jmx, appInfo.appId + ".add-lib");
}
}
postConstructResources(appInfo.resourceIds, classLoader, containerSystemContext, appContext);
deployedApplications.put(appInfo.path, appInfo);
resumePersistentSchedulers(appContext);
systemInstance.fireEvent(new AssemblerAfterApplicationCreated(appInfo, appContext, allDeployments));
logger.info("createApplication.success", appInfo.path);
// required by spec EE.5.3.4
if (setAppNamingContextReadOnly(allDeployments)) {
logger.info("createApplication.naming", appInfo.path);
}
return appContext;
} catch (final ValidationException | DeploymentException ve) {
throw ve;
} catch (final Throwable t) {
try {
destroyApplication(appInfo);
} catch (final Exception e1) {
logger.debug("createApplication.undeployFailed", e1, appInfo.path);
}
throw new OpenEJBException(messages.format("createApplication.failed", appInfo.path), t);
}
} finally {
// cleanup there as well by safety cause we have multiple deployment mode (embedded, tomcat...)
for (final WebAppInfo webApp : appInfo.webApps) {
appInfo.properties.remove(webApp);
}
}
}
use of org.apache.openejb.OpenEJBException in project tomee by apache.
the class Assembler method build.
@Override
public void build() throws OpenEJBException {
setContext(new HashMap<>());
try {
final OpenEjbConfiguration config = getOpenEjbConfiguration();
buildContainerSystem(config);
} catch (final OpenEJBException ae) {
/* OpenEJBExceptions contain useful information and are debbugable.
* Let the exception pass through to the top and be logged.
*/
throw ae;
} catch (final Exception e) {
/* General Exceptions at this level are too generic and difficult to debug.
* These exceptions are considered unknown bugs and are fatal.
* If you get an error at this level, please trap and handle the error
* where it is most relevant.
*/
OpenEJBErrorHandler.handleUnknownError(e, "Assembler");
throw new OpenEJBException(e);
} finally {
context.set(null);
}
}
use of org.apache.openejb.OpenEJBException in project tomee by apache.
the class Assembler method createContainer.
public void createContainer(final ContainerInfo serviceInfo) throws OpenEJBException {
final ObjectRecipe serviceRecipe = createRecipe(Collections.<ServiceInfo>emptyList(), serviceInfo);
serviceRecipe.setProperty("id", serviceInfo.id);
serviceRecipe.setProperty("transactionManager", props.get(TransactionManager.class.getName()));
serviceRecipe.setProperty("securityService", props.get(SecurityService.class.getName()));
serviceRecipe.setProperty("properties", new UnsetPropertiesRecipe());
// MDB container has a resource adapter string name that
// must be replaced with the real resource adapter instance
replaceResourceAdapterProperty(serviceRecipe);
final Object service = serviceRecipe.create();
// we forced it
serviceRecipe.getUnsetProperties().remove("id");
// we forced it
serviceRecipe.getUnsetProperties().remove("securityService");
logUnusedProperties(serviceRecipe, serviceInfo);
final Class interfce = serviceInterfaces.get(serviceInfo.service);
checkImplementation(interfce, service.getClass(), serviceInfo.service, serviceInfo.id);
bindService(serviceInfo, service);
setSystemInstanceComponent(interfce, service);
props.put(interfce.getName(), service);
props.put(serviceInfo.service, service);
props.put(serviceInfo.id, service);
containerSystem.addContainer(serviceInfo.id, (Container) service);
// Update the config tree
config.containerSystem.containers.add(serviceInfo);
logger.getChildLogger("service").debug("createService.success", serviceInfo.service, serviceInfo.id, serviceInfo.className);
if (Container.class.isInstance(service) && LocalMBeanServer.isJMXActive()) {
final ObjectName objectName = ObjectNameBuilder.uniqueName("containers", serviceInfo.id, service);
try {
LocalMBeanServer.get().registerMBean(new DynamicMBeanWrapper(new JMXContainer(serviceInfo, (Container) service)), objectName);
containerObjectNames.add(objectName);
} catch (final Exception | NoClassDefFoundError e) {
// no-op
}
}
}
Aggregations