Not sure of input parameters for Groovy call: Ambiguous method overloading - grails

I'm still new to groovy/grails, but I can't figure what's wrong with the following syntax when I try to call the mail plugin for Grails 3.0.9:
class Email {
String subject;
List<String> toEmail;
List<String> ccEmail;
List<String> bccEmail;
String body;
}
Email email = new Email(toEmail: ["test#mail.com"], body: "Hi", subject: "Yo")
mailService.sendMail {
to email.toEmail.toArray()
from "no-reply#fake.com"
cc email.ccEmail?.toArray()
bcc email.bccEmail?.toArray()
subject email.subject
body email.body
}
The exception below is being thrown at the cc parameter line when I don't have anyone to carbon copy. However, I would have thought that the elvis operator would have just returned null and all would have been well. What am I missing? I feel like perhaps I shouldn't be setting the cc and bcc fields at all if there is no data present but I'm not sure why this would cause an issue (maybe it's internal to the plugin) and how I could code around this edge case (build up the arguments separately and pass them in as a variable?)
groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method org.springframework.util.Assert#notEmpty.
Cannot resolve which method to invoke for [null, class java.lang.String] due to overlapping prototypes between:
[interface java.util.Collection, class java.lang.String]
[interface java.util.Map, class java.lang.String]
at groovy.lang.MetaClassImpl.chooseMostSpecificParams(MetaClassImpl.java:3241) ~[groovy-2.4.5.jar:2.4.5]
at groovy.lang.MetaClassImpl.chooseMethodInternal(MetaClassImpl.java:3194) ~[groovy-2.4.5.jar:2.4.5]
at groovy.lang.MetaClassImpl.chooseMethod(MetaClassImpl.java:3137) ~[groovy-2.4.5.jar:2.4.5]
at groovy.lang.MetaClassImpl.pickStaticMethod(MetaClassImpl.java:1508) ~[groovy-2.4.5.jar:2.4.5]
at groovy.lang.MetaClassImpl.retrieveStaticMethod(MetaClassImpl.java:1404) ~[groovy-2.4.5.jar:2.4.5]
at groovy.lang.MetaClassImpl.createStaticSite(MetaClassImpl.java:3383) ~[groovy-2.4.5.jar:2.4.5]
at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallStaticSite(CallSiteArray.java:77) [groovy-2.4.5.jar:2.4.5]
at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallSite(CallSiteArray.java:162) [groovy-2.4.5.jar:2.4.5]
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) [groovy-2.4.5.jar:2.4.5]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) [groovy-2.4.5.jar:2.4.5]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) [groovy-2.4.5.jar:2.4.5]
at grails.plugins.mail.MailMessageBuilder.cc(MailMessageBuilder.groovy:214) ~[mail-2.0.0.RC4.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_51]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_51]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_51]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_51]
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93) ~[groovy-2.4.5.jar:2.4.5]
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325) ~[groovy-2.4.5.jar:2.4.5]
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:384) ~[groovy-2.4.5.jar:2.4.5]
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1019) ~[groovy-2.4.5.jar:2.4.5]
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:69) ~[groovy-2.4.5.jar:2.4.5]
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52) [groovy-2.4.5.jar:2.4.5]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154) [groovy-2.4.5.jar:2.4.5]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:166) [groovy-2.4.5.jar:2.4.5]
at com.doctorsorders.email.EmailService$_sendEmail_closure1.doCall(EmailService.groovy:19) ~[main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_51]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_51]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_51]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_51]
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93) ~[groovy-2.4.5.jar:2.4.5]
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325) ~[groovy-2.4.5.jar:2.4.5]
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294) ~[groovy-2.4.5.jar:2.4.5]
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1019) ~[groovy-2.4.5.jar:2.4.5]
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:42) ~[groovy-2.4.5.jar:2.4.5]
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) [groovy-2.4.5.jar:2.4.5]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) [groovy-2.4.5.jar:2.4.5]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125) [groovy-2.4.5.jar:2.4.5]

Initialize your lists
class Email {
String subject
List<String> toEmail = []
List<String> ccEmail = []
List<String> bccEmail = []
String body
}

