Search in sources :

Example 71 with XPathException

use of org.exist.xquery.XPathException in project exist by eXist-db.

the class AddMatch method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    if (args[0].isEmpty()) {
        return args[0];
    }
    final NodeValue nv = (NodeValue) args[0].itemAt(0);
    if (!nv.isPersistentSet()) {
        return nv;
    }
    final NodeProxy node = (NodeProxy) nv;
    final int thisLevel = node.getNodeId().getTreeLevel();
    String matchStr = null;
    NodeId nodeId = null;
    try {
        for (final XMLStreamReader reader = context.getBroker().getXMLStreamReader(node, true); reader.hasNext(); ) {
            final int status = reader.next();
            if (status == XMLStreamConstants.CHARACTERS) {
                matchStr = reader.getText();
                nodeId = (NodeId) reader.getProperty(ExtendedXMLStreamReader.PROPERTY_NODE_ID);
                break;
            }
            final NodeId otherId = (NodeId) reader.getProperty(ExtendedXMLStreamReader.PROPERTY_NODE_ID);
            final int otherLevel = otherId.getTreeLevel();
            if (status == XMLStreamConstants.END_ELEMENT && otherLevel == thisLevel) {
                // exit-for
                break;
            }
        }
    } catch (IOException | XMLStreamException e) {
        throw new XPathException(this, ErrorCodes.FOER0000, "Exception caught while reading document");
    }
    if (nodeId != null) {
        Match match = new NGramMatch(getContextId(), node.getNodeId(), matchStr);
        match.addOffset(0, matchStr.length());
        node.addMatch(match);
    }
    return node;
}
Also used : NodeValue(org.exist.xquery.value.NodeValue) XMLStreamReader(javax.xml.stream.XMLStreamReader) ExtendedXMLStreamReader(org.exist.stax.ExtendedXMLStreamReader) XMLStreamException(javax.xml.stream.XMLStreamException) XPathException(org.exist.xquery.XPathException) NodeId(org.exist.numbering.NodeId) NGramMatch(org.exist.indexing.ngram.NGramMatch) IOException(java.io.IOException) NodeProxy(org.exist.dom.persistent.NodeProxy) Match(org.exist.dom.persistent.Match) NGramMatch(org.exist.indexing.ngram.NGramMatch)

Example 72 with XPathException

use of org.exist.xquery.XPathException in project exist by eXist-db.

the class AccountFunctions method getLdapRealm.

private LDAPRealm getLdapRealm(final SecurityManager sm) throws XPathException {
    try {
        final Method mFindRealm = sm.getClass().getDeclaredMethod("findRealmForRealmId", String.class);
        mFindRealm.setAccessible(true);
        final Realm realm = (Realm) mFindRealm.invoke(sm, LDAPRealm.ID);
        if (realm == null) {
            throw new XPathException("The LDAP Realm is not in use!");
        }
        return (LDAPRealm) realm;
    } catch (final NoSuchMethodException ex) {
        throw new XPathException(this, "The LDAP Realm is not in use!", ex);
    } catch (final SecurityException | IllegalArgumentException | IllegalAccessException se) {
        throw new XPathException(this, "Permission to access the LDAP Realm is denied: " + se.getMessage(), se);
    } catch (final InvocationTargetException ite) {
        throw new XPathException(this, "An error occured whilst accessing the LDAP Realm: " + ite.getMessage(), ite);
    }
}
Also used : LDAPRealm(org.exist.security.realm.ldap.LDAPRealm) XPathException(org.exist.xquery.XPathException) Method(java.lang.reflect.Method) LDAPRealm(org.exist.security.realm.ldap.LDAPRealm) Realm(org.exist.security.realm.Realm) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 73 with XPathException

use of org.exist.xquery.XPathException in project exist by eXist-db.

the class IPRangeRealm method authenticate.

