Updating other objects on #PreUpdate with JPA and Play causes exceptions - java

I have a Play 1.2.7 project, and need to do the following.
When a particular Article is updated the lastUpdate field is automatically set to the current time. Now related articles need to have their lastUpdate field set to the same as the edited article.
The super class of Article has the following:
#PrePersist
protected void onCreate() {
addDate = new Date();
if(autoLastUpdate) {
lastUpdate = addDate;
}
}
#PreUpdate
protected void onUpdate() {
if(autoLastUpdate) {
lastUpdate = new Date();
}
}
So in the Article class itself I have:
#PreUpdate
protected void onUpdate() {
super.onUpdate();
try{
this.editedBy = Security.connectedUser();
} catch (NullPointerException npe){
this.editedBy = null;
}
// Update all lastUpdate on other languages, needed for new selection of articles server side using lastUpdate.
for (Article article : getAllLanguages()) {
if (!article.id.equals(this.id) && !article.lastUpdate.equals(this.lastUpdate)) {
article.refresh();
article.setLastUpdate(this.lastUpdate);
article.save();
}
}
}
But this causes an stack overflow, as when article.save() is called, then actually it seems this.save() is called, as the procedure is run again on the current object:
java.lang.RuntimeException has been caught, java.lang.StackOverflowError
or a PersistenceException on the Article.save():
javax.persistence.PersistenceException has been caught, org.hibernate.HibernateException: Found shared references to a collection: models.Article.accessGroups
And I do not understand why. I have spend a few hours on this, as it seems to me simple problem, but cannot figure it out.
Can I not do a save() on another object in the #PreUdate? What way could I otherwise do this automatically on any change on the Article object?
[EDIT:]
An important item which I forgot:
public List<Article> getAllLanguages(boolean includeRemoved){
if(includeRemoved){
return find("commonId = ? AND commonId != 0 AND site.app = ?", this.commonId, this.site.app).fetch();
} else {
return find("commonId = ? AND commonId != 0 AND site.app = ? AND removed = ?", this.commonId, this.site.app, false).fetch();
}
}
I also tried to do the following instead of the above:
#PostUpdate
protected void afterUpdate(){
// Update all lastUpdate on other languages, needed for new selection of articles server side using lastUpdate.
for (Article anArticle : getAllLanguages()) {
Logger.debug("Article " + anArticle.id + " time " + anArticle.lastUpdate + " from afterUpdate of " + this.id + " " + this.lastUpdate);
if (!anArticle.id.equals(this.id) && anArticle.lastUpdate.before(this.lastUpdate)) {
//anArticle.refresh();
anArticle.setLastUpdate(this.lastUpdate);
Logger.debug("Going to save article " + anArticle.id + " from afterUpdate on " + this.id);
anArticle.save();
}
}
}
But now I get an error on my test runner, and I do not know what causes it:
A java.lang.IndexOutOfBoundsException has been caught, Index: 1, Size: 0
In /test/models/ArticleTest.java, line 786 :article1.save();
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:345)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:962)
at play.db.jpa.JPABase._save(JPABase.java:41)
at play.db.jpa.GenericModel.save(GenericModel.java:204)
at models.Article.afterUpdate(Article.java:327)
at sun.reflect.GeneratedMethodAccessor571.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.hibernate.ejb.event.BeanCallback.invoke(BeanCallback.java:37)
at org.hibernate.ejb.event.EntityCallbackHandler.callback(EntityCallbackHandler.java:94)
at org.hibernate.ejb.event.EntityCallbackHandler.postUpdate(EntityCallbackHandler.java:83)
at org.hibernate.ejb.event.EJB3PostUpdateEventListener.handlePostUpdate(EJB3PostUpdateEventListener.java:70)
at org.hibernate.ejb.event.EJB3PostUpdateEventListener.onPostUpdate(EJB3PostUpdateEventListener.java:62)
at org.hibernate.action.EntityUpdateAction.postUpdate(EntityUpdateAction.java:199)
at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:177)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:345)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:962)
at play.db.jpa.JPABase._save(JPABase.java:41)
at play.db.jpa.GenericModel.save(GenericModel.java:204)
at models.ArticleTest.testOnLastUpdatePropagationToOtherLanguages(ArticleTest.java:786)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at play.test.PlayJUnitRunner$StartPlay$2$1.evaluate(PlayJUnitRunner.java:114)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at play.test.PlayJUnitRunner.run(PlayJUnitRunner.java:58)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:24)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at org.junit.runner.JUnitCore.run(JUnitCore.java:136)
at org.junit.runner.JUnitCore.run(JUnitCore.java:117)
at play.test.TestEngine.run(TestEngine.java:112)
at controllers.TestRunner.run(TestRunner.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at play.mvc.ActionInvoker.invokeWithContinuation(ActionInvoker.java:557)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:508)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:484)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:479)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:161)
at play.server.PlayHandler$NettyInvocation.execute(PlayHandler.java:251)
at play.Invoker$Invocation.run(Invoker.java:278)
at play.server.PlayHandler$NettyInvocation.run(PlayHandler.java:229)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:178)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:292)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745

