Search in sources :

Example 21 with AnyURIValue

use of org.exist.xquery.value.AnyURIValue in project exist by eXist-db.

the class DocTest method doc_dynamicallyAvailableDocument_relativeUri.

@Test
public void doc_dynamicallyAvailableDocument_relativeUri() throws XPathException, EXistException, PermissionDeniedException, URISyntaxException {
    final BrokerPool pool = BrokerPool.getInstance();
    final String doc = "<timestamp>" + System.currentTimeMillis() + "</timestamp>";
    final String baseUri = "http://from-dynamic-context/";
    final String docRelativeUri = "doc1";
    final String query = "fn:doc('" + docRelativeUri + "')";
    try (final DBBroker broker = pool.getBroker()) {
        final XQueryContext context = new XQueryContext(pool);
        context.setBaseURI(new AnyURIValue(new URI(baseUri)));
        context.addDynamicallyAvailableDocument(baseUri + docRelativeUri, (broker2, transaction, uri) -> asInMemoryDocument(doc));
        final XQuery xqueryService = pool.getXQueryService();
        final CompiledXQuery compiled = xqueryService.compile(context, query);
        final Sequence result = xqueryService.execute(broker, compiled, null);
        assertFalse(result.isEmpty());
        assertEquals(1, result.getItemCount());
        assertTrue(result.itemAt(0) instanceof Node);
        final Source expectedSource = Input.fromString(doc).build();
        final Source actualSource = Input.fromNode((Node) result.itemAt(0)).build();
        final Diff diff = DiffBuilder.compare(expectedSource).withTest(actualSource).checkForIdentical().checkForSimilar().build();
        assertFalse(diff.toString(), diff.hasDifferences());
    }
}
Also used : DBBroker(org.exist.storage.DBBroker) Diff(org.xmlunit.diff.Diff) XQuery(org.exist.xquery.XQuery) CompiledXQuery(org.exist.xquery.CompiledXQuery) CompiledXQuery(org.exist.xquery.CompiledXQuery) AnyURIValue(org.exist.xquery.value.AnyURIValue) Node(org.w3c.dom.Node) XQueryContext(org.exist.xquery.XQueryContext) Sequence(org.exist.xquery.value.Sequence) URI(java.net.URI) BrokerPool(org.exist.storage.BrokerPool) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource)

Example 22 with AnyURIValue

use of org.exist.xquery.value.AnyURIValue in project exist by eXist-db.

the class AuditTrailSessionListener method executeXQuery.

private void executeXQuery(String xqueryResourcePath) {
    if (xqueryResourcePath != null && xqueryResourcePath.length() > 0) {
        xqueryResourcePath = xqueryResourcePath.trim();
        try {
            final BrokerPool pool = BrokerPool.getInstance();
            final Subject sysSubject = pool.getSecurityManager().getSystemSubject();
            try (final DBBroker broker = pool.get(Optional.of(sysSubject))) {
                if (broker == null) {
                    LOG.error("Unable to retrieve DBBroker for {}", sysSubject.getName());
                    return;
                }
                final XmldbURI pathUri = XmldbURI.create(xqueryResourcePath);
                try (final LockedDocument lockedResource = broker.getXMLResource(pathUri, LockMode.READ_LOCK)) {
                    final Source source;
                    if (lockedResource != null) {
                        if (LOG.isTraceEnabled()) {
                            LOG.trace("Resource [{}] exists.", xqueryResourcePath);
                        }
                        source = new DBSource(broker, (BinaryDocument) lockedResource.getDocument(), true);
                    } else {
                        LOG.error("Resource [{}] does not exist.", xqueryResourcePath);
                        return;
                    }
                    final XQuery xquery = pool.getXQueryService();
                    if (xquery == null) {
                        LOG.error("broker unable to retrieve XQueryService");
                        return;
                    }
                    final XQueryPool xqpool = pool.getXQueryPool();
                    CompiledXQuery compiled = xqpool.borrowCompiledXQuery(broker, source);
                    final XQueryContext context;
                    if (compiled == null) {
                        context = new XQueryContext(broker.getBrokerPool());
                    } else {
                        context = compiled.getContext();
                        context.prepareForReuse();
                    }
                    context.setStaticallyKnownDocuments(new XmldbURI[] { pathUri });
                    context.setBaseURI(new AnyURIValue(pathUri.toString()));
                    if (compiled == null) {
                        compiled = xquery.compile(context, source);
                    } else {
                        compiled.getContext().updateContext(context);
                        context.getWatchDog().reset();
                    }
                    final Properties outputProperties = new Properties();
                    try {
                        final long startTime = System.currentTimeMillis();
                        final Sequence result = xquery.execute(broker, compiled, null, outputProperties);
                        final long queryTime = System.currentTimeMillis() - startTime;
                        if (LOG.isTraceEnabled()) {
                            LOG.trace("XQuery execution results: {} in {}ms.", result.toString(), queryTime);
                        }
                    } finally {
                        context.runCleanupTasks();
                        xqpool.returnCompiledXQuery(source, compiled);
                    }
                }
            }
        } catch (final Exception e) {
            LOG.error("Exception while executing [{}] script", xqueryResourcePath, e);
        }
    }
}
Also used : CompiledXQuery(org.exist.xquery.CompiledXQuery) XQuery(org.exist.xquery.XQuery) CompiledXQuery(org.exist.xquery.CompiledXQuery) AnyURIValue(org.exist.xquery.value.AnyURIValue) XQueryContext(org.exist.xquery.XQueryContext) Sequence(org.exist.xquery.value.Sequence) Properties(java.util.Properties) Subject(org.exist.security.Subject) Source(org.exist.source.Source) DBSource(org.exist.source.DBSource) BinaryDocument(org.exist.dom.persistent.BinaryDocument) XQueryPool(org.exist.storage.XQueryPool) DBBroker(org.exist.storage.DBBroker) LockedDocument(org.exist.dom.persistent.LockedDocument) DBSource(org.exist.source.DBSource) BrokerPool(org.exist.storage.BrokerPool) XmldbURI(org.exist.xmldb.XmldbURI)

