Search in sources :

Example 81 with StringValue

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

the class SystemProperty method eval.

/* (non-Javadoc)
     * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
     */
@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    final String key = args[0].getStringValue();
    String value = SystemProperties.getInstance().getSystemProperty(key, null);
    if (value == null) {
        value = System.getProperty(key);
    }
    return value == null ? Sequence.EMPTY_SEQUENCE : new StringValue(value);
}
Also used : StringValue(org.exist.xquery.value.StringValue)

Example 82 with StringValue

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

the class UUID method eval.

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    final Sequence result = new ValueSequence();
    // Check input parameters
    if (args.length == 0) {
        final String uuid = UUIDGenerator.getUUIDversion4();
        result.add(new StringValue(uuid));
    } else if (args.length == 1) {
        final String parameter = args[0].getStringValue();
        final String uuid = UUIDGenerator.getUUIDversion3(parameter);
        result.add(new StringValue(uuid));
    } else {
        logger.error("Not a supported number of parameters");
        throw new XPathException("Not a supported number of parameters");
    }
    return result;
}
Also used : XPathException(org.exist.xquery.XPathException) ValueSequence(org.exist.xquery.value.ValueSequence) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) StringValue(org.exist.xquery.value.StringValue)

Example 83 with StringValue

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

the class RangeIndexUpdateTest method updates.

@Test
public void updates() throws EXistException, PermissionDeniedException, XPathException, ParserConfigurationException, IOException, SAXException, LockException {
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    final TransactionManager transact = pool.getTransactionManager();
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
        final Txn transaction = transact.beginTransaction()) {
        checkIndex(broker, docs, ITEM_QNAME, new StringValue("Chair"), 1);
        checkIndex(broker, docs, ITEM_QNAME, new StringValue("Table892.25"), 1);
        checkIndex(broker, docs, ITEM_QNAME, new StringValue("Cabinet1525.00"), 1);
        final XQuery xquery = pool.getXQueryService();
        assertNotNull(xquery);
        final Sequence seq = xquery.execute(broker, "//item[. = 'Chair']", null);
        assertNotNull(seq);
        assertEquals(1, seq.getItemCount());
        final XUpdateProcessor proc = new XUpdateProcessor(broker, docs);
        assertNotNull(proc);
        proc.setBroker(broker);
        proc.setDocumentSet(docs);
        String xupdate = XUPDATE_START + "   <xu:update select=\"//item[@id = '1']/description\">Wardrobe</xu:update>" + XUPDATE_END;
        Modification[] modifications = proc.parse(new InputSource(new StringReader(xupdate)));
        assertNotNull(modifications);
        long mods = modifications[0].process(transaction);
        proc.reset();
        assertEquals(1, mods);
        checkIndex(broker, docs, ITEM_QNAME, new StringValue("Chair"), 0);
        checkIndex(broker, docs, ITEM_QNAME, new StringValue("Wardrobe"), 1);
        proc.setBroker(broker);
        proc.setDocumentSet(docs);
        xupdate = XUPDATE_START + "   <xu:update select=\"//item[@id = '1']/description/text()\">Wheelchair</xu:update>" + XUPDATE_END;
        modifications = proc.parse(new InputSource(new StringReader(xupdate)));
        assertNotNull(modifications);
        mods = modifications[0].process(transaction);
        proc.reset();
        assertEquals(1, mods);
        checkIndex(broker, docs, ITEM_QNAME, new StringValue("Wardrobe"), 0);
        checkIndex(broker, docs, ITEM_QNAME, new StringValue("Wheelchair"), 1);
        proc.setBroker(broker);
        proc.setDocumentSet(docs);
        xupdate = XUPDATE_START + "   <xu:update select=\"//item[@id = '1']/@attr\">abc</xu:update>" + XUPDATE_END;
        modifications = proc.parse(new InputSource(new StringReader(xupdate)));
        assertNotNull(modifications);
        mods = modifications[0].process(transaction);
        proc.reset();
        assertEquals(1, mods);
        checkIndex(broker, docs, null, new StringValue("abc"), 1);
        transact.commit(transaction);
    }
}
Also used : XUpdateProcessor(org.exist.xupdate.XUpdateProcessor) Modification(org.exist.xupdate.Modification) InputSource(org.xml.sax.InputSource) XQuery(org.exist.xquery.XQuery) Txn(org.exist.storage.txn.Txn) Sequence(org.exist.xquery.value.Sequence) TransactionManager(org.exist.storage.txn.TransactionManager) StringReader(java.io.StringReader) StringValue(org.exist.xquery.value.StringValue)

