Search in sources :

Example 86 with DocumentImpl

use of org.exist.dom.persistent.DocumentImpl in project exist by eXist-db.

the class IntersectTest method persistent_intersect_memtree.

/**
 * Tests the XQuery `intersect` operator against a
 * persistent node on the left and an in-memory node on the right
 */
@Test
public void persistent_intersect_memtree() throws XPathException, NoSuchMethodException {
    final XQueryContext mockContext = createMock(XQueryContext.class);
    final PathExpr mockLeft = createMock(PathExpr.class);
    final PathExpr mockRight = createMock(PathExpr.class);
    final Sequence mockContextSequence = createMock(Sequence.class);
    final Item mockContextItem = createMock(Item.class);
    final Profiler mockProfiler = createMock(Profiler.class);
    final DocumentImpl mockPersistentDoc = createMock(DocumentImpl.class);
    final NodeProxy mockPersistentNode = createMockBuilder(NodeProxy.class).withConstructor(DocumentImpl.class, NodeId.class).withArgs(mockPersistentDoc, new DLN(1)).addMockedMethods(NodeProxy.class.getMethod("isEmpty", new Class[] {}), NodeProxy.class.getMethod("getItemType", new Class[] {}), NodeProxy.class.getMethod("equals", new Class[] { Object.class })).createMock();
    expect(mockContext.nextExpressionId()).andReturn(1);
    expect(mockContext.getProfiler()).andReturn(mockProfiler);
    // persistent node
    expect(mockLeft.eval(mockContextSequence, mockContextItem)).andReturn(mockPersistentNode);
    // memtree node
    expect(mockRight.eval(mockContextSequence, mockContextItem)).andReturn((org.exist.dom.memtree.ElementImpl) createInMemoryDocument().getDocumentElement());
    expect(mockPersistentNode.isEmpty()).andReturn(false);
    expect(mockPersistentNode.getItemType()).andReturn(Type.NODE);
    expect(mockPersistentDoc.getDocId()).andReturn(1).times(2);
    expect(mockContext.getProfiler()).andReturn(mockProfiler);
    replay(mockPersistentDoc, mockPersistentNode, mockRight, mockLeft, mockContext);
    // test
    final Intersect intersect = new Intersect(mockContext, mockLeft, mockRight);
    final Sequence result = intersect.eval(mockContextSequence, mockContextItem);
    assertEquals(0, ((ValueSequence) result).size());
    verify(mockPersistentDoc, mockPersistentNode, mockRight, mockLeft, mockContext);
}
Also used : Item(org.exist.xquery.value.Item) DLN(org.exist.numbering.DLN) NodeId(org.exist.numbering.NodeId) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) DocumentImpl(org.exist.dom.persistent.DocumentImpl) NodeProxy(org.exist.dom.persistent.NodeProxy) Test(org.junit.Test)

Example 87 with DocumentImpl

use of org.exist.dom.persistent.DocumentImpl in project exist by eXist-db.

the class InstallFunction method eval.

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    Sequence removed = BooleanValue.FALSE;
    boolean force = true;
    UserInteractionStrategy interact = new BatchUserInteraction();
    String pkgOrPath = args[0].getStringValue();
    Optional<ExistRepository> repo = getContext().getRepository();
    try {
        if (repo.isPresent()) {
            Repository parent_repo = repo.get().getParentRepo();
            Package pkg;
            if (isCalledAs("install")) {
                // download .xar from a URI
                URI uri = _getURI(pkgOrPath);
                pkg = parent_repo.installPackage(uri, force, interact);
                repo.get().reportAction(ExistRepository.Action.INSTALL, pkg.getName());
            } else {
                // .xar is stored as a binary resource
                try (final LockedDocument lockedDoc = getBinaryDoc(pkgOrPath);
                    final Txn transaction = context.getBroker().continueOrBeginTransaction()) {
                    final DocumentImpl doc = lockedDoc.getDocument();
                    LOG.debug("Installing file: {}", doc.getURI());
                    pkg = parent_repo.installPackage(new BinaryDocumentXarSource(context.getBroker().getBrokerPool(), transaction, (BinaryDocument) doc), force, interact);
                    repo.get().reportAction(ExistRepository.Action.INSTALL, pkg.getName());
                    transaction.commit();
                }
            }
            ExistPkgInfo info = (ExistPkgInfo) pkg.getInfo("exist");
            if (info != null && !info.getJars().isEmpty())
                ClasspathHelper.updateClasspath(context.getBroker().getBrokerPool(), pkg);
            // TODO: expath libs do not provide a way to see if there were any XQuery modules installed at all
            context.getBroker().getBrokerPool().getXQueryPool().clear();
            removed = BooleanValue.TRUE;
        } else {
            throw new XPathException("expath repository not available");
        }
    } catch (PackageException | TransactionException ex) {
        logger.error(ex.getMessage(), ex);
        return removed;
    // /TODO: _repo.removePackage seems to throw PackageException
    // throw new XPathException("Problem installing package " + pkg + " in expath repository, check that eXist-db has access permissions to expath repository file directory  ", ex);
    } catch (XPathException xpe) {
        logger.error(xpe.getMessage());
        return removed;
    }
    return removed;
}
Also used : XPathException(org.exist.xquery.XPathException) Sequence(org.exist.xquery.value.Sequence) Txn(org.exist.storage.txn.Txn) XmldbURI(org.exist.xmldb.XmldbURI) URI(java.net.URI) DocumentImpl(org.exist.dom.persistent.DocumentImpl) ExistPkgInfo(org.exist.repo.ExistPkgInfo) ExistRepository(org.exist.repo.ExistRepository) TransactionException(org.exist.storage.txn.TransactionException) LockedDocument(org.exist.dom.persistent.LockedDocument) Package(org.expath.pkg.repo.Package) BatchUserInteraction(org.expath.pkg.repo.tui.BatchUserInteraction) ExistRepository(org.exist.repo.ExistRepository)

