CORBA exception in EJB application - netbeans

I've got a problem with EJB/Glassfish. I'm working on a client-server application in which the client creates an entity object and must send it to the server application, which must persist the entity in its database. I've choose to use session beans to communicate with the server.
I've implemented some simple cases in which a method in the session bean takes as input a string or an int and it works fine. The problem arises when I try to give an entity object as input.
I report my entity class:
#Entity
public class Example implements Serializable {
private static final long serialVersionUID = 1L;
#Id
String nome;
public void setNome(String nome) {
this.nome = nome;
}
public String getNome() {
return nome;
}
Here my session bean:
#Stateless
public class GestoreLibreriaRemoto implements GestoreLibreriaRemotoRemote {
#Override
public String getProva(Example prova) {
return prova.getNome();
}
Here my client application:
public class GestoreLibreriaLocale {
public static void assegnaCategoriaACopia(CopiaUtente copia, Categoria categoria) throws
public void prova() {
GestoreLibreriaRemotoRemote gestore = lookupGestoreLibreriaRemotoRemote();
Example example = new Example();
prova.setNome("hodor");
System.out.println(gestore.getProva(example));
}
private GestoreLibreriaRemotoRemote lookupGestoreLibreriaRemotoRemote() {
try {
Context c = new InitialContext();
return (GestoreLibreriaRemotoRemote) c.lookup("java:global/ServerMDB/ServerMDB-ejb/GestoreLibreriaRemoto");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
In my main class I simply call GestoreLibreriaLocale.prova() and i get the following error:
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.glassfish.appclient.client.acc.AppClientContainer.launch(AppClientContainer.java:446)
at org.glassfish.appclient.client.AppClientFacade.main(AppClientFacade.java:166)
Caused by: javax.ejb.EJBException: java.rmi.MarshalException: CORBA MARSHAL 1330446346 Maybe; nested exception is:
org.omg.CORBA.MARSHAL: ----------BEGIN server-side stack trace----------
org.omg.CORBA.MARSHAL: AVVERTENZA: 00810010: Error from readValue on ValueHandler in CDRInputStream vmcid: OMG minor code: 10 completed: Maybe
at com.sun.proxy.$Proxy139.valuehandlerReadError(Unknown Source)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.readRMIIIOPValueType(CDRInputStream_1_0.java:912)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.read_value(CDRInputStream_1_0.java:1005)
at com.sun.corba.ee.impl.encoding.CDRInputObject.read_value(CDRInputObject.java:518)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl$14.read(DynamicMethodMarshallerImpl.java:383)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl.readArguments(DynamicMethodMarshallerImpl.java:450)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:171)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.sun.corba.ee.impl.io.IIOPInputStream
at com.sun.corba.ee.impl.io.ValueHandlerImpl.createInputStream(ValueHandlerImpl.java:820)
at com.sun.corba.ee.impl.io.ValueHandlerImpl.readValue(ValueHandlerImpl.java:263)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.readRMIIIOPValueType(CDRInputStream_1_0.java:903)
... 16 more
The error log continues, I don't report the whole log but if you need it I can post it.
Please help me, I'm working on it from days without resolving it.
Thanks for the attention,
Francesco

This seems to be a bug in the current Java versions (e.g. 1.7.0_55 and 1.8.0_05), have a look at this issue: GLASSFISH-21047
To make it work, install either an older or a newer Java version (e.g. 1.7.0_051 or 1.8.0_020).
See also:
Exception inside CORBA when accessing a remote bean

Related

Sling ResourceResolverFactory inside #Activate throws RunTimeException

I am new to AEM OSGI , any help would be appreciated
I have a class which contains #Activate annotated activate method inside which i am resolving and building up resources
#Component
#Service(MyTest.class)
public class MyTest {
private static final Logger LOG = LoggerFactory.getLogger(MyTest.class);
...
...
#Reference
private ResourceResolverFactory resolverFactory;
#Activate
protected void activate() {
final ResourceResolver resolver;
try {
resolver = resolverFactory.getAdministrativeResourceResolver(null);
} catch (LoginException e) {
LOG.error("error resolving resource resolver", e);
return;
}
I have a servlet that invokes this class and on the servlet i am using
#Reference
MyTest test;
#Override
protected void doPost
....
Here is the error i am getting
java.lang.RuntimeException: Unable to invoke method 'activate' for class com.demo.MyTest
java.lang.RuntimeException: Unable to invoke method 'activate' for class com.demo.MyTest at org.apache.sling.testing.mock.osgi.OsgiServiceUtil.invokeMethod(OsgiServiceUtil.java:263)
at org.apache.sling.testing.mock.osgi.OsgiServiceUtil.activateDeactivate(OsgiServiceUtil.java:101)
at org.apache.sling.testing.mock.osgi.MockOsgi.activate(MockOsgi.java:211)
at org.apache.sling.testing.mock.osgi.MockOsgi.activate(MockOsgi.java:222)
at org.apache.sling.testing.mock.osgi.context.OsgiContextImpl.registerInjectActivateService(OsgiContextImpl.java:155)
at org.apache.sling.testing.mock.osgi.context.OsgiContextImpl.registerInjectActivateService(OsgiContextImpl.java:142)
at com.Demo.MyDemoTest(MyDemoTest.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.NullPointerException
at com.Demo.MyTest.activate(MyTest.java:75)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.sling.testing.mock.osgi.OsgiServiceUtil.invokeMethod(OsgiServiceUtil.java:254)
... 33 more
Please help me understand where i am making the mistake
Also if i move the resolver factory definition to a public method inside that same class its working perfectly
Reason for the NullPointerException
Although not explicitly mentioned in the question the provided stacktrace reveals that the service is "run" within a unit test.
Furthermore, the stack trace reveals, that the OsgiContext is used, which does not provide an implementation of the ResourceResolverFactory.
Since no ResourceResolverFactory is registered within the mock OSGi context, the #Reference can not be injected upon service registration and activation. When the ResourceResolverFactory is then called in the activate method the reference is null and therefore the NullPointerExceptionis thrown.
Proposed Solution
Therefore, I would advise to use the excellent AemContext which is provided by the wcm.io aem-mock framework or at least the SlingContext provided by sling-mocks.
The unit test would look like this:
public class MyUnitTest {
#Rule
public AemContext context;
#Test
public void someTest() {
MyTest service = context.registerInjectActivateService(new MyTest());
[... additional test code ...]
}
}
Since the AemContext already has a functional ResourceResolverFactory (mock) registered, the unit test code does not have to create a mock and register it. When the registerInjectActivateService() method is called a new instance of the MyTest class is instantiated and the referenced ResourceResolverFactory is injected.
Additional Note
Please do not create service-wide ResourceResolvers. This is a bad practice. ResourceResolver should be short-lived. That means that they are only used for a few "operations" (like reading a resource) and then discarded.
The best way to do this is to use the try-with-resource statement like this:
public class MyTest {
private static final SERVICE_NAME = "MyTestService";
private static final Map<String, Object> authenticationInfo = Collections.singletonMap(ResourceResolverFactory.SUBSERVICE, SERVICE_NAME);
#Reference
private ResourceResolverFactory resourceResolverFactory;
public void someMethod() {
try (ResourceResolver resolver = getResourceResolver()) {
[... use resolver to do stuff in JCR ...]
}
}
private ResourceResolver getResourceResolver() {
try {
return resourceResolverFactory.getServiceResourceResolver(authenticationInfo);
} catch (LoginException cause) {
throw new IllegalStateException("Unable to obtain ResourceResolver!", cause)
}
}
}
I chose to create a separate method to create the ResourceResolver to avoid cluttering someMethod() with exception handling. But that is obviously something that can be changed.
Since administrative ResourceResolver are deprecated I also chose to use a service ResourceResolver. To use those you need to create a service user mapping. You can find out more about this in the documentation.
Please note that creating the resolver inside of Acivate method is anti-pattern. Your service might be called by multiple threads in parallel, and that these calls can be processed in parallel.
When we do write or read a resource then JCR session apply internal lock, which prevents multiple sessions to work in parallel on the very same session.
The best way to avoid this issue is to create resolver inside a method which you override.
#Override
performSomeOperation(){
final ResourceResolver resolver;
try {
resolver = resolverFactory.getAdministrativeResourceResolver(null);
} catch (LoginException e) {
LOG.error("error resolving resource resolver", e);
return;
}
}

Find and delete an item from a collection

I have the following problem with a method of JPA.
I can not delete an item from a collection.
Actually, the method only works if it is not the last element inserted.
Where I'm wrong?
This is the class of my model:
#Entity
public class JobOffer {
#SequenceGenerator(name="JobOffer_Gen", sequenceName="JobOffer_Seq", initialValue=1, allocationSize=1)
#Id #GeneratedValue(generator="JobOffer_Gen") #Column(name="ID_JOBOFFER")
private Long id;
#Column
private String title;
...
#OneToMany
#JoinTable(joinColumns = #JoinColumn(name = "JOBOFFER_IDFK"), inverseJoinColumns = #JoinColumn(name = "LANGUAGE_IDFK"))
private Collection<Language> languages = new HashSet<Language>();
...
}
This is my method in JPA:
#Override
#Transactional
public void deleteLanguage(JobOffer joboffer, Long idLingua) throws BusinessException {
for(Language l : joboffer.getLanguages()){
if (l.getId() == idLingua){
joboffer.getLanguages().remove(l);
}
}
em.merge(joboffer);
}
What is the correct way to search for an item in a collection and delete in JPA?
This is the error that I get from the console:
21-ott-2013 18.22.27 org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [jobbook] in context with path [/jobbook] threw exception [Request processing failed; nested exception is java.util.ConcurrentModificationException] with root cause
java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at org.eclipse.persistence.indirection.IndirectList$1.next(IndirectList.java:571)
at it.univaq.mwt.j2ee.jobbook.business.impl.JPAJobOfferService.deleteLanguage(JPAJobOfferService.java:95)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
and then continues
You may try something like this:
#Override
#Transactional
public void deleteLanguage(JobOffer joboffer, Long idLingua) throws BusinessException {
Language language = em.createQuery("SELECT lang from Language lang where lang.jobOffer.id = :job_id", Language.class).setParameter("job_id", joboffer.getId()).getSingleResult();
if(language != null){
joboffer.getLanguages().remove(language);
}
}
Please note:
this is not tested
I assumed that your "Language" Entity has a reference to your JobOffer Entity. Although I do not know your domain, this may indicate a bad design
If the parameter joboffer is in detached state, then you have to reattach it to the current session (using em.merge()).
Edit: Adapted Query in response to the comment of DataNucleus.

CommunicationException- failed to unmarshel Remote business interface looking up ejb3 in weblogic

My ejb 3 classes and remote interface are as follows :
package com.myeclipse.ejb3;
import java.io.Serializable;
public interface IMyBean extends Serializable
{
public void doSomething();
}
Remote interface:
package com.myeclipse.ejb3;
import javax.ejb.Remote;
#Remote
public interface MyBeanRemote extends IMyBean {
}
Stateless ejb:
package com.myeclipse.ejb3;
import javax.ejb.Stateless;
#Stateless(mappedName="ejb/MyBean")
public class MyBean implements MyBeanRemote
{
public void doSomething()
{
System.out.println("Hello world");
}
}
Project is successully deployed as a jar file in weblogic. I developed
a standalone client to call ejb. But this is failing. Kindly help.
I've included all the weblogic server libraries to connect to jndi and
remote business interface for complilation.
Client Code :
package Ejb3_Client;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class MyBeanClient {
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
try {
Properties p = new Properties();
p.put("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory");
p.put("java.naming.provider.url", "t3://172.21.123.70:8001");
InitialContext ctx = new InitialContext(p);
MyBeanRemote bean = (MyBeanRemote) ctx.lookup("ejb/MyBean#com.myeclipse.ejb3.MyBeanRemote");
System.out.println("bean instance "+ bean);
bean.doSomething();
System.out.println("bean worked");
} catch (NamingException e) {
e.printStackTrace();
}
}
}
But I am getting this exception:
javax.naming.CommunicationException [Root exception is
java.rmi.UnmarshalException: failed to unmarshal class
java.lang.Object; nested exception is:
java.lang.ClassNotFoundException: com.myeclipse.ejb3.MyBeanRemote]
at
weblogic.jndi.internal.ExceptionTranslator.toNamingException(ExceptionTranslator.java:74)
at
weblogic.jndi.internal.WLContextImpl.translateException(WLContextImpl.java:439)
at
weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:395)
at
weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:380)
at javax.naming.InitialContext.lookup(InitialContext.java:392) at
Ejb3_Client.MyBeanClient.main(MyBeanClient.java:33) Caused by:
java.rmi.UnmarshalException: failed to unmarshal class
java.lang.Object; nested exception is:
java.lang.ClassNotFoundException: com.myeclipse.ejb3.MyBeanRemote at
weblogic.rjvm.ResponseImpl.unmarshalReturn(ResponseImpl.java:244) at
weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:348)
at
weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:259)
at weblogic.jndi.internal.ServerNamingNode_1030_WLStub.lookup(Unknown
Source) at
weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:392)
... 3 more Caused by: java.lang.ClassNotFoundException:
com.myeclipse.ejb3.MyBeanRemote at
java.net.URLClassLoader$1.run(URLClassLoader.java:200) at
java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader.findClass(URLClassLoader.java:188) at
java.lang.ClassLoader.loadClass(ClassLoader.java:307) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at
java.lang.ClassLoader.loadClass(ClassLoader.java:252) at
weblogic.ejb.container.internal.RemoteBusinessIntfProxy.readObject(RemoteBusinessIntfProxy.java:200)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597) at
java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974)
at
java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1849)
at
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at
java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
at
java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871)
at
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at
weblogic.utils.io.ChunkedObjectInputStream.readObject(ChunkedObjectInputStream.java:197)
at
weblogic.rjvm.MsgAbbrevInputStream.readObject(MsgAbbrevInputStream.java:564)
at
weblogic.utils.io.ChunkedObjectInputStream.readObject(ChunkedObjectInputStream.java:193)
at weblogic.rmi.internal.ObjectIO.readObject(ObjectIO.java:62) at
weblogic.rjvm.ResponseImpl.unmarshalReturn(ResponseImpl.java:240) ...
7 more
I searched a lot but din find the problem why it can't unmarshel remote interface.
the reason for above error mainly because in some java file which implements Serializable interface has been changed you can revert those files to previous version

