Evaluate XPATH 2.0 expression with SAXON - saxon

I struggeled to find a working SAXON example to perform a simple task like evaluating the following XPATH 2.0 expression:
abs(-a)
Evaluating an expression like
3 + 4
works quite fine, but I didn't manage to provide SAXON a value for the variable a.
I tried stuff like:
final Processor proc = new Processor(false);
final XPathCompiler xpath = proc.newXPathCompiler();
QName a = new QName("a");
xpath.declareVariable(a);
System.out.println(xpath.evaluate("abs(-a)", null));
But obviously this doesn't work since I didn't provide a value for a.
How can I declare a value for a?
Any help would be highly appreciated!
Edit: This doesn't work either:
final Processor proc = new Processor(false);
final XPathCompiler xpath = proc.newXPathCompiler();
XPathSelector exp = xpath.compile("abs(-$a)").load();
exp.setVariable(new QName("a"), new XdmAtomicValue(17));
XdmItem result = exp.evaluateSingle();
This throws an exception:
net.sf.saxon.s9api.SaxonApiException: Undeclared variable in XPath expression: $a
at net.sf.saxon.s9api.XPathCompiler.internalCompile(XPathCompiler.java:500)
at net.sf.saxon.s9api.XPathCompiler.compile(XPathCompiler.java:472)
at xpathtest.SaxonTest.test(SaxonTest.java:26)
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.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.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)
Caused by: net.sf.saxon.trans.XPathException: Undeclared variable in XPath expression: $a
at net.sf.saxon.sxpath.IndependentContext.bindVariable(IndependentContext.java:458)
at net.sf.saxon.expr.parser.XPathParser.parseVariableReference(XPathParser.java:1905)
at net.sf.saxon.expr.parser.XPathParser.parseBasicStep(XPathParser.java:1703)
at net.sf.saxon.expr.parser.XPathParser.parseStepExpression(XPathParser.java:1638)
at net.sf.saxon.expr.parser.XPathParser.parseRelativePath(XPathParser.java:1564)
at net.sf.saxon.expr.parser.XPathParser.parsePathExpression(XPathParser.java:1529)
at net.sf.saxon.expr.parser.XPathParser.parseSimpleMappingExpression(XPathParser.java:1541)
at net.sf.saxon.expr.parser.XPathParser.parseUnaryExpression(XPathParser.java:1419)
at net.sf.saxon.expr.parser.XPathParser.parseUnaryExpression(XPathParser.java:1390)
at net.sf.saxon.expr.parser.XPathParser.parseExprSingle(XPathParser.java:511)
at net.sf.saxon.expr.parser.XPathParser.parseFunctionArgument(XPathParser.java:2629)
at net.sf.saxon.expr.parser.XPathParser.parseFunctionCall(XPathParser.java:2371)
at net.sf.saxon.expr.parser.XPathParser.parseBasicStep(XPathParser.java:1723)
at net.sf.saxon.expr.parser.XPathParser.parseStepExpression(XPathParser.java:1638)
at net.sf.saxon.expr.parser.XPathParser.parseRelativePath(XPathParser.java:1564)
at net.sf.saxon.expr.parser.XPathParser.parsePathExpression(XPathParser.java:1529)
at net.sf.saxon.expr.parser.XPathParser.parseSimpleMappingExpression(XPathParser.java:1541)
at net.sf.saxon.expr.parser.XPathParser.parseUnaryExpression(XPathParser.java:1419)
at net.sf.saxon.expr.parser.XPathParser.parseExprSingle(XPathParser.java:511)
at net.sf.saxon.expr.parser.XPathParser.parseExpression(XPathParser.java:450)
at net.sf.saxon.expr.parser.XPathParser.parse(XPathParser.java:386)
at net.sf.saxon.expr.parser.ExpressionTool.make(ExpressionTool.java:102)
at net.sf.saxon.sxpath.XPathEvaluator.createExpression(XPathEvaluator.java:153)
at net.sf.saxon.s9api.XPathCompiler.internalCompile(XPathCompiler.java:497)
... 25 more

Firstly, it should be abs(-$a). Note the $.
To provide parameters you can't use the "short-cut" method XPathCompiler.evaluate(). You have to do it the long way:
XPathSelector exp = xpath.compile("abs(-$a)").load();
exp.setVariable(new QName("a"), new XdmAtomicValue(17));
XdmItem result = exp.evaluateSingle();

I know this thread is old but I ran into this problem recently, and spent almost 2 hours searching for answers. Finally, I got this working with Saxon-HE 9.4. I kept getting an error from compile, in spite of declaring the external variable until I also called:
xpath.setAllowUndeclaredVariables(true);

