Using Blazeds To Connect to a EJB on Glassfish - apache-flex

The task is to try to connect directly to a stateless EJB deployed on Glassfish. I have already done this via Web Service and I can also connect to the EJB by calling a remote java object which uses JNDI to find and load the bean. What I cannot do is directly connect to the EJB with Blazeds. I am using EBJ3Factory BY Ryan Norris (downloaded from adobe site) as follows;
My WEB-INF/flex/services-config.xml has;
<factories>
<factory id="ejb3" class="com.adobe.ac.ejb.EJB3Factory" />
</factories>
My WEB-INF/flex/remoting-config.xml has;
<destination id="MyEJB">
<properties>
<factory>ejb3</factory>
<source>java:global/Together/PSearch!ejb.PSearch</source>
</properties>
</destination>
I have a simple java class that can access the bean so I can use Blazeds to call the class which then calls the bean;
public void getBean() {
PSearch search;
InitialContext ctx;
try {
ctx = new InitialContext();
search = (PSearch) ctx.lookup("java:global/Together/PSearch!ejb.PSearch");
System.out.println("jndi okay");
} catch (NamingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
The asadmin command for the context in glassfish shows me;
./asadmin list-jndi-entries --context java:global/Together
PSearch__3_x_Internal_RemoteBusinessHome__: javax.naming.Reference
PSearch!ejb.PSearchRemote: javax.naming.Reference
PSearch!ejb.PSearch: com.sun.ejb.containers.JavaGlobalJndiNamingObjectProxy
PSearch!ejb.PSearchLocal: com.sun.ejb.containers.JavaGlobalJndiNamingObjectProxy
Yet when I use Eclipse / Flash Builder to try to Import a BlazeDS service I get an introspection error;
java:global/Together/PSearch/!ejb.PSearch is not available in the specified location
I have also tried changing the remoting-config.xml to point to local and remote interfaces but no joy!
Any pointers would be greatly appreciated.

One workaround you could do would be to remove the factory XML element, replace the source JNDI name with the EJB fully qualified class name and create the service with Flash Builder using the BlazeDS RTS service as you tried to do.
<destination id="MyEJB">
<properties>
<source>packagename.EJBClassName</source>
</properties>
</destination>
When you are done making the service client, service and the value objects(return type etc) in your Flex project then put everything back as they were:
<destination id="MyEJB">
<properties>
<factory>ejb3</factory>
<source>java:global/Together/PSearch!ejb.PSearch</source>
</properties>
</destination>
What u r going to do actually is to treat the EJB 3.x as a normal POJO for the introspection in order to create the AS3 classes and when u r done change the destination to an EJB3 destination by using the factory.
I am working on a way to make this steps unnecessary. If I have time to finish it I will let you know.

Related

How to store files uploaded from client machine to jboss standalone directory?

I have requirement to store files uploaded (using spring mvc) from client machine to jboss standalone directory .Give step by step solution
I would give the community project called Spring Content a try. This project makes it very easy to handle files by injecting the service and controller implementations for you (so that you don't need to write them yourself).
Adding it would look something like this:
pom.xml (assuming maven. Spring boot starters also available)
<!-- Java API -->
<!-- just change this depdendency if you want to store somewhere else -->
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-fs</artifactId>
<version>0.8.0</version>
</dependency>
<!-- REST API -->
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-rest</artifactId>
<version>0.8.0</version>
</dependency>
StoreConfig.java
#Configuration
#EnableFilesystemStores
#Import(RestConfiguration.class)
public class StoreConfig {
#Bean
FileSystemResourceLoader fileSystemResourceLoader() throws IOException {
return new FileSystemResourceLoader(new File("/path/to/uploaded/files").getAbsolutePath());
}
}
FileStore.java
#StoreRestResource(path="files")
public interface FileStore extends Store<String> {
}
And that's it. The FileStore is essentially a generic Spring ResourceLoader. The spring-content-fs dependency will cause Spring Content to inject a filesystem-based implementation. The spring-content-rest dependency will cause Spring Content to also inject an implementation if an #Controller that forwards HTTP requests onto the methods of the FileStore service.
So you will now have a fully functional (POST, PUT, GET, DELETE) REST-based file service at /files that will use your FileStore to retrieve (and store) files in /path/to/uploaded/files on your jboss server.
So:
curl --upload-file some-image.jpg /files/some-image.jpg
will upload some-image.jpg and store it in /path/to/uploaded/files on your server.
And:
curl /files/some-image.jpg
would retrieve it again.
HTH
The injected controller also supports video streaming too, in case that is useful.
With this you could also remove all of your controller and service code as it is no longer required. Plus, as Spring Content is an abstraction over storage, in future, you could also shift to any of the other storage mediums supported by Spring Content; S3 for example.

How to configure Java Message Driven Beans and Websphere Activation specification without hardcoded JNDI Names?

We have a MDB listening to a Queue reading data and sending data to another Queue
#MessageDriven(
activationConfig = { #ActivationConfigProperty(
propertyName = "destinationType", propertyValue = "javax.jms.Queue"
) },
mappedName = "jms/dataQ")
public class DataMDB implements MessageListener {
#Resource(name="jms/dataQueueConnectionFactory")
private ConnectionFactory connectionfactory;
#Resource(name="jms/dataDestinationQ")
private Destination destination;
...
}
and an XML (ibm-ejb-jar-bnd.xml) with bean configuration
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar-bnd xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://websphere.ibm.com/xml/ns/javaee"
xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee http://websphere.ibm.com/xml/ns/javaee/ibm-ejb-jar-bnd_1_0.xsd"
version="1.0">
<message-driven name="DataMDB">
<jca-adapter activation-spec-binding-name="eis/dataListenerMDB"
destination-binding-name="jms/dataQ" />
<resource-ref name="jms/dataQueueConnectionFactory"
binding-name="jms/dataQueueConnectionFactory" />
<resource-env-ref name="jms/dataDestinationQ"
binding-name="jms/dataDestinationQ" />
</message-driven>
</ejb-jar-bnd>
and Activation specification for this MDB on WebSphere
As I have seen the examples over Google, this is the typical example of MDB and WAS Activation setup.
We have a problem here as all the JNDI names seen here are hardcoded in Java code anotations as well as in the ibm-ejb-jar-bnd.xml file.
So is there a way that these JNDI names can be brought outside the EJB project, so we could build one project for all customers and customers are free to have their Standard JNDI Names.
Else we have to build different .ear for each customer and which is not ideal.
Thanks in advance people.
Any ideas are welcome.
All values defined in the ibm-ejb-jar-bnd.xml maps references to the actual JNDI names. This can be overridden for each of your customers during application installation (mapping references to JNDI names steps in the admin console), after application installation, or during installation using scripts.
The binding file (ibm-ejb-jar-bnd.xml) provides only 'default names', in case you dont want to change them during installation.

How do you create CouchDB Views using Spring Bean Deployment with LightCouch

I am using Spring-MVC LightCouch and CouchDB and I have custom Views that need to be inserted into the DB on deployment. I have found the LightCouch has a method for pulling documents "from desk" as noted on their website:
DesignDocument designDoc = dbClient.design().getFromDesk("example");
Response response = dbClient.design().synchronizeWithDb(designDoc);
This Works good from within JAVA code, however I need to be able to do it in the Spring ApplicationContext.xml I have more than one so I would like to mimick the call of:
dbClient.dessign().synchronizeAllWithDB()
How would I do this in the bean definition of the ApplicationContext I already have this:
<bean id="dbClient" class="org.lightcouch.CouchDbClient" lazy-init="false" destroy- method="shutdown">
<constructor-arg value="couchdb.properties" />
</bean>
It seems you can't do it with Spring xml config, as the init method falls under a different instance; that is returned by the call to design() factory method. Maybe you can try Java code equivalence, i.e. #PostConstruct.
I ended up having to make a bean that synchronized the database on init and created that when the app starts

Can't get SessionContext on EJB

I can't get a SessionContext object on an EJB. I've tried all the options suggested on 4 Ways to Get EJBContext in EJB 3 and none of them worked. For example, the following code in my project...
#Stateful
public class SecurityService {
#Resource
private SessionContext context;
#PostConstruct
public void init() {
}
}
... generates the following exception during deploy:
[#|2012-02-28T14:35:02.805-0300|SEVERE|glassfish3.1.1|javax.enterprise.system.core.com.sun.enterprise.v3.server|_ThreadID=18;_ThreadName=admin-thread-pool-4848(5);|The log message is null.
java.lang.NullPointerException
at com.sun.appserv.connectors.internal.api.AppSpecificConnectorClassLoaderUtil.detectResourceInRA(AppSpecificConnectorClassLoaderUtil.java:266)
at com.sun.appserv.connectors.internal.api.AppSpecificConnectorClassLoaderUtil.processDescriptorForRAReferences(AppSpecificConnectorClassLoaderUtil.java:211)
at com.sun.appserv.connectors.internal.api.AppSpecificConnectorClassLoaderUtil.processDescriptorForRAReferences(AppSpecificConnectorClassLoaderUtil.java:130)
at com.sun.appserv.connectors.internal.api.AppSpecificConnectorClassLoaderUtil.detectReferredRARs(AppSpecificConnectorClassLoaderUtil.java:118)
at com.sun.appserv.connectors.internal.api.ConnectorClassLoaderServiceImpl.getConnectorClassLoader(ConnectorClassLoaderServiceImpl.java:111)
at com.sun.enterprise.v3.server.ClassLoaderHierarchyImpl.getConnectorClassLoader(ClassLoaderHierarchyImpl.java:117)
If I remove the #Resource annotation it deploys, but does not work (i've tried with JNDI and the other methods cited before).
I'm using Glassfish 3.1.1, and my project is JSF with CDI and EJB locally to services with JPA. I've tried injecting SessionContext on CDI beans but received the same errors. My EJB are configured with annotations, and my beans.xml have no configurations (but exists).
One strange thing is that with JNDI lookup I've managed to get an object of type SessionContextImpl on path java:/comp/EJBContext on the #PostConstruct init() method. BUT, it goes to null as soon as another EJB method is called (?) and it does not contain user's roles data (a call to isCallerInRole() throws an exception). Also, it is not an EJBContext object.
I'm packaging everything in a WAR using Maven, and the dependency of Java EE is marked as provided, as the following shows:
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
It seems to me that there is no SessionContext (EJBCOntext) been provided by the container at all. I don't know even if that is possible, and I have no idea on how to solve this.
Please, If you have ANY idea about this, I'll be glad to hear it. Thank you.
If your Principal has logged in using j_security_check, you can inject the SecurityContext in an EJB, or in a ManagedBean, and retrieve Principal's and role's information like this:
#Context private SecurityContext context;
....
boolean isInRole = context.isUserInRole("A role");
Principal p = context.getUserPrincipal();
Well, I've upgraded to Glassfish 3.1.2 and the problem was solved. Now I can inject javax.ejb.SessionContext as expected.
Special thanks to #perissf for the help.

How to obtain OSGi service references from a Servlet that is registered in OSGi HttpService?

It seems natural that a HttpServlet running in OSGi environment (i.e. registered in OSGi HttpService) would want to call some OSGi services to accomplish it's tasks. The question is how to obtain references to these OSGi service inside the servlet.
One way would be to inject dependencies into the HttpServlet instance that is being registered to the OSGi HttpService like this:
MyServlet servlet = new MyServlet();
servlet.setFooService(fooService);
httpService.registerServlet("/myservlet", servlet, initparams, context);
I'm not sure if this is a valid approach since in non-OSGi environment the servlet life-cycle is managed by the Web Container and hence the service reference would not be injected for the servlet instances created later on.
There is another way to solve this when using PAX Web as an implementation of the OSGi HttpService. PAX Web exports the OSGi BundleContext into the ServletContext as a special attribute "osgi-bundlecontext". The BundleContext can then be used to obtain necessary service references:
public void init(ServletConfig servletConfig) throws ServletException {
ServletContext context = servletConfig.getServletContext()
BundleContext bundleContext =
(BundleContext) context.getAttribute("osgi-bundlecontext");
ServiceReference serviceRef =
bundleContext.getServiceReference("com.foo.FooService")
}
However this approach is rather ugly and ties you to a concrete implementation of the OSGi HttpService. Do you know any other (and possibly better) solution to this problem?
If you use a setter for the dependency on the service, as you have shown, it can work outside of OSGi as well. You just need to use some other dependency injection mechanism. If there is none, you could provide a subclass that initializes the servlet using JNDI lookups or from the servlet context.
public class MyServlet_AdapterForMissingDI extends MyServlet{
public void init(ServletConfig config){
setFooService(getItFromSomewhere());
}
}
The point being that if you have DI capabilities that can inject setFooService, you can just use the same servlet in OSGi and elsewhere, if you do not (and still want to support this case), you provide an adapter.
On a related note, check out Felix SCR to configure your object's dependencies, and Pax Web Extender Whiteboard, which takes care of hooking your servlet up with the HttpService.
Specifically, without SCR and Whiteboard, you need to think about the case when the fooService becomes unavailable later, or the HttpService gets started after your servlet.
In these cases your servlet would have a reference to a dead service that prevents the bundle from being garbage-collected, or your servlet would not be registered with the HttpService.
Update: Here is the SCR descriptor I use for one of my servlets. SCR handles servlet instantiation, life-cycle, registration (via Whiteboard), and dependencies. There is no OSGi-specific code in the servlet. There is not even the need for a BundleActivator anymore (SCR registers all services):
<component name="oracle.statusServlet" >
<implementation class="mypackage.DataSourceStatusServlet"/>
<property name="service.description" value="Oracle DataSource status servlet" />
<property name="alias" value="/OracleDataSourceStatus" />
<property name="servlet-name" value="Oracle DataSource status servlet" />
<service>
<provide interface="javax.servlet.Servlet" />
</service>
<reference name="DATASOURCES"
interface="javax.sql.DataSource"
cardinality="0..n" policy="dynamic"
bind="bindDataSource" unbind="unbindDataSource"/>
</component>
The dependencies for the servlet are specified in the reference tag. SCR will do the service lookup and binding.
May be an old post and you already might have got the answer..
Are you launching felix or whatever OSGi container yourself. If that is the case you can set the bundle context as an attribute to the servlet context.
Whats wrong in using an http service by PAX. ultimately the thread management and other aspects are taken care of by the servlet container in which you run this http service.
You could inject the services into some object, which is then queried by the servlets.

Resources