@Override
public Subject authenticate(final String ipAddress, final Object credentials) throws AuthenticationException {
    // Elevaste to system privileges
    try (final DBBroker broker = getSecurityManager().database().get(Optional.of(getSecurityManager().getSystemSubject()))) {
        // Convert IP address
        final long ipToTest = ipToLong(InetAddress.getByName(ipAddress));
        // Get xquery service
        final XQuery queryService = broker.getBrokerPool().getXQueryService();
        if (queryService == null) {
            LOG.error("IPRange broker unable to retrieve XQueryService");
            return null;
        }
        // Construct XQuery
        final String query = "collection('/db/system/security/iprange/accounts')/account/" + "iprange[" + ipToTest + " ge number(start) and " + ipToTest + " le number(end)]/../name";
        final XQueryContext context = new XQueryContext(broker.getBrokerPool());
        final CompiledXQuery compiled = queryService.compile(context, query);
        final Properties outputProperties = new Properties();
        // Execute xQuery
        final Sequence result = queryService.execute(broker, compiled, null, outputProperties);
        final SequenceIterator i = result.iterate();
        // Get FIRST username when present
        final String username = i.hasNext() ? i.nextItem().getStringValue() : "";
        if (i.hasNext()) {
            LOG.warn("IP address {} matched multiple ipranges. Using first result only.", ipAddress);
        }
        if (!username.isEmpty()) {
            final Account account = getSecurityManager().getAccount(username);
            if (account != null) {
                LOG.info("IPRangeRealm trying {}", account.getName());
                return new SubjectAccreditedImpl((AbstractAccount) account, ipAddress);
            } else {
                LOG.info("IPRangeRealm couldn't resolve account for {}", username);
            }
        } else {
            LOG.info("IPRangeRealm xquery found no matches");
        }
        return null;
    } catch (final EXistException | UnknownHostException | XPathException | PermissionDeniedException e) {
        throw new AuthenticationException(AuthenticationException.UNNOWN_EXCEPTION, e.getMessage());
    }
}
Also used : UnknownHostException(java.net.UnknownHostException) XPathException(org.exist.xquery.XPathException) CompiledXQuery(org.exist.xquery.CompiledXQuery) XQuery(org.exist.xquery.XQuery) CompiledXQuery(org.exist.xquery.CompiledXQuery) XQueryContext(org.exist.xquery.XQueryContext) Sequence(org.exist.xquery.value.Sequence) EXistException(org.exist.EXistException) Properties(java.util.Properties) DBBroker(org.exist.storage.DBBroker) SequenceIterator(org.exist.xquery.value.SequenceIterator) SubjectAccreditedImpl(org.exist.security.internal.SubjectAccreditedImpl)

Example 74 with XPathException

use of org.exist.xquery.XPathException in project exist by eXist-db.

the class RedirectorServlet method service.

