Search in sources :

Example 81 with Resource

use of org.xmldb.api.base.Resource in project exist by eXist-db.

the class XQueryTest method evalLoosesContext_1740891.

/**
 * @see http://sourceforge.net/support/tracker.php?aid=1740891
 */
@Test
public void evalLoosesContext_1740891() throws XMLDBException {
    String module = "module namespace tst = \"urn:test\"; " + "declare namespace util = \"http://exist-db.org/xquery/util\";" + "declare function tst:bar() as element(Bar)* { " + "let $foo := <Foo><Bar/><Bar/><Bar/></Foo> " + "let $query := \"$foo/Bar\" " + "let $bar := util:eval($query) " + "return $bar };";
    String module_name = "module.xqy";
    Resource doc;
    // Store module
    Collection testCollection = getTestCollection();
    doc = testCollection.createResource(module_name, "BinaryResource");
    doc.setContent(module);
    ((EXistResource) doc).setMimeType("application/xquery");
    testCollection.storeResource(doc);
    String query = "import module namespace tst = \"urn:test\"" + "at \"xmldb:exist:///db/test/module.xqy\"; " + "tst:bar()";
    XPathQueryService service = (XPathQueryService) getTestCollection().getService("XPathQueryService", "1.0");
    ResourceSet result = service.query(query);
    assertEquals(3, result.getSize());
    assertEquals("First", "<Bar/>", result.getResource(0).getContent().toString());
    assertEquals("Second", "<Bar/>", result.getResource(1).getContent().toString());
    assertEquals("Third", "<Bar/>", result.getResource(2).getContent().toString());
}
Also used : EXistResource(org.exist.xmldb.EXistResource) XPathQueryService(org.xmldb.api.modules.XPathQueryService) EXistXPathQueryService(org.exist.xmldb.EXistXPathQueryService) XMLResource(org.xmldb.api.modules.XMLResource) EXistResource(org.exist.xmldb.EXistResource) Resource(org.xmldb.api.base.Resource) Collection(org.xmldb.api.base.Collection) ResourceSet(org.xmldb.api.base.ResourceSet)

Example 82 with Resource

use of org.xmldb.api.base.Resource in project exist by eXist-db.

the class ExtDocTest method parse.

@Test
public void parse() throws XMLDBException {
    final URI docUri = externalDoc.toUri();
    final ResourceSet result = existEmbeddedServer.executeQuery("xquery version \"3.1\";\n" + "\n" + "declare namespace output = \"http://www.w3.org/2010/xslt-xquery-serialization\";" + "declare option output:omit-xml-declaration \"yes\";\n" + "\n" + "fn:doc('" + docUri + "')");
    assertNotNull(result);
    assertEquals(1, result.getSize());
    final Resource resource = result.getResource(0);
    assertNotNull(resource);
    assertEquals(XMLResource.RESOURCE_TYPE, resource.getResourceType());
    final Source expectedSource = Input.fromString(docContent).build();
    final Source actualSource = Input.fromNode(((XMLResource) resource).getContentAsDOM()).build();
    final Diff diff = DiffBuilder.compare(expectedSource).withTest(actualSource).checkForSimilar().build();
    assertFalse(diff.toString(), diff.hasDifferences());
}
Also used : Diff(org.xmlunit.diff.Diff) XMLResource(org.xmldb.api.modules.XMLResource) Resource(org.xmldb.api.base.Resource) ResourceSet(org.xmldb.api.base.ResourceSet) URI(java.net.URI) Source(javax.xml.transform.Source) XMLResource(org.xmldb.api.modules.XMLResource) Test(org.junit.Test)

Example 83 with Resource

use of org.xmldb.api.base.Resource in project exist by eXist-db.

the class FunSubSequenceTest method setup.

@BeforeClass
public static void setup() throws XMLDBException {
    test = existEmbeddedServer.createCollection(existEmbeddedServer.getRoot(), TestConstants.TEST_COLLECTION_URI.lastSegment().toString());
    final Resource resource = test.createResource(SIMPLE_XML_FILENAME, XMLResource.RESOURCE_TYPE);
    resource.setContent(SIMPLE_XML);
    test.storeResource(resource);
}
Also used : XMLResource(org.xmldb.api.modules.XMLResource) Resource(org.xmldb.api.base.Resource) BeforeClass(org.junit.BeforeClass)

