use of org.exist.xquery.value.Item in project exist by eXist-db.
the class InspectModuleTest method xqDoc_onAnnotatedFunction.
@Test
public void xqDoc_onAnnotatedFunction() throws PermissionDeniedException, XPathException, EXistException {
final BrokerPool pool = existEmbeddedServer.getBrokerPool();
final XQuery xqueryService = pool.getXQueryService();
try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
final Txn transaction = pool.getTransactionManager().beginTransaction()) {
final String query = "import module namespace inspect = \"http://exist-db.org/xquery/inspection\";\n" + "inspect:inspect-module(xs:anyURI(\"xmldb:exist://" + TEST_COLLECTION.append(TEST_MODULE).toCollectionPathURI() + "\"))\n" + "/function[@name eq \"x:fun4\"]";
final Sequence result = xqueryService.execute(broker, query, null);
assertNotNull(result);
assertEquals(1, result.getItemCount());
final Item item1 = result.itemAt(0);
assertTrue(item1 instanceof ElementImpl);
final Element function = (Element) item1;
final NodeList descriptions = function.getElementsByTagName("description");
assertEquals(1, descriptions.getLength());
assertEquals("An annotated function.", descriptions.item(0).getFirstChild().getNodeValue());
final NodeList annotations = function.getElementsByTagName("annotation");
assertEquals(2, annotations.getLength());
assertEquals("public", ((Element) annotations.item(0)).getAttribute("name"));
assertEquals("x:path", ((Element) annotations.item(1)).getAttribute("name"));
assertEquals("/x/y/z", annotations.item(1).getFirstChild().getFirstChild().getNodeValue());
final NodeList arguments = function.getElementsByTagName("argument");
assertEquals(0, arguments.getLength());
final NodeList returns = function.getElementsByTagName("returns");
assertEquals(1, returns.getLength());
assertEquals("another result", returns.item(0).getFirstChild().getNodeValue());
transaction.commit();
}
}
use of org.exist.xquery.value.Item in project exist by eXist-db.
the class InspectModuleTest method xqDoc_multilineDesciption.
@Test
public void xqDoc_multilineDesciption() throws PermissionDeniedException, XPathException, EXistException {
final BrokerPool pool = existEmbeddedServer.getBrokerPool();
final XQuery xqueryService = pool.getXQueryService();
try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
final Txn transaction = pool.getTransactionManager().beginTransaction()) {
final String query = "import module namespace inspect = \"http://exist-db.org/xquery/inspection\";\n" + "inspect:inspect-module(xs:anyURI(\"xmldb:exist://" + TEST_COLLECTION.append(TEST_MODULE).toCollectionPathURI() + "\"))\n" + "/function[@name eq \"x:fun3\"]";
final Sequence result = xqueryService.execute(broker, query, null);
assertNotNull(result);
assertEquals(1, result.getItemCount());
final Item item1 = result.itemAt(0);
assertTrue(item1 instanceof ElementImpl);
final Element function = (Element) item1;
final NodeList descriptions = function.getElementsByTagName("description");
assertEquals(1, descriptions.getLength());
assertEquals("This is a multiline description and therefore\n spans multiple\n lines.", descriptions.item(0).getFirstChild().getNodeValue());
final NodeList arguments = function.getElementsByTagName("argument");
assertEquals(0, arguments.getLength());
final NodeList returns = function.getElementsByTagName("returns");
assertEquals(1, returns.getLength());
assertEquals("another result", returns.item(0).getFirstChild().getNodeValue());
transaction.commit();
}
}
use of org.exist.xquery.value.Item in project exist by eXist-db.
the class CustomIndexTest method indexKeys.
@Test
public void indexKeys() throws SAXException, PermissionDeniedException, XPathException, EXistException {
final BrokerPool pool = existEmbeddedServer.getBrokerPool();
try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) {
XQuery xquery = pool.getXQueryService();
assertNotNull(xquery);
Sequence seq = xquery.execute(broker, "util:index-key-occurrences(/test/item, 'cha', 'ngram-index')", null);
// Sequence seq = xquery.execute("util:index-key-occurrences(/test/item, 'cha', 'org.exist.indexing.impl.NGramIndex')", null);
assertNotNull(seq);
assertEquals(1, seq.getItemCount());
seq = xquery.execute(broker, "util:index-key-occurrences(/test/item, 'le8', 'ngram-index')", null);
// seq = xquery.execute("util:index-key-occurrences(/test/item, 'le8', 'org.exist.indexing.impl.NGramIndex')", null);
assertNotNull(seq);
assertEquals(1, seq.getItemCount());
seq = xquery.execute(broker, "util:index-key-documents(/test/item, 'le8', 'ngram-index')", null);
// seq = xquery.execute("util:index-key-documents(/test/item, 'le8', 'org.exist.indexing.impl.NGramIndex')", null);
assertNotNull(seq);
assertEquals(1, seq.getItemCount());
seq = xquery.execute(broker, "util:index-key-documents(/test/item, 'le8', 'ngram-index')", null);
// seq = xquery.execute("util:index-key-doucments(/test/item, 'le8', 'org.exist.indexing.impl.NGramIndex')", null);
assertNotNull(seq);
assertEquals(1, seq.getItemCount());
String queryBody = "declare function local:callback($key as item(), $data as xs:int+)\n" + "as element()+ {\n" + " <item>\n" + " <key>{$key}</key>\n" + " <frequency>{$data[1]}</frequency>\n" + " </item>\n" + "};\n" + "\n";
String query = queryBody + "util:index-keys(/test/item, \'\', util:function(xs:QName(\'local:callback\'), 2), 1000, 'ngram-index')";
// String query = queryBody + "util:index-keys(/test/item, \'\', util:function(xs:QName(\'local:callback\'), 2), 1000, 'org.exist.indexing.impl.NGramIndex')";
seq = xquery.execute(broker, query, null);
assertNotNull(seq);
// TODO : check cardinality
StringWriter out = new StringWriter();
Properties props = new Properties();
props.setProperty(OutputKeys.INDENT, "yes");
SAXSerializer serializer = new SAXSerializer(out, props);
serializer.startDocument();
for (SequenceIterator i = seq.iterate(); i.hasNext(); ) {
Item next = i.nextItem();
next.toSAX(broker, serializer, props);
}
serializer.endDocument();
// TODO : check content
}
}
use of org.exist.xquery.value.Item in project exist by eXist-db.
the class XQueryURLRewrite method service.
@Override
protected void service(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException {
if (rewriteConfig == null) {
configure();
rewriteConfig = new RewriteConfig(this);
}
final long start = System.currentTimeMillis();
if (LOG.isTraceEnabled()) {
LOG.trace(request.getRequestURI());
}
final Descriptor descriptor = Descriptor.getDescriptorSingleton();
if (descriptor != null && descriptor.requestsFiltered()) {
final String attr = (String) request.getAttribute("XQueryURLRewrite.forwarded");
if (attr == null) {
// logs the request if specified in the descriptor
descriptor.doLogRequestInReplayLog(request);
request.setAttribute("XQueryURLRewrite.forwarded", "true");
}
}
Subject user = defaultUser;
Subject requestUser = HttpAccount.getUserFromServletRequest(request);
if (requestUser != null) {
user = requestUser;
} else {
// Secondly try basic authentication
final String auth = request.getHeader("Authorization");
if (auth != null) {
requestUser = authenticator.authenticate(request, response, sendChallenge);
if (requestUser != null) {
user = requestUser;
}
}
}
try {
configure();
// checkCache(user);
final RequestWrapper modifiedRequest = new RequestWrapper(request);
final URLRewrite staticRewrite = rewriteConfig.lookup(modifiedRequest);
if (staticRewrite != null && !staticRewrite.isControllerForward()) {
modifiedRequest.setPaths(staticRewrite.resolve(modifiedRequest), staticRewrite.getPrefix());
if (LOG.isTraceEnabled()) {
LOG.trace("Forwarding to target: {}", staticRewrite.getTarget());
}
staticRewrite.doRewrite(modifiedRequest, response);
} else {
if (LOG.isTraceEnabled()) {
LOG.trace("Processing request URI: {}", request.getRequestURI());
}
if (staticRewrite != null) {
// fix the request URI
staticRewrite.updateRequest(modifiedRequest);
}
// check if the request URI is already in the url cache
ModelAndView modelView = getFromCache(request.getHeader("Host") + request.getRequestURI(), user);
if (LOG.isDebugEnabled()) {
LOG.debug("Checked cache for URI: {} original: {}", modifiedRequest.getRequestURI(), request.getRequestURI());
}
// no: create a new model and view configuration
if (modelView == null) {
modelView = new ModelAndView();
// Execute the query
try (final DBBroker broker = pool.get(Optional.ofNullable(user))) {
modifiedRequest.setAttribute(RQ_ATTR_REQUEST_URI, request.getRequestURI());
final Properties outputProperties = new Properties();
outputProperties.setProperty(OutputKeys.INDENT, "yes");
outputProperties.setProperty(OutputKeys.ENCODING, "UTF-8");
outputProperties.setProperty(OutputKeys.MEDIA_TYPE, MimeType.XML_TYPE.getName());
final Sequence result = runQuery(broker, modifiedRequest, response, modelView, staticRewrite, outputProperties);
logResult(broker, result);
if (response.isCommitted()) {
return;
}
// process the query result
if (result.getItemCount() == 1) {
final Item resource = result.itemAt(0);
if (!Type.subTypeOf(resource.getType(), Type.NODE)) {
throw new ServletException("XQueryURLRewrite: urlrewrite query should return an element!");
}
Node node = ((NodeValue) resource).getNode();
if (node.getNodeType() == Node.DOCUMENT_NODE) {
node = ((Document) node).getDocumentElement();
}
if (node.getNodeType() != Node.ELEMENT_NODE) {
// throw new ServletException("Redirect XQuery should return an XML element!");
response(broker, response, outputProperties, result);
return;
}
Element elem = (Element) node;
final String ns = elem.getNamespaceURI();
if (!Namespaces.EXIST_NS.equals(ns)) {
response(broker, response, outputProperties, result);
return;
}
final String nsUri = elem.getNamespaceURI();
if (Namespaces.EXIST_NS.equals(nsUri) && "dispatch".equals(elem.getLocalName())) {
node = elem.getFirstChild();
while (node != null) {
final String nodeNs = node.getNamespaceURI();
if (node.getNodeType() == Node.ELEMENT_NODE && Namespaces.EXIST_NS.equals(nodeNs)) {
final Element action = (Element) node;
if ("view".equals(action.getLocalName())) {
parseViews(modifiedRequest, action, modelView);
} else if ("error-handler".equals(action.getLocalName())) {
parseErrorHandlers(modifiedRequest, action, modelView);
} else if ("cache-control".equals(action.getLocalName())) {
final String option = action.getAttribute("cache");
modelView.setUseCache("yes".equals(option));
} else {
final URLRewrite urw = parseAction(modifiedRequest, action);
if (urw != null) {
modelView.setModel(urw);
}
}
}
node = node.getNextSibling();
}
if (modelView.getModel() == null) {
modelView.setModel(new PassThrough(config, elem, modifiedRequest));
}
} else if (nsUri != null && Namespaces.EXIST_NS.equals(elem.getNamespaceURI()) && "ignore".equals(elem.getLocalName())) {
modelView.setModel(new PassThrough(config, elem, modifiedRequest));
final NodeList nl = elem.getElementsByTagNameNS(Namespaces.EXIST_NS, "cache-control");
if (nl.getLength() > 0) {
elem = (Element) nl.item(0);
final String option = elem.getAttribute("cache");
modelView.setUseCache("yes".equals(option));
}
} else {
response(broker, response, outputProperties, result);
return;
}
} else if (result.getItemCount() > 1) {
response(broker, response, outputProperties, result);
return;
}
if (modelView.useCache()) {
LOG.debug("Caching request to {}", request.getRequestURI());
urlCache.put(modifiedRequest.getHeader("Host") + request.getRequestURI(), modelView);
}
}
// store the original request URI to org.exist.forward.request-uri
modifiedRequest.setAttribute(RQ_ATTR_REQUEST_URI, request.getRequestURI());
modifiedRequest.setAttribute(RQ_ATTR_SERVLET_PATH, request.getServletPath());
}
if (LOG.isTraceEnabled()) {
LOG.trace("URLRewrite took {}ms.", System.currentTimeMillis() - start);
}
final HttpServletResponse wrappedResponse = new CachingResponseWrapper(response, modelView.hasViews() || modelView.hasErrorHandlers());
if (modelView.getModel() == null) {
modelView.setModel(new PassThrough(config, modifiedRequest));
}
if (staticRewrite != null) {
if (modelView.getModel().doResolve()) {
staticRewrite.rewriteRequest(modifiedRequest);
} else {
modelView.getModel().setAbsolutePath(modifiedRequest);
}
}
modifiedRequest.allowCaching(!modelView.hasViews());
doRewrite(modelView.getModel(), modifiedRequest, wrappedResponse);
final int status = wrappedResponse.getStatus();
if (status == HttpServletResponse.SC_NOT_MODIFIED) {
response.flushBuffer();
} else if (status < HttpServletResponse.SC_BAD_REQUEST) {
if (modelView.hasViews()) {
applyViews(modelView, modelView.views, response, modifiedRequest, wrappedResponse);
} else {
((CachingResponseWrapper) wrappedResponse).flush();
}
} else {
// HTTP response code indicates an error
if (modelView.hasErrorHandlers()) {
final byte[] data = ((CachingResponseWrapper) wrappedResponse).getData();
if (data != null) {
modifiedRequest.setAttribute(RQ_ATTR_ERROR, new String(data, UTF_8));
}
applyViews(modelView, modelView.errorHandlers, response, modifiedRequest, wrappedResponse);
} else {
flushError(response, wrappedResponse);
}
}
}
} catch (final Throwable e) {
LOG.error("Error while processing {}: {}", request.getRequestURI(), e.getMessage(), e);
throw new ServletException("An error occurred while processing request to " + request.getRequestURI() + ": " + e.getMessage(), e);
}
}
use of org.exist.xquery.value.Item in project exist by eXist-db.
the class ElementConstructor method eval.
@Override
public Sequence eval(final Sequence contextSequence, final Item contextItem) throws XPathException {
context.expressionStart(this);
context.pushInScopeNamespaces();
if (newDocumentContext) {
context.pushDocumentContext();
}
try {
final MemTreeBuilder builder = context.getDocumentBuilder();
// declare namespaces
if (namespaceDecls != null) {
for (QName namespaceDecl : namespaceDecls) {
// if ("".equals(namespaceDecls[i].getNamespaceURI())) {
// TODO: the specs are unclear here: should we throw XQST0085 or not?
// context.inScopeNamespaces.remove(namespaceDecls[i].getLocalPart());
// if (context.inScopeNamespaces.remove(namespaceDecls[i].getLocalPart()) == null)
// throw new XPathException(getAS TNode(), "XQST0085 : can not undefine '" + namespaceDecls[i] + "'");
// } else
context.declareInScopeNamespace(namespaceDecl.getLocalPart(), namespaceDecl.getNamespaceURI());
}
}
// process attributes
final AttributesImpl attrs = new AttributesImpl();
if (attributes != null) {
// first, search for xmlns attributes and declare in-scope namespaces
for (final AttributeConstructor constructor : attributes) {
if (constructor.isNamespaceDeclaration()) {
final int p = constructor.getQName().indexOf(':');
if (p == Constants.STRING_NOT_FOUND) {
context.declareInScopeNamespace(XMLConstants.DEFAULT_NS_PREFIX, constructor.getLiteralValue());
} else {
final String prefix = constructor.getQName().substring(p + 1);
context.declareInScopeNamespace(prefix, constructor.getLiteralValue());
}
}
}
String v = null;
// process the remaining attributes
for (int i = 0; i < attributes.length; i++) {
context.proceed(this, builder);
final AttributeConstructor constructor = attributes[i];
final Sequence attrValues = constructor.eval(contextSequence, contextItem);
QName attrQName;
try {
attrQName = QName.parse(context, constructor.getQName(), XMLConstants.NULL_NS_URI);
} catch (final QName.IllegalQNameException e) {
throw new XPathException(this, ErrorCodes.XPTY0004, "'" + constructor.getQName() + "' is not a valid attribute name");
}
final String namespaceURI = attrQName.getNamespaceURI();
if (namespaceURI != null && !namespaceURI.isEmpty() && attrQName.getPrefix() == null) {
String prefix = context.getPrefixForURI(namespaceURI);
if (prefix != null) {
attrQName = new QName(attrQName.getLocalPart(), attrQName.getNamespaceURI(), prefix);
} else {
// generate prefix
for (final int n = 1; i < 100; i++) {
prefix = "eXnsp" + n;
if (context.getURIForPrefix(prefix) == null) {
attrQName = new QName(attrQName.getLocalPart(), attrQName.getNamespaceURI(), prefix);
break;
}
prefix = null;
}
if (prefix == null) {
throw new XPathException(this, "Prefix can't be generated.");
}
}
}
if (attrs.getIndex(attrQName.getNamespaceURI(), attrQName.getLocalPart()) != -1) {
throw new XPathException(this, ErrorCodes.XQST0040, "'" + attrQName.getLocalPart() + "' is a duplicate attribute name");
}
v = DynamicAttributeConstructor.normalize(this, attrQName, attrValues.getStringValue());
attrs.addAttribute(attrQName.getNamespaceURI(), attrQName.getLocalPart(), attrQName.getStringValue(), "CDATA", v);
}
}
context.proceed(this, builder);
// create the element
final Sequence qnameSeq = qnameExpr.eval(contextSequence, contextItem);
if (!qnameSeq.hasOne()) {
throw new XPathException(this, ErrorCodes.XPTY0004, "Type error: the node name should evaluate to a single item");
}
final Item qnitem = qnameSeq.itemAt(0);
QName qn;
if (qnitem instanceof QNameValue) {
qn = ((QNameValue) qnitem).getQName();
} else {
// Do we have the same result than Atomize there ? -pb
try {
qn = QName.parse(context, qnitem.getStringValue());
} catch (final QName.IllegalQNameException e) {
throw new XPathException(this, ErrorCodes.XPTY0004, "'" + qnitem.getStringValue() + "' is not a valid element name");
} catch (final XPathException e) {
e.setLocation(getLine(), getColumn(), getSource());
throw e;
}
/*
if (qn.getPrefix() == null && context.inScopeNamespaces.get("xmlns") != null) {
qn.setNamespaceURI((String)context.inScopeNamespaces.get("xmlns"));
}
*/
if (qn.getPrefix() == null && context.getInScopeNamespace(XMLConstants.DEFAULT_NS_PREFIX) != null) {
qn = new QName(qn.getLocalPart(), context.getInScopeNamespace(XMLConstants.DEFAULT_NS_PREFIX), qn.getPrefix());
}
}
// Not in the specs but... makes sense
if (!XMLNames.isName(qn.getLocalPart())) {
throw new XPathException(this, ErrorCodes.XPTY0004, "'" + qnitem.getStringValue() + "' is not a valid element name");
}
// add namespace declaration nodes
final int nodeNr = builder.startElement(qn, attrs);
if (namespaceDecls != null) {
for (QName namespaceDecl : namespaceDecls) {
builder.namespaceNode(namespaceDecl);
}
}
// do we need to add a namespace declaration for the current node?
if (qn.hasNamespace()) {
if (context.getInScopePrefix(qn.getNamespaceURI()) == null) {
String prefix = qn.getPrefix();
if (prefix == null) {
prefix = XMLConstants.DEFAULT_NS_PREFIX;
}
context.declareInScopeNamespace(prefix, qn.getNamespaceURI());
builder.namespaceNode(new QName(prefix, qn.getNamespaceURI(), XMLConstants.XMLNS_ATTRIBUTE));
}
} else if ((qn.getPrefix() == null || qn.getPrefix().length() == 0) && context.getInheritedNamespace(XMLConstants.DEFAULT_NS_PREFIX) != null) {
context.declareInScopeNamespace(XMLConstants.DEFAULT_NS_PREFIX, XMLConstants.NULL_NS_URI);
builder.namespaceNode(new QName("", XMLConstants.NULL_NS_URI, XMLConstants.XMLNS_ATTRIBUTE));
} else if (qn.getPrefix() == null || qn.getPrefix().length() == 0) {
context.declareInScopeNamespace(XMLConstants.DEFAULT_NS_PREFIX, XMLConstants.NULL_NS_URI);
}
// process element contents
if (content != null) {
content.eval(contextSequence, contextItem);
}
builder.endElement();
final NodeImpl node = builder.getDocument().getNode(nodeNr);
return node;
} finally {
context.popInScopeNamespaces();
if (newDocumentContext) {
context.popDocumentContext();
}
context.expressionEnd(this);
}
}
Aggregations