Example 84 with StringValue

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

the class XMLDBStore method evalWithCollection.

@Override
public Sequence evalWithCollection(Collection collection, Sequence[] args, Sequence contextSequence) throws XPathException {
    String docName = args[1].isEmpty() ? null : args[1].getStringValue();
    if (docName != null && docName.isEmpty()) {
        docName = null;
    } else if (docName != null) {
        docName = new AnyURIValue(docName).toXmldbURI().toString();
    }
    final Item item = args[2].itemAt(0);
    // determine the mime type
    final boolean storeAsBinary = isCalledAs(FS_STORE_BINARY_NAME);
    MimeType mimeType = null;
    if (getSignature().getArgumentCount() == 4) {
        final String strMimeType = args[3].getStringValue();
        mimeType = MimeTable.getInstance().getContentType(strMimeType);
    }
    if (mimeType == null && docName != null) {
        mimeType = MimeTable.getInstance().getContentTypeFor(docName);
    }
    if (mimeType == null) {
        mimeType = (storeAsBinary || !Type.subTypeOf(item.getType(), Type.NODE)) ? MimeType.BINARY_TYPE : MimeType.XML_TYPE;
    } else if (storeAsBinary) {
        mimeType = new MimeType(mimeType.getName(), MimeType.BINARY);
    }
    Resource resource;
    try {
        if (Type.subTypeOf(item.getType(), Type.JAVA_OBJECT)) {
            final Object obj = ((JavaObjectValue) item).getObject();
            if (obj instanceof java.io.File) {
                resource = loadFromFile(collection, ((java.io.File) obj).toPath(), docName, mimeType);
            } else if (obj instanceof java.nio.file.Path) {
                resource = loadFromFile(collection, (Path) obj, docName, mimeType);
            } else {
                LOGGER.error("Passed java object should be either a java.nio.file.Path or java.io.File");
                throw new XPathException(this, "Passed java object should be either a java.nio.file.Path or java.io.File");
            }
        } else if (Type.subTypeOf(item.getType(), Type.ANY_URI)) {
            try {
                final URI uri = new URI(item.getStringValue());
                resource = loadFromURI(collection, uri, docName, mimeType);
            } catch (final URISyntaxException e) {
                LOGGER.error("Invalid URI: {}", item.getStringValue());
                throw new XPathException(this, "Invalid URI: " + item.getStringValue(), e);
            }
        } else {
            if (mimeType.isXMLType()) {
                resource = collection.createResource(docName, "XMLResource");
            } else {
                resource = collection.createResource(docName, "BinaryResource");
            }
            if (Type.subTypeOf(item.getType(), Type.STRING)) {
                resource.setContent(item.getStringValue());
            } else if (item.getType() == Type.BASE64_BINARY) {
                resource.setContent(((BinaryValue) item).toJavaObject());
            } else if (Type.subTypeOf(item.getType(), Type.NODE)) {
                if (mimeType.isXMLType()) {
                    final ContentHandler handler = ((XMLResource) resource).setContentAsSAX();
                    handler.startDocument();
                    item.toSAX(context.getBroker(), handler, SERIALIZATION_PROPERTIES);
                    handler.endDocument();
                } else {
                    try (final StringWriter writer = new StringWriter()) {
                        final SAXSerializer serializer = new SAXSerializer();
                        serializer.setOutput(writer, null);
                        item.toSAX(context.getBroker(), serializer, SERIALIZATION_PROPERTIES);
                        resource.setContent(writer.toString());
                    } catch (final IOException e) {
                        LOGGER.error(e.getMessage(), e);
                    }
                }
            } else {
                LOGGER.error("Data should be either a node or a string");
                throw new XPathException(this, "Data should be either a node or a string");
            }
            ((EXistResource) resource).setMimeType(mimeType.getName());
            collection.storeResource(resource);
        }
    } catch (final XMLDBException e) {
        LOGGER.error(e.getMessage(), e);
        throw new XPathException(this, "XMLDB reported an exception while storing document: " + e.getMessage(), e);
    } catch (final SAXException e) {
        LOGGER.error(e.getMessage());
        throw new XPathException(this, "SAX reported an exception while storing document", e);
    }
    if (resource == null) {
        return Sequence.EMPTY_SEQUENCE;
    } else {
        try {
            // TODO : use dedicated function in XmldbURI
            return new StringValue(collection.getName() + "/" + resource.getId());
        } catch (final XMLDBException e) {
            LOGGER.error(e.getMessage());
            throw new XPathException(this, "XMLDB reported an exception while retrieving the " + "stored document", e);
        }
    }
}
Also used : XPathException(org.exist.xquery.XPathException) AnyURIValue(org.exist.xquery.value.AnyURIValue) BinaryResource(org.xmldb.api.modules.BinaryResource) XMLResource(org.xmldb.api.modules.XMLResource) EXistResource(org.exist.xmldb.EXistResource) Resource(org.xmldb.api.base.Resource) XMLDBException(org.xmldb.api.base.XMLDBException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) MimeType(org.exist.util.MimeType) ContentHandler(org.xml.sax.ContentHandler) SAXException(org.xml.sax.SAXException) Item(org.exist.xquery.value.Item) StringWriter(java.io.StringWriter) JavaObjectValue(org.exist.xquery.value.JavaObjectValue) SAXSerializer(org.exist.util.serializer.SAXSerializer) StringValue(org.exist.xquery.value.StringValue) Path(java.nio.file.Path)