Example 88 with DocumentImpl

use of org.exist.dom.persistent.DocumentImpl in project exist by eXist-db.

the class XQueryStartupTrigger method getScriptsInStartupCollection.

/**
 * List all xquery scripts in /db/system/autostart
 *
 * @param broker The exist-db broker
 * @return List of xquery scripts
 */
private List<String> getScriptsInStartupCollection(DBBroker broker) {
    // Return values
    List<String> paths = new ArrayList<>();
    XmldbURI uri = XmldbURI.create(AUTOSTART_COLLECTION);
    try (final Collection collection = broker.openCollection(uri, LockMode.READ_LOCK)) {
        if (collection == null) {
            LOG.debug("Collection {}' not found.", AUTOSTART_COLLECTION);
            createAutostartCollection(broker);
        } else {
            LOG.debug("Scanning collection '{}'.", AUTOSTART_COLLECTION);
            if (isPermissionsOK(collection)) {
                Iterator<DocumentImpl> documents = collection.iteratorNoLock(broker);
                while (documents.hasNext()) {
                    DocumentImpl document = documents.next();
                    String docPath = document.getURI().toString();
                    if (isPermissionsOK(document)) {
                        if (StringUtils.endsWithAny(docPath, XQUERY_EXTENSIONS)) {
                            paths.add(XmldbURI.EMBEDDED_SERVER_URI_PREFIX + docPath);
                        } else {
                            LOG.error("Skipped document '{}', not an xquery script.", docPath);
                        }
                    } else {
                        LOG.error("Document {} should be owned by DBA, mode {}, mimetype {}", docPath, Permission.DEFAULT_SYSTEM_SECURITY_COLLECTION_PERM, REQUIRED_MIMETYPE);
                    }
                }
            } else {
                LOG.error("Collection {} should be owned by SYSTEM/DBA, mode {}.", AUTOSTART_COLLECTION, Permission.DEFAULT_SYSTEM_SECURITY_COLLECTION_PERM);
            }
        }
        LOG.debug("Found {} XQuery scripts in '{}'.", paths.size(), AUTOSTART_COLLECTION);
    } catch (PermissionDeniedException ex) {
        LOG.error(ex.getMessage());
    }
    return paths;
}
Also used : Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) XmldbURI(org.exist.xmldb.XmldbURI)

Example 89 with DocumentImpl

use of org.exist.dom.persistent.DocumentImpl in project exist by eXist-db.

the class STXTransformerTrigger method configure.

