use of org.exist.xmldb.XmldbURI in project exist by eXist-db.
the class BinaryDocument method read.
/**
* Deserialize the document object from bytes.
*
* @param pool the database
* @param istream the byte stream to read
*
* @return the document object.
* @throws IOException in case of an I/O error
*/
public static BinaryDocument read(final BrokerPool pool, final VariableByteInput istream) throws IOException {
final int docId = istream.readInt();
final XmldbURI fileURI = XmldbURI.create(istream.readUTF());
final byte[] blobIdRaw = new byte[istream.readInt()];
istream.read(blobIdRaw);
final BlobId blobId = new BlobId(blobIdRaw);
final Permission permissions = PermissionFactory.getDefaultResourcePermission(pool.getSecurityManager());
permissions.read(istream);
final long realSize = istream.readLong();
// load document attributes
final long created = istream.readLong();
final long lastModified = istream.readLong();
final int mimeTypeSymbolsIndex = istream.readInt();
final String mimeType = pool.getSymbols().getMimeType(mimeTypeSymbolsIndex);
final int pageCount = istream.readInt();
final int userLock = istream.readInt();
final DocumentTypeImpl docType;
if (istream.readByte() == HAS_DOCTYPE) {
docType = DocumentTypeImpl.read(istream);
} else {
docType = null;
}
final LockToken lockToken;
if (istream.readByte() == HAS_LOCKTOKEN) {
lockToken = LockToken.read(istream);
} else {
lockToken = null;
}
final BinaryDocument doc = new BinaryDocument(pool, null, docId, fileURI, blobId, permissions, realSize, created, lastModified, mimeType, docType);
doc.pageCount = pageCount;
doc.userLock = userLock;
doc.lockToken = lockToken;
return doc;
}
use of org.exist.xmldb.XmldbURI in project exist by eXist-db.
the class XQueryURLRewrite method getSource.
private SourceInfo getSource(final DBBroker broker, final String moduleLoadPath) throws ServletException {
final SourceInfo sourceInfo;
if (query.startsWith(XmldbURI.XMLDB_URI_PREFIX)) {
// Is the module source stored in the database?
try {
final XmldbURI locationUri = XmldbURI.xmldbUriFor(query);
try (final LockedDocument lockedSourceDoc = broker.getXMLResource(locationUri.toCollectionPathURI(), LockMode.READ_LOCK)) {
if (lockedSourceDoc == null) {
throw new ServletException("XQuery resource: " + query + " not found in database");
}
final DocumentImpl sourceDoc = lockedSourceDoc.getDocument();
if (sourceDoc.getResourceType() != DocumentImpl.BINARY_FILE || !"application/xquery".equals(sourceDoc.getMimeType())) {
throw new ServletException("XQuery resource: " + query + " is not an XQuery or " + "declares a wrong mime-type");
}
sourceInfo = new SourceInfo(new DBSource(broker, (BinaryDocument) sourceDoc, true), locationUri.toString());
} catch (final PermissionDeniedException e) {
throw new ServletException("permission denied to read module source from " + query);
}
} catch (final URISyntaxException e) {
throw new ServletException(e.getMessage(), e);
}
} else {
try {
sourceInfo = new SourceInfo(SourceFactory.getSource(broker, moduleLoadPath, query, true), moduleLoadPath);
} catch (final IOException e) {
throw new ServletException("IO error while reading XQuery source: " + query);
} catch (final PermissionDeniedException e) {
throw new ServletException("Permission denied while reading XQuery source: " + query);
}
}
return sourceInfo;
}
use of org.exist.xmldb.XmldbURI in project exist by eXist-db.
the class Eval method doEval.
private Sequence doEval(final XQueryContext evalContext, final Sequence contextSequence, final Sequence[] args) throws XPathException {
if (evalContext.getProfiler().isEnabled()) {
evalContext.getProfiler().start(this);
evalContext.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies()));
if (contextSequence != null) {
evalContext.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
}
}
int argCount = 0;
Sequence exprContext = null;
if (isCalledAs(FS_EVAL_INLINE_NAME)) {
// the current expression context
exprContext = args[argCount++];
}
// get the query expression
final Item expr = args[argCount++].itemAt(0);
final Source querySource;
if (Type.subTypeOf(expr.getType(), Type.ANY_URI)) {
querySource = loadQueryFromURI(expr);
} else {
final String queryStr = expr.getStringValue();
if (queryStr.trim().isEmpty()) {
return new EmptySequence();
}
querySource = new StringSource(queryStr);
}
final NodeValue contextInit;
if (isCalledAs(FS_EVAL_WITH_CONTEXT_NAME)) {
// set the context initialization param for later use
contextInit = (NodeValue) args[argCount++].itemAt(0);
} else {
contextInit = null;
}
// should the compiled query be cached?
final boolean cache;
if (isCalledAs(FS_EVAL_AND_SERIALIZE_NAME)) {
cache = true;
} else if (argCount < getArgumentCount()) {
cache = ((BooleanValue) args[argCount++].itemAt(0)).effectiveBooleanValue();
} else {
cache = false;
}
// save some context properties
evalContext.pushNamespaceContext();
final LocalVariable mark = evalContext.markLocalVariables(false);
// save the static document set of the current context, so it can be restored later
final DocumentSet oldDocs = evalContext.getStaticDocs();
if (exprContext != null) {
evalContext.setStaticallyKnownDocuments(exprContext.getDocumentSet());
}
if (evalContext.isProfilingEnabled(2)) {
evalContext.getProfiler().start(this, "eval: " + expr);
}
// fixme! - hook for debugger here /ljo
final XQuery xqueryService = evalContext.getBroker().getBrokerPool().getXQueryService();
final XQueryContext innerContext;
final Sequence initContextSequence;
if (contextInit != null) {
// eval-with-context: initialize a new context
innerContext = new XQueryContext(context.getBroker().getBrokerPool());
initContextSequence = initContext(contextInit.getNode(), innerContext);
} else {
// use the existing outer context
// TODO: check if copying the static context would be sufficient???
innerContext = evalContext.copyContext();
innerContext.setShared(true);
// innerContext = context;
initContextSequence = null;
}
// set module load path
if (Type.subTypeOf(expr.getType(), Type.ANY_URI)) {
String uri = null;
if (querySource instanceof DBSource) {
final XmldbURI documentPath = ((DBSource) querySource).getDocumentPath();
uri = XmldbURI.EMBEDDED_SERVER_URI.append(documentPath).removeLastSegment().toString();
} else if (querySource instanceof FileSource) {
uri = ((FileSource) querySource).getPath().getParent().toString();
}
if (uri != null) {
innerContext.setModuleLoadPath(uri);
}
}
// bind external vars?
if (isCalledAs(FS_EVAL_NAME) && getArgumentCount() >= 3) {
final Sequence externalVars = args[argCount++];
for (int i = 0; i < externalVars.getItemCount(); i++) {
final Item varName = externalVars.itemAt(i);
if (varName.getType() == Type.QNAME) {
final Item varValue = externalVars.itemAt(++i);
innerContext.declareVariable(((QNameValue) varName).getQName(), varValue);
}
}
}
// determine if original line/column number are passed on
final boolean pass;
if (isCalledAs(FS_EVAL_NAME) && getArgumentCount() == 4) {
pass = args[3].itemAt(0).toJavaObject(Boolean.class);
} else if (isCalledAs(FS_EVAL_WITH_CONTEXT_NAME) && getArgumentCount() == 5) {
pass = args[4].itemAt(0).toJavaObject(Boolean.class);
} else if (isCalledAs(FS_EVAL_INLINE_NAME) && getArgumentCount() == 4) {
pass = args[3].itemAt(0).toJavaObject(Boolean.class);
} else if (isCalledAs(FS_EVAL_AND_SERIALIZE_NAME) && getArgumentCount() == 5) {
pass = args[4].itemAt(0).toJavaObject(Boolean.class);
} else {
// default
pass = false;
}
// fixme! - hook for debugger here /ljo
try {
if (isCalledAs(FS_EVAL_WITH_CONTEXT_NAME) && getArgumentCount() >= 4) {
final Item contextItem = args[argCount++].itemAt(0);
if (contextItem != null) {
// TODO : sort this out
if (exprContext != null) {
LOG.warn("exprContext and contextItem are not null");
}
exprContext = contextItem.toSequence();
}
}
if (initContextSequence != null) {
exprContext = initContextSequence;
}
Sequence result = null;
try {
if (!isCalledAs(FS_EVAL_AND_SERIALIZE_NAME)) {
result = execute(evalContext.getBroker(), xqueryService, querySource, innerContext, exprContext, cache, null);
return result;
} else {
// get the default serialization options
final Properties defaultOutputOptions;
if (getArgumentCount() >= 2 && !args[1].isEmpty()) {
defaultOutputOptions = FunSerialize.getSerializationProperties(this, args[1].itemAt(0));
} else {
defaultOutputOptions = new Properties();
}
// execute the query, XQuery prolog serialization options are collected into `xqueryOutputProperties`
final Properties xqueryOutputProperties = new Properties();
result = execute(evalContext.getBroker(), xqueryService, querySource, innerContext, exprContext, cache, xqueryOutputProperties);
// do we need to subsequence the results?
if (getArgumentCount() > 2) {
result = FunSubSequence.subsequence(result, ((DoubleValue) getArgument(2).eval(contextSequence, null).convertTo(Type.DOUBLE)), getArgumentCount() == 3 ? null : ((DoubleValue) getArgument(3).eval(contextSequence, null).convertTo(Type.DOUBLE)));
}
// override the default options with the ones from the xquery prolog
final Properties serializationProperties = new Properties();
serializationProperties.putAll(defaultOutputOptions);
serializationProperties.putAll(xqueryOutputProperties);
// serialize the results
try (final StringWriter writer = new StringWriter()) {
final XQuerySerializer xqSerializer = new XQuerySerializer(context.getBroker(), serializationProperties, writer);
final Sequence seq;
if (xqSerializer.normalize()) {
seq = FunSerialize.normalize(this, context, result);
} else {
seq = result;
}
xqSerializer.serialize(seq);
return new StringValue(writer.toString());
} catch (final IOException | SAXException e) {
throw new XPathException(this, FnModule.SENR0001, e.getMessage());
}
}
} finally {
cleanup(evalContext, innerContext, oldDocs, mark, expr, result);
}
} catch (final XPathException e) {
try {
e.prependMessage("Error while evaluating expression: " + querySource.getContent() + ". ");
} catch (final IOException e1) {
}
if (!pass) {
e.setLocation(line, column);
}
throw e;
}
}
use of org.exist.xmldb.XmldbURI in project exist by eXist-db.
the class XMLDBCopy method evalWithCollection.
@Override
public Sequence evalWithCollection(final Collection collection, final Sequence[] args, final Sequence contextSequence) throws XPathException {
if (isCalledAs(FS_COPY_RESOURCE_NAME)) {
final XmldbURI destination = new AnyURIValue(args[2].itemAt(0).getStringValue()).toXmldbURI();
final XmldbURI doc = new AnyURIValue(args[1].itemAt(0).getStringValue()).toXmldbURI();
try {
final Resource resource = collection.getResource(doc.toString());
if (resource == null) {
logger.error("Resource {} not found", doc);
throw new XPathException(this, "Resource " + doc + " not found");
}
final EXistCollectionManagementService service = (EXistCollectionManagementService) collection.getService("CollectionManagementService", "1.0");
final DBBroker.PreserveType preserve;
if (getArgumentCount() == 5) {
final boolean preserveArg = args[4].itemAt(0).toJavaObject(boolean.class);
if (preserveArg) {
preserve = DBBroker.PreserveType.PRESERVE;
} else {
preserve = DBBroker.PreserveType.DEFAULT;
}
} else {
preserve = DBBroker.PreserveType.DEFAULT;
}
final XmldbURI newName;
if (getArgumentCount() >= 4) {
if (!args[3].isEmpty()) {
newName = XmldbURI.create(args[3].itemAt(0).getStringValue());
} else {
newName = doc.lastSegment();
}
} else {
newName = null;
}
service.copyResource(doc, destination, newName, preserve.name());
if (isCalledAs(FS_COPY_RESOURCE_NAME)) {
return new StringValue(destination.append(newName).getRawCollectionPath());
} else {
return Sequence.EMPTY_SEQUENCE;
}
} catch (final XMLDBException e) {
logger.error("XMLDB exception caught: ", e);
throw new XPathException(this, "XMLDB exception caught: " + e.getMessage(), e);
}
} else {
final XmldbURI destination = new AnyURIValue(args[1].itemAt(0).getStringValue()).toXmldbURI();
try {
final EXistCollectionManagementService service = (EXistCollectionManagementService) collection.getService("CollectionManagementService", "1.0");
final DBBroker.PreserveType preserve;
if (getArgumentCount() == 3) {
final boolean preserveArg = args[2].itemAt(0).toJavaObject(boolean.class);
if (preserveArg) {
preserve = DBBroker.PreserveType.PRESERVE;
} else {
preserve = DBBroker.PreserveType.DEFAULT;
}
} else {
preserve = DBBroker.PreserveType.DEFAULT;
}
service.copy(XmldbURI.xmldbUriFor(collection.getName()), destination, null, preserve.name());
if (isCalledAs(FS_COPY_COLLECTION_NAME)) {
final XmldbURI targetName = XmldbURI.xmldbUriFor(collection.getName()).lastSegment();
return new StringValue(destination.append(targetName).getRawCollectionPath());
} else {
return Sequence.EMPTY_SEQUENCE;
}
} catch (final XMLDBException e) {
logger.error("Cannot copy collection: ", e);
throw new XPathException(this, "Cannot copy collection: " + e.getMessage(), e);
} catch (final URISyntaxException e) {
logger.error("URI exception: ", e);
throw new XPathException(this, "URI exception: " + e.getMessage(), e);
}
}
}
use of org.exist.xmldb.XmldbURI in project exist by eXist-db.
the class XMLDBGetMimeType method eval.
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
final String path = new AnyURIValue(args[0].itemAt(0).getStringValue()).toString();
if (path.matches("^[a-z]+://.*")) {
// external
final MimeTable mimeTable = MimeTable.getInstance();
final MimeType mimeType = mimeTable.getContentTypeFor(path);
if (mimeType != null) {
return new StringValue(mimeType.getName());
}
} else {
// database
try {
XmldbURI pathUri = XmldbURI.xmldbUriFor(path);
// relative collection Path: add the current base URI
pathUri = context.getBaseURI().toXmldbURI().resolveCollectionPath(pathUri);
// try to open the document and acquire a lock
try (final LockedDocument lockedDoc = context.getBroker().getXMLResource(pathUri, LockMode.READ_LOCK)) {
if (lockedDoc != null) {
return new StringValue(lockedDoc.getDocument().getMimeType());
}
}
} catch (final Exception e) {
logger.error(e.getMessage());
throw new XPathException(this, e);
}
}
return Sequence.EMPTY_SEQUENCE;
}
Aggregations