I wasn't able to get the right answer from the community, but, to be fair, I think a lot of the finnicky behavior is attributable to the way the mail plugin was written... or maybe it was the way I was using it.
I didn't realize it at the time, but I'm passing a closure to this plugin which contains the series of statements used to initialize the email arguments.
Having a statement within the closure like this:
bcc email.bccEmail?.toArray()
breaks the plugin when no e-mails are specified because the "bcc" var is created and the implementation of this plugin now expects a value. I coded around this by implementing my closure the following way:
Closure mailServiceArgs = {
to email.toEmail.toArray()
from fromEmail
subject email.subject
body email.body
if(email.ccEmail) cc email.ccEmail.toArray()
if(email.bccEmail) bcc email.bccEmail.toArray()
}
This brings up a couple of questions however, because I'm writing my closure with an if statement that is conditional based on the state of a variable (email.ccEmail) which is defined within the scope of my application. I assume this value is passed by reference so at the time the closure is invoked, the value has remained unchanged, but honestly I'm not sure how this works and will research that as well.
There's probably a 'prettier' or more elegant way to do this rather than using an 'if' statement as well.

Related

Jenkinsfile Groovy code not allowing me to call class contructor

I have a class like this:
class MyClass {
boolean mySetting
String mySetting2
List<String> mySetting3
...etc for another 10...
}
but when I try to call its constructor with what look like valid values, I get a java.lang.IllegalArgumentException with no message.
java.lang.IllegalArgumentException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
at groovy.lang.MetaClassImpl.setProperty(MetaClassImpl.java:2725)
at groovy.lang.MetaClassImpl.setProperty(MetaClassImpl.java:3770)
at groovy.lang.MetaClassImpl.setProperties(MetaClassImpl.java:1747)
at org.codehaus.groovy.runtime.callsite.ConstructorSite$NoParamSite.callConstructor(ConstructorSite.java:125)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:60)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:235)
at org.kohsuke.groovy.sandbox.impl.Checker$3.call(Checker.java:208)
at org.kohsuke.groovy.sandbox.GroovyInterceptor.onNewInstance(GroovyInterceptor.java:42)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onNewInstance(SandboxInterceptor.java:173)
at org.kohsuke.groovy.sandbox.impl.Checker$3.call(Checker.java:205)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedConstructor(Checker.java:210)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.constructorCall(SandboxInvoker.java:21)
at WorkflowScript.run(WorkflowScript:116)
at ___cps.transform___(Native Method)
I'd like to make it known publically that I hate Groovy and Jenkins could have been a reasonable system without it.
Eventually I changed my code to set all the parameters individually and discovered that one hadn't been set. This had obviously worked in all my PRs because the params object had default values defined already but not in my new branch because it was the first time it was run.
I changed my line to this:
myObj.mySetting = params.setting || false
java.lang.IllegalArgumentException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
at groovy.lang.MetaClassImpl.setProperty(MetaClassImpl.java:2725)
at groovy.lang.MetaClassImpl.setProperty(MetaClassImpl.java:3770)
at ExecutionConfiguration.setProperty(WorkflowScript)
at org.codehaus.groovy.runtime.InvokerHelper.setProperty(InvokerHelper.java:197)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.setProperty(ScriptBytecodeAdapter.java:484)
at org.kohsuke.groovy.sandbox.impl.Checker$8.call(Checker.java:412)
at org.kohsuke.groovy.sandbox.GroovyInterceptor.onSetProperty(GroovyInterceptor.java:84)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onSetProperty(SandboxInterceptor.java:229)
at org.kohsuke.groovy.sandbox.impl.Checker$8.call(Checker.java:409)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedSetProperty(Checker.java:416)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.setProperty(SandboxInvoker.java:33)
at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawSet(PropertyAccessBlock.java:24)
at WorkflowScript.run(WorkflowScript:131)
at ___cps.transform___(Native Method)

Jenkins pipeline: No such DSL method

