Search in sources :

Example 96 with XMLResource

use of org.xmldb.api.modules.XMLResource in project exist by eXist-db.

the class XPathUtil method javaObjectToXPath.

public static final Sequence javaObjectToXPath(Object obj, XQueryContext context, boolean expandChars) throws XPathException {
    if (obj == null) {
        // return Sequence.EMPTY_SEQUENCE;
        return null;
    } else if (obj instanceof Sequence) {
        return (Sequence) obj;
    } else if (obj instanceof String) {
        final StringValue v = new StringValue((String) obj);
        return (expandChars ? v.expand() : v);
    } else if (obj instanceof Boolean) {
        return BooleanValue.valueOf(((Boolean) obj));
    } else if (obj instanceof Float) {
        return new FloatValue(((Float) obj));
    } else if (obj instanceof Double) {
        return new DoubleValue(((Double) obj));
    } else if (obj instanceof Short) {
        return new IntegerValue(((Short) obj), Type.SHORT);
    } else if (obj instanceof Integer) {
        return new IntegerValue(((Integer) obj), Type.INT);
    } else if (obj instanceof Long) {
        return new IntegerValue(((Long) obj), Type.LONG);
    } else if (obj instanceof byte[]) {
        return BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), new UnsynchronizedByteArrayInputStream((byte[]) obj));
    } else if (obj instanceof ResourceSet) {
        final Sequence seq = new AVLTreeNodeSet();
        try {
            final DBBroker broker = context.getBroker();
            for (final ResourceIterator it = ((ResourceSet) obj).getIterator(); it.hasMoreResources(); ) {
                seq.add(getNode(broker, (XMLResource) it.nextResource()));
            }
        } catch (final XMLDBException xe) {
            throw new XPathException("Failed to convert ResourceSet to node: " + xe.getMessage());
        }
        return seq;
    } else if (obj instanceof XMLResource) {
        return getNode(context.getBroker(), (XMLResource) obj);
    } else if (obj instanceof Node) {
        context.pushDocumentContext();
        final DOMStreamer streamer = (DOMStreamer) SerializerPool.getInstance().borrowObject(DOMStreamer.class);
        try {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            builder.startDocument();
            final DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder);
            streamer.setContentHandler(receiver);
            streamer.serialize((Node) obj, false);
            if (obj instanceof Document) {
                return builder.getDocument();
            } else {
                return builder.getDocument().getNode(1);
            }
        } catch (final SAXException e) {
            throw new XPathException("Failed to transform node into internal model: " + e.getMessage());
        } finally {
            context.popDocumentContext();
            SerializerPool.getInstance().returnObject(streamer);
        }
    } else if (obj instanceof List<?>) {
        boolean createNodeSequence = true;
        for (Object next : ((List<?>) obj)) {
            if (!(next instanceof NodeProxy)) {
                createNodeSequence = false;
                break;
            }
        }
        Sequence seq = createNodeSequence ? new AVLTreeNodeSet() : new ValueSequence();
        for (Object o : ((List<?>) obj)) {
            seq.add((Item) javaObjectToXPath(o, context, expandChars));
        }
        return seq;
    } else if (obj instanceof NodeList) {
        context.pushDocumentContext();
        final DOMStreamer streamer = (DOMStreamer) SerializerPool.getInstance().borrowObject(DOMStreamer.class);
        try {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            builder.startDocument();
            final DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder);
            streamer.setContentHandler(receiver);
            final ValueSequence seq = new ValueSequence();
            final NodeList nl = (NodeList) obj;
            int last = builder.getDocument().getLastNode();
            for (int i = 0; i < nl.getLength(); i++) {
                final Node n = nl.item(i);
                streamer.serialize(n, false);
                final NodeImpl created = builder.getDocument().getNode(last + 1);
                seq.add(created);
                last = builder.getDocument().getLastNode();
            }
            return seq;
        } catch (final SAXException e) {
            throw new XPathException("Failed to transform node into internal model: " + e.getMessage());
        } finally {
            context.popDocumentContext();
            SerializerPool.getInstance().returnObject(streamer);
        }
    } else if (obj instanceof Object[]) {
        boolean createNodeSequence = true;
        final Object[] array = (Object[]) obj;
        for (Object arrayItem : array) {
            if (!(arrayItem instanceof NodeProxy)) {
                createNodeSequence = false;
                break;
            }
        }
        Sequence seq = createNodeSequence ? new AVLTreeNodeSet() : new ValueSequence();
        for (Object arrayItem : array) {
            seq.add((Item) javaObjectToXPath(arrayItem, context, expandChars));
        }
        return seq;
    } else {
        return new JavaObjectValue(obj);
    }
}
Also used : Node(org.w3c.dom.Node) XMLDBException(org.xmldb.api.base.XMLDBException) Document(org.w3c.dom.Document) NodeProxy(org.exist.dom.persistent.NodeProxy) SAXException(org.xml.sax.SAXException) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) NodeList(org.w3c.dom.NodeList) List(java.util.List) NodeImpl(org.exist.dom.memtree.NodeImpl) NodeList(org.w3c.dom.NodeList) ResourceSet(org.xmldb.api.base.ResourceSet) AVLTreeNodeSet(org.exist.dom.persistent.AVLTreeNodeSet) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) RemoteXMLResource(org.exist.xmldb.RemoteXMLResource) XMLResource(org.xmldb.api.modules.XMLResource) LocalXMLResource(org.exist.xmldb.LocalXMLResource) DBBroker(org.exist.storage.DBBroker) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) DOMStreamer(org.exist.util.serializer.DOMStreamer) ResourceIterator(org.xmldb.api.base.ResourceIterator)

