|
next
|
 Subject: XQUERY Java run-time error Author: Jack Tan Date: 17 Apr 2007 04:42 AM
|
Ivan,
thanks for late night reply ;-)
I am using Java generated code.
Interestingly when in the XQUERY script I changed:
let $svgDoc := "\SoftwareDevelopment\LVS_Workspace\tool\doc\graphs\rf_headers.xml"
let $doc := "C:\SoftwareDevelopment\LVS_Workspace\tool\doc\graphs\intermediate.xml"
to
let $svgDoc := "rf_headers.xml"
let $doc := "C:\SoftwareDevelopment\LVS_Workspace\tool\doc\graphs\intermediate.xml"
problem disapeared.
Below, I am attaching Java code.
Thx
Jack
/**
* Generated by Stylus Studio.
* This application skeleton demonstrates how to execute XQuery from Java.
*/
package m2c20;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.util.Properties;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.SourceLocator;
import net.sf.saxon.Configuration;
import net.sf.saxon.om.Item;
import net.sf.saxon.om.Validation;
import net.sf.saxon.om.SequenceIterator;
import net.sf.saxon.event.Builder;
import net.sf.saxon.query.DynamicQueryContext;
import net.sf.saxon.query.StaticQueryContext;
import net.sf.saxon.query.XQueryExpression;
import net.sf.saxon.query.QueryResult;
import net.sf.saxon.value.AtomicValue;
import net.sf.saxon.value.SequenceExtent;
import net.sf.saxon.value.UntypedAtomicValue;
import net.sf.saxon.value.Value;
import net.sf.saxon.value.Whitespace;
import java.util.Properties;
import javax.xml.transform.OutputKeys;
import java.io.BufferedReader;
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
import org.xml.sax.InputSource;
/**
* Run an XQuery.
* This class requires the following items in the classpath.
* C:/SoftwareDevelopment/LVS_Workspace/rf_record
* C:/Program Files/Stylus Studio 2006 Release 3 XML Enterprise Edition/bin/saxon8sa.jar
* C:/Program Files/Stylus Studio 2006 Release 3 XML Enterprise Edition/bin/saxon8.jar
*/
public class rf_generator
{
String m_baseURI;
String m_paramNames[];
String m_paramValues[];
boolean m_useResolver = true; // true = use the StylusFileFactory URIResolver
int m_selectedProcessor = 0;
int m_validationProcessor = 0;
BasicSource m_scriptSource;
BasicSource m_xmlSource;
BasicResult m_transformResult;
BasicResult m_finalResult;
boolean m_doValidation = false;
boolean m_doCopyStep = false;
boolean m_useApacheFop = false;
boolean m_useRenderX = false;
Reader m_queryReader;
InputSource m_foSource;
StreamSource m_xepSource;
String m_foInputFilename;
String m_foOutputFilename = "C:/SoftwareDevelopment/LVS_Workspace/rf_record/rf_generator.pdf";
OutputStream m_foOutputStream;
Configuration m_cfg;
StaticQueryContext m_sqc;
DynamicQueryContext m_dqc;
// items from the Saxon XSLT Settings dialog
int m_stripWhitespace;
boolean m_schemaAwareProcessor;
boolean m_tinyTree;
boolean m_enableFileExtensions;
boolean m_validateWithDTD;
boolean m_validationIssuesWarnings;
int m_sourceValidationLevel;
BufferedReader m_saxonLicenseReader;
String m_validatorInput;
File m_tmpFile;
// application constructor
public rf_generator() {}
public static void main(String[] args) throws Exception
{
rf_generator app = new rf_generator();
// This section lists all scenarios selected for this XQuery.
// Uncomment the setScenario call for the scenario you want
// the code to run. All other scenarios must be commented out.
try {
app.setScenario_Scenario1();
app.initialize();
app.process();
app.postProcess();
} finally {
app.cleanup();
}
}
/////////////////////////////////////////////////////////////////
// Only one of these setScenario methods can be called at a time.
/////////////////////////////////////////////////////////////////
public void setScenario_Scenario1()
throws IOException
{
m_useResolver = false;
m_scriptSource = new BasicSource();
m_xmlSource = new BasicSource();
m_finalResult = new BasicResult();
m_scriptSource.setFile("c:/SoftwareDevelopment/LVS_Workspace/tool_m2c2/doc/graphs/rf_generator.xquery");
m_baseURI = m_scriptSource.getSystemId();
m_xmlSource.setFile("c:/SoftwareDevelopment/LVS_Workspace/tool_m2c2/doc/graphs/rf_headers.xml");
m_finalResult.setFile("c:/SoftwareDevelopment/LVS_Workspace/tool_m2c2/doc/graphs/rf_data_java.txt");
m_paramNames = new String[] {};
m_paramValues = new String[] {};
m_selectedProcessor = SAXON8;
// If you are using schema aware version of Saxon, you must supply a license key.
// There are 2 options:
// 1) put the saxon-license.lic file in your classpath.
// 2) Supply a BufferedReader (could be a FileReader or a StringReader) which will return
// the license.
///////////////////////
// m_saxonLicenseReader = <<Insert the buffered reader here and uncomment this line.>>
///////////////////////
// items from the Saxon XQuery Settings dialog
m_schemaAwareProcessor = false;
m_tinyTree = true;
m_enableFileExtensions = true;
m_validateWithDTD = false;
m_sourceValidationLevel = Validation.SKIP;
m_validationIssuesWarnings = true;
m_stripWhitespace = Whitespace.IGNORABLE;
}
///////////////////////////////////////////////////////////
// Perform initialization common to all scenarios. One of
// the setScenario methods should have been called first.
///////////////////////////////////////////////////////////
public void initialize() throws Exception
{
initializeAll();
if (m_selectedProcessor==SAXON8) initializeSaxon();
}
public void process() throws IOException
, TransformerException
{
if (m_selectedProcessor==SAXON8) processSaxon();
}
public void initializeAll() throws Exception
{
if (!m_useApacheFop && !m_useRenderX && !m_doValidation) {
// In the simplest scenario, the XQuery output is sent
// directly to the output URL.
// xmlSource -> XQuery -> finalResult
m_transformResult = m_finalResult;
}
else
if (m_finalResult.isFile()) {
// The XQuery output is being written to a file, and there
// is also a validation and/or FOP step. After the
// XQuery output is written to the file, that file will be
// used as input for the validation and/or FOP step.
// xmlSource -> XQuery -> finalResult -> validator
// finalResult -> FOP
m_transformResult = m_finalResult;
m_validatorInput = m_finalResult.getFilename();
m_foInputFilename = m_finalResult.getFilename();
}
else
{ // The XQuery output is being written to a URL or to System.out.
// and there is also a validation and/or FOP step. The XQuery
// output will first be written to a temp file. Then, the
// temp file will be copied to the output URL (or System.out).
// The temp file will also be used as input for the validation
// and/or FOP step.
// xmlSource -> XQuery-> tmpFile -> doCopy -> finalResult
// tmpFile -> validator
// tmpFile -> FOP
m_tmpFile = File.createTempFile("tmp", ".xml");
m_transformResult = new BasicResult();
m_transformResult.setFile(m_tmpFile.getAbsolutePath());
m_doCopyStep = true;
m_validatorInput = m_tmpFile.getAbsolutePath();
m_foInputFilename = m_tmpFile.getAbsolutePath();
}
}
public void initializeSaxon() throws TransformerException {
m_cfg = new Configuration();
if (m_tinyTree)
m_cfg.setTreeModel(Builder.TINY_TREE);
else m_cfg.setTreeModel(Builder.STANDARD_TREE);
m_cfg.getSystemURIResolver().setRecognizeQueryParameters(m_enableFileExtensions);
m_cfg.setStripsWhiteSpace(m_stripWhitespace);
m_cfg.setErrorListener(new TransformerErrorListener());
m_cfg.setValidation(m_validateWithDTD);
m_sqc = new StaticQueryContext(m_cfg);
if (m_baseURI != null)
m_sqc.setBaseURI(m_baseURI);
m_dqc = new DynamicQueryContext(m_cfg);
parseParametersSaxon(m_cfg, m_paramNames, m_paramValues, m_baseURI, m_dqc);
m_queryReader = new InputStreamReader(m_scriptSource.getInputStream());
if (m_xmlSource!=null && m_xmlSource.getInputStream() != null)
m_dqc.setContextItem(m_sqc.buildDocument(m_xmlSource));
}
public void processSaxon() throws IOException, TransformerException
{
XQueryExpression exp = m_sqc.compileQuery(m_queryReader);
Properties props = new Properties();
props.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
try {
exp.run(m_dqc, m_transformResult, props);
} finally {
m_transformResult.close();
}
}
public void parseParametersSaxon(Configuration cfg, String[] paramNames, String[] paramValues, String uri, DynamicQueryContext globalDQC)
{
// loop over all parameter name/value pairs
// evaluate the value, and then do setParameter
for(int i=0; i<paramNames.length; i++) {
String xkey = paramNames[i];
String svalue = paramValues[i];
Value xvalue=null;
try {
StaticQueryContext sqc = new StaticQueryContext(cfg);
sqc.getConfiguration().setErrorListener(new TransformerErrorListener());
sqc.setBaseURI(uri);
DynamicQueryContext localDQC = new DynamicQueryContext(cfg);
StringReader sr = new StringReader(svalue);
XQueryExpression xqe = sqc.compileQuery(sr);
SequenceIterator si = xqe.iterator(localDQC).getAnother();
Item item = si.next();
if (item != null && si.next() == null && item instanceof AtomicValue) {
xvalue = (AtomicValue)item;
} else {
xvalue = new SequenceExtent(xqe.iterator(localDQC));
}
} catch (Throwable t) {
xvalue = new UntypedAtomicValue(svalue);
}
globalDQC.setParameter(xkey, xvalue);
}
}
private static final int XALANJ = 10;
private static final int SAXON6 = 11;
private static final int SAXON8 = 12;
private static final int XERCESJ = 13;
//////////////////
// helper methods
//////////////////
public void postProcess() throws Exception {
if (m_doCopyStep) copyOutput(m_validatorInput, m_finalResult);
}
/**
* Copy the XQuery or XSLT output from the temp output file to the
* proper result file.
* The XQuery or XSLT output was left in a temporary file.
* This routine copies it to the proper result: m_finalResult
*/
void copyOutput(String inFilename, BasicResult result) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(inFilename);
os = result.getOutputStream();
byte buffer[] = new byte[8000];
int bytesRead = 0;
while ((bytesRead = is.read(buffer)) != -1)
os.write(buffer, 0, bytesRead);
} finally {
result.close();
if (is != null)
is.close();
}
}
public void cleanup() throws IOException {
// The following code ensures that all streams opened by setScenario are closed.
if (m_scriptSource != null) m_scriptSource.close();
if (m_xmlSource != null) m_xmlSource.close();
if (m_transformResult != null) m_transformResult.close();
if (m_finalResult != null) m_finalResult.close();
if (m_tmpFile != null) m_tmpFile.delete();
if (m_foSource != null) m_foSource.getByteStream().close();
if (m_xepSource != null) m_xepSource.getInputStream().close();
if (m_foOutputStream != null) m_foOutputStream.close();
}
private class TransformerErrorListener implements ErrorListener {
public void warning(TransformerException exception) {
printMsg(exception, "(Warning) ");
}
public void error(TransformerException exception) {
printMsg(exception, "(Error) ");
}
public void fatalError(TransformerException exception) {
printMsg(exception, "(Fatal Error) ");
}
// Saxon sends the same exception 2 times. This is used to suppress the 2nd copy.
private String m_lastMsg;
private void printMsg(TransformerException exception, String errorType) {
String msg = errorType + exception.getLocalizedMessage();
SourceLocator loc = exception.getLocator();
if (loc!=null) {
String file = loc.getSystemId();
int line = loc.getLineNumber();
int col = loc.getColumnNumber();
msg = file + ":" + line + "," + col + ": " + msg;
}
Throwable t = exception.getCause();
while(t!=null) {
msg += ": " + t.getLocalizedMessage();
t = t.getCause();
}
if (!msg.equals(m_lastMsg)) // dont print the same message twice
System.out.println(msg);
m_lastMsg = msg;
}
}
///////////////////////////
// Support code for RenderX
///////////////////////////
//////////////////
// helper classes
//////////////////
// These helper classes are used to convert a URL string into a Source or Result:
// BasicSource and BasicResult are used if NOT using the Stylus Studio URIResolver.
// ResolverSource and ResolverResult are used with the Stylus Studio URIResolver.
private class BasicSource extends StreamSource {
void setFile(String filename) throws IOException {
setSystemId("file:///" + filename.replaceAll(" ", "%20"));
setInputStream(new FileInputStream(filename));
}
void setURL(String urlString) throws IOException {
setSystemId(urlString);
setInputStream(new java.net.URL(urlString).openStream());
}
void setNone() {
}
void close() throws IOException {
InputStream is = getInputStream();
if (is!=null) {
is.close();
setInputStream(null);
}
}
protected void finalize() throws Throwable { close(); }
}
private class BasicResult extends StreamResult {
protected boolean m_isStdout = false;
protected boolean m_isFile = false;
protected String m_filename = null;
void setFile(String filename) throws IOException {
m_filename = filename;
setSystemId("file:///" + filename.replaceAll(" ", "%20"));
setOutputStream(new FileOutputStream(filename));
m_isFile = true;
}
boolean isFile() { return m_isFile; }
String getFilename() { return m_filename; }
void setURL(String urlString) throws IOException {
setSystemId(urlString);
java.net.URLConnection c = new java.net.URL(urlString).openConnection();
c.setDoOutput(true);
c.setDoInput(false);
setOutputStream(c.getOutputStream());
}
void setNone() {
setOutputStream(System.out);
m_isStdout = true; // dont try to close System.out
}
void close() throws IOException {
OutputStream os = getOutputStream();
if (os!=null) {
os.flush();
if (!m_isStdout)
os.close();
setOutputStream(null);
m_isStdout = false;
}
}
protected void finalize() throws Throwable { close(); }
}
}
|
|
|
|