use of org.exist.util.serializer.SerializerPool in project exist by eXist-db.
the class Stream method eval.
@Override
public Sequence eval(final Sequence[] args, @Nonnull final ResponseWrapper response) throws XPathException {
if (args[0].isEmpty()) {
return Sequence.EMPTY_SEQUENCE;
}
final Sequence inputNode = args[0];
final Properties serializeOptions = new Properties();
final String serOpts = args[1].getStringValue();
final String[] contents = Option.tokenize(serOpts);
for (String content : contents) {
final String[] pair = Option.parseKeyValuePair(content);
if (pair == null) {
throw new XPathException(this, "Found invalid serialization option: " + content);
}
if (LOG.isDebugEnabled()) {
logger.debug("Setting serialization property: {} = {}", pair[0], pair[1]);
}
serializeOptions.setProperty(pair[0], pair[1]);
}
if (!"org.exist.http.servlets.HttpResponseWrapper".equals(response.getClass().getName())) {
throw new XPathException(this, ErrorCodes.XPDY0002, signature.toString() + " can only be used within the EXistServlet or XQueryServlet");
}
final String mediaType = serializeOptions.getProperty("media-type", "application/xml");
final String encoding = serializeOptions.getProperty("encoding", "UTF-8");
if (mediaType != null) {
response.setContentType(mediaType + "; charset=" + encoding);
}
try {
final BrokerPool db = BrokerPool.getInstance();
try (final DBBroker broker = db.getBroker();
final PrintWriter output = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), encoding))) {
final Serializer serializer = broker.borrowSerializer();
final SerializerPool serializerPool = SerializerPool.getInstance();
final SAXSerializer sax = (SAXSerializer) serializerPool.borrowObject(SAXSerializer.class);
try {
sax.setOutput(output, serializeOptions);
serializer.setProperties(serializeOptions);
serializer.setSAXHandlers(sax, sax);
serializer.toSAX(inputNode, 1, inputNode.getItemCount(), false, false, 0, 0);
} catch (final SAXException e) {
e.printStackTrace();
throw new IOException(e);
} finally {
serializerPool.returnObject(sax);
broker.returnSerializer(serializer);
}
output.flush();
}
// commit the response
response.flushBuffer();
} catch (final IOException e) {
throw new XPathException(this, "IO exception while streaming node: " + e.getMessage(), e);
} catch (final EXistException e) {
throw new XPathException(this, "Exception while streaming node: " + e.getMessage(), e);
}
return Sequence.EMPTY_SEQUENCE;
}
Aggregations