Example 97 with XMLResource

use of org.xmldb.api.modules.XMLResource in project exist by eXist-db.

the class TestDataGenerator method generate.

public Path[] generate(final org.xmldb.api.base.Collection collection, final String xqueryContent) throws SAXException {
    final String query = IMPORT + xqueryContent;
    try {
        final XQueryService service = (XQueryService) collection.getService("XQueryService", "1.0");
        service.declareVariable("filename", "");
        service.declareVariable("count", "0");
        final CompiledExpression compiled = service.compile(query);
        for (int i = 0; i < count; i++) {
            generatedFiles[i] = Files.createTempFile(prefix, ".xml");
            service.declareVariable("filename", generatedFiles[i].getFileName().toString());
            service.declareVariable("count", new Integer(i));
            final ResourceSet result = service.execute(compiled);
            try (final Writer out = Files.newBufferedWriter(generatedFiles[i], StandardCharsets.UTF_8)) {
                final SAXSerializer sax = new SAXSerializer(out, outputProps);
                for (ResourceIterator iter = result.getIterator(); iter.hasMoreResources(); ) {
                    XMLResource r = (XMLResource) iter.nextResource();
                    r.getContentAsSAX(sax);
                }
            }
        }
    } catch (final XMLDBException | IOException e) {
        LOG.error(e.getMessage(), e);
        throw new SAXException(e.getMessage(), e);
    }
    return generatedFiles;
}
Also used : XQueryService(org.xmldb.api.modules.XQueryService) XMLDBException(org.xmldb.api.base.XMLDBException) ResourceSet(org.xmldb.api.base.ResourceSet) CompiledExpression(org.xmldb.api.base.CompiledExpression) XMLResource(org.xmldb.api.modules.XMLResource) SAXException(org.xml.sax.SAXException) SAXSerializer(org.exist.util.serializer.SAXSerializer) ResourceIterator(org.xmldb.api.base.ResourceIterator)

Example 98 with XMLResource

use of org.xmldb.api.modules.XMLResource in project exist by eXist-db.

the class DocumentBuilderReceiverIntegrationTest method mergeDocuments.

@Test
public void mergeDocuments() throws XMLDBException {
    final ResourceSet result = existEmbeddedServer.executeQuery(query);
    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(expectedResult).build();
    final Source actualSource = Input.fromNode(((XMLResource) resource).getContentAsDOM()).build();
    final Diff diff = DiffBuilder.compare(expectedSource).withTest(actualSource).checkForSimilar().ignoreWhitespace().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) Source(javax.xml.transform.Source) XMLResource(org.xmldb.api.modules.XMLResource) Test(org.junit.Test)

Example 99 with XMLResource

use of org.xmldb.api.modules.XMLResource in project exist by eXist-db.

the class XQueryTriggerTest method storeDocument_invalidTriggerForPrepare.

