use of org.exist.xquery.value.Sequence in project exist by eXist-db.
the class ApacheFopTest method simplePdf.
@Test
public void simplePdf() throws EXistException, PermissionDeniedException, XPathException {
final String fopConfig = "<fop version=\"1.0\">\n" + " <strict-configuration>true</strict-configuration>\n" + " <strict-validation>false</strict-validation>\n" + " <base>./</base>\n" + " <renderers>\n" + " <renderer mime=\"application/pdf\"></renderer>\n" + " </renderers>\n" + "</fop>";
final String fo = "<fo:root xmlns:fo=\"http://www.w3.org/1999/XSL/Format\">\n" + " <fo:layout-master-set>\n" + " <fo:simple-page-master master-name=\"page-left\" page-height=\"297mm\" page-width=\"210mm\" margin-bottom=\"10mm\" margin-top=\"10mm\" margin-left=\"36mm\" margin-right=\"18mm\">\n" + " <fo:region-body margin-bottom=\"10mm\" margin-top=\"16mm\"/>\n" + " <fo:region-before region-name=\"head-left\" extent=\"10mm\"/>\n" + " </fo:simple-page-master>\n" + " <fo:simple-page-master master-name=\"page-right\" page-height=\"297mm\" page-width=\"210mm\" margin-bottom=\"10mm\" margin-top=\"10mm\" margin-left=\"18mm\" margin-right=\"36mm\">\n" + " <fo:region-body margin-bottom=\"10mm\" margin-top=\"16mm\"/>\n" + " <fo:region-before region-name=\"head-right\" extent=\"10mm\"/>\n" + " </fo:simple-page-master>\n" + " <fo:page-sequence-master master-name=\"page-content\">\n" + " <fo:repeatable-page-master-alternatives>\n" + " <fo:conditional-page-master-reference master-reference=\"page-right\" odd-or-even=\"odd\"/>\n" + " <fo:conditional-page-master-reference master-reference=\"page-left\" odd-or-even=\"even\"/>\n" + " </fo:repeatable-page-master-alternatives>\n" + " </fo:page-sequence-master>\n" + " </fo:layout-master-set>\n" + " <fo:page-sequence master-reference=\"page-content\">\n" + " <fo:flow flow-name=\"xsl-region-body\" hyphenate=\"true\" language=\"en\" xml:lang=\"en\">\n" + " <fo:block id=\"A97060-t\" line-height=\"16pt\" font-size=\"11pt\">\n" + " <fo:block id=\"A97060-e0\" page-break-after=\"right\">\n" + " <fo:block id=\"A97060-e100\" text-align=\"justify\" space-before=\".5em\" text-indent=\"1.5em\" space-after=\".5em\">\n" + " Hello World!\n" + " </fo:block>\n" + " </fo:block>\n" + " </fo:block>\n" + " </fo:flow>\n" + " </fo:page-sequence>\n" + "</fo:root>";
final String xquery = "xquery version \"3.1\";\n" + "\n" + "import module namespace xslfo=\"http://exist-db.org/xquery/xslfo\";\n" + "\n" + "let $config := " + fopConfig + "\n" + "let $fo := " + fo + "\n" + "\n" + "let $pdf := xslfo:render($fo, \"application/pdf\", (), $config)\n" + "return $pdf";
final BrokerPool pool = server.getBrokerPool();
final XQuery xqueryService = pool.getXQueryService();
try (final DBBroker broker = pool.getBroker()) {
final Sequence result = xqueryService.execute(broker, xquery, null);
assertNotNull(result);
assertEquals(1, result.getItemCount());
final Item pdf = result.itemAt(0);
assertEquals(Type.BASE64_BINARY, pdf.getType());
}
}
use of org.exist.xquery.value.Sequence 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.value.Sequence in project exist by eXist-db.
the class XQueryServlet method process.
/**
* Processes incoming HTTP requests for XQuery.
*
* @param request the http request
* @param response the http response
*
* @throws ServletException if the servlet raises an exception
* @throws IOException if an I/O error occurs
*/
protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// first, adjust the path
String path = request.getPathTranslated();
if (path == null) {
path = request.getRequestURI().substring(request.getContextPath().length());
final int p = path.lastIndexOf(';');
if (p != Constants.STRING_NOT_FOUND) {
path = path.substring(0, p);
}
path = getServletContext().getRealPath(path);
}
// second, perform descriptor actions
final Descriptor descriptor = Descriptor.getDescriptorSingleton();
if (descriptor != null && !descriptor.requestsFiltered()) {
// logs the request if specified in the descriptor
descriptor.doLogRequestInReplayLog(request);
// map's the path if a mapping is specified in the descriptor
path = descriptor.mapPath(path);
}
// if (request.getCharacterEncoding() == null)
// try {
// request.setCharacterEncoding(formEncoding);
// } catch (IllegalStateException e) {
// }
final ServletOutputStream sout = response.getOutputStream();
final PrintWriter output = new PrintWriter(new OutputStreamWriter(sout, getFormEncoding()));
// response.setContentType(contentType + "; charset=" + formEncoding);
response.addHeader("pragma", "no-cache");
response.addHeader("Cache-Control", "no-cache");
String requestPath = request.getRequestURI();
final int p = requestPath.lastIndexOf('/');
if (p != Constants.STRING_NOT_FOUND) {
requestPath = requestPath.substring(0, p);
}
String moduleLoadPath;
final Object loadPathAttrib = request.getAttribute(ATTR_MODULE_LOAD_PATH);
if (loadPathAttrib != null) {
moduleLoadPath = getValue(loadPathAttrib);
} else {
moduleLoadPath = getServletContext().getRealPath(requestPath.substring(request.getContextPath().length()));
}
Subject user = getDefaultUser();
// to determine the user, first check the request attribute "xquery.user", then
// the current session attribute "user"
final Object userAttrib = request.getAttribute(ATTR_XQUERY_USER);
final HttpSession session = request.getSession(false);
if (userAttrib != null || (session != null && request.isRequestedSessionIdValid())) {
final Object passwdAttrib = request.getAttribute(ATTR_XQUERY_PASSWORD);
String username;
String password;
if (userAttrib != null) {
username = getValue(userAttrib);
password = getValue(passwdAttrib);
} else {
username = getSessionAttribute(session, "user");
password = getSessionAttribute(session, "password");
}
// TODO authentication should use super.authenticate(...) !!!
try {
if (username != null && password != null) {
Subject newUser = getPool().getSecurityManager().authenticate(username, password);
if (newUser != null && newUser.isAuthenticated()) {
user = newUser;
}
}
} catch (final AuthenticationException e) {
getLog().error("User can not be authenticated ({}).", username);
}
}
if (user == getDefaultUser()) {
Subject requestUser = HttpAccount.getUserFromServletRequest(request);
if (requestUser != null) {
user = requestUser;
} else {
requestUser = getAuthenticator().authenticate(request, response, false);
if (requestUser != null) {
user = requestUser;
}
}
}
Source source = null;
final Object sourceAttrib = request.getAttribute(ATTR_XQUERY_SOURCE);
final Object urlAttrib = request.getAttribute(ATTR_XQUERY_URL);
if (sourceAttrib != null) {
String s;
if (sourceAttrib instanceof Item)
try {
s = ((Item) sourceAttrib).getStringValue();
} catch (final XPathException e) {
throw new ServletException("Failed to read XQuery source string from " + "request attribute '" + ATTR_XQUERY_SOURCE + "': " + e.getMessage(), e);
}
else {
s = sourceAttrib.toString();
}
source = new StringSource(s);
} else if (urlAttrib != null) {
try (final DBBroker broker = getPool().get(Optional.ofNullable(user))) {
source = SourceFactory.getSource(broker, moduleLoadPath, urlAttrib.toString(), true);
if (source == null) {
final String msg = "Could not read source: context=" + moduleLoadPath + ", location=" + urlAttrib.toString();
getLog().error(msg);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
sendError(output, "Error", msg);
}
} catch (final Exception e) {
getLog().error(e.getMessage(), e);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
sendError(output, "Error", e.getMessage());
}
} else {
final Path f = Paths.get(path);
if (!Files.isReadable(f)) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
sendError(output, "Cannot read source file", path);
return;
}
source = new FileSource(f, Charset.forName(encoding), true);
}
if (source == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
sendError(output, "Source not found", path);
}
boolean reportErrors = false;
final String errorOpt = (String) request.getAttribute(ATTR_XQUERY_REPORT_ERRORS);
if (errorOpt != null) {
reportErrors = errorOpt.equalsIgnoreCase("YES");
}
// allow source viewing for GET?
if ("GET".equals(request.getMethod().toUpperCase())) {
String option;
boolean allowSource = false;
if ((option = request.getParameter("_source")) != null)
allowSource = "yes".equals(option);
// Should we display the source of the XQuery or execute it
if (allowSource && descriptor != null) {
// System.out.println("path="+path);
if (descriptor.allowSource(path)) {
if (source instanceof DBSource) {
try {
((DBSource) source).validate(user, Permission.READ);
} catch (final PermissionDeniedException e) {
if (getDefaultUser().equals(user)) {
getAuthenticator().sendChallenge(request, response);
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Permission to view XQuery source for: " + path + " denied. (no read access)");
}
return;
}
}
// Show the source of the XQuery
// writeResourceAs(resource, broker, stylesheet, encoding, "text/plain", outputProperties, response);
response.setContentType("text/plain; charset=" + getFormEncoding());
output.write(source.getContent());
output.flush();
return;
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Permission to view XQuery source for: " + path + " denied. Must be explicitly defined in descriptor.xml");
return;
}
}
}
// -------------------------------
// URI baseUri;
// try {
// baseUri = new URI(request.getScheme(),
// null/*user info?*/, request.getLocalPart(), request.getLocalPort(),
// request.getRequestURI(), null, null);
// } catch(URISyntaxException e) {
// baseUri = null;
// }
final String requestAttr = (String) request.getAttribute(ATTR_XQUERY_ATTRIBUTE);
try (final DBBroker broker = getPool().get(Optional.ofNullable(user))) {
final XQuery xquery = broker.getBrokerPool().getXQueryService();
CompiledXQuery query = getPool().getXQueryPool().borrowCompiledXQuery(broker, source);
XQueryContext context;
if (query == null) {
context = new XQueryContext(getPool());
context.setModuleLoadPath(moduleLoadPath);
try {
query = xquery.compile(context, source);
} catch (final XPathException ex) {
throw new EXistException("Cannot compile xquery: " + ex.getMessage(), ex);
} catch (final IOException ex) {
throw new EXistException("I/O exception while compiling xquery: " + ex.getMessage(), ex);
}
} else {
context = query.getContext();
context.setModuleLoadPath(moduleLoadPath);
context.prepareForReuse();
}
final Properties outputProperties = new Properties();
outputProperties.put("base-uri", collectionURI.toString());
final HttpRequestWrapper reqw = new HttpRequestWrapper(request, getFormEncoding(), getContainerEncoding());
final ResponseWrapper respw = new HttpResponseWrapper(response);
context.setHttpContext(new XQueryContext.HttpContext(reqw, respw, session != null ? new HttpSessionWrapper(session) : null));
final String timeoutOpt = (String) request.getAttribute(ATTR_TIMEOUT);
if (timeoutOpt != null) {
try {
final long timeout = Long.parseLong(timeoutOpt);
context.getWatchDog().setTimeout(timeout);
} catch (final NumberFormatException e) {
throw new EXistException("Bad timeout option: " + timeoutOpt);
}
}
final String maxNodesOpt = (String) request.getAttribute(ATTR_MAX_NODES);
if (maxNodesOpt != null) {
try {
final int maxNodes = Integer.parseInt(maxNodesOpt);
context.getWatchDog().setMaxNodes(maxNodes);
} catch (final NumberFormatException e) {
throw new EXistException("Bad max-nodes option: " + maxNodesOpt);
}
}
DebuggeeFactory.checkForDebugRequest(request, context);
Sequence resultSequence;
try {
resultSequence = xquery.execute(broker, query, null, outputProperties);
} finally {
context.runCleanupTasks();
getPool().getXQueryPool().returnCompiledXQuery(source, query);
}
final String mediaType = outputProperties.getProperty(OutputKeys.MEDIA_TYPE);
if (mediaType != null) {
if (!response.isCommitted()) {
if (MimeTable.getInstance().isTextContent(mediaType)) {
response.setContentType(mediaType + "; charset=" + getFormEncoding());
response.setCharacterEncoding(getFormEncoding());
} else
response.setContentType(mediaType);
}
} else {
String contentType = this.contentType;
try {
contentType = getServletContext().getMimeType(path);
if (contentType == null) {
contentType = this.contentType;
}
} catch (final Throwable e) {
contentType = this.contentType;
} finally {
if (MimeTable.getInstance().isTextContent(contentType)) {
contentType += "; charset=" + getFormEncoding();
}
response.setContentType(contentType);
}
}
if (requestAttr != null && (XmldbURI.API_LOCAL.equals(collectionURI.getApiName()))) {
request.setAttribute(requestAttr, resultSequence);
} else {
XQuerySerializer serializer = new XQuerySerializer(broker, outputProperties, output);
serializer.serialize(resultSequence);
}
} catch (final PermissionDeniedException e) {
if (getDefaultUser().equals(user)) {
getAuthenticator().sendChallenge(request, response);
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "No permission to execute XQuery for: " + path + " denied.");
}
return;
} catch (final XPathException e) {
final Logger logger = getLog();
if (logger.isDebugEnabled()) {
logger.debug(e.getMessage(), e);
}
if (reportErrors) {
writeError(output, e);
} else {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
sendError(output, "Error", e.getMessage());
}
} catch (final Throwable e) {
getLog().error(e.getMessage(), e);
if (reportErrors) {
writeError(output, e);
} else {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
sendError(output, "Error", e.getMessage());
}
}
output.flush();
output.close();
}
use of org.exist.xquery.value.Sequence 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.value.Sequence in project exist by eXist-db.
the class ExtTestFinishedFunction method eval.
@Override
public Sequence eval(final Sequence contextSequence, final Item contextItem) throws XPathException {
final Sequence arg1 = getCurrentArguments()[0];
final String name = arg1.itemAt(0).getStringValue();
// notify JUnit
notifier.fireTestFinished(Description.createTestDescription(suiteName, name, new Annotation[0]));
return Sequence.EMPTY_SEQUENCE;
}
Aggregations