Search in sources :

Example 31 with StringValue

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

the class FileRead method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    if (!context.getSubject().hasDbaRole()) {
        XPathException xPathException = new XPathException(this, "Permission denied, calling user '" + context.getSubject().getName() + "' must be a DBA to call this function.");
        logger.error("Invalid user", xPathException);
        throw xPathException;
    }
    final String inputPath = args[0].getStringValue();
    final Path file = FileModuleHelper.getFile(inputPath);
    final Charset encoding;
    if (args.length == 2) {
        encoding = Charset.forName(args[1].getStringValue());
    } else {
        encoding = StandardCharsets.UTF_8;
    }
    try {
        return new StringValue(new String(Files.readAllBytes(file), encoding));
    } catch (final IOException e) {
        throw new XPathException(this, e);
    }
}
Also used : Path(java.nio.file.Path) XPathException(org.exist.xquery.XPathException) Charset(java.nio.charset.Charset) IOException(java.io.IOException) StringValue(org.exist.xquery.value.StringValue)

Example 32 with StringValue

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

the class GetThumbnailsFunction method eval.

/*
	 * (non-Javadoc)
	 * 
	 * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[],
	 *      org.exist.xquery.value.Sequence)
	 */
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    ValueSequence result = new ValueSequence();
    // boolean isDatabasePath = false;
    boolean isSaveToDataBase = false;
    if (args[0].isEmpty()) {
        return Sequence.EMPTY_SEQUENCE;
    }
    AnyURIValue picturePath = (AnyURIValue) args[0].itemAt(0);
    if (picturePath.getStringValue().startsWith("xmldb:exist://")) {
        picturePath = new AnyURIValue(picturePath.getStringValue().substring(14));
    }
    AnyURIValue thumbPath = null;
    if (args[1].isEmpty()) {
        thumbPath = new AnyURIValue(picturePath.toXmldbURI().append(THUMBPATH));
        isSaveToDataBase = true;
    } else {
        thumbPath = (AnyURIValue) args[1].itemAt(0);
        if (thumbPath.getStringValue().startsWith("file:")) {
            isSaveToDataBase = false;
            thumbPath = new AnyURIValue(thumbPath.getStringValue().substring(5));
        } else {
            isSaveToDataBase = true;
            try {
                XmldbURI thumbsURI = XmldbURI.xmldbUriFor(thumbPath.getStringValue());
                if (!thumbsURI.isAbsolute())
                    thumbsURI = picturePath.toXmldbURI().append(thumbPath.toString());
                thumbPath = new AnyURIValue(thumbsURI.toString());
            } catch (URISyntaxException e) {
                throw new XPathException(this, e.getMessage());
            }
        }
    }
    // result.add(new StringValue(picturePath.getStringValue()));
    // result.add(new StringValue(thumbPath.getStringValue() + " isDB?= "
    // + isSaveToDataBase));
    int maxThumbHeight = MAXTHUMBHEIGHT;
    int maxThumbWidth = MAXTHUMBWIDTH;
    if (!args[2].isEmpty()) {
        maxThumbHeight = ((IntegerValue) args[2].itemAt(0)).getInt();
        if (args[2].hasMany())
            maxThumbWidth = ((IntegerValue) args[2].itemAt(1)).getInt();
    }
    String prefix = THUMBPREFIX;
    if (!args[3].isEmpty()) {
        prefix = args[3].itemAt(0).getStringValue();
    }
    // result.add(new StringValue("maxThumbHeight = " + maxThumbHeight
    // + ", maxThumbWidth = " + maxThumbWidth));
    BrokerPool pool = null;
    try {
        pool = BrokerPool.getInstance();
    } catch (Exception e) {
        result.add(new StringValue(e.getMessage()));
        return result;
    }
    final DBBroker dbbroker = context.getBroker();
    // Start transaction
    final TransactionManager transact = pool.getTransactionManager();
    try (final Txn transaction = transact.beginTransaction()) {
        Collection thumbCollection = null;
        Path thumbDir = null;
        if (isSaveToDataBase) {
            try {
                thumbCollection = dbbroker.getOrCreateCollection(transaction, thumbPath.toXmldbURI());
                dbbroker.saveCollection(transaction, thumbCollection);
            } catch (Exception e) {
                throw new XPathException(this, e.getMessage());
            }
        } else {
            thumbDir = Paths.get(thumbPath.toString());
            if (!Files.isDirectory(thumbDir))
                try {
                    Files.createDirectories(thumbDir);
                } catch (IOException e) {
                    throw new XPathException(this, e.getMessage());
                }
        }
        Collection allPictures = null;
        Collection existingThumbsCol = null;
        List<Path> existingThumbsArray = null;
        try {
            allPictures = dbbroker.getCollection(picturePath.toXmldbURI());
            if (allPictures == null) {
                return Sequence.EMPTY_SEQUENCE;
            }
            if (isSaveToDataBase) {
                existingThumbsCol = dbbroker.getCollection(thumbPath.toXmldbURI());
            } else {
                existingThumbsArray = FileUtils.list(thumbDir, path -> {
                    final String fileName = FileUtils.fileName(path);
                    return fileName.endsWith(".jpeg") || fileName.endsWith(".jpg");
                });
            }
        } catch (PermissionDeniedException | IOException e) {
            throw new XPathException(this, e.getMessage(), e);
        }
        DocumentImpl docImage = null;
        BinaryDocument binImage = null;
        @SuppressWarnings("unused") BufferedImage bImage = null;
        @SuppressWarnings("unused") byte[] imgData = null;
        Image image = null;
        UnsynchronizedByteArrayOutputStream os = null;
        try {
            Iterator<DocumentImpl> i = allPictures.iterator(dbbroker);
            while (i.hasNext()) {
                docImage = i.next();
                // is not already existing??
                if (!((fileExist(context.getBroker(), existingThumbsCol, docImage, prefix)) || (fileExist(existingThumbsArray, docImage, prefix)))) {
                    if (docImage.getResourceType() == DocumentImpl.BINARY_FILE)
                        // TODO maybe extends for gifs too.
                        if (docImage.getMimeType().startsWith("image/jpeg")) {
                            binImage = (BinaryDocument) docImage;
                            try (final InputStream is = dbbroker.getBinaryResource(transaction, binImage)) {
                                image = ImageIO.read(is);
                            } catch (IOException ioe) {
                                throw new XPathException(this, ioe.getMessage());
                            }
                            try {
                                bImage = ImageModule.createThumb(image, maxThumbHeight, maxThumbWidth);
                            } catch (Exception e) {
                                throw new XPathException(this, e.getMessage());
                            }
                            if (isSaveToDataBase) {
                                os = new UnsynchronizedByteArrayOutputStream();
                                try {
                                    ImageIO.write(bImage, "jpg", os);
                                } catch (Exception e) {
                                    throw new XPathException(this, e.getMessage());
                                }
                                try (final StringInputSource sis = new StringInputSource(os.toByteArray())) {
                                    thumbCollection.storeDocument(transaction, dbbroker, XmldbURI.create(prefix + docImage.getFileURI()), sis, new MimeType("image/jpeg", MimeType.BINARY));
                                } catch (final Exception e) {
                                    throw new XPathException(this, e.getMessage());
                                }
                            // result.add(new
                            // StringValue(""+docImage.getFileURI()+"|"+thumbCollection.getURI()+THUMBPREFIX
                            // + docImage.getFileURI()));
                            } else {
                                try {
                                    ImageIO.write(bImage, "jpg", Paths.get(thumbPath.toString() + "/" + prefix + docImage.getFileURI()).toFile());
                                } catch (Exception e) {
                                    throw new XPathException(this, e.getMessage());
                                }
                            // result.add(new StringValue(
                            // thumbPath.toString() + "/"
                            // + THUMBPREFIX
                            // + docImage.getFileURI()));
                            }
                        }
                } else {
                    // result.add(new StringValue(""+docImage.getURI()+"|"
                    // + ((existingThumbsCol != null) ? ""
                    // + existingThumbsCol.getURI() : thumbDir
                    // .toString()) + "/" + prefix
                    // + docImage.getFileURI()));
                    result.add(new StringValue(docImage.getFileURI().toString()));
                }
            }
        } catch (final PermissionDeniedException | LockException e) {
            throw new XPathException(this, e.getMessage(), e);
        }
        try {
            transact.commit(transaction);
        } catch (Exception e) {
            throw new XPathException(this, e.getMessage());
        }
    }
    final Optional<JournalManager> journalManager = pool.getJournalManager();
    journalManager.ifPresent(j -> j.flush(true, false));
    dbbroker.closeDocument();
    return result;
}
Also used : Txn(org.exist.storage.txn.Txn) BrokerPool(org.exist.storage.BrokerPool) SequenceType(org.exist.xquery.value.SequenceType) FunctionParameterSequenceType(org.exist.xquery.value.FunctionParameterSequenceType) QName(org.exist.dom.QName) URISyntaxException(java.net.URISyntaxException) ValueSequence(org.exist.xquery.value.ValueSequence) StringInputSource(org.exist.util.StringInputSource) FunctionSignature(org.exist.xquery.FunctionSignature) PermissionDeniedException(org.exist.security.PermissionDeniedException) Cardinality(org.exist.xquery.Cardinality) MimeType(org.exist.util.MimeType) FileUtils(org.exist.util.FileUtils) BasicFunction(org.exist.xquery.BasicFunction) StringValue(org.exist.xquery.value.StringValue) UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream) LockException(org.exist.util.LockException) FunctionReturnSequenceType(org.exist.xquery.value.FunctionReturnSequenceType) ImageIO(javax.imageio.ImageIO) Collection(org.exist.collections.Collection) XmldbURI(org.exist.xmldb.XmldbURI) DocumentImpl(org.exist.dom.persistent.DocumentImpl) Path(java.nio.file.Path) XQueryContext(org.exist.xquery.XQueryContext) Iterator(java.util.Iterator) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) Files(java.nio.file.Files) JournalManager(org.exist.storage.journal.JournalManager) AnyURIValue(org.exist.xquery.value.AnyURIValue) Type(org.exist.xquery.value.Type) IOException(java.io.IOException) TransactionManager(org.exist.storage.txn.TransactionManager) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Paths(java.nio.file.Paths) DBBroker(org.exist.storage.DBBroker) IntegerValue(org.exist.xquery.value.IntegerValue) Optional(java.util.Optional) Sequence(org.exist.xquery.value.Sequence) LogManager(org.apache.logging.log4j.LogManager) BinaryDocument(org.exist.dom.persistent.BinaryDocument) XPathException(org.exist.xquery.XPathException) InputStream(java.io.InputStream) XPathException(org.exist.xquery.XPathException) URISyntaxException(java.net.URISyntaxException) Txn(org.exist.storage.txn.Txn) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) DocumentImpl(org.exist.dom.persistent.DocumentImpl) BufferedImage(java.awt.image.BufferedImage) MimeType(org.exist.util.MimeType) StringInputSource(org.exist.util.StringInputSource) LockException(org.exist.util.LockException) ValueSequence(org.exist.xquery.value.ValueSequence) StringValue(org.exist.xquery.value.StringValue) XmldbURI(org.exist.xmldb.XmldbURI) Path(java.nio.file.Path) InputStream(java.io.InputStream) AnyURIValue(org.exist.xquery.value.AnyURIValue) IntegerValue(org.exist.xquery.value.IntegerValue) JournalManager(org.exist.storage.journal.JournalManager) IOException(java.io.IOException) UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream) URISyntaxException(java.net.URISyntaxException) PermissionDeniedException(org.exist.security.PermissionDeniedException) LockException(org.exist.util.LockException) IOException(java.io.IOException) XPathException(org.exist.xquery.XPathException) BinaryDocument(org.exist.dom.persistent.BinaryDocument) DBBroker(org.exist.storage.DBBroker) TransactionManager(org.exist.storage.txn.TransactionManager) Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) BrokerPool(org.exist.storage.BrokerPool)