Related

org.neo4j.ogm.context.GraphEntityMapper throwing IllegalArgumentException: Can not set Double field to java.math.BigDecimal

Upgraded existing API to use Neo4j 4.3.3 and neo4j-ogm-http-driver to 3.2.25. spring-boot-starter-data-neo4j is 2.3.4.Release. Now if I try to create/fetch a relationship with one of the attribute as Double using org.springframework.data.repository CrudRepository.save() and org.springframework.data.neo4j.repository Neo4jRepository.findById(), it throws below error:
Found relationship type: OWNS to map to RelationshipEntity: RelationshipEntityName
2021-08-21 00:25:14.780 ERROR 3556 --- [nio-8303-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Error mapping GraphModel; nested exception is org.neo4j.ogm.exception.core.MappingException: Error mapping GraphModel] with root cause
java.lang.IllegalArgumentException: Can not set java.lang.Double field RelationshipEntityName.percentage to java.math.BigDecimal
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
at java.lang.reflect.Field.set(Field.java:764)
at org.neo4j.ogm.metadata.FieldInfo.lambda$write$0(FieldInfo.java:352)
at java.security.AccessController.doPrivileged(Native Method)
at org.neo4j.ogm.metadata.FieldInfo.write(FieldInfo.java:349)
at org.neo4j.ogm.metadata.FieldInfo.write(FieldInfo.java:383)
at org.neo4j.ogm.context.GraphEntityMapper.writeProperty(GraphEntityMapper.java:305)
at org.neo4j.ogm.context.GraphEntityMapper.setProperties(GraphEntityMapper.java:268)
at org.neo4j.ogm.context.GraphEntityMapper.createRelationshipEntity(GraphEntityMapper.java:409)
at org.neo4j.ogm.context.GraphEntityMapper.mapRelationshipEntity(GraphEntityMapper.java:354)
at org.neo4j.ogm.context.GraphEntityMapper.mapRelationships(GraphEntityMapper.java:330)
at org.neo4j.ogm.context.GraphEntityMapper.mapContentOf(GraphEntityMapper.java:158)
at org.neo4j.ogm.context.GraphEntityMapper.lambda$map$2(GraphEntityMapper.java:115)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.neo4j.ogm.context.GraphEntityMapper.map(GraphEntityMapper.java:117)
at org.neo4j.ogm.context.GraphRowModelMapper.map(GraphRowModelMapper.java:60)
at org.neo4j.ogm.session.delegates.ExecuteQueriesDelegate.lambda$executeAndMap$1(ExecuteQueriesDelegate.java:165)
at org.neo4j.ogm.session.Neo4jSession.doInTransaction(Neo4jSession.java:590)
at org.neo4j.ogm.session.Neo4jSession.doInTransaction(Neo4jSession.java:564)
at org.neo4j.ogm.session.delegates.ExecuteQueriesDelegate.executeAndMap(ExecuteQueriesDelegate.java:150)
at org.neo4j.ogm.session.delegates.ExecuteQueriesDelegate.query(ExecuteQueriesDelegate.java:117)
at org.neo4j.ogm.session.Neo4jSession.query(Neo4jSession.java:425)
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.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:282)
at org.springframework.data.neo4j.transaction.SharedSessionCreator$SharedSessionInvocationHandler.lambda$invoke$1(SharedSessionCreator.java:121)
at org.springframework.data.neo4j.transaction.SharedSessionCreator$SharedSessionInvocationHandler.invokeInTransaction(SharedSessionCreator.java:159)
at org.springframework.data.neo4j.transaction.SharedSessionCreator$SharedSessionInvocationHandler.invoke(SharedSessionCreator.java:123)
at com.sun.proxy.$Proxy88.query(Unknown Source)
at org.springframework.data.neo4j.repository.query.GraphQueryExecution$SingleEntityExecution.execute(GraphQueryExecution.java:64)
at org.springframework.data.neo4j.repository.query.GraphRepositoryQuery.doExecute(GraphRepositoryQuery.java:76)
at org.springframework.data.neo4j.repository.query.AbstractGraphRepositoryQuery.execute(AbstractGraphRepositoryQuery.java:57)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor$QueryMethodInvoker.invoke(QueryExecutorMethodInterceptor.java:195)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:152)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:130)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy111.findByResource(Unknown Source)
I tried changing the attribute percentage to Number, that does not throw the exception but percentage doesn't get saved.
I do not want to upgrade spring-boot-starter-data-neo4j to any major version at this point.
Upgrading to Spring-Data-Neo4j 6.x will again be big migration effort.
I am stuck now.
I found out the exact place where the error was coming from was neo4j.ogm.core files, I tried various versions of the jar but nothing worked.
Finally I resolved the problem by writing a custom converter as the implicit converter was not able to convert between Double and BigDecimal.
public class PercentageConverter implements AttributeConverter<Double, BigDecimal> {
#Override
public BigDecimal toGraphProperty(Double value) {
if (value == null) {
return null;
}
return new BigDecimal(value);
}
#Override
public Double toEntityAttribute(BigDecimal value) {
return value.doubleValue();
}
}
and annotate the entity attribute to use this converter
#Convert(PercentageConverter.class)
This resolved my error and now I can do all CRUD operations successfully

