EJB help needed - glassfish

public void runTest() throws Exception {
InitialContext ctx = new InitialContext();
ResourceManager bean = (ResourceManager) ctx.lookup("ejb/ResourceManagerJNDI");
System.out.println(bean.DummyText());
}
Hello. So i'm trying to create an EJB application, and this is the test client for it. the JNDI lookup is successful but when calling the "DummyText" method, i get the following error:
javax.ejb.EJBException: nested exception is: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.RemoteException: nested exception is: javax.ejb.EJBException: nested exception is: javax.ejb.CreateException: Could not create stateless EJB; nested exception is:
javax.ejb.EJBException: nested exception is: javax.ejb.CreateException: Could not create stateless EJB (...)
This is how the bean class looks:
#Stateless(name="ResourceManager", mappedName="ejb/ResourceManagerJNDI")
#Remote
#Local
public class ResourceManagerBean implements ResourceManager
{
#EJB
private AccessDAO accessDAO;
#EJB
private ResourceDAO resourceDAO;
#EJB
private DepartmentDAO departmentDAO;
(list of methods)
}
Any advice will be greatly appreciated. Thank you.

Here's my first thoughts.
You should have something like
#Remote
public interface ResourceManagerSessionRemote {
(list of methods)
}
Break your remote and local interfaces out
#Stateless(name="ResourceManager", mappedName="ejb/ResourceManagerJNDI")
public class ResourceManagerBean implements ResourceManagerSessionRemote
{
#EJB
private AccessDAO accessDAO;
#EJB
private ResourceDAO resourceDAO;
#EJB
private DepartmentDAO departmentDAO;
(list of methods)
}

Related

#Conditional annotation causing BeanCreationException on nested beans

I am using Spring 4.x in which I am using #Conditional annotation to control the bean registration.
I have classes defined as given below,
#Controller
class SchoolController{
#Autowired
#Qualifier("studentProcessor")
private StudentProcessor studentProcessor;
//Some code
}
#Component("studentProcessor")
class StudentProcessor{
#Autiwired
private SportService sportService;
//Some code
}
#Component
#Conditional(ServiceCondition.class)
class SportService{
//Some code
}
class ServiceCondition implements Condition{
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//Some condition
}
}
When I start the Tomcat, I get this exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentProcessor': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.student.service.SportService com.student.processors.StudentProcessor.sportService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.student.service.SportService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Is this the expected behavior?
If not then how do I get rid of this issue?
From your configuration, SportService bean is loaded based on the conditional implementation of ServiceCondition.
So, if the matches method returns false for some reason based on your logic, then SportService is would not be created and will not be available for autowiring.
That being said, StudentProcessor cannot have a concrete #Autowired for SportService.
I am not fully aware of your requirement, but for you to proceed with this configuration, you need to mark autowiring as optional.
#Autiwired
private SportService sportService;
//Some code
to
#Autiwired(required = false)
private SportService sportService;
//Some code
Further, you need to check if the instance is injected or not and then use it.

Failed to marshal EJB parameters --- IllegalArgumentException: Can not set org.apache.commons.collections.FastHashMap field