With this code i got an error in Jenkins pipeline. I don`t get it why?
Am I missing something?
node {
stage 'test'
def whatThe = someFunc('textToFunc')
{def whatThe2 = someFunc2('textToFunc2')}
}
def someFunc(String text){
echo text
text
}
def someFunc2(String text2){
echo text2
text2
}
Error:
java.lang.NoSuchMethodError: **No such DSL method 'someFunc'** found among [archive, bat, build, catchError, checkout, deleteDir, dir, echo, emailext, emailextrecipients, error, fileExists, git, input, isUnix, load, mail, node, parallel, properties, pwd, readFile, readTrusted, retry, sh, sleep, stage, stash, step, svn, timeout, timestamps, tool, unarchive, unstash, waitUntil, withCredentials, withEnv, wrap, writeFile, ws]
at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:124)
at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:117)
at groovy.lang.MetaClassImpl.invokeMethodOnGroovyObject(MetaClassImpl.java:1280)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1174)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1024)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:42)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.methodCall(DefaultInvoker.java:15)
at WorkflowScript.run(WorkflowScript:4)
at ___cps.transform___(Native Method)
at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:55)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:106)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:79)
at sun.reflect.GeneratedMethodAccessor878.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
at com.cloudbees.groovy.cps.impl.ClosureBlock.eval(ClosureBlock.java:40)
at com.cloudbees.groovy.cps.Next.step(Next.java:58)
at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:154)
at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:164)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:360)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$100(CpsThreadGroup.java:80)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:236)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:226)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:47)
at java.util.concurrent.FutureTask.run(Unknown Source)
at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Finished: FAILURE
remove the extra brackets from around the sumfunc2 invocation:
node {
stage 'test'
def whatThe = someFunc('textToFunc')
def whatThe2 = someFunc2('textToFunc2')
}
def someFunc(String text){
echo text
text
}
def someFunc2(String text2){
echo text2
text2
}
Update:
In Groovy if a method's last argument is of type Closure, then when calling the method the closure can be outside of the brackets like:
def foo(whatever, Closure c) {}
// Can be invoked as
foo(whatever, {
// This is the second argument of foo of type Closure
})
// It is also the same as writing
foo(whatever) {
// This is the second argument of foo of type Closure
}
The reason that the original throws is because the following code
def whatThe = someFunc('textToFunc')
{def whatThe2 = someFunc2('textToFunc2')}
is the same code as
def whatThe = someFunc('textToFunc') {
def whatThe2 = someFunc2('textToFunc2')
}
This means that what the interpreter will be looking for is
someFunc(String text, Closure c)
and there is no such method
Since this answer is the first one I found when I lookup the "No such DSL method" message, I would like to add that it might also be the interface that is not matching. In my case the first parameter was a list, but I tried to call the method with an array. So please check your interface matches what you expect, and your parameters are passed in correctly.
In my case what was happening is that I was referencing a variable using: ${} that was expanding to an empty string:
env.VAR1=${VAR2}
in my case, var2 didn't really exists, so what I had to do was actually:
env.VAR1=env.VAR2.
Silly mistake from my end.
You may have also forgotten to in include your library...
i.e.
#Library('shared-library') _

Rest Assured Output : print URL

I would like to see which URL Rest assured has constructed for test.
My code is pretty vanilla.
ValidatableResponse response = given().
auth().preemptive().basic("User", "Passwd").
contentType(MediaType.APPLICATION_JSON).
log().all().
when().
get("/ping").
then().
statusCode(200);
But the output is a heck of a stack trace which does not even tell me what was the target URL.
checkServer
"java.lang.AssertionError: 1 expectation failed.
Expected status code <200> doesn't match actual status code <500>.
at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrap.callConstructor(ConstructorSite.java:84)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:60)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:235)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:247)
at com.jayway.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure.validate(ResponseSpecificationImpl.groovy:598)
at com.jayway.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure$validate$1.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at com.jayway.restassured.internal.ResponseSpecificationImpl.validateResponseIfRequired(ResponseSpecificationImpl.groovy:760)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:166)
at com.jayway.restassured.internal.ResponseSpecificationImpl.statusCode(ResponseSpecificationImpl.groovy:120)
at com.jayway.restassured.specification.ResponseSpecification$statusCode$0.callCurrent(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:166)
at com.jayway.restassured.internal.ResponseSpecificationImpl.statusCode(ResponseSpecificationImpl.groovy:128)
at com.jayway.restassured.internal.ValidatableResponseOptionsImpl.statusCode(ValidatableResponseOptionsImpl.java:117)
at org.mystuff.EnvironmentCheck.checkServer(EnvironmentCheck.java:43)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:281)
at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:75)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:121)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121)
... Removed 31 stack frames
How would I go about that?
It looks like your request is using the default host and port number. From https://github.com/jayway/rest-assured/wiki/Usage#default-values: "By default REST assured assumes host localhost and port 8080 when doing a request."
If you want to actually see what RESTAssured is sending, rather than just inferring, see https://github.com/jayway/rest-assured/wiki/Usage#request-logging, which refers one to http://hc.apache.org/httpcomponents-client-ga/logging.html to see "what's actually sent on the wire." That document, under "Configuration Examples", has different options for enabling HttpClient communications logging.
From that document, the quick solution best suited to your question send to be the "Enable header wire + context logging - Best for Debugging" set of JVM system properties:
-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
-Dorg.apache.commons.logging.simplelog.showdatetime=true
-Dorg.apache.commons.logging.simplelog.log.org.apache.http=DEBUG
-Dorg.apache.commons.logging.simplelog.log.org.apache.http.wire=ERROR`

