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;
}
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);
}
}
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());
}
}
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);
}
}
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);
}
}
}
Aggregations