Example 23 with AnyURIValue

use of org.exist.xquery.value.AnyURIValue in project exist by eXist-db.

the class XMLDBRename method evalWithCollection.

/* (non-Javadoc)
	 * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
	 */
public Sequence evalWithCollection(Collection collection, Sequence[] args, Sequence contextSequence) throws XPathException {
    if (getSignature().getArgumentCount() == 3) {
        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 String newName = args[2].itemAt(0).getStringValue();
            final EXistCollectionManagementService service = (EXistCollectionManagementService) collection.getService("CollectionManagementService", "1.0");
            service.moveResource(doc, (XmldbURI) null, XmldbURI.xmldbUriFor(newName));
        } catch (final XMLDBException e) {
            logger.error(e.getMessage());
            throw new XPathException(this, "XMLDB exception caught: " + e.getMessage(), e);
        } catch (final URISyntaxException e) {
            logger.error(e.getMessage());
            throw new XPathException(this, "URI exception: " + e.getMessage(), e);
        }
    } else {
        try {
            final String newName = args[1].itemAt(0).getStringValue();
            final EXistCollectionManagementService service = (EXistCollectionManagementService) collection.getService("CollectionManagementService", "1.0");
            service.move(XmldbURI.xmldbUriFor(collection.getName()), null, XmldbURI.xmldbUriFor(newName));
        } catch (final XMLDBException e) {
            logger.error("Cannot rename collection: {}", e.getMessage());
            throw new XPathException(this, "Cannot rename collection: " + e.getMessage(), e);
        } catch (final URISyntaxException e) {
            logger.error(e.getMessage());
            throw new XPathException(this, "URI exception: " + e.getMessage(), e);
        }
    }
    return Sequence.EMPTY_SEQUENCE;
}
Also used : XPathException(org.exist.xquery.XPathException) EXistCollectionManagementService(org.exist.xmldb.EXistCollectionManagementService) AnyURIValue(org.exist.xquery.value.AnyURIValue) Resource(org.xmldb.api.base.Resource) XMLDBException(org.xmldb.api.base.XMLDBException) URISyntaxException(java.net.URISyntaxException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 24 with AnyURIValue

use of org.exist.xquery.value.AnyURIValue in project exist by eXist-db.

the class XMLDBSetMimeType method eval.

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    // Get handle to Mime-type info
    final MimeTable mimeTable = MimeTable.getInstance();
    // Get first parameter
    final String pathParameter = new AnyURIValue(args[0].itemAt(0).getStringValue()).toString();
    if (pathParameter.matches("^[a-z]+://.*")) {
        throw new XPathException("Can not set mime-type for resources outside the database.");
    }
    XmldbURI pathUri = null;
    try {
        pathUri = XmldbURI.xmldbUriFor(pathParameter);
    } catch (final URISyntaxException ex) {
        logger.debug(ex.getMessage());
        throw new XPathException("Invalid path '" + pathParameter + "'");
    }
    // Verify mime-type input
    MimeType newMimeType = null;
    if (args[1].isEmpty()) {
        // No input, use default mimetype
        newMimeType = mimeTable.getContentTypeFor(pathParameter);
        if (newMimeType == null) {
            throw new XPathException("Unable to determine mimetype for '" + pathParameter + "'");
        }
    } else {
        // Mimetype is provided, check if valid
        newMimeType = mimeTable.getContentType(args[1].getStringValue());
        if (newMimeType == null) {
            throw new XPathException("mime-type '" + args[1].getStringValue() + "' is not supported.");
        }
    }
    // Get mime-type of resource
    MimeType currentMimeType = getMimeTypeStoredResource(pathUri);
    if (currentMimeType == null) {
        // stored resource has no mime-type (unexpected situation)
        // fall back to document name
        logger.debug("Resource '{}' has no mime-type, retrieve from document name.", pathUri);
        currentMimeType = mimeTable.getContentTypeFor(pathUri);
        // if extension based lookup still fails
        if (currentMimeType == null) {
            throw new XPathException("Unable to determine mime-type from path '" + pathUri + "'.");
        }
    }
    // in some cases value null is set, then allow to set to new value (repair action)
    if (newMimeType.isXMLType() != currentMimeType.isXMLType()) {
        throw new XPathException("New mime-type must be a " + currentMimeType.getXMLDBType() + " mime-type");
    }
    // At this moment it is possible to update the mimetype
    final DBBroker broker = context.getBroker();
    final BrokerPool brokerPool = broker.getBrokerPool();
    // relative collection Path: add the current base URI
    pathUri = context.getBaseURI().toXmldbURI().resolveCollectionPath(pathUri);
    try (final Txn txn = broker.continueOrBeginTransaction();
        final LockedDocument lockedDocument = broker.getXMLResource(pathUri, LockMode.WRITE_LOCK)) {
        // try to open the document and acquire a lock
        final DocumentImpl doc = lockedDocument == null ? null : lockedDocument.getDocument();
        if (doc == null) {
            // no document selected, abort
            txn.abort();
        } else {
            // set new mime-type
            doc.setMimeType(newMimeType.getName());
            // store meta data into database
            broker.storeMetadata(txn, doc);
            // commit changes
            txn.commit();
        }
    } catch (final Exception e) {
        logger.error(e.getMessage());
        throw new XPathException(this, e);
    }
    return Sequence.EMPTY_SEQUENCE;
}
Also used : MimeTable(org.exist.util.MimeTable) XPathException(org.exist.xquery.XPathException) AnyURIValue(org.exist.xquery.value.AnyURIValue) URISyntaxException(java.net.URISyntaxException) Txn(org.exist.storage.txn.Txn) DocumentImpl(org.exist.dom.persistent.DocumentImpl) MimeType(org.exist.util.MimeType) URISyntaxException(java.net.URISyntaxException) PermissionDeniedException(org.exist.security.PermissionDeniedException) XPathException(org.exist.xquery.XPathException) DBBroker(org.exist.storage.DBBroker) LockedDocument(org.exist.dom.persistent.LockedDocument) XmldbURI(org.exist.xmldb.XmldbURI) BrokerPool(org.exist.storage.BrokerPool)