@Test
public void storeDocument_invalidTriggerForPrepare() throws XMLDBException {
    final BinaryResource invalidModule = (BinaryResource) testCollection.createResource(MODULE_NAME, "BinaryResource");
    ((EXistResource) invalidModule).setMimeType("application/xquery");
    invalidModule.setContent(INVALID_MODULE.getBytes());
    testCollection.storeResource(invalidModule);
    // configure the Collection with the trigger under test
    final IndexQueryService idxConf = (IndexQueryService) testCollection.getService("IndexQueryService", "1.0");
    idxConf.configureCollection(COLLECTION_CONFIG);
    final int max_store_attempts = 10;
    int count_prepare_exceptions = 0;
    for (int i = 0; i < max_store_attempts; i++) {
        try {
            // this will fire the trigger
            final XMLResource doc = (XMLResource) testCollection.createResource(DOCUMENT_NAME, "XMLResource");
            doc.setContent(DOCUMENT_CONTENT);
            testCollection.storeResource(doc);
        } catch (XMLDBException xdbe) {
            if (xdbe.getCause() instanceof TriggerException) {
                if (xdbe.getCause().getMessage().equals(XQueryTrigger.PREPARE_EXCEPTION_MESSAGE)) {
                    count_prepare_exceptions++;
                }
            }
        }
    }
    assertEquals(max_store_attempts, count_prepare_exceptions);
}
Also used : EXistResource(org.exist.xmldb.EXistResource) BinaryResource(org.xmldb.api.modules.BinaryResource) IndexQueryService(org.exist.xmldb.IndexQueryService) XMLDBException(org.xmldb.api.base.XMLDBException) XMLResource(org.xmldb.api.modules.XMLResource)

Example 100 with XMLResource

use of org.xmldb.api.modules.XMLResource in project exist by eXist-db.

the class XQueryTriggerTest method documentUpdate.

/**
 * test a trigger fired by a Document Update
 */
@Test
public void documentUpdate() throws XMLDBException {
    final IndexQueryService idxConf = (IndexQueryService) testCollection.getService("IndexQueryService", "1.0");
    idxConf.configureCollection(COLLECTION_CONFIG);
    final XMLResource doc = (XMLResource) testCollection.createResource(DOCUMENT_NAME, "XMLResource");
    doc.setContent(DOCUMENT_CONTENT);
    testCollection.storeResource(doc);
    // TODO : trigger UPDATE events !
    final XUpdateQueryService update = (XUpdateQueryService) testCollection.getService("XUpdateQueryService", "1.0");
    update.updateResource(DOCUMENT_NAME, DOCUMENT_UPDATE);
    idxConf.configureCollection(EMPTY_COLLECTION_CONFIG);
    final XPathQueryService service = (XPathQueryService) testCollection.getService("XPathQueryService", "1.0");
    // this is necessary to compare with MODIFIED_DOCUMENT_CONTENT ; TODO better compare with XML diff tool
    service.setProperty(OutputKeys.INDENT, "no");
    ResourceSet result = service.query(BEFORE + CREATE + DOCUMENT + documentURI);
    assertEquals(1, result.getSize());
    result = service.query(AFTER + CREATE + DOCUMENT + documentURI);
    assertEquals(1, result.getSize());
    result = service.query(BEFORE + UPDATE + DOCUMENT + documentURI);
    assertEquals(1, result.getSize());
    result = service.query(AFTER + UPDATE + DOCUMENT + documentURI);
    assertEquals(1, result.getSize());
    result = service.query(EVENTS);
    assertEquals(4, result.getSize());
// TODO: document itself
// result = service.query("/events/event[@id = 'trigger2']/document/test");
// assertEquals(2, result.getSize());
// assertXMLEqual(DOCUMENT_CONTENT, result.getResource(0).getContent().toString());
// assertXMLEqual(MODIFIED_DOCUMENT_CONTENT, result.getResource(1).getContent().toString());
}
Also used : XUpdateQueryService(org.xmldb.api.modules.XUpdateQueryService) XPathQueryService(org.xmldb.api.modules.XPathQueryService) IndexQueryService(org.exist.xmldb.IndexQueryService) ResourceSet(org.xmldb.api.base.ResourceSet) XMLResource(org.xmldb.api.modules.XMLResource)

Aggregations

XMLResource (org.xmldb.api.modules.XMLResource)142 Collection (org.xmldb.api.base.Collection)56 ResourceSet (org.xmldb.api.base.ResourceSet)56 XPathQueryService (org.xmldb.api.modules.XPathQueryService)49 Test (org.junit.Test)33 Resource (org.xmldb.api.base.Resource)24 XQueryService (org.xmldb.api.modules.XQueryService)23 Node (org.w3c.dom.Node)22 CollectionManagementService (org.xmldb.api.modules.CollectionManagementService)20 EXistXPathQueryService (org.exist.xmldb.EXistXPathQueryService)18 Document (org.w3c.dom.Document)16 XMLDBException (org.xmldb.api.base.XMLDBException)15 EXistResource (org.exist.xmldb.EXistResource)9 EXistXQueryService (org.exist.xmldb.EXistXQueryService)9 BinaryResource (org.xmldb.api.modules.BinaryResource)9 Path (java.nio.file.Path)8 Before (org.junit.Before)8 Element (org.w3c.dom.Element)8 Source (javax.xml.transform.Source)7 SAXSerializer (org.exist.util.serializer.SAXSerializer)7