SCP Plugin configuration using Groovy script - plugins

I am facing issues when configuring the Jenkins SCP plugin using Groovy scripts. I tried several approaches, but I did not succeed to add SCP site entries to the Jenkins configuration.
I tried the following:
import be.certipost.hudson.plugin.*
import jenkins.model.*
import hudson.model.*
import hudson.utils.*
import hudson.util.CopyOnWriteList
import org.kohsuke.stapler.StaplerRequest
import org.kohsuke.stapler.QueryParameter;
// Get the Jenkins instance.
def instance = Jenkins.getInstance()
// Get the Git plugin descriptor.
pluginURL = "be.certipost.hudson.plugin.SCPRepositoryPublisher"
def desc = instance.getDescriptor(pluginURL)
// Create a new SCPSite.
scpsite = new SCPSite('hostname', '22', 'username', 'password', 'rootRepositoryPath')
// Store it to an arraylist.
ArrayList<SCPSite> siteList = new ArrayList<SCPSite>();
siteList.add(scpsite)
// Also try to store it in a CopyOnWriteList.
lossitios = new CopyOnWriteList<SCPSite>()
lossitios.add(scpsite)
Each approach fails with an exception, either the replaceBy() method is not accessible, either I get an UnsupportedOperationException.
// Update the configuration (both approaches fail)
//desc.sites.replaceBy(siteList)
desc.sites.replaceBy(lossitios)
desc.save()
I also tried by using an approach I found here (https://github.com/jenkinsci/slack-plugin/issues/23):
scp = instance.getExtensionList(
be.certipost.hudson.plugin.SCPRepositoryPublisher.DescriptorImpl.class
)[0]
def params = [
hostname = "hostname",
port = 22,
username = "username",
password = "password",
rootRepositoryPath = "rootRepositoryPath",
]
def req = [
getParameter: { name -> params[name] }
] as org.kohsuke.stapler.StaplerRequest
desc.configure(req, null)
desc.save()
EDIT
The exception I get when I use the replaceBy() method is:
groovy.lang.MissingMethodException: No signature of method: [Lbe.certipost.hudson.plugin.SCPSite;.replaceBy() is applicable for argument types: (java.util.ArrayList) values: [[be.certipost.hudson.plugin.SCPSite#44605afb]]
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:55)
at org.codehaus.groovy.runtime.callsite.PojoMetaClassSite.call(PojoMetaClassSite.java:46)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at Script1.run(Script1.groovy:36)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:580)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:618)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:589)
at hudson.util.RemotingDiagnostics$Script.call(RemotingDiagnostics.java:142)
at hudson.util.RemotingDiagnostics$Script.call(RemotingDiagnostics.java:114)
at hudson.remoting.LocalChannel.call(LocalChannel.java:45)
at hudson.util.RemotingDiagnostics.executeGroovy(RemotingDiagnostics.java:111)
at jenkins.model.Jenkins._doScript(Jenkins.java:3566)
at jenkins.model.Jenkins.doScript(Jenkins.java:3538)
at sun.reflect.GeneratedMethodAccessor275.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:298)
at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:161)
at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:96)
at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:121)
at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:53)
at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)
at org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)
at org.kohsuke.stapler.Stapler.invoke(Stapler.java:649)
at org.kohsuke.stapler.Stapler.service(Stapler.java:238)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:686)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1494)
at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:132)
at hudson.plugins.greenballs.GreenBallFilter.doFilter(GreenBallFilter.java:59)
at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:129)
at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:200)
at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:178)
at net.bull.javamelody.PluginMonitoringFilter.doFilter(PluginMonitoringFilter.java:85)
at org.jvnet.hudson.plugins.monitoring.HudsonMonitoringFilter.doFilter(HudsonMonitoringFilter.java:99)
at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:129)
at hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:123)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:49)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84)
at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:76)
at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:171)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:49)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:81)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at org.kohsuke.stapler.DiagnosticThreadNameFilter.doFilter(DiagnosticThreadNameFilter.java:30)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1474)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:499)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:533)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:428)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:370)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:489)
at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:960)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:1021)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:865)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:240)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:668)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
at winstone.BoundedExecutorService$1.run(BoundedExecutorService.java:77)
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)
The exception I get when using the desc.configure() approach is:
java.lang.UnsupportedOperationException
at org.codehaus.groovy.runtime.ConvertedMap.invokeCustom(ConvertedMap.java:49)
at org.codehaus.groovy.runtime.ConversionHandler.invoke(ConversionHandler.java:82)
at com.sun.proxy.$Proxy59.bindParametersToList(Unknown Source)
at be.certipost.hudson.plugin.SCPRepositoryPublisher$DescriptorImpl.configure(SCPRepositoryPublisher.java:298)
at be.certipost.hudson.plugin.SCPRepositoryPublisher$DescriptorImpl$configure.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
at Script1.run(Script1.groovy:53)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:580)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:618)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:589)
at hudson.util.RemotingDiagnostics$Script.call(RemotingDiagnostics.java:142)
at hudson.util.RemotingDiagnostics$Script.call(RemotingDiagnostics.java:114)
at hudson.remoting.LocalChannel.call(LocalChannel.java:45)
at hudson.util.RemotingDiagnostics.executeGroovy(RemotingDiagnostics.java:111)
at jenkins.model.Jenkins._doScript(Jenkins.java:3566)
at jenkins.model.Jenkins.doScript(Jenkins.java:3538)
at sun.reflect.GeneratedMethodAccessor275.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:298)
at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:161)
at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:96)
at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:121)
at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:53)
at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)
at org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)
at org.kohsuke.stapler.Stapler.invoke(Stapler.java:649)
at org.kohsuke.stapler.Stapler.service(Stapler.java:238)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:686)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1494)
at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:132)
at hudson.plugins.greenballs.GreenBallFilter.doFilter(GreenBallFilter.java:59)
at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:129)
at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:200)
at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:178)
at net.bull.javamelody.PluginMonitoringFilter.doFilter(PluginMonitoringFilter.java:85)
at org.jvnet.hudson.plugins.monitoring.HudsonMonitoringFilter.doFilter(HudsonMonitoringFilter.java:99)
at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:129)
at hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:123)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:49)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84)
at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:76)
at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:171)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:49)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:81)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at org.kohsuke.stapler.DiagnosticThreadNameFilter.doFilter(DiagnosticThreadNameFilter.java:30)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1474)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:499)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:533)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:428)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:370)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:489)
at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:960)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:1021)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:865)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:240)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:668)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
at winstone.BoundedExecutorService$1.run(BoundedExecutorService.java:77)
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)
Where Script1.run(Script1.groovy:53) is my call to desc.configure(req, null).