Example 25 with AnyURIValue

use of org.exist.xquery.value.AnyURIValue in project exist by eXist-db.

the class XMLDBStore method evalWithCollection.

@Override
public Sequence evalWithCollection(Collection collection, Sequence[] args, Sequence contextSequence) throws XPathException {
    String docName = args[1].isEmpty() ? null : args[1].getStringValue();
    if (docName != null && docName.isEmpty()) {
        docName = null;
    } else if (docName != null) {
        docName = new AnyURIValue(docName).toXmldbURI().toString();
    }
    final Item item = args[2].itemAt(0);
    // determine the mime type
    final boolean storeAsBinary = isCalledAs(FS_STORE_BINARY_NAME);
    MimeType mimeType = null;
    if (getSignature().getArgumentCount() == 4) {
        final String strMimeType = args[3].getStringValue();
        mimeType = MimeTable.getInstance().getContentType(strMimeType);
    }
    if (mimeType == null && docName != null) {
        mimeType = MimeTable.getInstance().getContentTypeFor(docName);
    }
    if (mimeType == null) {
        mimeType = (storeAsBinary || !Type.subTypeOf(item.getType(), Type.NODE)) ? MimeType.BINARY_TYPE : MimeType.XML_TYPE;
    } else if (storeAsBinary) {
        mimeType = new MimeType(mimeType.getName(), MimeType.BINARY);
    }
    Resource resource;
    try {
        if (Type.subTypeOf(item.getType(), Type.JAVA_OBJECT)) {
            final Object obj = ((JavaObjectValue) item).getObject();
            if (obj instanceof java.io.File) {
                resource = loadFromFile(collection, ((java.io.File) obj).toPath(), docName, mimeType);
            } else if (obj instanceof java.nio.file.Path) {
                resource = loadFromFile(collection, (Path) obj, docName, mimeType);
            } else {
                LOGGER.error("Passed java object should be either a java.nio.file.Path or java.io.File");
                throw new XPathException(this, "Passed java object should be either a java.nio.file.Path or java.io.File");
            }
        } else if (Type.subTypeOf(item.getType(), Type.ANY_URI)) {
            try {
                final URI uri = new URI(item.getStringValue());
                resource = loadFromURI(collection, uri, docName, mimeType);
            } catch (final URISyntaxException e) {
                LOGGER.error("Invalid URI: {}", item.getStringValue());
                throw new XPathException(this, "Invalid URI: " + item.getStringValue(), e);
            }
        } else {
            if (mimeType.isXMLType()) {
                resource = collection.createResource(docName, "XMLResource");
            } else {
                resource = collection.createResource(docName, "BinaryResource");
            }
            if (Type.subTypeOf(item.getType(), Type.STRING)) {
                resource.setContent(item.getStringValue());
            } else if (item.getType() == Type.BASE64_BINARY) {
                resource.setContent(((BinaryValue) item).toJavaObject());
            } else if (Type.subTypeOf(item.getType(), Type.NODE)) {
                if (mimeType.isXMLType()) {
                    final ContentHandler handler = ((XMLResource) resource).setContentAsSAX();
                    handler.startDocument();
                    item.toSAX(context.getBroker(), handler, SERIALIZATION_PROPERTIES);
                    handler.endDocument();
                } else {
                    try (final StringWriter writer = new StringWriter()) {
                        final SAXSerializer serializer = new SAXSerializer();
                        serializer.setOutput(writer, null);
                        item.toSAX(context.getBroker(), serializer, SERIALIZATION_PROPERTIES);
                        resource.setContent(writer.toString());
                    } catch (final IOException e) {
                        LOGGER.error(e.getMessage(), e);
                    }
                }
            } else {
                LOGGER.error("Data should be either a node or a string");
                throw new XPathException(this, "Data should be either a node or a string");
            }
            ((EXistResource) resource).setMimeType(mimeType.getName());
            collection.storeResource(resource);
        }
    } catch (final XMLDBException e) {
        LOGGER.error(e.getMessage(), e);
        throw new XPathException(this, "XMLDB reported an exception while storing document: " + e.getMessage(), e);
    } catch (final SAXException e) {
        LOGGER.error(e.getMessage());
        throw new XPathException(this, "SAX reported an exception while storing document", e);
    }
    if (resource == null) {
        return Sequence.EMPTY_SEQUENCE;
    } else {
        try {
            // TODO : use dedicated function in XmldbURI
            return new StringValue(collection.getName() + "/" + resource.getId());
        } catch (final XMLDBException e) {
            LOGGER.error(e.getMessage());
            throw new XPathException(this, "XMLDB reported an exception while retrieving the " + "stored document", e);
        }
    }
}
Also used : XPathException(org.exist.xquery.XPathException) AnyURIValue(org.exist.xquery.value.AnyURIValue) BinaryResource(org.xmldb.api.modules.BinaryResource) XMLResource(org.xmldb.api.modules.XMLResource) EXistResource(org.exist.xmldb.EXistResource) Resource(org.xmldb.api.base.Resource) XMLDBException(org.xmldb.api.base.XMLDBException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) MimeType(org.exist.util.MimeType) ContentHandler(org.xml.sax.ContentHandler) SAXException(org.xml.sax.SAXException) Item(org.exist.xquery.value.Item) StringWriter(java.io.StringWriter) JavaObjectValue(org.exist.xquery.value.JavaObjectValue) SAXSerializer(org.exist.util.serializer.SAXSerializer) StringValue(org.exist.xquery.value.StringValue) Path(java.nio.file.Path)

Aggregations

AnyURIValue (org.exist.xquery.value.AnyURIValue)27 Sequence (org.exist.xquery.value.Sequence)14 XPathException (org.exist.xquery.XPathException)12 BrokerPool (org.exist.storage.BrokerPool)9 DBBroker (org.exist.storage.DBBroker)9 URI (java.net.URI)8 XmldbURI (org.exist.xmldb.XmldbURI)8 XQueryContext (org.exist.xquery.XQueryContext)8 CompiledXQuery (org.exist.xquery.CompiledXQuery)7 XQuery (org.exist.xquery.XQuery)7 StringValue (org.exist.xquery.value.StringValue)7 IOException (java.io.IOException)6 URISyntaxException (java.net.URISyntaxException)6 PermissionDeniedException (org.exist.security.PermissionDeniedException)6 Source (org.exist.source.Source)4 MimeType (org.exist.util.MimeType)4 Resource (org.xmldb.api.base.Resource)4 XMLDBException (org.xmldb.api.base.XMLDBException)4 Path (java.nio.file.Path)3 DBSource (org.exist.source.DBSource)3