Search in sources :

Example 31 with IntegerValue

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

the class XQueryDeclareContextItemTest method declareContextItemExternalDefaultOverrides.

@Test
public void declareContextItemExternalDefaultOverrides() throws EXistException, PermissionDeniedException, XPathException {
    final String query = "xquery version \"3.0\";\n" + "declare context item external := 3; \n" + ". + 4";
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    final XQuery xquery = pool.getXQueryService();
    try (final DBBroker broker = pool.getBroker()) {
        final Sequence result = xquery.execute(broker, query, new IntegerValue(20));
        assertEquals(1, result.getItemCount());
        assertEquals(24, (int) result.itemAt(0).toJavaObject(int.class));
    }
}
Also used : DBBroker(org.exist.storage.DBBroker) IntegerValue(org.exist.xquery.value.IntegerValue) Sequence(org.exist.xquery.value.Sequence) BrokerPool(org.exist.storage.BrokerPool) Test(org.junit.Test)

Example 32 with IntegerValue

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

the class FunGMLProducers method eval.

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    Sequence result = null;
    try {
        AbstractGMLJDBCIndexWorker indexWorker = (AbstractGMLJDBCIndexWorker) context.getBroker().getIndexController().getWorkerByIndexId(AbstractGMLJDBCIndex.ID);
        if (indexWorker == null) {
            logger.error("Unable to find a spatial index worker");
            throw new XPathException(this, "Unable to find a spatial index worker");
        }
        Geometry geometry = null;
        String targetSRS = null;
        if (isCalledAs("transform")) {
            if (args[0].isEmpty())
                result = Sequence.EMPTY_SEQUENCE;
            else {
                NodeValue geometryNode = (NodeValue) args[0].itemAt(0);
                // Try to get the geometry from the index
                String sourceSRS = null;
                if (geometryNode.getImplementationType() == NodeValue.PERSISTENT_NODE) {
                    sourceSRS = indexWorker.getGeometricPropertyForNode(context, (NodeProxy) geometryNode, "SRS_NAME").getStringValue();
                    geometry = indexWorker.getGeometryForNode(context.getBroker(), (NodeProxy) geometryNode, false);
                    hasUsedIndex = true;
                }
                // Otherwise, build it
                if (geometry == null) {
                    sourceSRS = ((Element) geometryNode.getNode()).getAttribute("srsName").trim();
                    geometry = indexWorker.streamNodeToGeometry(context, geometryNode);
                }
                if (geometry == null) {
                    logger.error("Unable to get a geometry from the node");
                    throw new XPathException("Unable to get a geometry from the node");
                }
                targetSRS = args[1].itemAt(0).getStringValue().trim();
                geometry = indexWorker.transformGeometry(geometry, sourceSRS, targetSRS);
            }
        } else if (isCalledAs("WKTtoGML")) {
            if (args[0].isEmpty())
                result = Sequence.EMPTY_SEQUENCE;
            else {
                String wkt = args[0].itemAt(0).getStringValue();
                WKTReader wktReader = new WKTReader();
                try {
                    geometry = wktReader.read(wkt);
                } catch (ParseException e) {
                    logger.error(e.getMessage());
                    throw new XPathException(e);
                }
                if (geometry == null) {
                    logger.error("Unable to get a geometry from the node");
                    throw new XPathException("Unable to get a geometry from the node");
                }
                targetSRS = args[1].itemAt(0).getStringValue().trim();
            }
        } else if (isCalledAs("buffer")) {
            if (args[0].isEmpty())
                result = Sequence.EMPTY_SEQUENCE;
            else {
                NodeValue geometryNode = (NodeValue) args[0].itemAt(0);
                // Try to get the geometry from the index
                if (geometryNode.getImplementationType() == NodeValue.PERSISTENT_NODE) {
                    targetSRS = indexWorker.getGeometricPropertyForNode(context, (NodeProxy) geometryNode, "SRS_NAME").getStringValue();
                    geometry = indexWorker.getGeometryForNode(context.getBroker(), (NodeProxy) geometryNode, false);
                    hasUsedIndex = true;
                }
                // Otherwise, build it
                if (geometry == null) {
                    targetSRS = ((Element) geometryNode.getNode()).getAttribute("srsName").trim();
                    geometry = indexWorker.streamNodeToGeometry(context, geometryNode);
                }
                if (geometry == null) {
                    logger.error("Unable to get a geometry from the node");
                    throw new XPathException("Unable to get a geometry from the node");
                }
                double distance = ((DoubleValue) args[1].itemAt(0)).getDouble();
                int quadrantSegments = 8;
                int endCapStyle = BufferOp.CAP_ROUND;
                if (getArgumentCount() > 2 && Type.subTypeOf(args[2].itemAt(0).getType(), Type.INTEGER))
                    quadrantSegments = ((IntegerValue) args[2].itemAt(0)).getInt();
                if (getArgumentCount() > 3 && Type.subTypeOf(args[3].itemAt(0).getType(), Type.INTEGER))
                    endCapStyle = ((IntegerValue) args[3].itemAt(0)).getInt();
                switch(endCapStyle) {
                    case BufferOp.CAP_ROUND:
                    case BufferOp.CAP_BUTT:
                    case BufferOp.CAP_SQUARE:
                        // OK
                        break;
                    default:
                        {
                            logger.error("Invalid line end style");
                            throw new XPathException("Invalid line end style");
                        }
                }
                geometry = geometry.buffer(distance, quadrantSegments, endCapStyle);
            }
        } else if (isCalledAs("getBbox")) {
            if (args[0].isEmpty())
                result = Sequence.EMPTY_SEQUENCE;
            else {
                NodeValue geometryNode = (NodeValue) args[0].itemAt(0);
                // Try to get the geometry from the index
                if (geometryNode.getImplementationType() == NodeValue.PERSISTENT_NODE) {
                    targetSRS = indexWorker.getGeometricPropertyForNode(context, (NodeProxy) geometryNode, "SRS_NAME").getStringValue();
                    geometry = indexWorker.getGeometryForNode(context.getBroker(), (NodeProxy) geometryNode, false);
                    hasUsedIndex = true;
                }
                // Otherwise, build it
                if (geometry == null) {
                    targetSRS = ((Element) geometryNode.getNode()).getAttribute("srsName").trim();
                    geometry = indexWorker.streamNodeToGeometry(context, geometryNode);
                }
                if (geometry == null) {
                    logger.error("Unable to get a geometry from the node");
                    throw new XPathException("Unable to get a geometry from the node");
                }
                geometry = geometry.getEnvelope();
            }
        } else if (isCalledAs("convexHull")) {
            if (args[0].isEmpty())
                result = Sequence.EMPTY_SEQUENCE;
            else {
                NodeValue geometryNode = (NodeValue) args[0].itemAt(0);
                // Try to get the geometry from the index
                if (geometryNode.getImplementationType() == NodeValue.PERSISTENT_NODE) {
                    targetSRS = indexWorker.getGeometricPropertyForNode(context, (NodeProxy) geometryNode, "SRS_NAME").getStringValue();
                    geometry = indexWorker.getGeometryForNode(context.getBroker(), (NodeProxy) geometryNode, false);
                    hasUsedIndex = true;
                }
                // Otherwise, build it
                if (geometry == null) {
                    targetSRS = ((Element) geometryNode.getNode()).getAttribute("srsName").trim();
                    geometry = indexWorker.streamNodeToGeometry(context, geometryNode);
                }
                if (geometry == null) {
                    logger.error("Unable to get a geometry from the node");
                    throw new XPathException("Unable to get a geometry from the node");
                }
                geometry = geometry.convexHull();
            }
        } else if (isCalledAs("boundary")) {
            if (args[0].isEmpty())
                result = Sequence.EMPTY_SEQUENCE;
            else {
                NodeValue geometryNode = (NodeValue) args[0].itemAt(0);
                // Try to get the geometry from the index
                if (geometryNode.getImplementationType() == NodeValue.PERSISTENT_NODE) {
                    targetSRS = indexWorker.getGeometricPropertyForNode(context, (NodeProxy) geometryNode, "SRS_NAME").getStringValue();
                    geometry = indexWorker.getGeometryForNode(context.getBroker(), (NodeProxy) geometryNode, false);
                    hasUsedIndex = true;
                }
                // Otherwise, build it
                if (geometry == null) {
                    targetSRS = ((Element) geometryNode.getNode()).getAttribute("srsName").trim();
                    geometry = indexWorker.streamNodeToGeometry(context, geometryNode);
                }
                if (geometry == null) {
                    logger.error("Unable to get a geometry from the node");
                    throw new XPathException("Unable to get a geometry from the node");
                }
                geometry = geometry.getBoundary();
            }
        } else {
            Geometry geometry1 = null;
            Geometry geometry2 = null;
            if (args[0].isEmpty() && args[1].isEmpty())
                result = Sequence.EMPTY_SEQUENCE;
            else if (!args[0].isEmpty() && args[1].isEmpty())
                result = args[0].itemAt(0).toSequence();
            else if (args[0].isEmpty() && !args[1].isEmpty())
                result = args[1].itemAt(0).toSequence();
            else {
                NodeValue geometryNode1 = (NodeValue) args[0].itemAt(0);
                NodeValue geometryNode2 = (NodeValue) args[1].itemAt(0);
                String srsName1 = null;
                String srsName2 = null;
                // Try to get the geometries from the index
                if (geometryNode1.getImplementationType() == NodeValue.PERSISTENT_NODE) {
                    srsName1 = indexWorker.getGeometricPropertyForNode(context, (NodeProxy) geometryNode1, "SRS_NAME").getStringValue();
                    geometry1 = indexWorker.getGeometryForNode(context.getBroker(), (NodeProxy) geometryNode1, false);
                    hasUsedIndex = true;
                }
                if (geometryNode2.getImplementationType() == NodeValue.PERSISTENT_NODE) {
                    srsName2 = indexWorker.getGeometricPropertyForNode(context, (NodeProxy) geometryNode2, "SRS_NAME").getStringValue();
                    geometry2 = indexWorker.getGeometryForNode(context.getBroker(), (NodeProxy) geometryNode2, false);
                    hasUsedIndex = true;
                }
                // Otherwise build them
                if (geometry1 == null) {
                    srsName1 = ((Element) geometryNode1.getNode()).getAttribute("srsName").trim();
                    geometry1 = indexWorker.streamNodeToGeometry(context, geometryNode1);
                }
                if (geometry2 == null) {
                    srsName2 = ((Element) geometryNode2.getNode()).getAttribute("srsName").trim();
                    geometry2 = indexWorker.streamNodeToGeometry(context, geometryNode2);
                }
                if (geometry1 == null) {
                    logger.error("Unable to get a geometry from the first node");
                    throw new XPathException("Unable to get a geometry from the first node");
                }
                if (geometry2 == null) {
                    logger.error("Unable to get a geometry from the second node");
                    throw new XPathException("Unable to get a geometry from the second node");
                }
                if (srsName1 == null)
                    throw new XPathException("Unable to get a SRS for the first geometry");
                if (srsName2 == null)
                    throw new XPathException("Unable to get a SRS for the second geometry");
                // Transform the second geometry in the SRS of the first one if necessary
                if (!srsName1.equalsIgnoreCase(srsName2)) {
                    geometry2 = indexWorker.transformGeometry(geometry2, srsName1, srsName2);
                }
                if (isCalledAs("intersection")) {
                    geometry = geometry1.intersection(geometry2);
                } else if (isCalledAs("union")) {
                    geometry = geometry1.union(geometry2);
                } else if (isCalledAs("difference")) {
                    geometry = geometry1.difference(geometry2);
                } else if (isCalledAs("symetricDifference")) {
                    geometry = geometry1.symDifference(geometry2);
                }
                targetSRS = srsName1;
            }
        }
        if (result == null) {
            String gmlPrefix = context.getPrefixForURI(AbstractGMLJDBCIndexWorker.GML_NS);
            if (gmlPrefix == null) {
                logger.error("namespace is not defined:" + SpatialModule.PREFIX);
                throw new XPathException("'" + AbstractGMLJDBCIndexWorker.GML_NS + "' namespace is not defined");
            }
            context.pushDocumentContext();
            try {
                MemTreeBuilder builder = context.getDocumentBuilder();
                DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder);
                result = (NodeValue) indexWorker.streamGeometryToElement(geometry, targetSRS, receiver);
            } finally {
                context.popDocumentContext();
            }
        }
    } catch (SpatialIndexException e) {
        logger.error(e.getMessage());
        throw new XPathException(e);
    }
    return result;
}
Also used : NodeValue(org.exist.xquery.value.NodeValue) XPathException(org.exist.xquery.XPathException) Element(org.w3c.dom.Element) IntegerValue(org.exist.xquery.value.IntegerValue) Sequence(org.exist.xquery.value.Sequence) SpatialIndexException(org.exist.indexing.spatial.SpatialIndexException) WKTReader(com.vividsolutions.jts.io.WKTReader) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) NodeProxy(org.exist.dom.persistent.NodeProxy) Geometry(com.vividsolutions.jts.geom.Geometry) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) DoubleValue(org.exist.xquery.value.DoubleValue) AbstractGMLJDBCIndexWorker(org.exist.indexing.spatial.AbstractGMLJDBCIndexWorker) ParseException(com.vividsolutions.jts.io.ParseException)

