Getting error when querying the audit table using haschanged - postgresql

I have Template entity which has:
#ManyToOne
#JsonView(JsonDefinitionMapper.SecondLevel.class)
#Audited
private TemplateType templateType;
instance.
When I am going to query the all the changes using loop through entity properties as below (properties are get by metadata of entity) :
for(String property:PropertiesList){
newValue = auditReader.createQuery()
.forRevisionsOfEntity(Template.class, false, true)
.addProjection(AuditEntity.property(property))
.add(AuditEntity.property(property).hasChanged())
.add(AuditEntity.id().eq(templateId))
.add(AuditEntity.revisionNumber().eq(revisionNumber)).getSingleResult();
}
the generated Template_AUD table has template_type_mod,template_type_id columns(Auto generated)
I am getting this error when running above query:
org.hibernate.QueryException: could not resolve property: templateType of: com.templates.domain.Template_AUD [select e__.templateType from com.templates.domain.Template_AUD e__, com.template.domain.AuditedRevisionEntity r where e__.templateType_MOD = :_p0 and e__.originalId.id = :_p1 and e__.originalId.REV.id = :_p2 and e__.originalId.REV.id = r.id]
at org.hibernate.QueryException.generateQueryException(QueryException.java:120)
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:218)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142)
at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:76)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:150)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:302)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:240)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1894)
at org.hibernate.envers.internal.tools.query.QueryBuilder.toQuery(QueryBuilder.java:226)
at org.hibernate.envers.query.internal.impl.AbstractAuditQuery.buildQuery(AbstractAuditQuery.java:79)
at org.hibernate.envers.query.internal.impl.AbstractAuditQuery.buildAndExecuteQuery(AbstractAuditQuery.java:85)
at org.hibernate.envers.query.internal.impl.RevisionsOfEntityQuery.list(RevisionsOfEntityQuery.java:108)
at org.hibernate.envers.query.internal.impl.AbstractAuditQuery.getSingleResult(AbstractAuditQuery.java:97)
at com.template.dataRepository.TemplateRevisionRepository.getAllChangedPropertiesWithREvisions(TemplateRevisionRepository.java:211)
at com.template.dataRepository.TemplateRevisionRepository$$FastClassBySpringCGLIB$$5bf5efd1.invoke()
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at com.template.dataRepository.TemplateRevisionRepository$$EnhancerBySpringCGLIB$$952a9450.getAllChangedPropertiesWithREvisions()
at com.template.EnversTest.getAllChangedPropertiesWithREvisions(EnversTest.java:151)
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:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
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:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
i am using postgres database

My initial idea was to leverage the new relation traversal API added in Envers 5.2 by which you would have written your query much like the following:
final List results = auditReader.createQuery()
.forEntitiesModifiedAtRevision( Template.class, revNo )
.traverseRelation( "templateType", JoinType.INNER )
.addProjection( AuditEntity.selectEntity( false ) )
.up()
.add( AuditEntity.property( "templateType" ).hasChanged() )
.getResultList();
The idea here is that we'd basically request that the TemplateType be returned in the resulting list but only if it was deemed modified on the root entity, Template; however, this query introduces what I believe is a bug:
org.hibernate.QueryException: Named parameter [revision] not set
This is because the subquery added to the root query specifies a named parameter revision; however, the query logic never binds the revision value; leading to this problem.
I've filed issue HHH-11981 to address this problem.
So for now, the only suggestion I have is if your entity class has anything beyond basic type properties, you'll likely need to resort to using reflection in your code to actually obtain the values from the returned bean
final List results = auditReader.createQuery()
.forEntitiesModifiedAtRevision( Template.class, revNo )
.add( AuditEntity.property( propertyName ).hasChanged() )
.getResultList();
For the entry in the list, you'd need to use reflection to call the appropriate getter for the appropriate property identified by propertyName. It is less than ideal but at least circumvents the query problems you're facing.

Related

Why my unit test is giving me an AssertionFailedError when I try to render another page