Recently had to solve this, the problem is in the request you are creating. If you look at the source code for he plugin at https://github.com/jenkinsci/scp-plugin/blob/7ce951d1a3861c6837d71f87cbb553feb7b6c222/src/main/java/be/certipost/hudson/plugin/SCPRepositoryPublisher.java#L318
#Override
public boolean configure(StaplerRequest req, JSONObject formData) {
sites.replaceBy(req.bindJSONToList(SCPSite.class,
formData.get("sites")));
save();
return true;
}
The call on the StaplerRequest object that you need to provide is the bindJSONToList, and secondly you also need to provide a JSONObject that can have '.get("sites")' called on it.
Following code solves both of these (probably some improvements possible since I just threw this together to get past the same issue):
import be.certipost.hudson.plugin.*;
import org.kohsuke.stapler.StaplerRequest;
import net.sf.json.JSONObject;
def instance = Jenkins.getInstance()
pluginURL = "be.certipost.hudson.plugin.SCPRepositoryPublisher"
def desc = instance.getDescriptor(pluginURL)
params = [
sites: [
// one site per line as an array of options
// displayname, hostname, port, username, password, keyfile, path
["site-name", "hostname", "22", "username", "password", null, "/root/path"]
]
]
scp_sites = params['sites'].collect { it -> it as SCPSite }
// notice the only call we are providing as for the the request
// object is bindJSONToList, and we don't care about the
// original arguments since just returning predefined data
def req = [
bindJSONToList: { klazz, data -> scp_sites }
] as org.kohsuke.stapler.StaplerRequest
desc.configure(req, params as JSONObject)
desc.save()

