use of org.apache.openejb.Injection in project tomee by apache.
the class TomcatWebAppBuilder method startInternal.
/**
* {@inheritDoc}
*/
// @Override
private void startInternal(final StandardContext standardContext) {
if (isIgnored(standardContext)) {
return;
}
if (shouldNotDeploy(standardContext)) {
return;
}
final CoreContainerSystem cs = getContainerSystem();
final Assembler a = getAssembler();
if (a == null) {
LOGGER.warning("OpenEJB has not been initialized so war will not be scanned for nested modules " + standardContext.getPath());
return;
}
AppContext appContext = null;
// Look for context info, maybe context is already scanned
ContextInfo contextInfo = getContextInfo(standardContext);
ClassLoader classLoader = standardContext.getLoader().getClassLoader();
// bind jta before the app starts to ensure we have it in CDI
final Thread thread = Thread.currentThread();
final ClassLoader originalLoader = thread.getContextClassLoader();
thread.setContextClassLoader(classLoader);
final String listenerName = standardContext.getNamingContextListener().getName();
ContextAccessController.setWritable(listenerName, standardContext.getNamingToken());
try {
final Context comp = Context.class.cast(ContextBindings.getClassLoader().lookup("comp"));
// bind TransactionManager
final TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
safeBind(comp, "TransactionManager", transactionManager);
// bind TransactionSynchronizationRegistry
final TransactionSynchronizationRegistry synchronizationRegistry = SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class);
safeBind(comp, "TransactionSynchronizationRegistry", synchronizationRegistry);
} catch (final NamingException e) {
// no-op
} finally {
thread.setContextClassLoader(originalLoader);
ContextAccessController.setReadOnly(listenerName);
}
if (contextInfo == null) {
final AppModule appModule = loadApplication(standardContext);
appModule.getProperties().put("loader.from", "tomcat");
final boolean skipTomeeResourceWrapping = !"true".equalsIgnoreCase(SystemInstance.get().getProperty("tomee.tomcat.resource.wrap", "true"));
if (!skipTomeeResourceWrapping && OpenEJBNamingResource.class.isInstance(standardContext.getNamingResources())) {
// we can get the same resource twice as in tomcat
final Collection<String> importedNames = new ArrayList<>();
// add them to the app as resource
final boolean forceDataSourceWrapping = "true".equalsIgnoreCase(SystemInstance.get().getProperty("tomee.tomcat.datasource.wrap", "false"));
final OpenEJBNamingResource nr = (OpenEJBNamingResource) standardContext.getNamingResources();
for (final ResourceBase resource : nr.getTomcatResources()) {
final String name = resource.getName();
// already init (org.apache.catalina.core.NamingContextListener.addResource())
// skip wrapping to ensure resource consistency
final boolean isDataSource = DataSource.class.getName().equals(resource.getType());
final boolean isAlreadyCreated = ContextResource.class.isInstance(resource) && ContextResource.class.cast(resource).getSingleton() && isDataSource;
if (!importedNames.contains(name)) {
importedNames.add(name);
} else {
continue;
}
boolean found = false;
for (final ResourceInfo r : SystemInstance.get().getComponent(OpenEjbConfiguration.class).facilities.resources) {
if (r.id.equals(name)) {
nr.removeResource(name);
found = true;
LOGGER.warning(name + " resource was defined in both tomcat and tomee so removing tomcat one");
break;
}
}
if (!found) {
final Resource newResource;
if (forceDataSourceWrapping || (!isAlreadyCreated && isDataSource)) {
// we forward it to TomEE datasources
newResource = new Resource(name, resource.getType());
boolean jta = false;
final Properties properties = newResource.getProperties();
final Iterator<String> params = resource.listProperties();
while (params.hasNext()) {
final String paramName = params.next();
final String paramValue = (String) resource.getProperty(paramName);
// handling some param name conversion to OpenEJB style
if ("driverClassName".equals(paramName)) {
properties.setProperty("JdbcDriver", paramValue);
} else if ("url".equals(paramName)) {
properties.setProperty("JdbcUrl", paramValue);
} else {
properties.setProperty(paramName, paramValue);
}
if ("JtaManaged".equalsIgnoreCase(paramName)) {
jta = Boolean.parseBoolean(paramValue);
}
}
if (!jta) {
properties.setProperty("JtaManaged", "false");
}
} else {
// custom type, let it be created
newResource = new Resource(name, resource.getType(), "org.apache.tomee:ProvidedByTomcat");
final Properties properties = newResource.getProperties();
properties.setProperty("jndiName", newResource.getId());
properties.setProperty("appName", getId(standardContext));
properties.setProperty("factory", (String) resource.getProperty("factory"));
final Reference reference = createReference(resource);
if (reference != null) {
properties.put("reference", reference);
}
}
appModule.getResources().add(newResource);
}
}
}
if (appModule != null) {
try {
contextInfo = addContextInfo(Contexts.getHostname(standardContext), standardContext);
// ensure to do it before an exception can be thrown
contextInfo.standardContext = standardContext;
contextInfo.appInfo = configurationFactory.configureApplication(appModule);
final Boolean autoDeploy = DeployerEjb.AUTO_DEPLOY.get();
contextInfo.appInfo.autoDeploy = autoDeploy == null || autoDeploy;
DeployerEjb.AUTO_DEPLOY.remove();
if (!appModule.isWebapp()) {
classLoader = appModule.getClassLoader();
} else {
final ClassLoader loader = standardContext.getLoader().getClassLoader();
if (loader instanceof TomEEWebappClassLoader) {
final TomEEWebappClassLoader tomEEWebappClassLoader = (TomEEWebappClassLoader) loader;
for (final URL url : appModule.getWebModules().iterator().next().getAddedUrls()) {
tomEEWebappClassLoader.addURL(url);
}
}
}
setFinderOnContextConfig(standardContext, appModule);
servletContextHandler.getContexts().put(classLoader, standardContext.getServletContext());
try {
appContext = a.createApplication(contextInfo.appInfo, classLoader);
} finally {
servletContextHandler.getContexts().remove(classLoader);
}
// todo add watched resources to context
eagerInitOfLocalBeanProxies(appContext.getBeanContexts(), classLoader);
} catch (final Exception e) {
LOGGER.error("Unable to deploy collapsed ear in war " + standardContext, e);
undeploy(standardContext, contextInfo);
// just to force tomee to start without EE part
if (System.getProperty(TomEESystemConfig.TOMEE_EAT_EXCEPTION_PROP) == null) {
final TomEERuntimeException tre = new TomEERuntimeException(e);
final DeploymentExceptionManager dem = SystemInstance.get().getComponent(DeploymentExceptionManager.class);
dem.saveDeploymentException(contextInfo.appInfo, tre);
throw tre;
}
return;
}
}
} else {
contextInfo.standardContext = standardContext;
if (contextInfo.module != null && contextInfo.module.getFinder() != null) {
// TODO: make it more explicit or less hacky not using properties
final OpenEJBContextConfig openEJBContextConfig = findOpenEJBContextConfig(standardContext);
if (openEJBContextConfig != null) {
openEJBContextConfig.finder(contextInfo.module.getFinder(), contextInfo.module.getClassLoader());
}
}
}
final String id = getId(standardContext);
WebAppInfo webAppInfo = null;
// appInfo is null when deployment fails
if (contextInfo.appInfo != null) {
for (final WebAppInfo w : contextInfo.appInfo.webApps) {
if (id.equals(getId(w.host, w.contextRoot, contextInfo.version)) || id.equals(getId(w.host, w.moduleId, contextInfo.version))) {
if (webAppInfo == null) {
webAppInfo = w;
} else if (w.host != null && w.host.equals(Contexts.getHostname(standardContext))) {
webAppInfo = w;
}
break;
}
}
if (appContext == null) {
appContext = cs.getAppContext(contextInfo.appInfo.appId);
}
}
if (webAppInfo != null) {
if (appContext == null) {
appContext = getContainerSystem().getAppContext(contextInfo.appInfo.appId);
}
// ensure matching (see getId() usage)
webAppInfo.host = Contexts.getHostname(standardContext);
webAppInfo.contextRoot = standardContext.getPath();
// save jsf stuff
final Map<String, Set<String>> scannedJsfClasses = new HashMap<>();
for (final ClassListInfo info : webAppInfo.jsfAnnotatedClasses) {
scannedJsfClasses.put(info.name, info.list);
}
jsfClasses.put(classLoader, scannedJsfClasses);
try {
// determine the injections
final Set<Injection> injections = new HashSet<>();
injections.addAll(appContext.getInjections());
if (!contextInfo.appInfo.webAppAlone) {
updateInjections(injections, classLoader, false);
for (final BeanContext bean : appContext.getBeanContexts()) {
// TODO: how if the same class in multiple webapps?
updateInjections(bean.getInjections(), classLoader, true);
}
}
injections.addAll(new InjectionBuilder(classLoader).buildInjections(webAppInfo.jndiEnc));
// merge OpenEJB jndi into Tomcat jndi
final TomcatJndiBuilder jndiBuilder = new TomcatJndiBuilder(standardContext, webAppInfo, injections);
NamingUtil.setCurrentContext(standardContext);
try {
jndiBuilder.mergeJndi();
} finally {
NamingUtil.setCurrentContext(null);
}
// create EMF included in this webapp when nested in an ear
for (final PersistenceUnitInfo unitInfo : contextInfo.appInfo.persistenceUnits) {
if (unitInfo.webappName != null && unitInfo.webappName.equals(webAppInfo.moduleId)) {
try {
final ReloadableEntityManagerFactory remf = (ReloadableEntityManagerFactory) SystemInstance.get().getComponent(ContainerSystem.class).getJNDIContext().lookup(Assembler.PERSISTENCE_UNIT_NAMING_CONTEXT + unitInfo.id);
remf.overrideClassLoader(classLoader);
remf.createDelegate();
} catch (final NameNotFoundException nnfe) {
LOGGER.warning("Can't find " + unitInfo.id + " persistence unit");
}
}
}
// add WebDeploymentInfo to ContainerSystem
final WebContext webContext = new WebContext(appContext);
webContext.setServletContext(standardContext.getServletContext());
webContext.setJndiEnc(new InitialContext());
webContext.setClassLoader(classLoader);
webContext.setId(webAppInfo.moduleId);
webContext.setContextRoot(webAppInfo.contextRoot);
webContext.setHost(webAppInfo.host);
webContext.setBindings(new HashMap<String, Object>());
webContext.getInjections().addAll(injections);
appContext.getWebContexts().add(webContext);
cs.addWebContext(webContext);
standardContext.getServletContext().setAttribute("openejb.web.context", webContext);
if (!contextInfo.appInfo.webAppAlone) {
final List<BeanContext> beanContexts = assembler.initEjbs(classLoader, contextInfo.appInfo, appContext, injections, new ArrayList<BeanContext>(), webAppInfo.moduleId);
OpenEJBLifecycle.CURRENT_APP_INFO.set(contextInfo.appInfo);
servletContextHandler.getContexts().put(classLoader, standardContext.getServletContext());
try {
new CdiBuilder().build(contextInfo.appInfo, appContext, beanContexts, webContext);
} catch (final Exception e) {
final DeploymentExceptionManager dem = SystemInstance.get().getComponent(DeploymentExceptionManager.class);
if (dem != null) {
dem.saveDeploymentException(contextInfo.appInfo, e);
}
throw e;
} finally {
servletContextHandler.getContexts().remove(classLoader);
OpenEJBLifecycle.CURRENT_APP_INFO.remove();
}
assembler.startEjbs(true, beanContexts);
assembler.bindGlobals(appContext.getBindings());
eagerInitOfLocalBeanProxies(beanContexts, standardContext.getLoader().getClassLoader());
deployWebServicesIfEjbCreatedHere(contextInfo.appInfo, beanContexts);
}
// jndi bindings
webContext.getBindings().putAll(appContext.getBindings());
webContext.getBindings().putAll(getJndiBuilder(classLoader, webAppInfo, injections, appContext.getProperties()).buildBindings(JndiEncBuilder.JndiScope.comp));
final JavaeeInstanceManager instanceManager = new JavaeeInstanceManager(standardContext, webContext);
standardContext.setInstanceManager(instanceManager);
instanceManagers.put(classLoader, instanceManager);
standardContext.getServletContext().setAttribute(InstanceManager.class.getName(), standardContext.getInstanceManager());
} catch (final Exception e) {
LOGGER.error("Error merging Java EE JNDI entries in to war " + standardContext.getPath() + ": Exception: " + e.getMessage(), e);
if (System.getProperty(TomEESystemConfig.TOMEE_EAT_EXCEPTION_PROP) == null) {
final DeploymentExceptionManager dem = SystemInstance.get().getComponent(DeploymentExceptionManager.class);
if (dem != null && dem.getDeploymentException(contextInfo.appInfo) != null) {
if (RuntimeException.class.isInstance(e)) {
throw RuntimeException.class.cast(e);
}
throw new TomEERuntimeException(e);
}
}
}
final WebBeansContext webBeansContext = appContext.getWebBeansContext();
if (webBeansContext != null && webBeansContext.getBeanManagerImpl().isInUse()) {
OpenEJBLifecycle.initializeServletContext(standardContext.getServletContext(), webBeansContext);
}
}
// router
final URL routerConfig = RouterValve.configurationURL(standardContext.getServletContext());
if (routerConfig != null) {
final RouterValve filter = new RouterValve();
filter.setPrefix(standardContext.getName());
filter.setConfigurationPath(routerConfig);
standardContext.getPipeline().addValve(filter);
}
// register realm to have it in TomcatSecurityService
final Realm realm = standardContext.getRealm();
realms.put(standardContext.getName(), realm);
}
use of org.apache.openejb.Injection in project tomee by apache.
the class JndiRequestHandler method doLookup.
private void doLookup(final JNDIRequest req, final JNDIResponse res, final String prefix) {
Object object;
final String name = req.getRequestString();
try {
if (name.equals("info/injections")) {
// noinspection unchecked
final List<Injection> injections = (List<Injection>) rootContext.lookup(prefix + name);
final InjectionMetaData metaData = new InjectionMetaData();
for (final Injection injection : injections) {
if (injection.getTarget() == null) {
continue;
}
metaData.addInjection(injection.getTarget().getName(), injection.getName(), injection.getJndiName());
}
res.setResponseCode(ResponseCodes.JNDI_INJECTIONS);
res.setResult(metaData);
return;
} else {
try {
object = rootContext.lookup(prefix + name);
} catch (NameNotFoundException nnfe) {
// fallback to resources
object = rootContext.lookup("openejb/Resource/" + name);
}
}
if (object instanceof Context) {
res.setResponseCode(ResponseCodes.JNDI_CONTEXT);
return;
} else if (object == null) {
throw new NullPointerException("lookup of '" + name + "' returned null");
} else if (object instanceof DataSource) {
if (DataSourceFactory.knows(object)) {
try {
final DbcpDataSource cf = new DbcpDataSource(object);
final DataSourceMetaData dataSourceMetaData = new DataSourceMetaData(cf.getDriverClassName(), cf.getUrl(), cf.getUsername(), cf.getPassword());
res.setResponseCode(ResponseCodes.JNDI_DATA_SOURCE);
res.setResult(dataSourceMetaData);
} catch (Exception e) {
res.setResponseCode(ResponseCodes.JNDI_ERROR);
res.setResult(new ThrowableArtifact(e));
}
return;
} else if (object instanceof Referenceable) {
res.setResponseCode(ResponseCodes.JNDI_REFERENCE);
res.setResult(((Referenceable) object).getReference());
return;
}
} else if (object instanceof ConnectionFactory) {
res.setResponseCode(ResponseCodes.JNDI_RESOURCE);
res.setResult(ConnectionFactory.class.getName());
return;
} else if (ORB_CLASS != null && ORB_CLASS.isInstance(object)) {
res.setResponseCode(ResponseCodes.JNDI_RESOURCE);
res.setResult(ORB_CLASS.getName());
return;
} else if (object instanceof ValidatorFactory) {
res.setResponseCode(ResponseCodes.JNDI_RESOURCE);
res.setResult(ValidatorFactory.class.getName());
return;
} else if (object instanceof Validator) {
res.setResponseCode(ResponseCodes.JNDI_RESOURCE);
res.setResult(Validator.class.getName());
return;
} else if (object instanceof Queue) {
res.setResponseCode(ResponseCodes.JNDI_RESOURCE);
res.setResult(Queue.class.getName());
return;
} else if (object instanceof Topic) {
res.setResponseCode(ResponseCodes.JNDI_RESOURCE);
res.setResult(Topic.class.getName());
return;
}
final ServiceRefData serviceRef;
if (object instanceof ServiceRefData) {
serviceRef = (ServiceRefData) object;
} else {
serviceRef = ServiceRefData.getServiceRefData(object);
}
if (serviceRef != null) {
final WsMetaData serviceMetaData = new WsMetaData();
// service class
String serviceClassName = null;
if (serviceRef.getServiceClass() != null) {
serviceClassName = serviceRef.getServiceClass().getName();
}
serviceMetaData.setServiceClassName(serviceClassName);
// reference class
String referenceClassName = null;
if (serviceRef.getReferenceClass() != null) {
referenceClassName = serviceRef.getReferenceClass().getName();
}
serviceMetaData.setReferenceClassName(referenceClassName);
// set service qname
if (serviceRef.getServiceQName() != null) {
serviceMetaData.setServiceQName(serviceRef.getServiceQName().toString());
}
// get the port addresses for this service
final PortAddressRegistry portAddressRegistry = SystemInstance.get().getComponent(PortAddressRegistry.class);
Set<PortAddress> portAddresses = null;
if (portAddressRegistry != null) {
portAddresses = portAddressRegistry.getPorts(serviceRef.getId(), serviceRef.getServiceQName(), referenceClassName);
}
// resolve the wsdl url
if (serviceRef.getWsdlURL() != null) {
serviceMetaData.setWsdlUrl(serviceRef.getWsdlURL().toExternalForm());
}
if (portAddresses.size() == 1) {
final PortAddress portAddress = portAddresses.iterator().next();
serviceMetaData.setWsdlUrl(portAddress.getAddress() + "?wsdl");
}
// add handler chains
for (final HandlerChainData handlerChain : serviceRef.getHandlerChains()) {
final HandlerChainMetaData handlerChainMetaData = new HandlerChainMetaData();
handlerChainMetaData.setServiceNamePattern(handlerChain.getServiceNamePattern());
handlerChainMetaData.setPortNamePattern(handlerChain.getPortNamePattern());
handlerChainMetaData.getProtocolBindings().addAll(handlerChain.getProtocolBindings());
for (final HandlerData handler : handlerChain.getHandlers()) {
final HandlerMetaData handlerMetaData = new HandlerMetaData();
handlerMetaData.setHandlerClass(handler.getHandlerClass().getName());
for (final Method method : handler.getPostConstruct()) {
final CallbackMetaData callbackMetaData = new CallbackMetaData();
callbackMetaData.setClassName(method.getDeclaringClass().getName());
callbackMetaData.setMethod(method.getName());
handlerMetaData.getPostConstruct().add(callbackMetaData);
}
for (final Method method : handler.getPreDestroy()) {
final CallbackMetaData callbackMetaData = new CallbackMetaData();
callbackMetaData.setClassName(method.getDeclaringClass().getName());
callbackMetaData.setMethod(method.getName());
handlerMetaData.getPreDestroy().add(callbackMetaData);
}
handlerChainMetaData.getHandlers().add(handlerMetaData);
}
serviceMetaData.getHandlerChains().add(handlerChainMetaData);
}
// add port refs
final Map<QName, PortRefMetaData> portsByQName = new HashMap<>();
for (final PortRefData portRef : serviceRef.getPortRefs()) {
final PortRefMetaData portRefMetaData = new PortRefMetaData();
portRefMetaData.setQName(portRef.getQName());
portRefMetaData.setServiceEndpointInterface(portRef.getServiceEndpointInterface());
portRefMetaData.setEnableMtom(portRef.isEnableMtom());
portRefMetaData.getProperties().putAll(portRef.getProperties());
portRefMetaData.getAddresses().addAll(portRef.getAddresses());
if (portRef.getQName() != null) {
portsByQName.put(portRef.getQName(), portRefMetaData);
}
serviceMetaData.getPortRefs().add(portRefMetaData);
}
// add PortRefMetaData for any portAddress not added above
for (final PortAddress portAddress : portAddresses) {
PortRefMetaData portRefMetaData = portsByQName.get(portAddress.getPortQName());
if (portRefMetaData == null) {
portRefMetaData = new PortRefMetaData();
portRefMetaData.setQName(portAddress.getPortQName());
portRefMetaData.setServiceEndpointInterface(portAddress.getServiceEndpointInterface());
portRefMetaData.getAddresses().add(portAddress.getAddress());
serviceMetaData.getPortRefs().add(portRefMetaData);
} else {
portRefMetaData.getAddresses().add(portAddress.getAddress());
if (portRefMetaData.getServiceEndpointInterface() == null) {
portRefMetaData.setServiceEndpointInterface(portAddress.getServiceEndpointInterface());
}
}
}
res.setResponseCode(ResponseCodes.JNDI_WEBSERVICE);
res.setResult(serviceMetaData);
return;
}
} catch (NameNotFoundException e) {
res.setResponseCode(ResponseCodes.JNDI_NOT_FOUND);
return;
} catch (NamingException e) {
res.setResponseCode(ResponseCodes.JNDI_NAMING_EXCEPTION);
res.setResult(new ThrowableArtifact(e));
return;
}
BaseEjbProxyHandler handler;
try {
handler = (BaseEjbProxyHandler) ProxyManager.getInvocationHandler(object);
} catch (Exception e) {
try {
final Field field = object.getClass().getDeclaredField("invocationHandler");
field.setAccessible(true);
handler = (BaseEjbProxyHandler) field.get(object);
} catch (Exception e1) {
// Not a proxy. See if it's serializable and send it
if (object instanceof java.io.Serializable) {
res.setResponseCode(ResponseCodes.JNDI_OK);
res.setResult(object);
return;
} else {
res.setResponseCode(ResponseCodes.JNDI_NAMING_EXCEPTION);
final NamingException namingException = new NamingException("Expected an ejb proxy, found unknown object: type=" + object.getClass().getName() + ", toString=" + object);
res.setResult(new ThrowableArtifact(namingException));
return;
}
}
}
final ProxyInfo proxyInfo = handler.getProxyInfo();
final BeanContext beanContext = proxyInfo.getBeanContext();
final String deploymentID = beanContext.getDeploymentID().toString();
updateServer(req, res, proxyInfo);
switch(proxyInfo.getInterfaceType()) {
case EJB_HOME:
{
res.setResponseCode(ResponseCodes.JNDI_EJBHOME);
final EJBMetaDataImpl metaData = new EJBMetaDataImpl(beanContext.getHomeInterface(), beanContext.getRemoteInterface(), beanContext.getPrimaryKeyClass(), beanContext.getComponentType().toString(), deploymentID, -1, convert(proxyInfo.getInterfaceType()), null, beanContext.getAsynchronousMethodSignatures());
metaData.loadProperties(beanContext.getProperties());
log(metaData);
res.setResult(metaData);
break;
}
case EJB_LOCAL_HOME:
{
res.setResponseCode(ResponseCodes.JNDI_NAMING_EXCEPTION);
final NamingException namingException = new NamingException("Not remotable: '" + name + "'. EJBLocalHome interfaces are not remotable as per the EJB specification.");
res.setResult(new ThrowableArtifact(namingException));
break;
}
case BUSINESS_REMOTE:
{
res.setResponseCode(ResponseCodes.JNDI_BUSINESS_OBJECT);
final EJBMetaDataImpl metaData = new EJBMetaDataImpl(null, null, beanContext.getPrimaryKeyClass(), beanContext.getComponentType().toString(), deploymentID, -1, convert(proxyInfo.getInterfaceType()), proxyInfo.getInterfaces(), beanContext.getAsynchronousMethodSignatures());
metaData.setPrimaryKey(proxyInfo.getPrimaryKey());
metaData.loadProperties(beanContext.getProperties());
log(metaData);
res.setResult(metaData);
break;
}
case BUSINESS_LOCAL:
{
res.setResponseCode(ResponseCodes.JNDI_NAMING_EXCEPTION);
final NamingException namingException = new NamingException("Not remotable: '" + name + "'. Business Local interfaces are not remotable as per the EJB specification. To disable this restriction, set the system property 'openejb.remotable.businessLocals=true' in the server.");
res.setResult(new ThrowableArtifact(namingException));
break;
}
case LOCALBEAN:
{
res.setResponseCode(ResponseCodes.JNDI_NAMING_EXCEPTION);
final NamingException namingException = new NamingException("Not remotable: '" + name + "'. LocalBean classes are not remotable as per the EJB specification.");
res.setResult(new ThrowableArtifact(namingException));
break;
}
default:
{
res.setResponseCode(ResponseCodes.JNDI_NAMING_EXCEPTION);
final NamingException namingException = new NamingException("Not remotable: '" + name + "'.");
res.setResult(new ThrowableArtifact(namingException));
}
}
}
use of org.apache.openejb.Injection in project tomee by apache.
the class WsService method afterApplicationCreated.
public void afterApplicationCreated(final AppInfo appInfo, final WebAppInfo webApp) {
final WebContext webContext = containerSystem.getWebContextByHost(webApp.moduleId, webApp.host != null ? webApp.host : virtualHost);
if (webContext == null)
return;
// if already deployed skip this webapp
if (!deployedWebApps.add(webApp))
return;
final Map<String, PortInfo> ports = new TreeMap<>();
for (final PortInfo port : webApp.portInfos) {
ports.put(port.serviceLink, port);
}
URL moduleBaseUrl = null;
try {
moduleBaseUrl = new File(webApp.path).toURI().toURL();
} catch (final MalformedURLException e) {
LOGGER.error("Invalid ejb jar location " + webApp.path, e);
}
// lazy init
Collection<IdPropertiesInfo> pojoConfiguration = null;
for (final ServletInfo servlet : webApp.servlets) {
if (servlet.servletName == null) {
continue;
}
final PortInfo portInfo = ports.get(servlet.servletName);
if (portInfo == null) {
continue;
}
final ClassLoader old = Thread.currentThread().getContextClassLoader();
final ClassLoader classLoader = webContext.getClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try {
final Collection<Injection> injections = webContext.getInjections();
final Context context = webContext.getJndiEnc();
final Class target = classLoader.loadClass(servlet.servletClass);
final Map<String, Object> bindings = webContext.getBindings();
final PortData port = WsBuilder.toPortData(portInfo, injections, moduleBaseUrl, classLoader);
pojoConfiguration = PojoUtil.findPojoConfig(pojoConfiguration, appInfo, webApp);
final HttpListener container = createPojoWsContainer(classLoader, moduleBaseUrl, port, portInfo.serviceLink, target, context, webApp.contextRoot, bindings, new ServiceConfiguration(PojoUtil.findConfiguration(pojoConfiguration, target.getName()), appInfo.services));
if (wsRegistry != null) {
String auth = authMethod;
String realm = realmName;
String transport = transportGuarantee;
if ("BASIC".equals(portInfo.authMethod) || "DIGEST".equals(portInfo.authMethod) || "CLIENT-CERT".equals(portInfo.authMethod)) {
auth = portInfo.authMethod;
realm = portInfo.realmName;
transport = portInfo.transportGuarantee;
}
// give servlet a reference to the webservice container
final List<String> addresses = wsRegistry.setWsContainer(container, classLoader, webApp.contextRoot, host(webApp), servlet, realm, transport, auth, webApp.moduleId);
// one of the registered addresses to be the connonical address
final String address = HttpUtil.selectSingleAddress(addresses);
if (address != null) {
// add address to global registry
portAddressRegistry.addPort(portInfo.serviceId, portInfo.wsdlService, portInfo.portId, portInfo.wsdlPort, portInfo.seiInterfaceName, address);
setWsdl(container, address);
LOGGER.info("Webservice(wsdl=" + address + ", qname=" + port.getWsdlService() + ") --> Pojo(id=" + portInfo.portId + ")");
/*
In POJO webservices it is very common to have the same JAW-WS endpoint published under different URLs
using url-pattern for the servlet. We only deploy one instance of the WsServlet and keep the same
set of url-pattern the user defined. At the moment we can't add additional ports, with different
addresses. So at least we should list other URLs so the user knows they are successfully deployed
and is aware of the different URLs
*/
for (String urlAddress : addresses) {
if (address.equals(urlAddress)) {
continue;
}
LOGGER.info("Webservice(wsdl=" + urlAddress + ", qname=" + port.getWsdlService() + ") --> Pojo(id=" + portInfo.portId + ")");
}
servletAddresses.put(webApp.moduleId + "." + servlet.servletName, address);
addressesForApp(webApp.moduleId).add(new EndpointInfo(address, port.getWsdlService(), target.getName()));
}
}
} catch (final Throwable e) {
LOGGER.error("Error deploying CXF webservice for servlet " + portInfo.serviceLink, e);
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
}
use of org.apache.openejb.Injection in project tomee by apache.
the class DynamicProxyImplFactory method newProxy.
public static Object newProxy(final BeanContext context, final InvocationHandler invocationHandler) {
if (QueryProxy.class.isInstance(invocationHandler)) {
EntityManager em = null;
for (final Injection injection : context.getInjections()) {
if (QueryProxy.class.equals(injection.getTarget())) {
try {
em = (EntityManager) context.getJndiEnc().lookup(injection.getJndiName());
} catch (final NamingException e) {
throw new OpenEJBRuntimeException("a dynamic bean should reference at least one correct PersistenceContext", e);
}
}
}
if (em == null) {
throw new OpenEJBRuntimeException("can't find the entity manager to use for the dynamic bean " + context.getEjbName());
}
QueryProxy.class.cast(invocationHandler).setEntityManager(em);
}
return newProxy(context.getBeanClass(), invocationHandler);
}
use of org.apache.openejb.Injection in project tomee by apache.
the class HandlerResolverImpl method buildHandlers.
private List<Handler> buildHandlers(final PortInfo portInfo, final HandlerChainData handlerChain) {
if (!matchServiceName(portInfo, handlerChain.getServiceNamePattern()) || !matchPortName(portInfo, handlerChain.getPortNamePattern()) || !matchBinding(portInfo, handlerChain.getProtocolBindings())) {
return Collections.emptyList();
}
final List<Handler> handlers = new ArrayList<>(handlerChain.getHandlers().size());
for (final HandlerData handler : handlerChain.getHandlers()) {
final WebBeansContext webBeansContext = AppFinder.findAppContextOrWeb(Thread.currentThread().getContextClassLoader(), AppFinder.WebBeansContextTransformer.INSTANCE);
if (webBeansContext != null) {
// cdi
final BeanManagerImpl bm = webBeansContext.getBeanManagerImpl();
if (bm.isInUse()) {
try {
final Set<Bean<?>> beans = bm.getBeans(handler.getHandlerClass());
final Bean<?> bean = bm.resolve(beans);
if (bean != null) {
// proxy so faster to do it
final boolean normalScoped = bm.isNormalScope(bean.getScope());
final CreationalContextImpl<?> creationalContext = bm.createCreationalContext(bean);
final Handler instance = Handler.class.cast(bm.getReference(bean, bean.getBeanClass(), creationalContext));
// hack for destroyHandlers()
handlers.add(instance);
handlerInstances.add(new InjectionProcessor<Handler>(instance, Collections.<Injection>emptySet(), null) {
@Override
public void preDestroy() {
if (!normalScoped) {
creationalContext.release();
}
}
});
continue;
}
} catch (final InjectionException ie) {
LOGGER.info(ie.getMessage(), ie);
}
}
}
try {
// old way
final Class<? extends Handler> handlerClass = handler.getHandlerClass().asSubclass(Handler.class);
final InjectionProcessor<Handler> processor = new InjectionProcessor<>(handlerClass, injections, handler.getPostConstruct(), handler.getPreDestroy(), unwrap(context));
processor.createInstance();
processor.postConstruct();
final Handler handlerInstance = processor.getInstance();
handlers.add(handlerInstance);
handlerInstances.add(processor);
} catch (final Exception e) {
throw new WebServiceException("Failed to instantiate handler", e);
}
}
return handlers;
}
Aggregations