Example 84 with Resource

use of org.xmldb.api.base.Resource in project exist by eXist-db.

the class AbstractExtractFunction method processCompressedEntry.

/**
 * Processes a compressed entry from an archive
 *
 * @param name The name of the entry
 * @param isDirectory true if the entry is a directory, false otherwise
 * @param is an InputStream for reading the uncompressed data of the entry
 * @param filterParam is an additional param for entry filtering function
 * @param storeParam is an additional param for entry storing function
 *
 * @return the result of processing the compressed entry.
 *
 * @throws XPathException if a query error occurs
 * @throws XMLDBException if a database error occurs
 * @throws IOException if an I/O error occurs
 */
protected Sequence processCompressedEntry(String name, boolean isDirectory, InputStream is, Sequence filterParam, Sequence storeParam) throws IOException, XPathException, XMLDBException {
    String dataType = isDirectory ? "folder" : "resource";
    // call the entry-filter function
    Sequence[] filterParams = new Sequence[3];
    filterParams[0] = new StringValue(name);
    filterParams[1] = new StringValue(dataType);
    filterParams[2] = filterParam;
    Sequence entryFilterFunctionResult = entryFilterFunction.evalFunction(contextSequence, null, filterParams);
    if (BooleanValue.FALSE == entryFilterFunctionResult.itemAt(0)) {
        return Sequence.EMPTY_SEQUENCE;
    } else {
        Sequence entryDataFunctionResult;
        Sequence uncompressedData = Sequence.EMPTY_SEQUENCE;
        if (entryDataFunction.getSignature().getReturnType().getPrimaryType() != Type.EMPTY && entryDataFunction.getSignature().getArgumentCount() == 3) {
            Sequence[] dataParams = new Sequence[3];
            System.arraycopy(filterParams, 0, dataParams, 0, 2);
            dataParams[2] = storeParam;
            entryDataFunctionResult = entryDataFunction.evalFunction(contextSequence, null, dataParams);
            String path = entryDataFunctionResult.itemAt(0).getStringValue();
            Collection root = new LocalCollection(context.getSubject(), context.getBroker().getBrokerPool(), new AnyURIValue("/db").toXmldbURI());
            if (isDirectory) {
                XMLDBAbstractCollectionManipulator.createCollection(root, path);
            } else {
                Resource resource;
                Path file = Paths.get(path).normalize();
                name = FileUtils.fileName(file);
                path = file.getParent().toAbsolutePath().toString();
                Collection target = (path == null) ? root : XMLDBAbstractCollectionManipulator.createCollection(root, path);
                MimeType mime = MimeTable.getInstance().getContentTypeFor(name);
                // copy the input data
                final byte[] entryData;
                try (final UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
                    baos.write(is);
                    entryData = baos.toByteArray();
                }
                try (final InputStream bis = new UnsynchronizedByteArrayInputStream(entryData)) {
                    NodeValue content = ModuleUtils.streamToXML(context, bis);
                    resource = target.createResource(name, "XMLResource");
                    ContentHandler handler = ((XMLResource) resource).setContentAsSAX();
                    handler.startDocument();
                    content.toSAX(context.getBroker(), handler, null);
                    handler.endDocument();
                } catch (SAXException e) {
                    resource = target.createResource(name, "BinaryResource");
                    resource.setContent(entryData);
                }
                if (resource != null) {
                    if (mime != null) {
                        ((EXistResource) resource).setMimeType(mime.getName());
                    }
                    target.storeResource(resource);
                }
            }
        } else {
            // copy the input data
            final byte[] entryData;
            try (final UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
                baos.write(is);
                entryData = baos.toByteArray();
            }
            // try and parse as xml, fall back to binary
            try (final InputStream bis = new UnsynchronizedByteArrayInputStream(entryData)) {
                uncompressedData = ModuleUtils.streamToXML(context, bis);
            } catch (SAXException saxe) {
                if (entryData.length > 0) {
                    try (final InputStream bis = new UnsynchronizedByteArrayInputStream(entryData)) {
                        uncompressedData = BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), bis);
                    }
                }
            }
            // call the entry-data function
            Sequence[] dataParams = new Sequence[4];
            System.arraycopy(filterParams, 0, dataParams, 0, 2);
            dataParams[2] = uncompressedData;
            dataParams[3] = storeParam;
            entryDataFunctionResult = entryDataFunction.evalFunction(contextSequence, null, dataParams);
        }
        return entryDataFunctionResult;
    }
}
Also used : Path(java.nio.file.Path) LocalCollection(org.exist.xmldb.LocalCollection) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) InputStream(java.io.InputStream) XMLResource(org.xmldb.api.modules.XMLResource) EXistResource(org.exist.xmldb.EXistResource) Resource(org.xmldb.api.base.Resource) UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream) MimeType(org.exist.util.MimeType) ContentHandler(org.xml.sax.ContentHandler) XMLResource(org.xmldb.api.modules.XMLResource) SAXException(org.xml.sax.SAXException) EXistResource(org.exist.xmldb.EXistResource) LocalCollection(org.exist.xmldb.LocalCollection) Collection(org.xmldb.api.base.Collection) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream)