I'm getting the below error while trying to save a search results using the Remote interface for SearchFacade.java
"Failed to marshal EJB parameters"
Can not set org.apache.commons.collections.FastHashMap field
org.apache.commons.validator.Field.hMsgs to
org.apache.commons.collections.FastHashMap at
sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:146)
at
I'm Using struts 1.1, EJB 2.1 using xdoclet 1.2.3 jars for generating the dependency files.(which is inevitable to use), Where my Local,Home interfaces are being generated using Xdoclet..
I'm also using Java 6, Jboss EAP 6.1 Alpha in my project.
Note: The same code works fine when running in Jboss 4.0
So wonder is my remote calling is correct.
Any help is welcome.
Error Logs
java.lang.RuntimeException: JBAS014154: Failed to marshal EJB parameters at org.jboss.as.ejb3.remote.LocalEjbReceiver.clone(LocalEjbReceiver.java:270) at org.jboss.as.ejb3.remote.LocalEjbReceiver.clone(LocalEjbReceiver.java:259) at org.jboss.as.ejb3.remote.LocalEjbReceiver.processInvocation(LocalEjbReceiver.java:170) at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:181) at org.jboss.ejb.client.EJBHomeCreateInterceptor.handleInvocation(EJBHomeCreateInterceptor.java:79) at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:183) at org.jboss.ejb.client.TransactionInterceptor.handleInvocation(TransactionInterceptor.java:42) at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:183) at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:125) at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:183) at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:177) at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:161) at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:124) at $Proxy25.saveSearch(Unknown Source) at com.web.history.SearchFormDelegate.saveSearch(SearchFormDelegate.java:177) at com.history.SaveSearchAction.createNewSavedSearch(SaveSearchAction.java:109) at com.history.SaveSearchAction.executeSynchronized(SaveSearchAction.java:296) at com.dispatch.SynchronizedAction.execute(SynchronizedAction.java:206) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432) at javax.servlet.http.HttpServlet.service(HttpServlet.java:754) at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:295) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at com.security.AuthenticationFilter.doFilter(AuthenticationFilter.java:672) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at com.planetj.servlet.filter.compression.CompressingFilter.doFilter(CompressingFilter.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:149) at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:169) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:145) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:97) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:102) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:336) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:653) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:920) at java.lang.Thread.run(Thread.java:662) Caused by: java.lang.IllegalArgumentException: Can not set org.apache.commons.collections.FastHashMap field org.apache.commons.validator.Field.hMsgs to org.apache.commons.collections.FastHashMap at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:146) at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:150) at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:63) at java.lang.reflect.Field.set(Field.java:657) at org.jboss.marshalling.cloner.SerializingCloner.storeFields(SerializingCloner.java:368) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:313) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner.cloneFields(SerializingCloner.java:348) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:309) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner$StepObjectInput.doReadObject(SerializingCloner.java:836) at org.jboss.marshalling.AbstractObjectInput.readObject(AbstractObjectInput.java:37) at org.jboss.marshalling.MarshallerObjectInputStream.readObjectOverride(MarshallerObjectInputStream.java:57) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:344) at java.util.HashMap.readObject(HashMap.java:1030) at sun.reflect.GeneratedMethodAccessor119.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.jboss.marshalling.reflect.SerializableClass.callReadObject(SerializableClass.java:218) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:302) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner.cloneFields(SerializingCloner.java:348) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:309) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner.cloneFields(SerializingCloner.java:348) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:309) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:285) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.marshalling.cloner.SerializingCloner.cloneFields(SerializingCloner.java:348) at org.jboss.marshalling.cloner.SerializingCloner.initSerializableClone(SerializingCloner.java:309) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:253) at org.jboss.marshalling.cloner.SerializingCloner.clone(SerializingCloner.java:134) at org.jboss.as.ejb3.remote.LocalEjbReceiver.clone(LocalEjbReceiver.java:268) ... 42 more
Code:
saveAction.java
protected void newSavedSearch(final SrchFrmDelegate sfd,
final String userId, final HttpServletRequest request,
final SaveSearchForm form) throws RemoteException,
UsrNotFoundException {
BseSrchValue srchValue = SrchResultsAction.retrieveSrchCriteria(request);
FrmLayout frmLayout = (FrmLayout) request.getSession().getAttribute(
FrmBuilderAction.FRM_LAYOUT_KEY);
Integer resultCount = null;
SrchResultValue srchResult = SearchResultsAction.retrieveSearchResults(request);
if (srchResult != null) {
resultCount = new Integer(srchResult.getTotal());
}
sfd.saveSearch(userGuid,
form.getTitle(),
form.getDesc(),
form.getNewTtle(),
srchValue,
frmLayout,
resultCount,
form.getSearches());
}
SrchFrmDelegate.java
/**
* Reference to the remote interface.
*/
private SrhFrmFacadeRemote srhFacadeRemote;
public String saveSearch(final String userId, final String srchTtle,
final String srchDesc, final Boolean newTtle,
final BsSearchValue srchValue, final FrmLay frmLay,
final Integer resultCount, final List alerts)
throws UsrNotFoundException,
RemoteException {
return srhFacadeRemote.saveSearch(userId, srchTtle,
srchDesc, newTtle, srchValue, frmLay,
resultCount, alerts);
}
SrchFrmFacadeRemote.java
/**
* Remote interface for SrchFrmFacade.
*/
public java.lang.String saveSearch( java.lang.String userId,java.lang.String srchTtle,java.lang.String srchDesc,java.lang.Boolean newTtle,com.common.search.BsSearchValue srchValue,com.common.search.advanced.FrmLay frmLay,java.lang.Integer resultCount,java.util.List alerts ) throws com.common.admin.UserNotFoundException, java.rmi.RemoteException;
Objects that passed as parameters or as response on remote calls must be Serializable.
example:-
public class APIGetVerificationProofs implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String fileName;
private String mimeType;
private String itemId;
private String type;
.
.
.
.
}
After adding the below jars in Jboss 7 modules & altering the standalone.xml file accordingly, Issue is fixed.
jboss-eap-6.1.0.Alpha\modules\system\layers\base\org\apache\commons\validator
commons-validator-1.1.0.jar
jboss-eap-6.1.0.Alpha\modules\system\layers\base\org\apache\commons\collections commons-collections-3.2.1.jar
In Standalone.xml
<subsystem xmlns="urn:jboss:domain:ee:1.1">
<spec-descriptor-property-replacement>false</spec-descriptor-property-replacement>
<jboss-descriptor-property-replacement>true</jboss-descriptor-property-replacement>
<global-modules>
<module name="org.apache.commons.collections" slot="main"/>
<module name="org.apache.commons.validator" slot="main"/>
</global-modules>
</subsystem>
In EJB3 this error can also occur when invoking an EJB Session Bean across a #Remote view of the EJB. Depending on the design and usage scenario, you may be able to invoke the EJB over a #Local interface. Using the #Local interface will eliminate the requirement for the parameters to be Serializable but this can markedly change your design. If using the #Local view is an option for you, you can simply add the #Local to the EJB without removing the #Remote.
public class MySessionBeanImpl implements MySessionBean {
...
}
#Local
#Remote
public interface MySessionBean {
...
}
The JEE App Server will make the right decision to use the local view if the client of the invocation is in-container. According to the API docs, the Local annotation can appear on either the class or the interface. If on the class, the value attribute must be specified.
remember to add serialVersionUID to let class to be serialized and restored (generate it as getter or setter)
For this problem first, you have to implement Serializable interface in your POJO class (java beans) as:
package com.test;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private int empID;
private String empName;
private int empSalary;
public int getEmpID() {
return empID;
}
//alt_shift_s_r-getter and setter method
//alt_shift_s_s override toString()
public void setEmpID(int empID) {
this.empID = empID;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getEmpSalary() {
return empSalary;
}
public void setEmpSalary(int empSalary) {
this.empSalary = empSalary;
}
#Override
public String toString() {
return "Employee [empID=" + empID + ", empName=" + empName + ", empSalary=" + empSalary + "]";
}
}
Note: if you are adding some external jars into your project then follow the below procedure to add jars.
Right Click on your EJB project and go to properties.
Then Select Deployment assembly then clicks on add.
From the appears option select appropriate source (As Archive from File System) then go to next.
Now Add jars from your desired location and finish the procedure.
enter code here