Related

javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException:

How to pass and set the ID in BetRecordAgEBR? Please Help me:) Thanks in advance. This is my only problem that encounter. The BetRecordAgEBR class is for may database using jpa.
if ("GR".equals(dataType)) {
ByteArrayInputStream bis = new ByteArrayInputStream(
aw.getBytes());
StreamSource ss = new StreamSource(bis);
brElement = (JAXBElement<T>) jaxbUnmarshaller
.unmarshal(ss, BetRecordAgGR.class);
ret2 = brElement.getValue();
counter++;
if (counter > 100) {
return brList;
}
/*
*
* String uuid1 = java.util.UUID.randomUUID()
* .toString(); dataOpe.setEntityManager(em);
* ret2.setID(uuid1); dataOpe.add(ret2);
*/
brList.add((T) ret2);
System.out.println(brList);
}
The Exception:
javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): us.kirin.bc.BetRecordAgGR
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1316)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:881)
at us.kirin.bc.service.DataService.add(DataService.java:40)
at us.kirin.bc.service.AGServiceTest.BetHistoryAGIN(AGServiceTest.java:255)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
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: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): us.kirin.bc.BetRecordAgGR
at org.hibernate.id.Assigned.generate(Assigned.java:52)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
at org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:78)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:208)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:151)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:78)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:852)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:826)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:830)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:875)
... 26 more
I change ret2 to BetRecordAgGR ret2;
if ("GR".equals(dataType)) {
ByteArrayInputStream bis = new ByteArrayInputStream(
aw.getBytes());
StreamSource ss = new StreamSource(bis);
brElement = (JAXBElement<T>) jaxbUnmarshaller
.unmarshal(ss, BetRecordAgGR.class);
ret2= (BetRecordAgGR) brElement.getValue();
counter++;
if (counter > 100) {
return brList;
}
String uuid1 = java.util.UUID.randomUUID()
.toString();
ret2.setID(uuid1);
dataOpe.setEntityManager(em);
dataOpe.add(ret2);
brList.add((T) ret2);
System.out.println(brList);
}

Java weird NoClassDefFoundError