Example 85 with Resource

use of org.xmldb.api.base.Resource in project exist by eXist-db.

the class XMLDBExtractTask method execute.

@Override
public void execute() throws BuildException {
    if (uri == null) {
        if (failonerror) {
            throw (new BuildException("You need to specify an XMLDB collection URI"));
        }
    } else {
        registerDatabase();
        try {
            final Collection base = DatabaseManager.getCollection(uri, user, password);
            if (base == null) {
                throw (new BuildException("Collection " + uri + " could not be found."));
            }
            if ((resource != null) && (destDir == null)) {
                // extraction of a single resource
                log("Extracting resource: " + resource + " to " + destFile.toAbsolutePath().toString(), Project.MSG_INFO);
                final Resource res = base.getResource(resource);
                if (res == null) {
                    final String msg = "Resource " + resource + " not found.";
                    if (failonerror) {
                        throw (new BuildException(msg));
                    } else {
                        log(msg, Project.MSG_ERR);
                    }
                } else {
                    writeResource(res, destFile);
                }
            } else {
                // extraction of a collection
                extractResources(base, null);
                if (subcollections) {
                    extractSubCollections(base, null);
                }
            }
        } catch (final XMLDBException e) {
            final String msg = "XMLDB exception caught while executing query: " + e.getMessage();
            if (failonerror) {
                throw (new BuildException(msg, e));
            } else {
                log(msg, e, Project.MSG_ERR);
            }
        } catch (final IOException e) {
            final String msg = "XMLDB exception caught while writing destination file: " + e.getMessage();
            if (failonerror) {
                throw (new BuildException(msg, e));
            } else {
                log(msg, e, Project.MSG_ERR);
            }
        }
    }
}
Also used : ExtendedResource(org.exist.xmldb.ExtendedResource) XMLResource(org.xmldb.api.modules.XMLResource) Resource(org.xmldb.api.base.Resource) Collection(org.xmldb.api.base.Collection) XMLDBException(org.xmldb.api.base.XMLDBException) BuildException(org.apache.tools.ant.BuildException)

Aggregations

Resource (org.xmldb.api.base.Resource)173 XMLResource (org.xmldb.api.modules.XMLResource)126 Collection (org.xmldb.api.base.Collection)111 BinaryResource (org.xmldb.api.modules.BinaryResource)86 Test (org.junit.Test)77 UserManagementService (org.exist.xmldb.UserManagementService)52 ResourceSet (org.xmldb.api.base.ResourceSet)46 XMLDBException (org.xmldb.api.base.XMLDBException)38 EXistCollectionManagementService (org.exist.xmldb.EXistCollectionManagementService)32 EXistResource (org.exist.xmldb.EXistResource)27 CollectionManagementService (org.xmldb.api.modules.CollectionManagementService)25 XPathQueryService (org.xmldb.api.modules.XPathQueryService)18 EXistXPathQueryService (org.exist.xmldb.EXistXPathQueryService)16 Path (java.nio.file.Path)11 Database (org.xmldb.api.base.Database)11 XPathException (org.exist.xquery.XPathException)10 InputStream (java.io.InputStream)9 Source (javax.xml.transform.Source)9 BuildException (org.apache.tools.ant.BuildException)9 Diff (org.xmlunit.diff.Diff)9