Grails / Gorm / Exception in thread "Thread-8" BUG! exception in phase 'semantic analysis' in source unit

Getting this exception in Gorm 6.1 with Grails 3.3.2:
Exception in thread "Thread-8" BUG! exception in phase 'semantic analysis' in source unit '/Users/emmanuj/projects/cleena/demo/src/main/groovy/com/emmanuj/cleena/UserService.groovy' unexpected NullpointerException
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1070)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:537)
at grails.boot.GrailsApp.compileGroovyFile(GrailsApp.groovy:313)
at grails.boot.GrailsApp.recompile(GrailsApp.groovy:299)
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.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1427)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:384)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:69)
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:182)
at grails.boot.GrailsApp$_enableDevelopmentModeWatch_closure1.doCall(GrailsApp.groovy:240)
at grails.boot.GrailsApp$_enableDevelopmentModeWatch_closure1.doCall(GrailsApp.groovy)
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.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1427)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
at groovy.lang.Closure.call(Closure.java:414)
at groovy.lang.Closure.call(Closure.java:408)
at groovy.lang.Closure.run(Closure.java:495)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
at org.grails.datastore.gorm.services.implementers.AbstractDetachedCriteriaServiceImplementor.doImplement(AbstractDetachedCriteriaServiceImplementor.groovy:79)
at org.grails.datastore.gorm.services.implementers.AbstractReadOperationImplementer.implement(AbstractReadOperationImplementer.groovy:62)
at org.grails.datastore.gorm.services.transform.ServiceTransformation.visitAfterTraitApplied(ServiceTransformation.groovy:278)
at org.grails.datastore.gorm.transform.AbstractTraitApplyingGormASTTransformation.visit(AbstractTraitApplyingGormASTTransformation.groovy:52)
at org.grails.datastore.gorm.transform.AbstractTraitApplyingGormASTTransformation.visit(AbstractTraitApplyingGormASTTransformation.groovy:42)
at org.grails.datastore.gorm.transform.AbstractGormASTTransformation.visit(AbstractGormASTTransformation.groovy:59)
at org.codehaus.groovy.transform.ASTTransformationVisitor.visitClass(ASTTransformationVisitor.java:134)
at org.codehaus.groovy.transform.ASTTransformationVisitor$2.call(ASTTransformationVisitor.java:178)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1065)
... 34 more
Steps To Reproduce
Create a new Grails 3.3.2 project
Create a domain class called User like below:
import grails.compiler.GrailsCompileStatic
#GrailsCompileStatic
class User {
String name
static constraints = {
}
}
And the Following Gorm Data Services Interface and class:
package com.emmanuj.cleena
/**
* DataService interface for user domain
*/
interface IUserService {
User get(Serializable id)
List<User> list(Map args)
Long count()
void delete(Serializable id)
User save(User user)
}
And an abstract class implementation:
#Slf4j
#Service(User)
abstract class UserService implements IUserService {
def grailsApplication
List<User> search(User currentUser, long radius, int offset, int max){
return []
}
def getZipcodes(String zipCode, long radius) {
return []
}
}
Run your grails app from the interactive prompt.
Make a change to UserService
Exception/Crash during recompile.
Groovy version is 2.4.13
I opened an issue on the github repo. Looks like a GORM Hibernate bug: https://github.com/grails/gorm-hibernate5/issues/72. But they've closed it as "won't fix". Not sure why...
Restarting the Grails server fixed the issue.
Below is the actual explanation -
I Created a class that was working fine and then I updated it to Associate another dependent class, and Grails threw this error.
The error simply means it cannot compile your already compiled class when it requires creating few more objects when server is running.

Grails: How to reference Service itself and use it in Java?