Could not use POST method with Feign

im trying to write wrapper for stockfigher game api, just to learn how feign works and I have issues with very first POST method:
#RequestMapping(method = RequestMethod.POST, value = "/venues/KHEX/stocks/LMC/orders")
void newOrderForAStock(String order);
whenever I try to call it, I get exception:
Caused by: feign.RetryableException: cannot retry due to redirection, in streaming mode executing POST https://api.stockfighter.io/ob/api//venues/KHEX/stocks/LMC/orders
at feign.FeignException.errorExecuting(FeignException.java:56)
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:97)
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:71)
at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:94)
at com.sun.proxy.$Proxy50.newOrderForAStock(Unknown Source)
at karolik.michal.stockfighter.runner.TestIt.buyFirst(TestIt.java:45)
at karolik.michal.stockfighter.runner.TestIt.runIt(TestIt.java:32)
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:497)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:349)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:300)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:133)
... 22 common frames omitted
is there any way to tweak it?
Your order needs to be #RequestParam("order") String order

No view scope in faces-config.xml

Why is there no view scope in faces-config.xml? How would I set a bean to view scope, if I am not using faces-config.xml?
I have used the following bean file:
#ManagedBean
#ViewScoped
public class StatusBean2 implements Serializable {
/**
*
*/
private static final long serialVersionUID = -7528998562821856315L;
private EntityManager em;
public StatusBean2() {
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("FreeBird");
em = emf.createEntityManager();
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext()
.getSession(true);
int toIndex = 5;
session.setAttribute("toIndex", toIndex);
}
public List<Status> getStatusList() {
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext()
.getSession(true);
User user = (User) session.getAttribute("userdet");
Query query = em.createQuery("SELECT s FROM Status s WHERE s.email='"
+ user.getEmail() + "' ORDER BY s.timeMillis desc",
Status.class);
List<Status> results = query.getResultList();
Query query1 = em.createQuery("SELECT f FROM Friend f WHERE f.email='"
+ user.getEmail() + "'", Friend.class);
List<Friend> results1 = query1.getResultList();
Iterator<Friend> it = results1.listIterator();
while (it.hasNext()) {
String email = it.next().getFriendEmail();
Query query2 = em.createQuery(
"SELECT s FROM Status s WHERE s.email='" + email
+ "' ORDER BY s.timeMillis desc", Status.class);
List<Status> results2 = query2.getResultList();
results.addAll(results2);
}
Collections.sort(results);
int toIndex = (int) session.getAttribute("toIndex");
List<Status> subList = results.subList(0, toIndex);
return subList;
}
}
The exception that I am getting when I am using annotations is as follows:
Apr 16, 2013 8:41:23 PM com.sun.faces.application.view.FaceletViewHandlingStrategy handleRenderException
SEVERE: Error Rendering View[/Home.xhtml]
java.io.NotSerializableException: com.bean.StatusBean2
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeArray(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at com.sun.faces.renderkit.ClientSideStateHelper.doWriteState(ClientSideStateHelper.java:293)
at com.sun.faces.renderkit.ClientSideStateHelper.writeState(ClientSideStateHelper.java:167)
at com.sun.faces.renderkit.ResponseStateManagerImpl.writeState(ResponseStateManagerImpl.java:119)
at com.sun.faces.application.StateManagerImpl.writeState(StateManagerImpl.java:155)
at com.sun.faces.application.view.WriteBehindStateWriter.flushToWriter(WriteBehindStateWriter.java:221)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:406)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:127)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:117)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:135)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:309)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Apr 16, 2013 8:41:23 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/FreeBird_New2] threw exception
java.io.NotSerializableException: com.bean.StatusBean2
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeArray(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at com.sun.faces.renderkit.ClientSideStateHelper.doWriteState(ClientSideStateHelper.java:293)
at com.sun.faces.renderkit.ClientSideStateHelper.writeState(ClientSideStateHelper.java:167)
at com.sun.faces.renderkit.ResponseStateManagerImpl.writeState(ResponseStateManagerImpl.java:119)
at com.sun.faces.application.StateManagerImpl.writeState(StateManagerImpl.java:155)
at com.sun.faces.application.view.WriteBehindStateWriter.flushToWriter(WriteBehindStateWriter.java:221)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:406)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:127)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:117)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:135)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:309)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Use #ViewScoped annotation on managed bean:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean
#ViewScoped
public class AViewScopedBean {
//managed bean contents...
}
If you don't like the annotations configuration (really odd), you can just set the view scope on faces-config.xml
<managed-bean>
<managed-bean-name>aViewScopedBean<managed-bean-name>
<managed-bean-class>some.package.AViewScopedBean</managed-bean-class>
<managed-bean-scope>view</managed-bean-scope>
</managed-bean>
Note that this only works on JSF 2. Check that your faces-config file is configured to handle JSF 2.x version:
<!-- relevant part of faces-config.xml file for this Q/A -->
<faces-config ... version="2.1">
Edit based on your question update:
The error message is pretty straightforward:
java.io.NotSerializableException: com.bean.StatusBean2
This means that your com.bean.StatusBean2 must also implement the Serializable interface. From java.io.Serializable documentation:
When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object. (this is the error you're getting)
You can learn more about Java Serialization here: Java Serialization
From your question: is it necessary to implement serializable?, BalusC already posted a good answer/explanation: JSF backing bean should be serializable?
Checking the xsd listed in your faces-config.xml (for example: http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd) should show you that view scope is an allowed managed bean scope:
<xsd:complexType name="faces-config-managed-bean-scopeOrNoneType">
<xsd:annotation>
<xsd:documentation>
<![CDATA[[
Defines the legal values for the <managed-bean-scope>
element's body content, which includes all of the scopes
normally used in a web application, plus the "none" value
indicating that a created bean should not be stored into
any scope. Alternatively, an EL expression may be used
as the value of this element. The result of evaluating this
expression must by of type java.util.Map.
]]>
</xsd:documentation>
</xsd:annotation>
<xsd:simpleContent>
<xsd:restriction base="javaee:string">
<xsd:pattern value="view|request|session|application|none|#\{.*\}"/>
</xsd:restriction>
</xsd:simpleContent>
</xsd:complexType>
Assuming jsf 2.0 or later
This is not a new answer per-se, just another way to find out for yourself that it is allowed
--------------- EDIT ----------------
Check this article:
Note that the bean needs to implement Serializable as it will be
stored in the view map which is in turn stored in the session. Some
servletcontainer configurations will namely store sessions on disk
instead of in memory. This is also mandatory when you have configured
JSF view state saving method to client instead of (default) server.
To explain why view scope requires Serializable.

Resources