I am learning unit testing and trying to check if the login is valid on the HomePage and if so that the SuccessPage is rendered but it is giving me an AssertionFailedError
.java:
#Test
public void validLogin(){
tester.startPage(HomePage.class);
FormTester form = tester.newFormTester("userForm");
form.setValue("username", "emile");
form.setValue("password", "123");
form.submit();
//onsubmit the Successpage is rendered in response
tester.assertRenderedPage(SuccessPage.class);
}
the error:
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-768a67f4-8bf1-45d0-bdcb-3a9be18172e1] init: Wicket core library initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-768a67f4-8bf1-45d0-bdcb-3a9be18172e1] init: Wicket extensions initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-768a67f4-8bf1-45d0-bdcb-3a9be18172e1] init: Wicket jQuery UI initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-768a67f4-8bf1-45d0-bdcb-3a9be18172e1] init: Wicket jQuery UI initializer (theme-uilightness)
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
junit.framework.AssertionFailedError: classes not the same, expected 'class com.mycompany.SuccessPage', current 'class com.mycompany.HomePage'
at org.apache.wicket.util.tester.WicketTester.assertResult(WicketTester.java:798)
at org.apache.wicket.util.tester.WicketTester.assertRenderedPage(WicketTester.java:697)
at com.mycompany.TestHomePage.validLogin(TestHomePage.java:48)
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:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
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.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
I got the answer, so I didn't reference the form.submit(); to the onSubmit() function so I basically did this:
#Test
public void validLogin() throws Exception {
tester.startPage(HomePage.class);
// tester.startComponentInPage(HomePage.class);
FormTester form = tester.newFormTester("userForm");
form.setValue("username", "emile");
form.setValue("password", "123");
form.submit("error"); // new code that was edited
//onsubmit the Successpage is rendered in response
tester.assertRenderedPage(SuccessPage.class);
}
the form.submit("error"); now references to the wicket:id="error" and passed the test :D

java.lang.ClassCastException: java.util.HashMap cannot be cast to com.spacestudy.model.Investigator

I am trying to write test case for Repository method. In that Test case I want to test Investigator name using assertEquals(). Return type of method is set for that I use for each loop to retrieve result from set and then checked expected and actual result using assertEquals() but I am getting java.lang.ClassCastException: java.util.HashMap cannot be cast to com.spacestudy.model.Investigator
can any one please tell me what I am doing wrong in test case?
InvestigatorRepository
#Query("select new map(invest.sInvestigatorName as sInvestigatorName)"
+ " from Investigator invest")
Set<Investigator> findSinvestigatorName();
I tried Like this
#RunWith(SpringRunner.class)
#DataJpaTest
public class TestInvestigatorRepository {
#Autowired
public TestEntityManager testEm;
#Autowired
InvestigatorRepository investRepo;
#Test
public void testFindSinvestigatorName() {
Investigator invest = new Investigator();
invest.setsInvestigatorName("abc");
invest.setnInstId(60);
Investigator saveInDb = testEm.merge(invest);
Set<Investigator> getFromDb = investRepo.findSinvestigatorName();
for(Investigator result : getFromDb) {
assertEquals(saveInDb.getsInvestigatorName(),result.sInvestigatorName);
}
}
}
Stack Trace
java.lang.ClassCastException: java.util.HashMap cannot be cast to com.spacestudy.model.Investigator
at com.spacestudy.repository.TestInvestigatorRepository.testFindSinvestigatorName(TestInvestigatorRepository.java:39)
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:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
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:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
The HQL query you specify explicitly returns a Map, but the return type specified for the method specifies Set<Investigator> which are incompatible types, hence the error.
Spring Data tries to convert the types but fails and in the end, just tries to cast the result to the desired type.
In order to fix this you need to use compatible types options are:
let your query return Investigators.
let your query return a tuple by just listing the attributes: select invest.sInvestigatorName as sInvestigatorName from Investigator invest. Spring Data should be able to map that to an Investigator although your "interesting" property names might cause some troubles.
Since you are really just return a single attribute you might as well make the method return a Set<String> and use the query given in the previous point.

NoSuchMethodException with "select new" after upgrading to Spring Data JPA 1.10.3

