Search in sources :

Example 11 with Base64BinaryValueType

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

the class GMLHSQLIndexWorker method getGeometricPropertyForNode.

@Override
protected AtomicValue getGeometricPropertyForNode(XQueryContext context, NodeProxy p, Connection conn, String propertyName) throws SQLException, XPathException {
    PreparedStatement ps = conn.prepareStatement("SELECT " + propertyName + " FROM " + GMLHSQLIndex.TABLE_NAME + " WHERE DOCUMENT_URI = ? AND NODE_ID_UNITS = ? AND NODE_ID = ?");
    ps.setString(1, p.getOwnerDocument().getURI().toString());
    ps.setInt(2, p.getNodeId().units());
    byte[] bytes = new byte[p.getNodeId().size()];
    p.getNodeId().serialize(bytes, 0);
    ps.setBytes(3, bytes);
    ResultSet rs = null;
    try {
        rs = ps.executeQuery();
        if (!rs.next())
            // Nothing returned
            return AtomicValue.EMPTY_VALUE;
        AtomicValue result = null;
        if (rs.getMetaData().getColumnClassName(1).equals(Boolean.class.getName())) {
            result = new BooleanValue(rs.getBoolean(1));
        } else if (rs.getMetaData().getColumnClassName(1).equals(Double.class.getName())) {
            result = new DoubleValue(rs.getDouble(1));
        } else if (rs.getMetaData().getColumnClassName(1).equals(String.class.getName())) {
            result = new StringValue(rs.getString(1));
        } else if (rs.getMetaData().getColumnType(1) == java.sql.Types.BINARY) {
            result = BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), new UnsynchronizedByteArrayInputStream(rs.getBytes(1)));
        } else
            throw new SQLException("Unable to make an atomic value from '" + rs.getMetaData().getColumnClassName(1) + "'");
        if (rs.next()) {
            // Should be impossible
            throw new SQLException("More than one geometry for node " + p);
        }
        return result;
    } finally {
        if (rs != null)
            rs.close();
        ps.close();
    }
}
Also used : DoubleValue(org.exist.xquery.value.DoubleValue) BooleanValue(org.exist.xquery.value.BooleanValue) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) AtomicValue(org.exist.xquery.value.AtomicValue) Base64BinaryValueType(org.exist.xquery.value.Base64BinaryValueType) StringValue(org.exist.xquery.value.StringValue)

Example 12 with Base64BinaryValueType

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

the class GMLHSQLIndexWorker method getGeometricPropertyForNodes.