CDI injection not done in base class for jax-rs controller

I'm struggling with CDI and class inheritence.
I've a JAX-RS controller declared as :
#Path("/share")
public class ControllerShare extends BaseController {
#Inject
private ServiceShare serviceShare;
#PostConstruct
private void verifInit() throws ExceptionTechnique {
log.warn("Checking CDI injection");
if (serviceShare == null) {
log.error("serviceAccount not initialized. Check your EJB configuration");
throw new ExceptionTechnique("serviceShare not initialized. Check your EJB configuration.");
}
}
...
}
This controller extends a base controller declared as :
public abstract class BaseController {
private Logger log = LoggerFactory.getLogger(ControllerShare.class);
#Context protected HttpServletRequest request;
#Inject private ControlerSession ctrlSession;
public BaseController() {}
#PostConstruct
private void verifInit() throws ExceptionTechnique {
log.warn("Checking CDI injection");
if (ctrlSession == null) {
log.error("controllerSession not initialized. Check your CDI configuration");
throw new ExceptionTechnique("serviceAccount not initialized. Check your CDI configuration.");
}
}
...
}
The problem is that injection is correctly done in ControllerShare (I correctly see "Checking CDI injection"), but is not done in the BaseController class (ctrlSession is null).
I try #Named and others combination without success. Injection is just done in ControllerShare and not in BaseController.
EDIT:
One more thing : curiously the #Context is working fine. My request is set and the value is correct.
Thank's for any explanation and solution.
Actually, this should work according to
http://docs.jboss.org/cdi/spec/1.0/html/inheritance.html
4.2. Inheritance of member-level metadata
Suppose a class X is extended directly or indirectly by the bean class of a managed bean or session bean Y.
If X declares an injected field x then Y inherits x.
On a side note: #PostConstruct however is not inherited if you specify it anew. Therefore, in your sub-class your method must be named differently to have both initializers executed.
If X declares an initializer, non-static observer, #PostConstruct or #PreDestroy method x() then Y inherits x() if and only if neither Y nor any intermediate class that is a subclass of X and a superclass of Y overrides the method x().

GemFire: serialize objects in Java and then deserialize them in c#

