final Collection collection = broker.getCollection(XmldbURI.create(request.getPath()));
if (collection == null)
{throw new BadRequestException("Collection " + request.getPath() + " does not exist.");}
final XQuery xquery = broker.getXQueryService();
CompiledXQuery feedQuery = xquery.getXQueryPool().borrowCompiledXQuery(broker, config.querySource);
XQueryContext context;
if (feedQuery == null) {
context = xquery.newContext(AccessContext.REST);
context.setModuleLoadPath(getContext().getModuleLoadPath());
try {
feedQuery = xquery.compile(context, config.querySource);
} catch (final XPathException ex) {
throw new EXistException("Cannot compile xquery "
+ config.querySource.getURL(), ex);
} catch (final IOException ex) {
throw new EXistException(
"I/O exception while compiling xquery "
+ config.querySource.getURL(), ex);
}
} else {
context = feedQuery.getContext();
context.setModuleLoadPath(getContext().getModuleLoadPath());
}
context.setStaticallyKnownDocuments(new XmldbURI[] { XmldbURI.create(
request.getPath()).append(AtomProtocol.FEED_DOCUMENT_NAME) });
try {
declareVariables(context, request.getRequest(), response.getResponse());
final Sequence resultSequence = xquery.execute(feedQuery, null);
if (resultSequence.isEmpty())
{throw new BadRequestException("No topic was found.");}
final String charset = getContext().getDefaultCharset();
response.setStatusCode(200);
response.setContentType(config.contentType + "; charset=" + charset);
final Serializer serializer = broker.getSerializer();
serializer.reset();
try {
final Writer w = new OutputStreamWriter(response.getOutputStream(), charset);
final SAXSerializer sax = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
final Properties outputProperties = new Properties();
sax.setOutput(w, outputProperties);
serializer.setProperties(outputProperties);
serializer.setSAXHandlers(sax, sax);
serializer.toSAX(resultSequence, 1, 1, false, false);
SerializerPool.getInstance().returnObject(sax);
w.flush();
w.close();
} catch (final IOException ex) {
LOG.fatal("Cannot read resource " + request.getPath(), ex);
throw new EXistException("I/O error on read of resource "
+ request.getPath(), ex);
} catch (final SAXException saxe) {
LOG.warn(saxe);
throw new BadRequestException("Error while serializing XML: "
+ saxe.getMessage());
}
resultSequence.itemAt(0);
} catch (final XPathException ex) {
throw new EXistException("Cannot execute xquery "
+ config.querySource.getURL(), ex);
} finally {
xquery.getXQueryPool().returnCompiledXQuery(config.querySource,
feedQuery);
}
}