@Override
protected ValueSequence getGeometricPropertyForNodes(XQueryContext context, NodeSet contextSet, Connection conn, String propertyName) throws SQLException, XPathException {
    // TODO : generate it in AbstractGMLJDBCIndexWorker
    String docConstraint = "";
    boolean refine_query_on_doc = false;
    if (contextSet != null) {
        if (contextSet.getDocumentSet().getDocumentCount() <= index.getMaxDocsInContextToRefineQuery()) {
            DocumentImpl doc;
            Iterator<DocumentImpl> it = contextSet.getDocumentSet().getDocumentIterator();
            doc = it.next();
            docConstraint = "(DOCUMENT_URI = '" + doc.getURI().toString() + "')";
            while (it.hasNext()) {
                doc = it.next();
                docConstraint = docConstraint + " OR (DOCUMENT_URI = '" + doc.getURI().toString() + "')";
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("Refine query on documents is enabled.");
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Refine query on documents is disabled.");
            }
        }
    }
    PreparedStatement ps = conn.prepareStatement("SELECT " + propertyName + ", DOCUMENT_URI, NODE_ID_UNITS, NODE_ID" + " FROM " + GMLHSQLIndex.TABLE_NAME + (refine_query_on_doc ? " WHERE " + docConstraint : ""));
    ResultSet rs = null;
    try {
        rs = ps.executeQuery();
        ValueSequence result;
        if (contextSet == null)
            result = new ValueSequence();
        else
            result = new ValueSequence(contextSet.getLength());
        while (rs.next()) {
            DocumentImpl doc = null;
            try {
                doc = (DocumentImpl) broker.getXMLResource(XmldbURI.create(rs.getString("DOCUMENT_URI")));
            } catch (PermissionDeniedException e) {
                LOG.debug(e);
                // Untested, but that is roughly what should be returned.
                if (rs.getMetaData().getColumnClassName(1).equals(Boolean.class.getName())) {
                    result.add(AtomicValue.EMPTY_VALUE);
                } else if (rs.getMetaData().getColumnClassName(1).equals(Double.class.getName())) {
                    result.add(AtomicValue.EMPTY_VALUE);
                } else if (rs.getMetaData().getColumnClassName(1).equals(String.class.getName())) {
                    result.add(AtomicValue.EMPTY_VALUE);
                } else if (rs.getMetaData().getColumnType(1) == java.sql.Types.BINARY) {
                    result.add(AtomicValue.EMPTY_VALUE);
                } else
                    throw new SQLException("Unable to make an atomic value from '" + rs.getMetaData().getColumnClassName(1) + "'");
                // Ignore since the broker has no right on the document
                continue;
            }
            if (contextSet.getDocumentSet().contains(doc.getDocId())) {
                NodeId nodeId = new DLN(rs.getInt("NODE_ID_UNITS"), rs.getBytes("NODE_ID"), 0);
                NodeProxy p = new NodeProxy(doc, nodeId);
                // VirtualNodeSet when on the DESCENDANT_OR_SELF axis
                if (contextSet.get(p) != null) {
                    if (rs.getMetaData().getColumnClassName(1).equals(Boolean.class.getName())) {
                        result.add(new BooleanValue(rs.getBoolean(1)));
                    } else if (rs.getMetaData().getColumnClassName(1).equals(Double.class.getName())) {
                        result.add(new DoubleValue(rs.getDouble(1)));
                    } else if (rs.getMetaData().getColumnClassName(1).equals(String.class.getName())) {
                        result.add(new StringValue(rs.getString(1)));
                    } else if (rs.getMetaData().getColumnType(1) == java.sql.Types.BINARY) {
                        result.add(BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), new UnsynchronizedByteArrayInputStream(rs.getBytes(1))));
                    } else
                        throw new SQLException("Unable to make an atomic value from '" + rs.getMetaData().getColumnClassName(1) + "'");
                }
            }
        }
        return result;
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
    }
}
Also used : DLN(org.exist.numbering.DLN) Base64BinaryValueType(org.exist.xquery.value.Base64BinaryValueType) DoubleValue(org.exist.xquery.value.DoubleValue) BooleanValue(org.exist.xquery.value.BooleanValue) ValueSequence(org.exist.xquery.value.ValueSequence) NodeId(org.exist.numbering.NodeId) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) PermissionDeniedException(org.exist.security.PermissionDeniedException) StringValue(org.exist.xquery.value.StringValue)

Example 13 with Base64BinaryValueType

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