To cross the language boundary in Java side the class to be serialized needs to implement the DataSerializable interface; and in order to let the deserializer in c# know what class it is , we need to register a classID. Following the example, I write my class in Java like this:
public class Stuff implements DataSerializable{
static { // note that classID (7) must match C#
Instantiator.register(new Instantiator(Stuff.class,(byte)0x07) {
#Override
public DataSerializable newInstance() {
return new Stuff();
}
});
}
private Stuff(){}
public boolean equals(Object obj) {...}
public int hashCode() {...}
public void toData(DataOutput dataOutput) throws IOException {...}
public void fromData(DataInput dataInput) throws IOException, ClassNotFoundException { ...}
}
It looks OK but when I run it I get this exception:
[warning 2012/03/30 15:06:00.239 JST tid=0x1] Error registering
instantiator on pool:
com.gemstone.gemfire.cache.client.ServerOperationException: : While
performing a remote registerInstantiators at
com.gemstone.gemfire.cache.client.internal.AbstractOp.processAck(AbstractOp.java:247)
at
com.gemstone.gemfire.cache.client.internal.RegisterInstantiatorsOp$RegisterInstantiatorsOpImpl.processResponse(RegisterInstantiatorsOp.java:76)
at
com.gemstone.gemfire.cache.client.internal.AbstractOp.attemptReadResponse(AbstractOp.java:163)
at
com.gemstone.gemfire.cache.client.internal.AbstractOp.attempt(AbstractOp.java:363)
at
com.gemstone.gemfire.cache.client.internal.ConnectionImpl.execute(ConnectionImpl.java:229)
at
com.gemstone.gemfire.cache.client.internal.pooling.PooledConnection.execute(PooledConnection.java:321)
at
com.gemstone.gemfire.cache.client.internal.OpExecutorImpl.executeWithPossibleReAuthentication(OpExecutorImpl.java:646)
at
com.gemstone.gemfire.cache.client.internal.OpExecutorImpl.execute(OpExecutorImpl.java:108)
at
com.gemstone.gemfire.cache.client.internal.PoolImpl.execute(PoolImpl.java:624)
at
com.gemstone.gemfire.cache.client.internal.RegisterInstantiatorsOp.execute(RegisterInstantiatorsOp.java:39)
at
com.gemstone.gemfire.internal.cache.PoolManagerImpl.allPoolsRegisterInstantiator(PoolManagerImpl.java:216)
at
com.gemstone.gemfire.internal.InternalInstantiator.sendRegistrationMessageToServers(InternalInstantiator.java:188)
at
com.gemstone.gemfire.internal.InternalInstantiator._register(InternalInstantiator.java:143)
at
com.gemstone.gemfire.internal.InternalInstantiator.register(InternalInstantiator.java:71)
at com.gemstone.gemfire.Instantiator.register(Instantiator.java:168)
at Stuff.(Stuff.java)
Caused by: java.lang.ClassNotFoundException: Stuff$1
I could not figure out why, is there anyone who has experience can help? Thanks in advance!
In most configurations GemFire servers need to deserialize objects in order to index them, run queries and call listeners. So when you register instantiator the class will be registered on all machines in the Distributed System. Hence, the class itself must be available for loading everywhere in the cluster.
As exception stack trace says the error happens on a remote node.
Check if you have the class Stuff on all machines participating in the cluster. At least on cache servers.

Glassfish ejb ref resolution error for remote business interface

I've created very basic EJB3 stateful bean but can't access it remotely.
I'm getting:
Caused by: javax.naming.NamingException: ejb ref resolution error for remote business interfacecom.s9120.ejb.Calculator [Root exception is java.lang.ClassNotFoundException: com.s9120.ejb.Calculator]
I have 1 bean and 1 interface.
It looks like the interface is not deployed (I'm using GlassFish):
Here is the code:
package com.calc.ejb;
import javax.ejb.Remote;
#Remote
public interface Calculator {
public Double multiply(Double multiplier, Double multiplicand);
public Double divide(Double dividend, Double divisor);
public Double add(Double addend, Double augend);
public Double subtract(Double minuend, Double subtrahend);
public void saveToMemory(Double number);
public Double retrieveFromMemory();
}
Bean:
package com.calc.ejb;
import javax.ejb.Remote;
import javax.ejb.Stateful;
/**
* Session Bean implementation class CalculatorBean
*/
#Stateful
#Remote(Calculator.class)
public class CalculatorBean implements Calculator{
/* Implementation */
}
Accessing it:
context = new InitialContext();
Calculator calculator = (Calculator) context.lookup("java:global/Zad3_s9120/CalculatorBean");
Do I have to do some steps to make interface available to session bean?
I'm adding it from Eclipse with "Add and Remove" server menu.
From what I can see, you have different packages.
You've defined interface as:
com.calc.ejb.Calculator
but your exception tells you about:
com.s9120.ejb.Calculator
Perhaps you don't have appropriate class in your client project?
BTW: You don't need to specify #Remote on both - the interface and EJB. You can do only #Remote(MyClass.class) on EJB or #Remote on interface.