I keep getting a NoClassDefFoundError whenever I try to run this block of code
ClassTable.getInstance();
Here is the code for ClassTable
public class ClassTable
{
private static ClassTable classTable = new ClassTable();
private Map<String,Object> pricingTable;
private Date expiry;
private ClassTable()
{
this.expiry = this.getExpiry();
this.pricingTable = buildPricingTables();
}
private Date getExpiry()
{
return DateUtils.INSTANCE.getCutOff();
}
public static ClassTable getInstance()
{
return classTable;
}
}
I tried stepping into the method getInstance(); however, it throws the error instantly. Here is the stack trace
java.lang.NoClassDefFoundError: Could not initialize class helper.ClassTable
at models.SinglePaymentLoan.getPricingTable(SinglePaymentLoan.java:742)
at unit.SinglePaymentLoanTest.testPricingTable(SinglePaymentLoanTest.java:135)
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:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at play.test.PlayJUnitRunner$StartPlay$2$1.evaluate(PlayJUnitRunner.java:114)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:47)
at org.junit.rules.RunRules.evaluate(RunRules.java:18)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at play.test.PlayJUnitRunner.run(PlayJUnitRunner.java:58)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:24)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at org.junit.runner.JUnitCore.run(JUnitCore.java:136)
at org.junit.runner.JUnitCore.run(JUnitCore.java:117)
at play.test.TestEngine.run(TestEngine.java:112)
at controllers.TestRunner$1.doJobWithResult(TestRunner.java:71)
at controllers.TestRunner$1.doJobWithResult(TestRunner.java:1)
at play.jobs.Job.call(Job.java:146)
at play.jobs.Job$1.call(Job.java:66)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:206)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:695)
Note that it states that it cannot initialize the class. That indicates a problem with static initialization of the class.
You have one static variable classTable that attempts to create a new ClassTable instance.
private static ClassTable classTable = new ClassTable();
private Map<String,Object> pricingTable;
private Date expiry;
private ClassTable()
{
this.expiry = this.getExpiry();
this.pricingTable = buildPricingTables();
}
So now any error in creating a ClassTable instance will lead to a class initialization failure. You do 2 things in the constructor, each of which could fail.
You call getExpiry, which we see turns and calls DateUtils.INSTANCE.getCutOff(). You have not provided this code, so it is unclear what this does.
Finally, you call buildPricingTables(). Again, code has not been provided for this method.
So your 2 mostly likely culprits are DateUtils.INSTANCE.getCutOff() and buildPricingTables().

Dropwizard / Jersey returns 204 for a resource

I am trying to set up a test for a Resource:
#Override
protected void setUpResources() throws Exception {
when(ratingDao.getRating("karan")).thenReturn(rating);
addResource(new RatingResource(ratingDao));
}
#Test
public void testRatingsGetsTracks() throws Exception{
assertThat(client().resource("/ratings").queryParam("username", "karan").get(Rating.class)).isEqualTo(rating);
verify(ratingDao).getRating("karan");
}
However, I get a 204:
1 > GET /ratings?username=karan
1 >
23:18:24.705 [main] INFO c.s.j.a.c.filter.LoggingFilter - 1 * Server out-bound response
1 < 204
1 < Content-Type: application/json
1 <
23:18:24.708 [main] INFO c.s.j.t.f.s.c.i.InMemoryTestContainerFactory$InMemoryTestContainer - Stopping low level InMemory test container
com.sun.jersey.api.client.UniformInterfaceException: Client response status: 204
at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:540)
at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:517)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:684)
at com.sun.jersey.api.client.WebResource.get(WebResource.java:191)
at RatingResourceTest.testRatingsGetsTracks(RatingResourceTest.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:77)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:195)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
I have no idea why. I have tested that a Rating can be serialized into a json.
Here is the implementation of the resource:
#Path("/ratings")
#Produces(MediaType.APPLICATION_JSON)
public class RatingResource {
private RatingDAO ratingDao;
public RatingResource(RatingDAO ratingDao) {
this.ratingDao = ratingDao;
}
#GET
#Timed
public Rating getRating(#QueryParam("username") String username) {
return ratingDao.getRating(username);
}
}
#Override
protected void setUpResources() throws Exception {
when(ratingDao.getRating("karan")).thenReturn(rating);
addResource(new RatingResource(ratingDao));
}
For some reason, the ratingDao mock was not being set up. When I moved that line to the setUp method, this worked.

How to handle Bean Validation Exceptions