Example 85 with StringValue

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

the class Delete method eval.

/* (non-Javadoc)
     * @see org.exist.xquery.AbstractExpression#eval(org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
     */
public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().start(this);
        context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies()));
        if (contextSequence != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
        }
        if (contextItem != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());
        }
    }
    if (contextItem != null) {
        contextSequence = contextItem.toSequence();
    }
    final Sequence inSeq = select.eval(contextSequence);
    /* If we try and Delete a node at an invalid location,
         * trap the error in a context variable,
         * this is then accessible from xquery via. the context extension module - deliriumsky
         * TODO: This trapping could be expanded further - basically where XPathException is thrown from thiss class
         * TODO: Maybe we could provide more detailed messages in the trap, e.g. couldnt delete node `xyz` into `abc` becuase... this would be nicer for the end user of the xquery application 
         */
    if (!Type.subTypeOf(inSeq.getItemType(), Type.NODE)) {
        // Indicate the failure to perform this update by adding it to the sequence in the context variable XQueryContext.XQUERY_CONTEXTVAR_XQUERY_UPDATE_ERROR
        ValueSequence prevUpdateErrors = null;
        final XPathException xpe = new XPathException(this, Messages.getMessage(Error.UPDATE_SELECT_TYPE));
        final Object ctxVarObj = context.getAttribute(XQueryContext.XQUERY_CONTEXTVAR_XQUERY_UPDATE_ERROR);
        if (ctxVarObj == null) {
            prevUpdateErrors = new ValueSequence();
        } else {
            prevUpdateErrors = (ValueSequence) XPathUtil.javaObjectToXPath(ctxVarObj, context);
        }
        prevUpdateErrors.add(new StringValue(xpe.getMessage()));
        context.setAttribute(XQueryContext.XQUERY_CONTEXTVAR_XQUERY_UPDATE_ERROR, prevUpdateErrors);
        if (!inSeq.isEmpty()) {
            // TODO: should we trap this instead of throwing an exception - deliriumsky?
            throw xpe;
        }
    }
    if (!inSeq.isEmpty()) {
        // start a transaction
        try (final Txn transaction = getTransaction()) {
            final NotificationService notifier = context.getBroker().getBrokerPool().getNotificationService();
            final StoredNode[] ql = selectAndLock(transaction, inSeq);
            for (final StoredNode node : ql) {
                final DocumentImpl doc = node.getOwnerDocument();
                if (!doc.getPermissions().validate(context.getSubject(), Permission.WRITE)) {
                    // transact.abort(transaction);
                    throw new PermissionDeniedException("User '" + context.getSubject().getName() + "' does not have permission to write to the document '" + doc.getDocumentURI() + "'!");
                }
                // update the document
                final NodeImpl parent = (NodeImpl) getParent(node);
                if (parent == null) {
                    LOG.debug("Cannot remove the document element (no parent node)");
                    throw new XPathException(this, "It is not possible to remove the document element.");
                } else if (parent.getNodeType() != Node.ELEMENT_NODE) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("parent = {}; {}", parent.getNodeType(), parent.getNodeName());
                    }
                    // transact.abort(transaction);
                    throw new XPathException(this, "you cannot remove the document element. Use update " + "instead");
                } else {
                    parent.removeChild(transaction, node);
                }
                doc.setLastModified(System.currentTimeMillis());
                modifiedDocuments.add(doc);
                context.getBroker().storeXMLResource(transaction, doc);
                notifier.notifyUpdate(doc, UpdateListener.UPDATE);
            }
            finishTriggers(transaction);
            // commit the transaction
            transaction.commit();
        } catch (final EXistException | PermissionDeniedException | LockException | TriggerException e) {
            throw new XPathException(this, e.getMessage(), e);
        } finally {
            unlockDocuments();
        }
    }
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().end(this, "", Sequence.EMPTY_SEQUENCE);
    }
    return Sequence.EMPTY_SEQUENCE;
}
Also used : NodeImpl(org.exist.dom.persistent.NodeImpl) XPathException(org.exist.xquery.XPathException) NotificationService(org.exist.storage.NotificationService) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) Txn(org.exist.storage.txn.Txn) EXistException(org.exist.EXistException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) LockException(org.exist.util.LockException) ValueSequence(org.exist.xquery.value.ValueSequence) PermissionDeniedException(org.exist.security.PermissionDeniedException) StringValue(org.exist.xquery.value.StringValue) TriggerException(org.exist.collections.triggers.TriggerException) StoredNode(org.exist.dom.persistent.StoredNode)

Aggregations

StringValue (org.exist.xquery.value.StringValue)96 Sequence (org.exist.xquery.value.Sequence)49 XPathException (org.exist.xquery.XPathException)40 ValueSequence (org.exist.xquery.value.ValueSequence)27 IOException (java.io.IOException)11 PermissionDeniedException (org.exist.security.PermissionDeniedException)10 Item (org.exist.xquery.value.Item)10 XQueryContext (org.exist.xquery.XQueryContext)8 Txn (org.exist.storage.txn.Txn)7 AnyURIValue (org.exist.xquery.value.AnyURIValue)7 QName (org.exist.dom.QName)6 LockException (org.exist.util.LockException)6 NodeValue (org.exist.xquery.value.NodeValue)6 Path (java.nio.file.Path)5 EXistException (org.exist.EXistException)5 TriggerException (org.exist.collections.triggers.TriggerException)5 DocumentImpl (org.exist.dom.persistent.DocumentImpl)5 StoredNode (org.exist.dom.persistent.StoredNode)5 NotificationService (org.exist.storage.NotificationService)5 MimeType (org.exist.util.MimeType)5