@Override
protected void service(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException {
    final RequestWrapper request = new HttpRequestWrapper(req);
    final ResponseWrapper response = new HttpResponseWrapper(res);
    if (request.getCharacterEncoding() == null)
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (final IllegalStateException e) {
        }
    // Try to find the XQuery
    final String qpath = getServletContext().getRealPath(query);
    final Path p = Paths.get(qpath);
    if (!(Files.isReadable(p) && Files.isRegularFile(p))) {
        throw new ServletException("Cannot read XQuery source from " + p.toAbsolutePath());
    }
    final FileSource source = new FileSource(p, true);
    try {
        // Prepare and execute the XQuery
        final Sequence result = executeQuery(source, request, response);
        String redirectTo = null;
        String servletName = null;
        String path = null;
        ModifiableRequestWrapper modifiedRequest = null;
        // parse the query result element
        if (result != null && result.getItemCount() == 1) {
            Node node = (Node) result.itemAt(0);
            if (node.getNodeType() == Node.DOCUMENT_NODE) {
                node = ((Document) node).getDocumentElement();
            }
            if (node.getNodeType() != Node.ELEMENT_NODE) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Redirect XQuery should return an XML element. Received: " + node);
                return;
            }
            Element elem = (Element) node;
            final String ns = elem.getNamespaceURI();
            if (ns == null || ((!Namespaces.EXIST_NS.equals(ns)) && "dispatch".equals(elem.getLocalName()))) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Redirect XQuery should return an element <exist:dispatch>. Received: " + node);
                return;
            }
            if (elem.hasAttribute("path")) {
                path = elem.getAttribute("path");
            } else if (elem.hasAttribute("servlet-name")) {
                servletName = elem.getAttribute("servlet-name");
            } else if (elem.hasAttribute("redirect")) {
                redirectTo = elem.getAttribute("redirect");
            } else {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Element <exist:dispatch> should either provide an attribute 'path' or 'servlet-name'. Received: " + node);
                return;
            }
            // Check for add-parameter elements etc.
            if (elem.hasChildNodes()) {
                node = elem.getFirstChild();
                while (node != null) {
                    final String nsUri = node.getNamespaceURI();
                    if (node.getNodeType() == Node.ELEMENT_NODE && nsUri != null && Namespaces.EXIST_NS.equals(nsUri)) {
                        elem = (Element) node;
                        if ("add-parameter".equals(elem.getLocalName())) {
                            if (modifiedRequest == null) {
                                modifiedRequest = new ModifiableRequestWrapper(req);
                            }
                            modifiedRequest.addParameter(elem.getAttribute("name"), elem.getAttribute("value"));
                        }
                    }
                    node = node.getNextSibling();
                }
            }
        }
        if (redirectTo != null) {
            // directly redirect to the specified URI
            response.sendRedirect(redirectTo);
            return;
        }
        // Get a RequestDispatcher, either from the servlet context or the request
        RequestDispatcher dispatcher;
        if (servletName != null && servletName.length() > 0) {
            dispatcher = getServletContext().getNamedDispatcher(servletName);
        } else {
            LOG.debug("Dispatching to {}", path);
            dispatcher = getServletContext().getRequestDispatcher(path);
            if (dispatcher == null) {
                dispatcher = request.getRequestDispatcher(path);
            }
        }
        if (dispatcher == null) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not create a request dispatcher. Giving up.");
            return;
        }
        if (modifiedRequest != null) {
            // store the original request URI to org.exist.forward.request-uri
            modifiedRequest.setAttribute("org.exist.forward.request-uri", modifiedRequest.getRequestURI());
            modifiedRequest.setAttribute("org.exist.forward.servlet-path", modifiedRequest.getServletPath());
            // finally, execute the forward
            dispatcher.forward(modifiedRequest, res);
        } else {
            // store the original request URI to org.exist.forward.request-uri
            request.setAttribute("org.exist.forward.request-uri", request.getRequestURI());
            request.setAttribute("org.exist.forward.servlet-path", request.getServletPath());
            // finally, execute the forward
            dispatcher.forward(req, res);
        }
    } catch (final XPathException | EXistException | PermissionDeniedException | IOException e) {
        throw new ServletException("An error occurred while executing the RedirectorServlet XQuery: " + e.getMessage(), e);
    }
}
Also used : Path(java.nio.file.Path) XPathException(org.exist.xquery.XPathException) FileSource(org.exist.source.FileSource) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) Sequence(org.exist.xquery.value.Sequence) EXistException(org.exist.EXistException) IOException(java.io.IOException) RequestDispatcher(javax.servlet.RequestDispatcher) ServletException(javax.servlet.ServletException) PermissionDeniedException(org.exist.security.PermissionDeniedException)

Example 75 with XPathException

use of org.exist.xquery.XPathException in project exist by eXist-db.

the class XQueryCompilationTest method executeQuery.

protected static Either<XPathException, Sequence> executeQuery(final String string) throws EXistException, PermissionDeniedException {
    final BrokerPool pool = server.getBrokerPool();
    final XQuery xqueryService = pool.getXQueryService();
    try (final DBBroker broker = pool.getBroker()) {
        try {
            return Right(xqueryService.execute(broker, string, null));
        } catch (final XPathException e) {
            return Left(e);
        }
    }
}
Also used : DBBroker(org.exist.storage.DBBroker) XPathException(org.exist.xquery.XPathException) CompiledXQuery(org.exist.xquery.CompiledXQuery) XQuery(org.exist.xquery.XQuery) BrokerPool(org.exist.storage.BrokerPool)

Aggregations

XPathException (org.exist.xquery.XPathException)306 Sequence (org.exist.xquery.value.Sequence)86 IOException (java.io.IOException)61 SAXException (org.xml.sax.SAXException)43 StringValue (org.exist.xquery.value.StringValue)40 PermissionDeniedException (org.exist.security.PermissionDeniedException)34 NodeValue (org.exist.xquery.value.NodeValue)34 DBBroker (org.exist.storage.DBBroker)32 IntegerValue (org.exist.xquery.value.IntegerValue)32 ValueSequence (org.exist.xquery.value.ValueSequence)27 Item (org.exist.xquery.value.Item)26 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)24 EXistException (org.exist.EXistException)23 Path (java.nio.file.Path)22 XmldbURI (org.exist.xmldb.XmldbURI)22 BrokerPool (org.exist.storage.BrokerPool)21 Txn (org.exist.storage.txn.Txn)21 XQueryContext (org.exist.xquery.XQueryContext)21 Element (org.w3c.dom.Element)21 XQuery (org.exist.xquery.XQuery)20