I encountered an issue after upgrading our Spring Data JPA from 1.9.2 to 1.10.3.
I have the following repository:
public interface ShipmentStatisticRepository extends JpaRepository<Shipment, Long> {
...
#Query("select new de.l.b.model.dto.shipment.ShipmentStatistic(s.createdYmd, count(distinct s.oid), count(op), sum(op.price)) " +
"from Shipment s " +
"join s.orderPosition op " +
"where s.created between ?1 and ?2 " +
"group by s.createdYmd")
List<ShipmentStatistic> findPerDayBetweenCreated(Date from, Date to);
...
}
When I call this method I get the following Exception:
org.springframework.dao.InvalidDataAccessApiUsageException: Could not instantiate Collection type: org.apache.openjpa.kernel.DelegatingResultList; nested exception is java.lang.IllegalArgumentException: Could not instantiate Collection type: org.apache.openjpa.kernel.DelegatingResultList
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:384)
at org.springframework.orm.jpa.DefaultJpaDialect.translateExceptionIfPossible(DefaultJpaDialect.java:122)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:436)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy154.findPerDayBetweenCreated(Unknown Source)
at de.l.b.hazelcast.map.ShipmentStatisticPerDayMapLoader.getShipmentStatistic(ShipmentStatisticPerDayMapLoader.java:40)
at de.l.b.hazelcast.map.AbstractShipmentStatisticMapLoader.load(AbstractShipmentStatisticMapLoader.java:38)
at de.l.b.hazelcast.map.AbstractShipmentStatisticMapLoader.loadAll(AbstractShipmentStatisticMapLoader.java:48)
at com.hazelcast.map.impl.MapStoreWrapper.loadAll(MapStoreWrapper.java:143)
at com.hazelcast.map.impl.mapstore.AbstractMapDataStore.loadAll(AbstractMapDataStore.java:56)
at com.hazelcast.map.impl.mapstore.writebehind.WriteBehindStore.loadAll(WriteBehindStore.java:205)
at com.hazelcast.map.impl.recordstore.BasicRecordStoreLoader.loadAndGet(BasicRecordStoreLoader.java:170)
at com.hazelcast.map.impl.recordstore.BasicRecordStoreLoader.doBatchLoad(BasicRecordStoreLoader.java:143)
at com.hazelcast.map.impl.recordstore.BasicRecordStoreLoader.loadValuesInternal(BasicRecordStoreLoader.java:129)
at com.hazelcast.map.impl.recordstore.BasicRecordStoreLoader.access$100(BasicRecordStoreLoader.java:54)
at com.hazelcast.map.impl.recordstore.BasicRecordStoreLoader$GivenKeysLoaderTask.call(BasicRecordStoreLoader.java:112)
at com.hazelcast.util.executor.CompletableFutureTask.run(CompletableFutureTask.java:67)
at com.hazelcast.util.executor.CachedExecutorServiceDelegate$Worker.run(CachedExecutorServiceDelegate.java:212)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
at com.hazelcast.util.executor.HazelcastManagedThread.executeRun(HazelcastManagedThread.java:76)
at com.hazelcast.util.executor.HazelcastManagedThread.run(HazelcastManagedThread.java:92)
Caused by: java.lang.IllegalArgumentException: Could not instantiate Collection type: org.apache.openjpa.kernel.DelegatingResultList
at org.springframework.core.CollectionFactory.createCollection(CollectionFactory.java:208)
at org.springframework.core.CollectionFactory.createCollection(CollectionFactory.java:151)
at org.springframework.data.repository.query.ResultProcessor.processResult(ResultProcessor.java:146)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:119)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:104)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:482)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 25 more
Caused by: java.lang.InstantiationException: org.apache.openjpa.kernel.DelegatingResultList
at java.lang.Class.newInstance(Class.java:427)
at org.springframework.core.CollectionFactory.createCollection(CollectionFactory.java:204)
... 39 more
Caused by: java.lang.NoSuchMethodException: org.apache.openjpa.kernel.DelegatingResultList.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)
... 40 more
It looks like the repository can't resolve the correct constructor to fill my projection. With version 1.9.2 everything works fine.
This is my projection class:
public class ShipmentStatistic implements Serializable {
private Date date;
private long totalParcelsSent;
private long totalPositionsSent;
private long totalValue;
public ShipmentStatistic(Date date) {
this.date = date;
this.totalPositionsSent = 0;
this.totalParcelsSent = 0;
this.totalValue = 0;
}
public ShipmentStatistic(Date date, long totalParcelsSent, long totalPositionsSent, long totalValue) {
this.date = date;
this.totalPositionsSent = totalPositionsSent;
this.totalParcelsSent = totalParcelsSent;
this.totalValue = totalValue;
}
public ShipmentStatistic add(ShipmentStatistic other) {
this.totalPositionsSent += other.totalPositionsSent;
this.totalParcelsSent += other.totalParcelsSent;
this.totalValue += other.totalValue;
return this;
}
// getter and setter
}
I made a random shot and tried to add a default constructor but without success.
I can not see my error especially the only change a made was the framework update. We use OpenJPA 2.2.2 as Persistence API by the way. I upgraded to the current version 2.4.1 but this had no effect either.
Any suggestions? May this be a bug in Spring Data JPA in combination with OpenJPA?
From stacktrace, it looks like openjpa is searching for the default constructor. Could you try adding default constructor explicitly in ShipmentStatistic.java?
JPA specification mandates the use of default no-argument constructor.
http://openjpa.apache.org/builds/1.2.3/apache-openjpa/docs/jpa_overview_pc.html#jpa_overview_pc_no_arg