the class FunGeometricProperties method eval.

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    Sequence result = null;
    Sequence nodes = args[0];
    if (nodes.isEmpty()) {
        result = Sequence.EMPTY_SEQUENCE;
    } else {
        try {
            Geometry geometry = null;
            String sourceCRS = null;
            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");
            }
            String propertyName = null;
            if (isCalledAs("getWKT")) {
                propertyName = "WKT";
            } else if (isCalledAs("getWKB")) {
                propertyName = "WKB";
            } else if (isCalledAs("getMinX")) {
                propertyName = "MINX";
            } else if (isCalledAs("getMaxX")) {
                propertyName = "MAXX";
            } else if (isCalledAs("getMinY")) {
                propertyName = "MINY";
            } else if (isCalledAs("getMaxY")) {
                propertyName = "MAXY";
            } else if (isCalledAs("getCentroidX")) {
                propertyName = "CENTROID_X";
            } else if (isCalledAs("getCentroidY")) {
                propertyName = "CENTROID_Y";
            } else if (isCalledAs("getArea")) {
                propertyName = "AREA";
            } else if (isCalledAs("getEPSG4326WKT")) {
                propertyName = "EPSG4326_WKT";
            } else if (isCalledAs("getEPSG4326WKB")) {
                propertyName = "EPSG4326_WKB";
            } else if (isCalledAs("getEPSG4326MinX")) {
                propertyName = "EPSG4326_MINX";
            } else if (isCalledAs("getEPSG4326MaxX")) {
                propertyName = "EPSG4326_MAXX";
            } else if (isCalledAs("getEPSG4326MinY")) {
                propertyName = "EPSG4326_MINY";
            } else if (isCalledAs("getEPSG4326MaxY")) {
                propertyName = "EPSG4326_MAXY";
            } else if (isCalledAs("getEPSG4326CentroidX")) {
                propertyName = "EPSG4326_CENTROID_X";
            } else if (isCalledAs("getEPSG4326CentroidY")) {
                propertyName = "EPSG4326_CENTROID_Y";
            } else if (isCalledAs("getEPSG4326Area")) {
                propertyName = "EPSG4326_AREA";
            } else if (isCalledAs("getSRS")) {
                propertyName = "SRS_NAME";
            } else if (isCalledAs("getGeometryType")) {
                propertyName = "GEOMETRY_TYPE";
            } else if (isCalledAs("isClosed")) {
                propertyName = "IS_CLOSED";
            } else if (isCalledAs("isSimple")) {
                propertyName = "IS_SIMPLE";
            } else if (isCalledAs("isValid")) {
                propertyName = "IS_VALID";
            } else {
                logger.error("Unknown spatial property: {}", getName().getLocalPart());
                throw new XPathException("Unknown spatial property: " + getName().getLocalPart());
            }
            NodeValue geometryNode = (NodeValue) nodes.itemAt(0);
            if (geometryNode.getImplementationType() == NodeValue.PERSISTENT_NODE) {
                // The node should be indexed : get its property
                result = indexWorker.getGeometricPropertyForNode(context, (NodeProxy) geometryNode, propertyName);
                hasUsedIndex = true;
            } else {
                // builds the geometry
                sourceCRS = ((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");
                }
                // Transform the geometry to EPSG:4326 if relevant
                if (propertyName.contains("EPSG4326")) {
                    geometry = indexWorker.transformGeometry(geometry, sourceCRS, "EPSG:4326");
                    if (isCalledAs("getEPSG4326WKT")) {
                        result = new StringValue(wktWriter.write(geometry));
                    } else if (isCalledAs("getEPSG4326WKB")) {
                        byte[] data = wkbWriter.write(geometry);
                        return BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), new UnsynchronizedByteArrayInputStream(data));
                    } else if (isCalledAs("getEPSG4326MinX")) {
                        result = new DoubleValue(geometry.getEnvelopeInternal().getMinX());
                    } else if (isCalledAs("getEPSG4326MaxX")) {
                        result = new DoubleValue(geometry.getEnvelopeInternal().getMaxX());
                    } else if (isCalledAs("getEPSG4326MinY")) {
                        result = new DoubleValue(geometry.getEnvelopeInternal().getMinY());
                    } else if (isCalledAs("getEPSG4326MaxY")) {
                        result = new DoubleValue(geometry.getEnvelopeInternal().getMaxY());
                    } else if (isCalledAs("getEPSG4326CentroidX")) {
                        result = new DoubleValue(geometry.getCentroid().getX());
                    } else if (isCalledAs("getEPSG4326CentroidY")) {
                        result = new DoubleValue(geometry.getCentroid().getY());
                    } else if (isCalledAs("getEPSG4326Area")) {
                        result = new DoubleValue(geometry.getArea());
                    }
                } else if (isCalledAs("getWKT")) {
                    result = new StringValue(wktWriter.write(geometry));
                } else if (isCalledAs("getWKB")) {
                    byte[] data = wkbWriter.write(geometry);
                    return BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), new UnsynchronizedByteArrayInputStream(data));
                } else if (isCalledAs("getMinX")) {
                    result = new DoubleValue(geometry.getEnvelopeInternal().getMinX());
                } else if (isCalledAs("getMaxX")) {
                    result = new DoubleValue(geometry.getEnvelopeInternal().getMaxX());
                } else if (isCalledAs("getMinY")) {
                    result = new DoubleValue(geometry.getEnvelopeInternal().getMinY());
                } else if (isCalledAs("getMaxY")) {
                    result = new DoubleValue(geometry.getEnvelopeInternal().getMaxY());
                } else if (isCalledAs("getCentroidX")) {
                    result = new DoubleValue(geometry.getCentroid().getX());
                } else if (isCalledAs("getCentroidY")) {
                    result = new DoubleValue(geometry.getCentroid().getY());
                } else if (isCalledAs("getArea")) {
                    result = new DoubleValue(geometry.getArea());
                } else if (isCalledAs("getSRS")) {
                    result = new StringValue(((Element) geometryNode).getAttribute("srsName"));
                } else if (isCalledAs("getGeometryType")) {
                    result = new StringValue(geometry.getGeometryType());
                } else if (isCalledAs("isClosed")) {
                    result = new BooleanValue(!geometry.isEmpty());
                } else if (isCalledAs("isSimple")) {
                    result = new BooleanValue(geometry.isSimple());
                } else if (isCalledAs("isValid")) {
                    result = new BooleanValue(geometry.isValid());
                } else {
                    logger.error("Unknown spatial property: {}", getName().getLocalPart());
                    throw new XPathException("Unknown spatial property: " + getName().getLocalPart());
                }
            }
        } 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) Base64BinaryValueType(org.exist.xquery.value.Base64BinaryValueType) Sequence(org.exist.xquery.value.Sequence) SpatialIndexException(org.exist.indexing.spatial.SpatialIndexException) NodeProxy(org.exist.dom.persistent.NodeProxy) Geometry(com.vividsolutions.jts.geom.Geometry) DoubleValue(org.exist.xquery.value.DoubleValue) AbstractGMLJDBCIndexWorker(org.exist.indexing.spatial.AbstractGMLJDBCIndexWorker) BooleanValue(org.exist.xquery.value.BooleanValue) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) StringValue(org.exist.xquery.value.StringValue)