Example 33 with IntegerValue

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

the class BaseConversionFunctionsTest method intToOctal.

/**
 * Test of eval method, of class PermissionsFunctions.
 */
@Test
public void intToOctal() throws XPathException {
    final XQueryContext mckContext = EasyMock.createMock(XQueryContext.class);
    final BaseConversionFunctions baseConversionFunctions = new BaseConversionFunctions(mckContext, BaseConversionFunctions.FNS_INT_TO_OCTAL);
    Sequence[] args = { new IntegerValue(511) };
    final Sequence result = baseConversionFunctions.eval(args, null);
    assertEquals(1, result.getItemCount());
    assertEquals("0777", result.itemAt(0).toString());
}
Also used : IntegerValue(org.exist.xquery.value.IntegerValue) XQueryContext(org.exist.xquery.XQueryContext) Sequence(org.exist.xquery.value.Sequence) Test(org.junit.Test)

Example 34 with IntegerValue

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

the class ConnectionIT method getConnectionIsAutomaticallyClosed.

@Test
public void getConnectionIsAutomaticallyClosed() throws EXistException, XPathException, PermissionDeniedException, IOException {
    final String mainQuery = "import module namespace sql = \"http://exist-db.org/xquery/sql\";\n" + "sql:get-connection(\"" + h2Database.getDriverClass().getName() + "\", \"" + h2Database.getUrl() + "\", \"" + h2Database.getUser() + "\", \"" + h2Database.getPassword() + "\")";
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    final Source mainQuerySource = new StringSource(mainQuery);
    try (final DBBroker broker = pool.getBroker();
        final Txn transaction = pool.getTransactionManager().beginTransaction()) {
        final XQueryContext escapedMainQueryContext = withCompiledQuery(broker, mainQuerySource, mainCompiledQuery -> {
            final XQueryContext mainQueryContext = mainCompiledQuery.getContext();
            // execute the query
            final Sequence result = executeQuery(broker, mainCompiledQuery);
            // check that the handle for the sql connection that was created was valid
            assertEquals(1, result.getItemCount());
            assertTrue(result.itemAt(0) instanceof IntegerValue);
            assertEquals(Type.LONG, result.itemAt(0).getType());
            final long connectionHandle = result.itemAt(0).toJavaObject(long.class);
            assertFalse(connectionHandle == 0);
            // intentionally escape the context from the lambda
            return mainQueryContext;
        });
        // check the connections map is empty
        final int connectionsCount = ModuleUtils.readContextMap(escapedMainQueryContext, SQLModule.CONNECTIONS_CONTEXTVAR, Map::size);
        assertEquals(0, connectionsCount);
        transaction.commit();
    }
}
Also used : DBBroker(org.exist.storage.DBBroker) IntegerValue(org.exist.xquery.value.IntegerValue) StringSource(org.exist.source.StringSource) Txn(org.exist.storage.txn.Txn) Sequence(org.exist.xquery.value.Sequence) Map(java.util.Map) BrokerPool(org.exist.storage.BrokerPool) StringSource(org.exist.source.StringSource) StringInputSource(org.exist.util.StringInputSource) Source(org.exist.source.Source) Test(org.junit.Test)