Related

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.

Getting error when querying the audit table using haschanged

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.

Weblogic 12c (12.1.3) and eclipselink 2.3.1 Getting a ClassCastException for Named Native Queries

Recently we migrated from weblogic 10 to weblogic12c. The application was working fine until we migrated to the new weblogic12c server. My web application is using JPA and eclipselink to fetch some information from the database. All other named query seems to be working fine, expect the Native Named query. I'm getting a classcastException. Below is the code. Any help is greatly appreciated.
This is my Named Native Query
#NamedNativeQueries({
#NamedNativeQuery(name="Channel.findValue",
query="SELECT ID, APP_ID , APPLICATION_TYPE_ID, CHANNEL_ID, VALUE, EFFECTIVE_DATE FROM TABLENAME "+
" WHERE APP_ID = ? AND STATUS= ? AND APPLICATION_TYPE_ID = ? AND CHANNEL_ID = ? AND EXPIRY_DATE >= ? AND EFFECTIVE_DATE <= ? "
,resultSetMapping="findFeeByAppTypeAndChannel")
})
#SqlResultSetMappings({
#SqlResultSetMapping(name="findValue",
entities={#EntityResult(entityClass=Channel.class)}
)
})
Code that's calling that's calling query:
List<Channel> channels = em.createNamedQuery("channel.findVale").setParameter(1, app.getId())
.setParameter(2, ConstStatus.ACTIVE)
.setParameter(3, appType.getId())
.setParameter(4, channelId)
.setParameter(5, effectiveDate)
.setParameter(6, effectiveDate).setHint("eclipselink.refresh", "true").getResultList();
Error that I am getting:
java.lang.ClassCastException: org.eclipse.persistence.queries.ResultSetMappingQuery cannot be cast to org.eclipse.persistence.queries.ObjectLevelReadQuery
Full Stack trace:
SEVERE: Value Service Response:EJB Exception: : java.lang.ClassCastException: org.eclipse.persistence.queries.ResultSetMappingQuery cannot be cast to org.eclipse.persistence.queries.ObjectLevelReadQuery
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRowInternal(ForeignReferenceMapping.java:2073)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRow(ForeignReferenceMapping.java:1987)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.readFromRowIntoObject(ForeignReferenceMapping.java:1353)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder.java:445)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.refreshObjectIfRequired(ObjectBuilder.java:3591)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:826)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildWorkingCopyCloneNormally(ObjectBuilder.java:715)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObjectInUnitOfWork(ObjectBuilder.java:668)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:601)
at org.eclipse.persistence.queries.EntityResult.getValueFromRecord(EntityResult.java:192)
at org.eclipse.persistence.queries.ResultSetMappingQuery.buildObjectsFromRecords(ResultSetMappingQuery.java:144)
at org.eclipse.persistence.queries.ResultSetMappingQuery.executeDatabaseQuery(ResultSetMappingQuery.java:195)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:743)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2871)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1463)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.executeReadQuery(EJBQueryImpl.java:485)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getResultList(EJBQueryImpl.java:742)
at weblogic.persistence.QueryProxyImpl.getResultList(QueryProxyImpl.java:140)
at com.database.service.app.app.service.appServiceBean.getFeeByAppTypeAndChannel(appServiceBean.java:413)
at com.database.service.app.app.service.appServiceBean_7omfhq_appServiceLocalImpl.__WL_invoke(Unknown Source)
at weblogic.ejb.container.internal.SessionLocalMethodInvoker.invoke(SessionLocalMethodInvoker.java:33)
at com.database.service.app.app.service.appServiceBean_7omfhq_appServiceLocalImpl.getFeeByAppTypeAndChannel(Unknown Source)
at com.database.service.app.ws.service.FeeService.getFeeInfo(FeeService.java:89)
at com.database.service.app.ws.service.FeeService.getFee(FeeService.java:191)
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 weblogic.wsee.jaxws.WLSInstanceResolver$WLSInvoker.invoke(WLSInstanceResolver.java:117)
at weblogic.wsee.jaxws.WLSInstanceResolver$WLSInvoker.invoke(WLSInstanceResolver.java:91)
at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:149)
at com.sun.xml.ws.server.sei.SEIInvokerTube.processRequest(SEIInvokerTube.java:88)
at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
at com.sun.xml.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:419)
at com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:868)
at com.sun.xml.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:422)
at com.sun.xml.ws.transport.http.servlet.ServletAdapter.handle(ServletAdapter.java:169)
at weblogic.wsee.jaxws.WLSServletAdapter.handle(WLSServletAdapter.java:199)
at weblogic.wsee.jaxws.HttpServletAdapter$AuthorizedInvoke.run(HttpServletAdapter.java:640)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
at weblogic.wsee.util.ServerSecurityHelper.authenticatedInvoke(ServerSecurityHelper.java:108)
at weblogic.wsee.jaxws.HttpServletAdapter$3.run(HttpServletAdapter.java:284)
at weblogic.wsee.jaxws.HttpServletAdapter.post(HttpServletAdapter.java:293)
at weblogic.wsee.jaxws.JAXWSServlet.doRequest(JAXWSServlet.java:128)
at weblogic.servlet.http.AbstractAsyncServlet.service(AbstractAsyncServlet.java:99)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:280)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:254)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:136)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:346)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:243)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3432)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3402)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2285)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2201)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1572)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:255)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)>
<31-Mar-2016 11:26:58 o'clock AM ADT> <Error> <com.database.service.app.ws.service.FeeService> <BEA-000000> <Value Service Response:EJB Exception: : java.lang.ClassCastException: org.eclipse.persistence.queries.ResultSetMappingQuery cannot be cast to org.eclipse.persistence.queries.ObjectLevelReadQuery
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRowInternal(ForeignReferenceMapping.java:2073)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRow(ForeignReferenceMapping.java:1987)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.readFromRowIntoObject(ForeignReferenceMapping.java:1353)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder.java:445)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.refreshObjectIfRequired(ObjectBuilder.java:3591)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:826)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildWorkingCopyCloneNormally(ObjectBuilder.java:715)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObjectInUnitOfWork(ObjectBuilder.java:668)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:601)
at org.eclipse.persistence.queries.EntityResult.getValueFromRecord(EntityResult.java:192)
at org.eclipse.persistence.queries.ResultSetMappingQuery.buildObjectsFromRecords(ResultSetMappingQuery.java:144)
at org.eclipse.persistence.queries.ResultSetMappingQuery.executeDatabaseQuery(ResultSetMappingQuery.java:195)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:743)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2871)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1463)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.executeReadQuery(EJBQueryImpl.java:485)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getResultList(EJBQueryImpl.java:742)
at weblogic.persistence.QueryProxyImpl.getResultList(QueryProxyImpl.java:140)
at com.database.service.app.app.service.appServiceBean.getFeeByAppTypeAndChannel(appServiceBean.java:413)
at com.database.service.app.app.service.appServiceBean_7omfhq_appServiceLocalImpl.__WL_invoke(Unknown Source)
at weblogic.ejb.container.internal.SessionLocalMethodInvoker.invoke(SessionLocalMethodInvoker.java:33)
at com.database.service.app.app.service.appServiceBean_7omfhq_appServiceLocalImpl.getFeeByAppTypeAndChannel(Unknown Source)
at com.database.service.app.ws.service.FeeService.getFeeInfo(FeeService.java:89)
at com.database.service.app.ws.service.FeeService.getFee(FeeService.java:191)
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 weblogic.wsee.jaxws.WLSInstanceResolver$WLSInvoker.invoke(WLSInstanceResolver.java:117)
at weblogic.wsee.jaxws.WLSInstanceResolver$WLSInvoker.invoke(WLSInstanceResolver.java:91)
at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:149)
at com.sun.xml.ws.server.sei.SEIInvokerTube.processRequest(SEIInvokerTube.java:88)
at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
at com.sun.xml.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:419)
at com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:868)
at com.sun.xml.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:422)
at com.sun.xml.ws.transport.http.servlet.ServletAdapter.handle(ServletAdapter.java:169)
at weblogic.wsee.jaxws.WLSServletAdapter.handle(WLSServletAdapter.java:199)
at weblogic.wsee.jaxws.HttpServletAdapter$AuthorizedInvoke.run(HttpServletAdapter.java:640)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
at weblogic.wsee.util.ServerSecurityHelper.authenticatedInvoke(ServerSecurityHelper.java:108)
at weblogic.wsee.jaxws.HttpServletAdapter$3.run(HttpServletAdapter.java:284)
at weblogic.wsee.jaxws.HttpServletAdapter.post(HttpServletAdapter.java:293)
at weblogic.wsee.jaxws.JAXWSServlet.doRequest(JAXWSServlet.java:128)
at weblogic.servlet.http.AbstractAsyncServlet.service(AbstractAsyncServlet.java:99)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:280)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:254)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:136)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:346)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:243)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3432)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3402)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2285)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2201)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1572)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:255)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)
Error got resolved when I removed the
setHint("eclipselink.refresh", "true")
from
List<Channel> channels = em.createNamedQuery("channel.findVale")
.setParameter(1, app.getId())
.setParameter(2, ConstStatus.ACTIVE)
.setParameter(3, appType.getId())
.setParameter(4, channelId) .setParameter(5, effectiveDate)
.setParameter(6, effectiveDate)
.setHint("eclipselink.refresh", "true").getResultList();