Example 33 with StringValue

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

the class ExampleFunctions method sayHello.

/**
 * Creates an XML document like <hello>name</hello>.
 *
 * @param name An optional name, if empty then "stranger" is used.
 *
 * @return An XML document
 */
private DocumentImpl sayHello(final Optional<StringValue> name) throws XPathException {
    try {
        final MemTreeBuilder builder = new MemTreeBuilder(context);
        builder.startDocument();
        builder.startElement(new QName("hello"), null);
        builder.characters(name.map(StringValue::toString).orElse("stranger"));
        builder.endElement();
        builder.endDocument();
        return builder.getDocument();
    } catch (final QName.IllegalQNameException e) {
        throw new XPathException(this, e.getMessage(), e);
    }
}
Also used : MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) XPathException(org.exist.xquery.XPathException) QName(org.exist.dom.QName) StringValue(org.exist.xquery.value.StringValue)

Example 34 with StringValue

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

the class ListFunction method eval.

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    ValueSequence result = new ValueSequence();
    Optional<ExistRepository> repo = getContext().getRepository();
    if (repo.isPresent()) {
        try {
            Repository parent_repo = repo.get().getParentRepo();
            for (Packages pkg : parent_repo.listPackages()) {
                String name = pkg.name();
                result.add(new StringValue(name));
            }
        } catch (Exception ex) {
            throw new XPathException("Problem listing packages in expath repository ", ex);
        }
        return result;
    } else {
        throw new XPathException("expath repository not available");
    }
}
Also used : Repository(org.expath.pkg.repo.Repository) ExistRepository(org.exist.repo.ExistRepository) XPathException(org.exist.xquery.XPathException) Packages(org.expath.pkg.repo.Packages) ValueSequence(org.exist.xquery.value.ValueSequence) StringValue(org.exist.xquery.value.StringValue) XPathException(org.exist.xquery.XPathException) ExistRepository(org.exist.repo.ExistRepository)