Restlet Client doesnt communicate well with Jersey Service

I want to realise a restlet client for my jersey service. I know that the service works, because I already developed a jersey client for it. But it seems like jersey and rest get problems to communicate with each other.
Jersey Service
Ressource:
#Path("/object")
#RolesAllowed({"admin", "user"})
public class ObjectResourceBean implements ObjectResourceIF {
#POST
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response postObject(JAXBElement<ObjectDTO> object) {
ObjectDTO c = object.getValue();
String generatedId = generateID();
c.setObjectId(generatedId);
c.setOwner(sec.getUserPrincipal().getName());
return postAndGetResponse(c);
}
private Response postAndGetResponse(ObjectDTO object) {
Response res;
res = Response.created(UriBuilder.fromUri(uriInfo.getAbsolutePath() + "/" + object.getObjectId()).build()).entity(object).build();
ObjectDAO.instance.getObjectDao().put(object.getObjectId(), object);
System.out.println("Response: " + res);
}
return res;
}
Restlet Wrap Interface:
#Path("/object")
#RolesAllowed({"admin", "user"})
public interface ObjectResourceIF {
#Post
public Response postObject(JAXBElement<ObjectDTO> object);
}
Already here I can't work with Jersey Annotations like #POST. I have to use #Post from Restlet Framework. But thats not the real problem.
Restlet Client
ClientResource service = new ClientResource("http://localhost:8080/com-project-core/rest");
service.setChallengeResponse(ChallengeScheme.HTTP_BASIC, "admin", "xxx");
service.getReference().addSegment("object");
// *create object*
JAXBElement<ObjectDTO> object = new JAXBElement<ObjectDTO>(new QName("object"), ObjectDTO.class, objectOne);
ObjectResourceIF objectResource = service.wrap(ObjectResourceIF.class);
List<Preference<MediaType>> acceptedMediaTypes = new ArrayList<Preference<MediaType>>();
acceptedMediaTypes.add(new Preference(MediaType.APPLICATION_JSON));
service.getClientInfo().setAcceptedMediaTypes(acceptedMediaTypes);
Response res = objectResource.postObject(object);
I just get a Internal Server Error (500).
Internal Server Error (500) - The server encountered an unexpected condition which prevented it from fulfilling the request
at org.restlet.resource.UniformResource.toObject(UniformResource.java:649)
at org.restlet.resource.ClientResource$1.invoke(ClientResource.java:1669)
at $Proxy12.postObject(Unknown Source)
at com.project.restlet.RestletConnectedTest.postObject(RestletConnectedTest.java:108)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: com.thoughtworks.xstream.mapper.CannotResolveClassException: objectId : objectId
at com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:68)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.DynamicProxyMapper.realClass(DynamicProxyMapper.java:71)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.PackageAliasingMapper.realClass(PackageAliasingMapper.java:88)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.ClassAliasingMapper.realClass(ClassAliasingMapper.java:86)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.ArrayMapper.realClass(ArrayMapper.java:96)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.CachingMapper.realClass(CachingMapper.java:52)
at com.thoughtworks.xstream.core.util.HierarchicalStreams.readClassType(HierarchicalStreams.java:29)
at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:136)
at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:33)
at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:923)
at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:909)
at com.thoughtworks.xstream.XStream.fromXML(XStream.java:861)
at org.restlet.ext.xstream.XstreamRepresentation.getObject(XstreamRepresentation.java:166)
at org.restlet.ext.xstream.XstreamConverter.toObject(XstreamConverter.java:200)
at org.restlet.service.ConverterService.toObject(ConverterService.java:161)
at org.restlet.resource.UniformResource.toObject(UniformResource.java:647)
... 27 more
On Server Side the request gets done to
return res;
When I try it without wrapping the Interface with
service.post(object, MediaType.APPLICATION_JSON).write(System.out);
it works!
As I said, the Jersey Client works as well.
Maybe the transfered Class ObjectDTO is useful for the solution:
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class ObjectDTO implements Serializable{
/**
*
*/
private static final long serialVersionUID = -8545841080597549468L;
#XmlElement(name="objectId")
private String objectId;
#XmlElement(name="owner")
private String owner;
#XmlElement(name="objectName")
private String objectName;
public ObjectDTO() {
}
public ObjectDTO(String objectName) {
this.objectName = objectName;
}
public String getObjectId() {
return objectId;
}
public void setObjectId(String objectId) {
this.objectId = objectId;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
}
I tried it without serializable as well. Also without #XmlElement and #XmlAccessorType(XmlAccessType.FIELD). As well I tried it with
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
annotation at the interface.
We had the same Problem with a Jersey server and Restlet client, but with a get Request.
With a Restlet client to Restlet server communication we hat no problems. So the only difference we could see was, that Restlet server implementation wraps the full qualified class name of the marshalled POJO as a JSON Object around the JSON Object which contains the POJOs payload.
package com.xyz;
public class ExamplePojo implements Serializable{
private static final long serialVersionUID = 1L;
private String var;
public ExamplePojo(){
}
//...
}
Resulting json string on Restlet server:
{"com.xyz.ExamplePojo":{"var":"10:23:53 30.10.2012"}}
but Jersey server in its default implementation if producing MediaType.APPLICATION_JSON doesn't. Resulting json string on Jersey server:
{"var":"10:23:53 30.10.2012"}
The problem was, that if we attempt communication with the Jersey server via a Restlet client, we got the same error like in your stacktrace with the root cause:
Caused by: com.thoughtworks.xstream.mapper.CannotResolveClassException: var : var
The soulution in our case was, that we explicitly had to define the JacksonConverter if using a Restlet client with a Jersey server implementation.
So we put the libraries from the Restlet zip on our build path of the client project
org.restlet.ext.jackson.jar
org.codehaus.jackson.core.jar
org.codehaus.jackson.mapper.jar
(interface of the resource)
public interface PojoResource {
#Get("json")
public ExamplePojo retrieve();
}
and then we add explicit the JacksonConverter to the registered converters
public ExamplePojo doRequest(){
ClientResource cr = new ClientResource( url );
// this is essential for Restlet-Jersey marshalling
Engine.getInstance().getRegisteredConverters().add( 0, new JacksonConverter() );
PojoResource resource = cr.wrap( PojoResource.class );
return resource.retrieve();
}
and everything worked fine.
Note that an explicit call to
Engine.getInstance().getRegisteredConverters().add( 0, new JacksonConverter() );
on a Reslet-Client to Restlet-Server communication did not work, but led to an
org.codehaus.jackson.map.JsonMappingException
because of the wrapping JSON Object 'com.xyz.ExamplePojo' as an unrecognized field, which must be marked as ignoreable.
So in your case it seems that Restlet doesn't find a converter for the unmarshalling either, so try to specify an explicit one.

Morphia-MongoDB - "Please override this method for user marked Id field entity"

I am following a tutorial mention on code.google, but my example fails giving the following trace :
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at com.google.code.morphia.mapping.MappedClass.callLifecycleMethods(MappedClass.java:323)
at com.google.code.morphia.mapping.Mapper.toDBObject(Mapper.java:371)
at com.google.code.morphia.DatastoreImpl.entityToDBObj(DatastoreImpl.java:674)
at com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:722)
at com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:802)
at com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:796)
at models.com.vlist.activity.classes.TestMongoData.testUserData(TestMongoData.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.code.morphia.mapping.MappedClass.callLifecycleMethods(MappedClass.java:304)
... 28 more
Caused by: java.lang.UnsupportedOperationException: Please override this method for user marked Id field entity: models.com.vlist.activity.classes.User
at play.modules.morphia.Model.setId_(Model.java:284)
at play.modules.morphia.Model.generateId_(Model.java:299)
... 33 more
My example is as following:
import javax.persistence.Entity;
import org.bson.types.ObjectId;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.annotations.Id;
import play.modules.morphia.Model;
#Entity
public class User extends Model {
#Id ObjectId id;
private String firstName;
private String lastName;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName(){
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
}
and
import static org.junit.Assert.*;
import org.junit.Test;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
public class TestMongoData {
#Test
public void testUserData() {
User user = new User();
user.setFirstName("first");
user.setLastName("last");
Morphia morphia = new Morphia();
Datastore ds = morphia.createDatastore("testData");
ds.save(user);
}
}
What could be wrong?
Update:
When I use play test, i see the following:
08:01:55,783 ERROR ~
#66h1bm10d
Internal Server Error (500) for request GET /#tests
Compilation error (In {module:morphia}/app/morphia/Filter.java around line 8)
The file {module:morphia}/app/morphia/Filter.java could not be compiled. Error raised is : The type Filter is already defined
play.exceptions.CompilationException: The type Filter is already defined
at play.classloading.ApplicationCompiler$2.acceptResult(ApplicationCompiler.java:246)
at org.eclipse.jdt.internal.compiler.Compiler.handleInternalException(Compiler.java:672)
at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:516)
at play.classloading.ApplicationCompiler.compile(ApplicationCompiler.java:278)
at play.classloading.ApplicationClassloader.getAllClasses(ApplicationClassloader.java:406)
at play.Play.start(Play.java:453)
at play.Play.detectChanges(Play.java:574)
at play.Invoker$Invocation.init(Invoker.java:186)
at Invocation.HTTP Request(Play!)
The problem comes from your #Entity definition. You're using JPA annotation while you should use the Morphia ones.
On startup, the Morphia plugin will retrieve all classes marked with the morphia Entity annotation and enhance them with various injected model methods. You're receiving this exception because your model class hasn't been enhanced.
If you annotate #Id then play morphia won't enhance your model by providing right implementation for void setId_(Object id) method. Try defining one yourself like this.
#Entity
class User extends Model {
#Id String email;
protected void setId_(Object id) {
}
}
Try removing the #Id ObjectId id; from your model. The Morphia Module for Play Framework will add the id for you.
Then make the fields public and remove the getter/setter methods.
public String firstName;
public String lastName;
Also, your Entity import is incorrect. Try this
import com.google.code.morphia.annotations.Entity;
Try this for a test case:
import static org.junit.Assert.*;
import org.junit.Test;
import play.test.UnitTest;
public class TestMongoData extends UnitTest {
#Test
public void testUserData() {
User user = new User();
user.setFirstName("first");
user.setLastName("last");
user.save();
}
}
It's seems that you have defined the morphia module in the dependency file and in the application conf file.
In the dependencies file : - play -> morphia [1.2.1beta6,)
In the application conf file : module.morphia=${play.path}/modules/morphia
You must removed one of this declaration otherwise the morphia module is loaded twice ...