I have a class according to:
#Entity
public class Car {
#Id
#GeneratedValue
private Long id;
#NotNull
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "OWNER_ID")
private Owner owner;
#NotNull()
#Column(nullable = false)
private String make;
#NotNull()
#Column(nullable = true)
private String model;
#Column(nullable = false)
private String gears;
// More fields
Say I am trying to percist the object and one field, make field for instance, is null which is not supposed to be. Following exceptions is thrown:
WARNING: EJB5184:A system exception occurred during an invocation on EJB CarEJB, method: public se.while_se.domain.Car se.while_se.business.CarEJB.createCar(se.while_se.domain.Car)
Sep 09, 2012 12:37:37 PM com.sun.ejb.containers.BaseContainer postInvoke
WARNING:
javax.ejb.EJBException
at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5215)
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5113)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4901)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2045)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1994)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at $Proxy137.createCar(Unknown Source)
at se.while_se.business.__EJB31_Generated__CarEJB__Intf____Bean__.createCar(Unknown Source)
at test.CarTest.populate(CarTest.java:197)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:45)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.
What I would like to do is to find a best practice to validate the entity before persist it in the database. Sure, I could implement a help method inside the entity class something like:
public boolean validate() {
if(owner == null) {
return false;
}
if(make == null) {
return false;
}
if(model == null) {
return false;
}
return true;
}
But that does not feel as the right approach. Can you please guide me?
Best regards
You can and should validate the entity before persisting like this and return an appropriate error:
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Car>> constraintViolations = validator.validate(myCar);
if (constraintViolations.size() > 0) {
Set<String> violationMessages = new HashSet<String>();
for (ConstraintViolation<T> constraintViolation : constraintViolations) {
violationMessages.add(constraintViolation.getPropertyPath() + ": " + constraintViolation.getMessage());
}
throw new RuntimeException("Car is not valid:\n" + StringUtils.join(violationMessages, "\n"));
}

java.lang.AssertionError and both entities are the same? What could cause this?

I am getting the following error when testing my DAO using Assert.AssertEquals() method:
java.lang.AssertionError: expected: com.develop.test.data.entity.Rpoint<com.develop.test.data.entity.Rpoint#7668e5b5> but was: com.develop.test.data.entity.Rpoint<com.develop.test.data.entity.Rpoint#7668e5b5>
at org.junit.Assert.fail(Assert.java:91)
at org.junit.Assert.failNotEquals(Assert.java:645)
at org.junit.Assert.assertEquals(Assert.java:126)
at org.junit.Assert.assertEquals(Assert.java:145)
at com.develop.test.data.dao.RpointDAOTest.testFindById(RpointDAOTest.java:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
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.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:71)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:199)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Here's the snippet:
#Test
#Transactional(isolation = Isolation.SERIALIZABLE)
public void testFindById(){
Category newCategory = new Category("C", "Recognize a Co-Worker", true);
Rpoint newRPoint = new Rpoint.Builder()
.id(3)
.category(newCategory)
.description("Maximize Resources")
.points(50)
.active(true)
.build();
Assert.assertEquals(newRPoint, this.RpointDao.findById(3));
}
I've been using debug, and both entities have the same data. Could this be caused by the equals/HashCode implementation in the entity?
Edit: added equals and hashcode:
#Override
public boolean equals(Object instance) {
if (instance == null)
return false;
if (!(instance instanceof Rpoint))
return false;
Rpoint o = (Rpoint) instance;
return new EqualsBuilder().append(this.getId(), o.getId()).
append(this.getCategory(), o.getCategory()).
append(this.getDescription(), o.getDescription()).
append(this.getPoints(), o.getPoints()).
append(this.getActive(), o.getActive()).
isEquals();
}
#Override
public int hashCode() {
return new HashCodeBuilder(23, 25).append(this.getId()).
append(this.getCategory()).
append(this.getDescription()).
append(this.getPoints()).
append(this.getActive()).
toHashCode();
}
Yes, if equals is implemented badly so that it returns false even if you use the same reference, this would definitely cause the failure. Note that it's not just a case of the data within the object being the same, but the diagnostics suggest it's the same object on both sides:
expected [...].Rpoint<com.develop.test.data.entity.Rpoint#7668e5b5>
but was: [...].Rpoint<com.develop.test.data.entity.Rpoint#7668e5b5>
The 7668e5b5 shouldn't really be treated as object identity, but it's extremely suggestive here...
Please show the equals method you're using.

Categories

Resources