A SomeService is defined and in a closure it is passed to a Java class:
package somepackage
class SomeService{
...
def process(){
...
//here, how to reference [thisService]? this keyword?
//I tried this keyword, but an exception occurs
JavaClass javaObject = new JavaClass(thisService, otherParams)
...
}
...
}
Exception is thrown when using this referring to SomeService:
Groovyc: java.lang.NoClassDefFoundError: somepackage/SomeService
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2427)
at java.lang.Class.getDeclaredMethods(Class.java:1791)
at org.codehaus.groovy.vmplugin.v5.Java5.configureClassNode(Java5.java:318)
at org.codehaus.groovy.ast.ClassNode.lazyClassInit(ClassNode.java:263)
at org.codehaus.groovy.ast.ClassNode.getUnresolvedSuperClass(ClassNode.java:957)
at org.codehaus.groovy.ast.ClassNode.getUnresolvedSuperClass(ClassNode.java:952)
at org.codehaus.groovy.ast.ClassNode.getSuperClass(ClassNode.java:946)
at org.codehaus.groovy.ast.ClassNode.isDerivedFrom(ClassNode.java:889)
at org.codehaus.groovy.classgen.AsmClassGenerator.assignmentCastAndVisit(AsmClassGenerator.java:4049)
at org.codehaus.groovy.classgen.AsmClassGenerator.evaluateEqual(AsmClassGenerator.java:4002)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitDeclarationExpression(AsmClassGenerator.java:1468)
at org.codehaus.groovy.ast.expr.DeclarationExpression.visit(DeclarationExpression.java:53)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitAndAutoboxBoolean(AsmClassGenerator.java:4111)
at org.codehaus.groovy.classgen.AsmClassGenerator.evaluateExpression(AsmClassGenerator.java:1437)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitReturnStatement(AsmClassGenerator.java:1398)
at org.codehaus.groovy.ast.stmt.ReturnStatement.visit(ReturnStatement.java:47)
at org.codehaus.groovy.ast.CodeVisitorSupport.visitBlockStatement(CodeVisitorSupport.java:35)
at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitBlockStatement(ClassCodeVisitorSupport.java:165)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitBlockStatement(AsmClassGenerator.java:728)
at org.codehaus.groovy.ast.stmt.BlockStatement.visit(BlockStatement.java:69)
at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitClassCodeContainer(ClassCodeVisitorSupport.java:101)
at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitConstructorOrMethod(ClassCodeVisitorSupport.java:112)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitStdMethod(AsmClassGenerator.java:616)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitConstructorOrMethod(AsmClassGenerator.java:591)
at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitMethod(ClassCodeVisitorSupport.java:123)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitMethod(AsmClassGenerator.java:686)
at org.codehaus.groovy.ast.ClassNode.visitContents(ClassNode.java:1039)
at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitClass(ClassCodeVisitorSupport.java:50)
at org.codehaus.groovy.classgen.AsmClassGenerator.visitClass(AsmClassGenerator.java:276)
at org.codehaus.groovy.control.CompilationUnit$12.call(CompilationUnit.java:748)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:942)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:519)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:497)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:474)
at org.jetbrains.groovy.compiler.rt.GroovyCompilerWrapper.compile(GroovyCompilerWrapper.java:54)
at org.jetbrains.groovy.compiler.rt.DependentGroovycRunner.runGroovyc(DependentGroovycRunner.java:80)
at org.jetbrains.groovy.compiler.rt.GroovycRunner.main(GroovycRunner.java:85)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:121)
Caused by: java.lang.ClassNotFoundException: entrust.EnTrustService
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
... 43 more
My question is: how to reference the service itself to other classes? if this is applicable, is this problem related to the calling class being Java class other than groovy class?
You can get a reference to someService bean from ApplicationContext as:
class SomeService{
def grailsApplication
def process(){
...
//here, how to reference [thisService]? this keyword?
//I tried this keyword, but an exception occurs
JavaClass javaObject =
new JavaClass(grailsApplication.mainContext.someService, otherParams)
...
}
}
Doing this, the control goes out of the proxy and fetches the bean from the context. This same principle is applied in transactions or any aspects (AOP) related transition from one method to other in the same service class. Here is an example.

NullPointerException when trying to reload IndexedContainer with fresh data

