use of org.exist.xquery.XPathException in project exist by eXist-db.
the class JSONSerializer method serialize.
public void serialize(Sequence sequence, Writer writer) throws SAXException {
JsonFactory factory = new JsonFactory();
try {
JsonGenerator generator = factory.createGenerator(writer);
generator.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
if ("yes".equals(outputProperties.getProperty(OutputKeys.INDENT, "no"))) {
generator.useDefaultPrettyPrinter();
}
if ("yes".equals(outputProperties.getProperty(EXistOutputKeys.ALLOW_DUPLICATE_NAMES, "yes"))) {
generator.enable(JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION);
} else {
generator.disable(JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION);
}
serializeSequence(sequence, generator);
generator.close();
} catch (IOException | XPathException e) {
throw new SAXException(e.getMessage(), e);
}
}
use of org.exist.xquery.XPathException in project exist by eXist-db.
the class BinaryDoc method eval.
@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
final Sequence emptyParamReturnValue = (isCalledAs(FS_BINARY_DOC_NAME) || isCalledAs(FS_BINARY_DOC_CONTENT_DIGEST_NAME)) ? Sequence.EMPTY_SEQUENCE : BooleanValue.FALSE;
if (args[0].isEmpty()) {
return emptyParamReturnValue;
}
final String path = args[0].getStringValue();
try (final LockedDocument lockedDoc = context.getBroker().getXMLResource(XmldbURI.xmldbUriFor(path), LockMode.READ_LOCK)) {
if (lockedDoc == null) {
return emptyParamReturnValue;
}
final DocumentImpl doc = lockedDoc.getDocument();
if (doc.getResourceType() != DocumentImpl.BINARY_FILE) {
return emptyParamReturnValue;
} else if (isCalledAs(FS_BINARY_DOC_NAME)) {
try (final Txn transaction = context.getBroker().continueOrBeginTransaction()) {
final BinaryDocument bin = (BinaryDocument) doc;
final InputStream is = context.getBroker().getBinaryResource(transaction, bin);
final Base64BinaryDocument b64doc = Base64BinaryDocument.getInstance(context, is);
b64doc.setUrl(path);
transaction.commit();
return b64doc;
}
} else if (isCalledAs(FS_BINARY_DOC_CONTENT_DIGEST_NAME)) {
final String algorithm = args[1].getStringValue();
final DigestType digestType;
try {
digestType = DigestType.forCommonName(algorithm);
} catch (final IllegalArgumentException e) {
throw new XPathException(this, "Invalid algorithm: " + algorithm, e);
}
try (final Txn transaction = context.getBroker().getBrokerPool().getTransactionManager().beginTransaction()) {
final BinaryDocument bin = (BinaryDocument) doc;
final MessageDigest messageDigest = context.getBroker().getBinaryResourceContentDigest(transaction, bin, digestType);
final InputStream is = new UnsynchronizedByteArrayInputStream(messageDigest.getValue());
final Sequence result = BinaryValueFromInputStream.getInstance(context, new HexBinaryValueType(), is);
transaction.commit();
return result;
}
} else {
return BooleanValue.TRUE;
}
} catch (final URISyntaxException e) {
logger.error("Invalid resource URI", e);
throw new XPathException(this, "Invalid resource uri", e);
} catch (final PermissionDeniedException e) {
logger.error("{}: permission denied to read resource", path, e);
throw new XPathException(this, path + ": permission denied to read resource");
} catch (final IOException | TransactionException e) {
logger.error("{}: I/O error while reading resource", path, e);
throw new XPathException(this, path + ": I/O error while reading resource", e);
}
}
use of org.exist.xquery.XPathException in project exist by eXist-db.
the class Compile method eval.
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
// get the query expression
final String expr = args[0].getStringValue();
if (expr.trim().isEmpty()) {
return new EmptySequence();
}
context.pushNamespaceContext();
logger.debug("eval: {}", expr);
// TODO(pkaminsk2): why replicate XQuery.compile here?
String error = null;
ErrorCodes.ErrorCode code = null;
int line = -1;
int column = -1;
final XQueryContext pContext = new XQueryContext(context.getBroker().getBrokerPool());
if (getArgumentCount() == 2 && args[1].hasOne()) {
pContext.setModuleLoadPath(args[1].getStringValue());
}
final XQueryLexer lexer = new XQueryLexer(pContext, new StringReader(expr));
final XQueryParser parser = new XQueryParser(lexer);
// shares the context of the outer expression
final XQueryTreeParser astParser = new XQueryTreeParser(pContext);
try {
parser.xpath();
if (parser.foundErrors()) {
logger.debug(parser.getErrorMessage());
throw new XPathException(this, "error found while executing expression: " + parser.getErrorMessage());
}
final AST ast = parser.getAST();
final PathExpr path = new PathExpr(pContext);
astParser.xpath(ast, path);
if (astParser.foundErrors()) {
throw astParser.getLastException();
}
path.analyze(new AnalyzeContextInfo());
} catch (final RecognitionException | TokenStreamException e) {
error = e.toString();
} catch (final XPathException e) {
line = e.getLine();
column = e.getColumn();
code = e.getCode();
error = e.getDetailMessage();
} catch (final Exception e) {
error = e.getMessage();
} finally {
context.popNamespaceContext();
pContext.reset(false);
}
if (isCalledAs("compile")) {
return error == null ? Sequence.EMPTY_SEQUENCE : new StringValue(error);
} else {
return response(pContext, error, code, line, column);
}
}
use of org.exist.xquery.XPathException in project exist by eXist-db.
the class GrammarTooling method eval.
/**
* @see org.exist.xquery.BasicFunction#eval(Sequence[], Sequence)
*/
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
final GrammarPool grammarpool = (GrammarPool) config.getProperty(XMLReaderObjectFactory.GRAMMAR_POOL);
if (isCalledAs("clear-grammar-cache")) {
final Sequence result = new ValueSequence();
final int before = countTotalNumberOfGrammar(grammarpool);
LOG.debug("Clearing {} grammars", before);
clearGrammarPool(grammarpool);
final int after = countTotalNumberOfGrammar(grammarpool);
LOG.debug("Remained {} grammars", after);
final int delta = before - after;
result.add(new IntegerValue(delta));
return result;
} else if (isCalledAs("show-grammar-cache")) {
context.pushDocumentContext();
try {
final MemTreeBuilder builder = context.getDocumentBuilder();
final NodeImpl result = writeReport(grammarpool, builder);
return result;
} finally {
context.popDocumentContext();
}
} else if (isCalledAs("pre-parse-grammar")) {
if (args[0].isEmpty()) {
return Sequence.EMPTY_SEQUENCE;
}
// Setup for XML schema support only
final XMLGrammarPreparser parser = new XMLGrammarPreparser();
parser.registerPreparser(TYPE_XSD, null);
final List<Grammar> allGrammars = new ArrayList<>();
// iterate through the argument sequence and parse url
for (final SequenceIterator i = args[0].iterate(); i.hasNext(); ) {
String url = i.nextItem().getStringValue();
// Fix database urls
if (url.startsWith("/")) {
url = "xmldb:exist://" + url;
}
LOG.debug("Parsing {}", url);
// parse XSD grammar
try {
if (url.endsWith(".xsd")) {
final InputStream is = new URL(url).openStream();
final XMLInputSource xis = new XMLInputSource(null, url, url, is, null);
final Grammar schema = parser.preparseGrammar(TYPE_XSD, xis);
is.close();
allGrammars.add(schema);
} else {
throw new XPathException(this, "Only XMLSchemas can be preparsed.");
}
} catch (final Exception ex) {
LOG.debug(ex);
throw new XPathException(this, ex);
}
}
LOG.debug("Successfully parsed {} grammars.", allGrammars.size());
// Send all XSD grammars to grammarpool
Grammar[] grammars = new Grammar[allGrammars.size()];
grammars = allGrammars.toArray(grammars);
grammarpool.cacheGrammars(TYPE_XSD, grammars);
// Construct result to end user
final ValueSequence result = new ValueSequence();
for (final Grammar one : grammars) {
result.add(new StringValue(one.getGrammarDescription().getNamespace()));
}
return result;
} else {
// oh oh
LOG.error("function not found error");
throw new XPathException(this, "function not found");
}
}
use of org.exist.xquery.XPathException in project exist by eXist-db.
the class Jaxv method eval.
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
// Check input parameters
if (args.length != 2 && args.length != 3) {
return Sequence.EMPTY_SEQUENCE;
}
final ValidationReport report = new ValidationReport();
StreamSource instance = null;
StreamSource[] grammars = null;
String schemaLang = XMLConstants.W3C_XML_SCHEMA_NS_URI;
try {
report.start();
// Get inputstream for instance document
instance = Shared.getStreamSource(args[0].itemAt(0), context);
// Validate using resource speciefied in second parameter
grammars = Shared.getStreamSource(args[1], context);
// Check input
for (final StreamSource grammar : grammars) {
final String grammarUrl = grammar.getSystemId();
if (grammarUrl != null && !grammarUrl.endsWith(".xsd") && !grammarUrl.endsWith(".rng")) {
throw new XPathException("Only XML schemas (.xsd) and RELAXNG grammars (.rng) are supported" + ", depending on the used XML parser.");
}
}
// Fetch third argument if available, and override defailt value
if (args.length == 3) {
schemaLang = args[2].getStringValue();
}
// Get language specific factory
SchemaFactory factory = null;
try {
factory = SchemaFactory.newInstance(schemaLang);
} catch (final IllegalArgumentException ex) {
final String msg = "Schema language '" + schemaLang + "' is not supported. " + ex.getMessage();
LOG.error(msg);
throw new XPathException(msg);
}
// Create grammar
final Schema schema = factory.newSchema(grammars);
// Setup validator
final Validator validator = schema.newValidator();
validator.setErrorHandler(report);
// Perform validation
validator.validate(instance);
} catch (final MalformedURLException ex) {
LOG.error(ex.getMessage());
report.setException(ex);
} catch (final Throwable ex) {
LOG.error(ex);
report.setException(ex);
} finally {
report.stop();
Shared.closeStreamSource(instance);
Shared.closeStreamSources(grammars);
}
// Create response
if (isCalledAs("jaxv")) {
final Sequence result = new ValueSequence();
result.add(new BooleanValue(report.isValid()));
return result;
} else /* isCalledAs("jaxv-report") */
{
context.pushDocumentContext();
try {
final MemTreeBuilder builder = context.getDocumentBuilder();
final NodeImpl result = Shared.writeReport(report, builder);
return result;
} finally {
context.popDocumentContext();
}
}
}
Aggregations