NullPointerException from Jboss LdapExtLoginModule

I am attempting to configure Ldap authentication for a Jboss web-app. Jboss loads my module, but does not authenticate credentials that are known to be good. I should point out that my module just extends LdapExtLoginModule without adding any logic. I get the same error when defering directly to LdapExtLoginModule. The error:
PBOX000070: Password invalid/Password required
is returned when I attempt to login. I tracked the error down to a null pointer being thrown by a hashtable.put() operation in org.jboss.security.auth.spi.LdapExtLoginModule.constructInitialLdapContext. Here is the stack trace:
javax.security.auth.login.FailedLoginException: PBOX000070: Password invalid/Password required
at org.jboss.security.auth.spi.UsernamePasswordLoginModule.login(UsernamePasswordLoginModule.java:284)
at com.alstom.auth.login.ldap.CustomLdapLoginModule.login(CustomLdapLoginModule.java:164)
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 javax.security.auth.login.LoginContext.invoke(LoginContext.java:762)
at javax.security.auth.login.LoginContext.access$000(LoginContext.java:203)
at javax.security.auth.login.LoginContext$4.run(LoginContext.java:690)
at javax.security.auth.login.LoginContext$4.run(LoginContext.java:688)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.login.LoginContext.invokePriv(LoginContext.java:687)
at javax.security.auth.login.LoginContext.login(LoginContext.java:595)
at org.springframework.security.authentication.jaas.AbstractJaasAuthenticationProvider.authenticate(AbstractJaasAuthenticationProvider.java:149)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
at com.etse.security.SecureMethodAuthenticationManager.authenticate(SecureMethodAuthenticationManager.java:29)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:195)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
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:745)
Caused by: java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:514)
at org.jboss.security.auth.spi.LdapExtLoginModule.constructInitialLdapContext(LdapExtLoginModule.java:742)
at org.jboss.security.auth.spi.LdapExtLoginModule.createLdapInitContext(LdapExtLoginModule.java:463)
at org.jboss.security.auth.spi.LdapExtLoginModule.validatePassword(LdapExtLoginModule.java:340)
at com.alstom.auth.login.ldap.CustomLdapLoginModule.validatePassword(CustomLdapLoginModule.java:152)
at org.jboss.security.auth.spi.UsernamePasswordLoginModule.login(UsernamePasswordLoginModule.java:281)
... 40 more
The function:
private InitialLdapContext constructInitialLdapContext(String dn, Object credential) throws NamingException
{
String protocol = (String)options.get(Context.SECURITY_PROTOCOL);
String providerURL = (String) options.get(Context.PROVIDER_URL);
if (providerURL == null)
providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");
Properties env = constructLdapContextEnvironment(providerURL, dn, credential);
return new InitialLdapContext(env, null);
}
No hashtable.put() operations there so it must come from the InitialLdapContext constructor right?
public InitialLdapContext(Hashtable<?,?> environment,Control[] connCtls) throws NamingException {
super(true); // don't initialize yet
// Clone environment since caller owns it.
Hashtable env = (environment == null)
? new Hashtable(11)
: (Hashtable)environment.clone();
// Put connect controls into environment. Copy them first since
// caller owns the array.
if (connCtls != null) {
Control[] copy = new Control[connCtls.length];
System.arraycopy(connCtls, 0, copy, 0, connCtls.length);
env.put(BIND_CONTROLS_PROPERTY, copy);
}
// set version to LDAPv3
env.put("java.naming.ldap.version", "3");
// Initialize with updated environment
init(env);
}
connCtls is null (see constructor call) so the only put operation is env.put("java.naming.ldap.version", "3") which is obviously fine.
Any idea what's going on here? Thanks.
HashTable does not allow keys to be null. Verify that none of the keys you put into Hashtable env is not null. For example, for
env.put(BIND_CONTROLS_PROPERTY, copy);
BIND_CONTROLS_PROPERTY must not be null.
Hope that helps
IMO, You have a code from another version of the LdapExtLoginModule. The correct one could be this one on GitHub.
The code there is:
private InitialLdapContext constructInitialLdapContext(String dn, Object credential) throws NamingException
{
Properties env = new Properties();
Iterator iter = options.entrySet().iterator();
while (iter.hasNext())
{
Entry entry = (Entry) iter.next();
env.put(entry.getKey(), entry.getValue()); /* this is the line 742 */
}
So there seems to be a login module option with null value. Try to check your configuration.
Please, share more details about your environment next time. It will help a lot to evaluate your problem. The most important details:
application server version
used server configuration (i.e. configuration of the security domain in this case)

I have to write JUnit test case for service layer which uses ListIterator and returns list

Problem:
I have service method which returns list of objects in reverse order.
It is fetching list of objects from MongoDB using MongoTemplate,Query and uses ListIterator for reversing the list.
Now, I have to write JUnit test case for the above.
My present code where I am Mocking mongotemplate
MongoTemplate mongoTemplate = Mockito.mock(MongoTemplate.class);
Query query = Mockito.mock(Query.class);
CRDetails crDetails = new CRDetails();
CertificateGuidelines certG1 = new CertificateGuidelines("certG1", Constants.CERTIFICATION_TEAM, Constants.DOC_DEVELOPER_STATUS, 1);
CertificateGuidelines certG2 = new CertificateGuidelines("certG2", Constants.DOCDEVELOPER, Constants.CERT_TEAM_STATUS, 2);
CertificateGuidelines certG3 = new CertificateGuidelines("certG3", Constants.CERTIFICATION_TEAM, Constants.DOC_DEVELOPER_STATUS, 3);
List<CertificateGuidelines> newHistoryList = new ArrayList<CertificateGuidelines>();
newHistoryList.add(certG1);
newHistoryList.add(certG2);
newHistoryList.add(certG3);
Mockito.when(mongoTemplate.findOne((org.springframework.data.mongodb.core.query.Query) Matchers.any(Query.class), Matchers.any(Class.class))).thenReturn(crDetails);
CRService service = new CRService();
service.setCertMongoTemplate(mongoTemplate);
assertEquals(historyList, newHistoryList);
My service method:
public List<CertificateGuidelines> getHistoryForCertGuidelines(String crNum) {
Query query = new Query(Criteria.where("cr").is(crNum));
CRDetails details = certMongoTemplate.findOne(query, CRDetails.class,
Constants.COLLECTION_NAME);
logger.debug("in history");
if (details != null) {
logger.debug("Certification Guidelines has " + details.getCertGuidelinesList().size() + "previous updates");
}
List<CertificateGuidelines> historyList = new ArrayList<CertificateGuidelines>();
// Add objects to list.
// Generate an iterator. Start just after the last CG object.
ListIterator<CertificateGuidelines> listItr = details.getCertGuidelinesList().listIterator(
details.getCertGuidelinesList().size());
// Iterate in reverse.
while (listItr.hasPrevious()) {
historyList.add((CertificateGuidelines) listItr.previous());
}
return historyList;
}
I know I am doing some mistake in writing test case. Not clear on how to approach. Please Guide.
Error Trace
java.lang.AssertionError: expected:<historyList> but was:<[com.cerner.docworks.domain.CertificateGuidelines#13805618, com.cerner.docworks.domain.CertificateGuidelines#56ef9176, com.cerner.docworks.domain.CertificateGuidelines#4566e5bd]>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:743)
at org.junit.Assert.assertEquals(Assert.java:118)
at org.junit.Assert.assertEquals(Assert.java:144)
at com.cerner.docworks.service.test.CRServiceTest.testServiceHistoryDB(CRServiceTest.java:113)
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.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.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
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.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:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Thanks in advance
I believe that you are testing the equality of two lists, when what you really want to do is check that the lists contain the same elements.
The easiest way to do this is to use Hamcrest, which has the added advantage that it will show a better message in the event of failure.
Assert.assertThat(historyList,IsIterableContainingOrder.contains(newHistoryList.toArray()));