I'm trying to "reload" an IndexedContainer with new fresh data, but get a NPE.
I have a addItemsToContainer(List<Person> persons) method that I use to populate my container.
Let's say my Person list contains 100 person objects. When I first call addItemsToContainer(List<Person> persons), my container is populated and everything is fine.
However, the second time I call the method, I get a NullPointerException in setValue().
Now, it seems like removeAllItems() do remove all items, but all ItemId's are left in the container. This means that the second time I call the method, the first automatically generated ItemId is 101. Is this the reason I get the NPE? When debugging, I can see that I get the proper value back from person.getId().
My addItemsToContainer method
public void addItemsToContainer(List<Person> persons) {
removeAllItems();
for (Person person : persons) {
Object itemId = addItem();
getContainerProperty(itemId, "Id").setValue(person.getId()); // <-- NPE here
getContainerProperty(itemId, "Name").setValue(person.getName());
}
}
The stacktrace
(ExampleMainTableContainer.java:94 is the statement I marked in the addItemsToContainer method)
com.vaadin.server.ServerRpcManager$RpcInvocationException: Unable to invoke method click in com.vaadin.shared.ui.button.ButtonServerRpc
at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:170)
at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:118)
at com.vaadin.server.communication.ServerRpcHandler.handleBurst(ServerRpcHandler.java:214)
at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:111)
at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:91)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:37)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1371)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:238)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:168)
... 24 more
Caused by: com.vaadin.event.ListenerMethod$MethodException: Invocation of method buttonClick in com.example.myapp.web.view.ExampleView$1 failed.
at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:528)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:167)
at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:969)
at com.vaadin.ui.Button.fireClick(Button.java:368)
at com.vaadin.ui.Button$1.click(Button.java:57)
... 29 more
Caused by: java.lang.NullPointerException
at com.example.myapp.web.view.ExampleMainTableContainer.addItemsToContainer(ExampleMainTableContainer.java:94)
at com.example.myapp.web.view.ExampleMainTable.addMainTableItems(ExampleMainTable.java:172)
at com.example.myapp.web.view.ExampleMainTable.experiment(ExampleMainTable.java:86)
at com.example.myapp.web.view.ExampleView$1.buttonClick(ExampleView.java:208)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:508)
... 33 more
The method getContainerProperty(...) returned null, leading to the NPE.
This happened because I filtered my container prior to the second call to addItemsToContainer(...).
When I add a new item to my container, it gets added to allItemIds - the filteredItemIds is left empty. Now, when getContainerProperty(...) is called, it does a check if the container was filtered. If it was filtered, it returns filteredItemIds instead of allItemIds. This meant, of course, that this statement returned an empty list of objects, leading to ´getContainerProperty(...)´ returning null - which finally lead to the NPE.
The solution was to simply add removeAllContainerFilters(); before my ´getContainerProperty(...)´ calls.

IllegalArgument exception in custom setter after upgrading to JSF2

After upgrading to JSF2 (probably) one special accessor in an .xhtml file generates IllegalArgumentExceptions but I can't really find out why. Running the app on my local JBoss (4.2.2) does not generate this exception but this can be related to a difference between debug and live data.
Following stack trace is generated that I could extract from the production server log:
Caused by: javax.el.ELException: /xy/xy-subtemplate1.xhtml #131,45 value="#{someClass.someProperty}": java.lang.IllegalArgumentException
at com.sun.facelets.el.TagValueExpression.setValue(TagValueExpression.java:101)
at javax.faces.component.UIInput.updateModel(UIInput.java:818)
... 36 more
Caused by: java.lang.IllegalArgumentException
at sun.reflect.GeneratedMethodAccessor1134.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at javax.el.BeanELResolver.setValue(BeanELResolver.java:108)
at com.sun.faces.el.DemuxCompositeELResolver._setValue(DemuxCompositeELResolver.java:255)
at com.sun.faces.el.DemuxCompositeELResolver.setValue(DemuxCompositeELResolver.java:281)
at org.apache.el.parser.AstValue.setValue(AstValue.java:114)
at org.apache.el.ValueExpressionImpl.setValue(ValueExpressionImpl.java:249)
at com.sun.facelets.el.TagValueExpression.setValue(TagValueExpression.java:93)
... 37 more
someClass is being iterated over in a list and has the following methods to access someProperty:
public int getSomeProperty() {
return this.getSomeRelatedEnum().ordinal();
}
public void setSomeProperty( final int index) {
this.setSomeRelatedEnum( SomeRelatedEnum.fromOrdinal( index) );
}
How can this lead to the IllegalArgumentException mentioned above?
That can happen when the setter method after all expects a different argument type than the one which is provided from EL on.
I guess that it's related to the fact that hardcoded/unconverted numbers in EL are by default treated as long and not as int. Try either changing the int to be long, or providing an explicit integer converter on the input component like so <h:someInput converter="javax.faces.Integer">.
By the way, why don't you just get/set the enum itself directly? Getting/setting the enum by its ordinal is whacky.

Resources