Example 35 with IntegerValue

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

the class ConnectionIT method getConnectionFromModuleIsAutomaticallyClosed.

@Test
public void getConnectionFromModuleIsAutomaticallyClosed() throws EXistException, XPathException, PermissionDeniedException, IOException, LockException, SAXException {
    final String moduleQuery = "module namespace mymodule = \"http://mymodule.com\";\n" + "import module namespace sql = \"http://exist-db.org/xquery/sql\";\n" + "declare function mymodule:get-handle() {\n" + "    sql:get-connection(\"" + h2Database.getDriverClass().getName() + "\", \"" + h2Database.getUrl() + "\", \"" + h2Database.getUser() + "\", \"" + h2Database.getPassword() + "\")\n" + "};\n";
    final String mainQuery = "import module namespace mymodule = \"http://mymodule.com\" at \"xmldb:exist:///db/mymodule.xqm\";\n" + "mymodule:get-handle()";
    final Source mainQuerySource = new StringSource(mainQuery);
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
        final Txn transaction = pool.getTransactionManager().beginTransaction()) {
        // store module
        try (final Collection collection = broker.openCollection(XmldbURI.create("/db"), Lock.LockMode.WRITE_LOCK)) {
            broker.storeDocument(transaction, XmldbURI.create("mymodule.xqm"), new StringInputSource(moduleQuery.getBytes(UTF_8)), MimeType.XQUERY_TYPE, collection);
        }
        final Tuple2<XQueryContext, ModuleContext> escapedContexts = withCompiledQuery(broker, mainQuerySource, mainCompiledQuery -> {
            final XQueryContext mainQueryContext = mainCompiledQuery.getContext();
            // get the context of the library module
            final Module[] libraryModules = mainQueryContext.getModules("http://mymodule.com");
            assertEquals(1, libraryModules.length);
            assertTrue(libraryModules[0] instanceof ExternalModule);
            final ExternalModule libraryModule = (ExternalModule) libraryModules[0];
            final XQueryContext libraryQueryContext = libraryModule.getContext();
            assertTrue(libraryQueryContext instanceof ModuleContext);
            // execute the query
            final Sequence result = executeQuery(broker, mainCompiledQuery);
            // check that the handle for the sql connection that was created was valid
            assertEquals(1, result.getItemCount());
            assertTrue(result.itemAt(0) instanceof IntegerValue);
            assertEquals(Type.LONG, result.itemAt(0).getType());
            final long connectionHandle = result.itemAt(0).toJavaObject(long.class);
            assertFalse(connectionHandle == 0);
            // intentionally escape the contexts from the lambda
            return Tuple(mainQueryContext, (ModuleContext) libraryQueryContext);
        });
        final XQueryContext escapedMainQueryContext = escapedContexts._1;
        final ModuleContext escapedLibraryQueryContext = escapedContexts._2;
        assertTrue(escapedMainQueryContext != escapedLibraryQueryContext);
        // check the connections were closed in the main module
        final int mainConnectionsCount = ModuleUtils.readContextMap(escapedMainQueryContext, SQLModule.CONNECTIONS_CONTEXTVAR, Map::size);
        assertEquals(0, mainConnectionsCount);
        // check the connections were closed in the library module
        final int libraryConnectionsCount = ModuleUtils.readContextMap(escapedLibraryQueryContext, SQLModule.CONNECTIONS_CONTEXTVAR, Map::size);
        assertEquals(0, libraryConnectionsCount);
        transaction.commit();
    }
}
Also used : IntegerValue(org.exist.xquery.value.IntegerValue) Txn(org.exist.storage.txn.Txn) Sequence(org.exist.xquery.value.Sequence) StringSource(org.exist.source.StringSource) StringInputSource(org.exist.util.StringInputSource) Source(org.exist.source.Source) DBBroker(org.exist.storage.DBBroker) StringInputSource(org.exist.util.StringInputSource) Collection(org.exist.collections.Collection) StringSource(org.exist.source.StringSource) Map(java.util.Map) BrokerPool(org.exist.storage.BrokerPool) Test(org.junit.Test)

Aggregations

IntegerValue (org.exist.xquery.value.IntegerValue)63 Sequence (org.exist.xquery.value.Sequence)33 XPathException (org.exist.xquery.XPathException)32 BrokerPool (org.exist.storage.BrokerPool)11 DBBroker (org.exist.storage.DBBroker)11 Test (org.junit.Test)11 Txn (org.exist.storage.txn.Txn)8 MessagingException (jakarta.mail.MessagingException)7 StringInputSource (org.exist.util.StringInputSource)7 NamingException (javax.naming.NamingException)6 DirContext (javax.naming.directory.DirContext)6 QName (org.exist.dom.QName)6 Source (org.exist.source.Source)6 StringSource (org.exist.source.StringSource)6 InputStream (java.io.InputStream)5 Map (java.util.Map)5 StringValue (org.exist.xquery.value.StringValue)5 ValueSequence (org.exist.xquery.value.ValueSequence)5 Folder (jakarta.mail.Folder)4 Image (java.awt.Image)4