@Override
public void configure(DBBroker broker, Txn transaction, Collection parent, Map<String, List<?>> parameters) throws TriggerException {
    super.configure(broker, transaction, parent, parameters);
    final String stylesheet = (String) parameters.get("src").get(0);
    if (stylesheet == null) {
        throw new TriggerException("STXTransformerTrigger requires an attribute 'src'");
    }
    /*
        String origProperty = System.getProperty("javax.xml.transform.TransformerFactory");
        System.setProperty("javax.xml.transform.TransformerFactory",  "net.sf.joost.trax.TransformerFactoryImpl");
        factory = (SAXTransformerFactory)TransformerFactory.newInstance();
        // reset property to previous setting
        if(origProperty != null) {
                System.setProperty("javax.xml.transform.TransformerFactory", origProperty);
        }
         */
    /*ServiceLoader<TransformerFactory> loader = ServiceLoader.load(TransformerFactory.class);
        for(TransformerFactory transformerFactory : loader) {
            if(transformerFactory.getClass().getName().equals("net.sf.joost.trax.TransformerFactoryImpl")) {
                    factory = transformerFactory.ne
            }
        }*/
    XmldbURI stylesheetUri = null;
    try {
        stylesheetUri = XmldbURI.xmldbUriFor(stylesheet);
    } catch (final URISyntaxException e) {
    }
    // TODO: allow full XmldbURIs to be used as well.
    if (stylesheetUri == null || stylesheet.indexOf(':') == Constants.STRING_NOT_FOUND) {
        stylesheetUri = parent.getURI().resolveCollectionPath(stylesheetUri);
        DocumentImpl doc;
        try {
            doc = (DocumentImpl) broker.getXMLResource(stylesheetUri);
            if (doc == null) {
                throw new TriggerException("stylesheet " + stylesheetUri + " not found in database");
            }
            if (doc instanceof BinaryDocument) {
                throw new TriggerException("stylesheet " + stylesheetUri + " must be stored as an xml document and not a binary document!");
            }
            handler = factory.newTransformerHandler(STXTemplatesCache.getInstance().getOrUpdateTemplate(broker, doc));
        } catch (final TransformerConfigurationException | PermissionDeniedException | SAXException | LockException e) {
            throw new TriggerException(e.getMessage(), e);
        }
    } else {
        try {
            LOG.debug("compiling stylesheet {}", stylesheet);
            final Templates template = factory.newTemplates(new StreamSource(stylesheet));
            handler = factory.newTransformerHandler(template);
        } catch (final TransformerConfigurationException e) {
            throw new TriggerException(e.getMessage(), e);
        }
    }
}
Also used : TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) StreamSource(javax.xml.transform.stream.StreamSource) Templates(javax.xml.transform.Templates) URISyntaxException(java.net.URISyntaxException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) SAXException(org.xml.sax.SAXException) BinaryDocument(org.exist.dom.persistent.BinaryDocument) LockException(org.exist.util.LockException) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 90 with DocumentImpl

use of org.exist.dom.persistent.DocumentImpl in project exist by eXist-db.

the class Dumper method prepare.

public void prepare(int event, DBBroker broker, Txn txn, XmldbURI documentName, DocumentImpl existingDocument) throws TriggerException {
    System.out.println("\nstoring document " + documentName + " into collection " + getCollection().getURI());
    if (existingDocument != null) {
        System.out.println("replacing document " + ((DocumentImpl) existingDocument).getFileURI());
    }
    System.out.println("collection contents:");
    final DefaultDocumentSet docs = new DefaultDocumentSet();
    try {
        getCollection().getDocuments(broker, docs);
    } catch (final PermissionDeniedException | LockException e) {
        throw new TriggerException(e.getMessage(), e);
    }
    for (final Iterator<DocumentImpl> i = docs.getDocumentIterator(); i.hasNext(); ) {
        System.out.println("\t" + i.next().getFileURI());
    }
}
Also used : DefaultDocumentSet(org.exist.dom.persistent.DefaultDocumentSet) LockException(org.exist.util.LockException) PermissionDeniedException(org.exist.security.PermissionDeniedException) DocumentImpl(org.exist.dom.persistent.DocumentImpl)

Aggregations

DocumentImpl (org.exist.dom.persistent.DocumentImpl)128 PermissionDeniedException (org.exist.security.PermissionDeniedException)51 Collection (org.exist.collections.Collection)40 LockedDocument (org.exist.dom.persistent.LockedDocument)39 Txn (org.exist.storage.txn.Txn)35 XmldbURI (org.exist.xmldb.XmldbURI)34 EXistException (org.exist.EXistException)27 LockException (org.exist.util.LockException)26 DBBroker (org.exist.storage.DBBroker)25 IOException (java.io.IOException)19 NodeProxy (org.exist.dom.persistent.NodeProxy)18 URISyntaxException (java.net.URISyntaxException)17 BrokerPool (org.exist.storage.BrokerPool)17 TransactionManager (org.exist.storage.txn.TransactionManager)17 Test (org.junit.Test)17 XPathException (org.exist.xquery.XPathException)16 NodeId (org.exist.numbering.NodeId)14 SAXException (org.xml.sax.SAXException)13 StoredNode (org.exist.dom.persistent.StoredNode)12 BinaryDocument (org.exist.dom.persistent.BinaryDocument)11