Project

Profile

Help

Bug #2170 ยป ExternalVar.java

Example of workaround invoking reflection - O'Neil Delpratt, 2014-10-08 17:13

 
import java.lang.reflect.Field;
import java.util.Map;

import net.sf.saxon.Configuration;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.expr.instruct.Bindery;
import net.sf.saxon.expr.instruct.GlobalParameterSet;
import net.sf.saxon.lib.ExtensionFunctionCall;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
import net.sf.saxon.om.Sequence;
import net.sf.saxon.om.StructuredQName;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.XQueryCompiler;
import net.sf.saxon.s9api.XQueryEvaluator;
import net.sf.saxon.s9api.XQueryExecutable;
import net.sf.saxon.s9api.XdmValue;
import net.sf.saxon.value.SequenceType;
import net.sf.saxon.value.StringValue;

public class ExternalVar {

public static void main(String[] args) throws Exception {
Configuration configuration = new Configuration();
Processor processor = new Processor(configuration);
processor.registerExtensionFunction(new ExtensionFunctionDefinition() {
@Override
public StructuredQName getFunctionQName() {
return new StructuredQName("external", "http://external.module", "function");
}

@Override
public SequenceType[] getArgumentTypes() {
return new SequenceType[]{};
}

@Override
public SequenceType getResultType(SequenceType[] arg0) {
return SequenceType.SINGLE_STRING;
}

@Override
public ExtensionFunctionCall makeCallExpression() {
return new ExtensionFunctionCall() {
@Override
public Sequence call(XPathContext context, Sequence[] args) {
try {
Bindery bindery = context.getController().getBindery();

Field field = Bindery.class.getDeclaredField("globalParameters");
field.setAccessible(true);
GlobalParameterSet globalParameterSet = (GlobalParameterSet) field.get(bindery);
return globalParameterSet.get(new StructuredQName("external", "http://external.module", "variable"));
}
catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
throw new RuntimeException("failed with exception", e);
}
}
};
}
});
XQueryCompiler compiler = processor.newXQueryCompiler();
XQueryExecutable executable = compiler.compile(
"declare namespace external='http://external.module';\n" +
"external:function()"
);
XQueryEvaluator evaluator = executable.load();
evaluator.setExternalVariable(new QName("http://external.module", "variable"), XdmValue.wrap(new StringValue("value")));
evaluator.run(processor.newSerializer(System.out));
}
}
    (1-1/1)