Example 35 with StringValue

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

the class ParseCQL method eval.

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    Sequence ret = Sequence.EMPTY_SEQUENCE;
    if (args[0].isEmpty())
        return Sequence.EMPTY_SEQUENCE;
    String query = args[0].getStringValue();
    String output = "XCQL";
    if (!args[1].isEmpty())
        output = args[1].getStringValue();
    try {
        CQLParser parser = new CQLParser(CQLParser.V1POINT2);
        // String local_full_query_string = query;
        // local_full_query_string = local_full_query_string.replace("-", "%2D");
        CQLNode query_cql = parser.parse(query);
        if (output.equals(OutputTypeXCQL)) {
            String xmlContent = query_cql.toXCQL();
            if (xmlContent.isEmpty()) {
                return Sequence.EMPTY_SEQUENCE;
            }
            StringReader reader = new StringReader(xmlContent);
            SAXAdapter adapter = new SAXAdapter(context);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            InputSource src = new InputSource(reader);
            SAXParser saxParser = factory.newSAXParser();
            XMLReader xr = saxParser.getXMLReader();
            xr.setContentHandler(adapter);
            xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
            xr.parse(src);
            ret = (DocumentImpl) adapter.getDocument();
        } else if (output.equals(OutputTypeString)) {
            ret = new StringValue(query_cql.toString());
        } else {
            ret = new StringValue(query_cql.toCQL());
        }
        return ret;
    } catch (CQLParseException e) {
        throw new XPathException(this, "An error occurred while parsing the query expression (CQLParseException): " + e.getMessage(), e);
    } catch (SAXException e) {
        throw new XPathException(this, "Error while parsing XML: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new XPathException(this, "An error occurred while parsing the query expression (IOException): " + e.getMessage(), e);
    } catch (ParserConfigurationException e) {
        throw new XPathException(this, "Error while constructing XML parser: " + e.getMessage(), e);
    }
}
Also used : InputSource(org.xml.sax.InputSource) XPathException(org.exist.xquery.XPathException) Sequence(org.exist.xquery.value.Sequence) IOException(java.io.IOException) CQLParser(org.z3950.zing.cql.CQLParser) CQLNode(org.z3950.zing.cql.CQLNode) SAXException(org.xml.sax.SAXException) StringReader(java.io.StringReader) SAXAdapter(org.exist.dom.memtree.SAXAdapter) SAXParser(javax.xml.parsers.SAXParser) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) StringValue(org.exist.xquery.value.StringValue) CQLParseException(org.z3950.zing.cql.CQLParseException) XMLReader(org.xml.sax.XMLReader) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

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