Example 14 with Base64BinaryValueType

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

the class RestXqServiceImpl method extractRequestBody.

@Override
protected Sequence extractRequestBody(final HttpRequest request) throws RestXqServiceException {
    // TODO don't use close shield input stream and move parsing of form parameters from HttpServletRequestAdapter into RequestBodyParser
    InputStream is;
    FilterInputStreamCache cache = null;
    try {
        // first, get the content of the request
        is = new CloseShieldInputStream(request.getInputStream());
        if (is.available() <= 0) {
            return null;
        }
        // if marking is not supported, we have to cache the input stream, so we can reread it, as we may use it twice (once for xml attempt and once for string attempt)
        if (!is.markSupported()) {
            cache = FilterInputStreamCacheFactory.getCacheInstance(() -> {
                final Configuration configuration = getBrokerPool().getConfiguration();
                return (String) configuration.getProperty(Configuration.BINARY_CACHE_CLASS_PROPERTY);
            }, is);
            is = new CachingFilterInputStream(cache);
        }
        is.mark(Integer.MAX_VALUE);
    } catch (final IOException ioe) {
        throw new RestXqServiceException(RestXqErrorCodes.RQDY0014, ioe);
    }
    Sequence result = null;
    try {
        // was there any POST content?
        if (is != null && is.available() > 0) {
            String contentType = request.getContentType();
            // 1) determine if exists mime database considers this binary data
            if (contentType != null) {
                // strip off any charset encoding info
                if (contentType.contains(";")) {
                    contentType = contentType.substring(0, contentType.indexOf(";"));
                }
                MimeType mimeType = MimeTable.getInstance().getContentType(contentType);
                if (mimeType != null && !mimeType.isXMLType()) {
                    // binary data
                    try {
                        final BinaryValue binaryValue = BinaryValueFromInputStream.getInstance(binaryValueManager, new Base64BinaryValueType(), is);
                        if (binaryValue != null) {
                            result = new SequenceImpl<>(new BinaryTypedValue(binaryValue));
                        }
                    } catch (final XPathException xpe) {
                        throw new RestXqServiceException(RestXqErrorCodes.RQDY0014, xpe);
                    }
                }
            }
            if (result == null) {
                // 2) not binary, try and parse as an XML document
                final DocumentImpl doc = parseAsXml(is);
                if (doc != null) {
                    result = new SequenceImpl<>(new DocumentTypedValue(doc));
                }
            }
            if (result == null) {
                String encoding = request.getCharacterEncoding();
                // 3) not a valid XML document, return a string representation of the document
                if (encoding == null) {
                    encoding = "UTF-8";
                }
                try {
                    // reset the stream, as we need to reuse for string parsing
                    is.reset();
                    final StringValue str = parseAsString(is, encoding);
                    if (str != null) {
                        result = new SequenceImpl<>(new StringTypedValue(str));
                    }
                } catch (final IOException ioe) {
                    throw new RestXqServiceException(RestXqErrorCodes.RQDY0014, ioe);
                }
            }
        }
    } catch (IOException e) {
        throw new RestXqServiceException(e.getMessage());
    } finally {
        if (cache != null) {
            try {
                cache.invalidate();
            } catch (final IOException ioe) {
                LOG.error(ioe.getMessage(), ioe);
            }
        }
        if (is != null) {
            /*
                 * Do NOT close the stream if its a binary value,
                 * because we will need it later for serialization
                 */
            boolean isBinaryType = false;
            if (result != null) {
                try {
                    final Type type = result.head().getType();
                    isBinaryType = (type == Type.BASE64_BINARY || type == Type.HEX_BINARY);
                } catch (final IndexOutOfBoundsException ioe) {
                    LOG.warn("Called head on an empty HTTP Request body sequence", ioe);
                }
            }
            if (!isBinaryType) {
                try {
                    is.close();
                } catch (final IOException ioe) {
                    LOG.error(ioe.getMessage(), ioe);
                }
            }
        }
    }
    if (result != null) {
        return result;
    } else {
        return Sequence.EMPTY_SEQUENCE;
    }
}
Also used : RestXqServiceException(org.exquery.restxq.RestXqServiceException) Configuration(org.exist.util.Configuration) DocumentTypedValue(org.exist.extensions.exquery.xdm.type.impl.DocumentTypedValue) XPathException(org.exist.xquery.XPathException) BinaryValueFromInputStream(org.exist.xquery.value.BinaryValueFromInputStream) CloseShieldInputStream(org.apache.commons.io.input.CloseShieldInputStream) CachingFilterInputStream(org.exist.util.io.CachingFilterInputStream) InputStream(java.io.InputStream) BinaryValue(org.exist.xquery.value.BinaryValue) Base64BinaryValueType(org.exist.xquery.value.Base64BinaryValueType) IOException(java.io.IOException) Sequence(org.exquery.xquery.Sequence) FilterInputStreamCache(org.exist.util.io.FilterInputStreamCache) DocumentImpl(org.exist.dom.memtree.DocumentImpl) MimeType(org.exist.util.MimeType) BinaryTypedValue(org.exist.extensions.exquery.xdm.type.impl.BinaryTypedValue) StringTypedValue(org.exist.extensions.exquery.xdm.type.impl.StringTypedValue) MimeType(org.exist.util.MimeType) Base64BinaryValueType(org.exist.xquery.value.Base64BinaryValueType) Type(org.exquery.xquery.Type) CachingFilterInputStream(org.exist.util.io.CachingFilterInputStream) StringValue(org.exist.xquery.value.StringValue) CloseShieldInputStream(org.apache.commons.io.input.CloseShieldInputStream)

Aggregations

Base64BinaryValueType (org.exist.xquery.value.Base64BinaryValueType)14 XPathException (org.exist.xquery.XPathException)10 UnsynchronizedByteArrayOutputStream (org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream)7 IOException (java.io.IOException)6 BinaryValue (org.exist.xquery.value.BinaryValue)6 StringValue (org.exist.xquery.value.StringValue)5 InputStream (java.io.InputStream)4 BinaryValueFromInputStream (org.exist.xquery.value.BinaryValueFromInputStream)4 UnsynchronizedByteArrayInputStream (org.apache.commons.io.input.UnsynchronizedByteArrayInputStream)3 BooleanValue (org.exist.xquery.value.BooleanValue)3 DoubleValue (org.exist.xquery.value.DoubleValue)3 Item (org.exist.xquery.value.Item)3 Image (java.awt.Image)2 BufferedImage (java.awt.image.BufferedImage)2 Path (java.nio.file.Path)2 Properties (java.util.Properties)2 AtomicValue (org.exist.xquery.value.AtomicValue)2 NodeValue (org.exist.xquery.value.NodeValue)2 ValueSequence (org.exist.xquery.value.ValueSequence)2 RestXqServiceException (org.exquery.restxq.RestXqServiceException)2