Not able to invoke #GET in Jersey Rest with #PathParam

Below is the structure of my Restful API
#GET
#Path("/getprovider/{queryKey}/requests/{queryValue}")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response getApiProv(HttpServletRequest request,HttpServletResponse response,#PathParam("queryKey") String queryKey, #PathParam("queryValue") String queryValue) {
..........
..........
}
while invoking it with below url http://localhost:8080/v1/getprovider/service/requests/abc_demo
it is showing
HTTP ERROR 500
Problem accessing /v1/getprovider/service/requests/abc_demo
Reason:
java.io.EOFException: No content to map to Object due to end of input
at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2766)
at org.codehaus.jackson.map.ObjectMapper._readValue(ObjectMapper.java:2682)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1308)
at org.codehaus.jackson.jaxrs.JacksonJsonProvider.readFrom(JacksonJsonProvider.java:419)
at com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.readFrom(JacksonProviderProxy.java:139)
at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:490)
at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:123)
at com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:86)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:684)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:503)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:533)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:429)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:255)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:370)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:494)
at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:971)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:1033)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:644)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:696)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:53)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
at java.lang.Thread.run(Thread.java:745)
I am not able to get why it is not even going to method body. Please help.
The #Consumes(MediaType.APPLICATION_JSON) says that the request body will contain a valid JSON object, but the error message says you have not provided one. Did you mean to add that #Consumes, and if so, did you supply a JSON object in the request body?
(Note that the request body for GET is not widely supported, and if you're actually trying to consume that content, then your endpoint is likely not idempotent, which is a key property of HTTP GET. If you actually want to consume a JSON in the request body, then you should switch to #PUT or #POST).

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()));