Search in sources :

Example 11 with MimeType

use of org.exist.util.MimeType in project exist by eXist-db.

the class ExportGUI method btnConfSelectActionPerformed.

// GEN-LAST:event_menuQuitActionPerformed
private void btnConfSelectActionPerformed(final java.awt.event.ActionEvent evt) {
    // GEN-FIRST:event_btnConfSelectActionPerformed
    final Path dir = Paths.get(dbConfig.getText()).normalize().getParent();
    final JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(false);
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setSelectedFile(Optional.ofNullable(System.getProperty("exist.configurationFile")).map(Paths::get).orElse(dir.resolve("etc").resolve("conf.xml")).toFile());
    chooser.setCurrentDirectory(dir.resolve("etc").toFile());
    chooser.setFileFilter(new FileFilter() {

        public boolean accept(final File f) {
            if (f.isDirectory()) {
                return (true);
            }
            final MimeType mime = MimeTable.getInstance().getContentTypeFor(f.getName());
            if (mime == null) {
                return false;
            }
            return mime.isXMLType();
        }

        public String getDescription() {
            return ("Database XML configuration file");
        }
    });
    if (chooser.showDialog(this, "Select") == JFileChooser.APPROVE_OPTION) {
        dbConfig.setText(chooser.getSelectedFile().getAbsolutePath());
    }
}
Also used : Path(java.nio.file.Path) FileFilter(javax.swing.filechooser.FileFilter) File(java.io.File) MimeType(org.exist.util.MimeType)

Example 12 with MimeType

use of org.exist.util.MimeType in project exist by eXist-db.

the class InMemoryOutputStream method stream.

public void stream(final XmldbURL xmldbURL, final InputStream is, @Deprecated final int length) throws IOException {
    BrokerPool db;
    try {
        db = BrokerPool.getInstance();
    } catch (EXistException e) {
        throw new IOException(e);
    }
    try (final DBBroker broker = db.getBroker()) {
        final XmldbURI collectionUri = XmldbURI.create(xmldbURL.getCollection());
        final XmldbURI documentUri = XmldbURI.create(xmldbURL.getDocumentName());
        final TransactionManager transact = db.getTransactionManager();
        try (final Txn txn = transact.beginTransaction();
            final Collection collection = broker.getOrCreateCollection(txn, collectionUri)) {
            if (collection == null) {
                throw new IOException("Resource " + collectionUri.toString() + " is not a collection.");
            }
            final LockManager lockManager = db.getLockManager();
            txn.acquireCollectionLock(() -> lockManager.acquireCollectionWriteLock(collectionUri));
            if (collection.hasChildCollection(broker, documentUri)) {
                throw new IOException("Resource " + documentUri.toString() + " is a collection.");
            }
            try (final FilterInputStreamCache cache = FilterInputStreamCacheFactory.getCacheInstance(() -> (String) broker.getConfiguration().getProperty(Configuration.BINARY_CACHE_CLASS_PROPERTY), is);
                final CachingFilterInputStream cfis = new CachingFilterInputStream(cache)) {
                final MimeType mime = MimeTable.getInstance().getContentTypeFor(documentUri);
                try (final ManagedDocumentLock lock = lockManager.acquireDocumentWriteLock(documentUri)) {
                    broker.storeDocument(txn, documentUri, new CachingFilterInputStreamInputSource(cfis), mime, collection);
                }
            }
            txn.commit();
        }
    } catch (final IOException ex) {
        LOG.debug(ex);
        throw ex;
    } catch (final Exception ex) {
        LOG.debug(ex);
        throw new IOException(ex.getMessage(), ex);
    }
}
Also used : EXistException(org.exist.EXistException) IOException(java.io.IOException) Txn(org.exist.storage.txn.Txn) FilterInputStreamCache(org.exist.util.io.FilterInputStreamCache) CachingFilterInputStreamInputSource(org.exist.util.CachingFilterInputStreamInputSource) MimeType(org.exist.util.MimeType) IOException(java.io.IOException) EXistException(org.exist.EXistException) LockManager(org.exist.storage.lock.LockManager) DBBroker(org.exist.storage.DBBroker) ManagedDocumentLock(org.exist.storage.lock.ManagedDocumentLock) TransactionManager(org.exist.storage.txn.TransactionManager) Collection(org.exist.collections.Collection) CachingFilterInputStream(org.exist.util.io.CachingFilterInputStream) BrokerPool(org.exist.storage.BrokerPool) XmldbURI(org.exist.xmldb.XmldbURI)

Example 13 with MimeType

use of org.exist.util.MimeType in project exist by eXist-db.

the class ScaleImageJAI method doGet.

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    String filePath = request.getPathInfo();
    if (filePath.startsWith("/")) {
        filePath = filePath.substring(1);
    }
    filePath = URIUtils.urlDecodeUtf8(filePath);
    String action = "scale";
    Matcher matcher = URL_PATTERN.matcher(filePath);
    if (!matcher.matches()) {
        throw new ServletException("Bad URL format: " + filePath);
    }
    action = matcher.group(1);
    filePath = matcher.group(2);
    Path file = store.getFile(filePath);
    log("action: " + action + " path: " + file.toAbsolutePath());
    String name = FileUtils.fileName(file);
    Path dir = file.getParent();
    file = findFile(dir, name);
    if (file != null && !(Files.isReadable(file) && Files.isRegularFile(file))) {
        log("Cannot read image file: " + file.toAbsolutePath());
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    if (file == null && "crop".equals(action)) {
        log("Image file not found.");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    // determine mime type for generated image
    String mimeParam = request.getParameter("type");
    if (mimeParam == null)
        mimeParam = defaultMimeType;
    boolean doCache = caching;
    String cacheParam = request.getParameter("cache");
    if (cacheParam != null)
        doCache = cacheParam.equalsIgnoreCase("yes") || cacheParam.equalsIgnoreCase("true");
    MimeType mime;
    if (file == null)
        mime = MimeTable.getInstance().getContentType("image/png");
    else
        mime = MimeTable.getInstance().getContentType(mimeParam);
    response.setContentType(mime.getName());
    if ("scale".equals(action)) {
        float size = getParameter(request, "s");
        if (file != null) {
            Path scaled = getFile(dir, file, mime, size < 0 ? "" : Integer.toString((int) size));
            log("thumb = " + scaled.toAbsolutePath());
            if (useScaled(file, scaled)) {
                streamScaled(scaled, response.getOutputStream());
            } else {
                PlanarImage image = loadImage(file);
                image = scale(image, size);
                writeToResponse(response, mime, scaled, image, doCache);
            }
        } else {
            BufferedImage image = new BufferedImage((int) size, (int) size, BufferedImage.TYPE_INT_ARGB);
            // Graphics2D graphics = image.createGraphics();
            // Color color = new Color(0x00FFFFFF, true);
            // graphics.setColor(color);
            // graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
            // graphics.dispose();
            writeToResponse(response, mime, null, image, false);
        }
    } else if ("crop".equals(action)) {
        float x = getParameter(request, "x");
        float y = getParameter(request, "y");
        float width = getParameter(request, "w");
        float height = getParameter(request, "h");
        StringBuilder suffix = new StringBuilder();
        suffix.append("x").append((int) x).append("y").append((int) y).append("+").append((int) width).append("y").append((int) height);
        Path scaled = getFile(dir, file, mime, suffix.toString());
        log("thumb = " + scaled.toAbsolutePath());
        if (useScaled(file, scaled)) {
            streamScaled(scaled, response.getOutputStream());
        } else {
            PlanarImage image = loadImage(file);
            image = crop(image, x, y, width, height);
            writeToResponse(response, mime, scaled, image.getAsBufferedImage(), doCache);
        }
    }
    response.flushBuffer();
}
Also used : ServletException(javax.servlet.ServletException) Path(java.nio.file.Path) Matcher(java.util.regex.Matcher) MimeType(org.exist.util.MimeType) PlanarImage(javax.media.jai.PlanarImage) BufferedImage(java.awt.image.BufferedImage)

Example 14 with MimeType

use of org.exist.util.MimeType in project exist by eXist-db.

the class XMLDBSetMimeType method eval.

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    // Get handle to Mime-type info
    final MimeTable mimeTable = MimeTable.getInstance();
    // Get first parameter
    final String pathParameter = new AnyURIValue(args[0].itemAt(0).getStringValue()).toString();
    if (pathParameter.matches("^[a-z]+://.*")) {
        throw new XPathException("Can not set mime-type for resources outside the database.");
    }
    XmldbURI pathUri = null;
    try {
        pathUri = XmldbURI.xmldbUriFor(pathParameter);
    } catch (final URISyntaxException ex) {
        logger.debug(ex.getMessage());
        throw new XPathException("Invalid path '" + pathParameter + "'");
    }
    // Verify mime-type input
    MimeType newMimeType = null;
    if (args[1].isEmpty()) {
        // No input, use default mimetype
        newMimeType = mimeTable.getContentTypeFor(pathParameter);
        if (newMimeType == null) {
            throw new XPathException("Unable to determine mimetype for '" + pathParameter + "'");
        }
    } else {
        // Mimetype is provided, check if valid
        newMimeType = mimeTable.getContentType(args[1].getStringValue());
        if (newMimeType == null) {
            throw new XPathException("mime-type '" + args[1].getStringValue() + "' is not supported.");
        }
    }
    // Get mime-type of resource
    MimeType currentMimeType = getMimeTypeStoredResource(pathUri);
    if (currentMimeType == null) {
        // stored resource has no mime-type (unexpected situation)
        // fall back to document name
        logger.debug("Resource '{}' has no mime-type, retrieve from document name.", pathUri);
        currentMimeType = mimeTable.getContentTypeFor(pathUri);
        // if extension based lookup still fails
        if (currentMimeType == null) {
            throw new XPathException("Unable to determine mime-type from path '" + pathUri + "'.");
        }
    }
    // in some cases value null is set, then allow to set to new value (repair action)
    if (newMimeType.isXMLType() != currentMimeType.isXMLType()) {
        throw new XPathException("New mime-type must be a " + currentMimeType.getXMLDBType() + " mime-type");
    }
    // At this moment it is possible to update the mimetype
    final DBBroker broker = context.getBroker();
    final BrokerPool brokerPool = broker.getBrokerPool();
    // relative collection Path: add the current base URI
    pathUri = context.getBaseURI().toXmldbURI().resolveCollectionPath(pathUri);
    try (final Txn txn = broker.continueOrBeginTransaction();
        final LockedDocument lockedDocument = broker.getXMLResource(pathUri, LockMode.WRITE_LOCK)) {
        // try to open the document and acquire a lock
        final DocumentImpl doc = lockedDocument == null ? null : lockedDocument.getDocument();
        if (doc == null) {
            // no document selected, abort
            txn.abort();
        } else {
            // set new mime-type
            doc.setMimeType(newMimeType.getName());
            // store meta data into database
            broker.storeMetadata(txn, doc);
            // commit changes
            txn.commit();
        }
    } catch (final Exception e) {
        logger.error(e.getMessage());
        throw new XPathException(this, e);
    }
    return Sequence.EMPTY_SEQUENCE;
}
Also used : MimeTable(org.exist.util.MimeTable) XPathException(org.exist.xquery.XPathException) AnyURIValue(org.exist.xquery.value.AnyURIValue) URISyntaxException(java.net.URISyntaxException) Txn(org.exist.storage.txn.Txn) DocumentImpl(org.exist.dom.persistent.DocumentImpl) MimeType(org.exist.util.MimeType) URISyntaxException(java.net.URISyntaxException) PermissionDeniedException(org.exist.security.PermissionDeniedException) XPathException(org.exist.xquery.XPathException) DBBroker(org.exist.storage.DBBroker) LockedDocument(org.exist.dom.persistent.LockedDocument) XmldbURI(org.exist.xmldb.XmldbURI) BrokerPool(org.exist.storage.BrokerPool)

Example 15 with MimeType

use of org.exist.util.MimeType 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)

Aggregations

MimeType (org.exist.util.MimeType)17 XPathException (org.exist.xquery.XPathException)7 IOException (java.io.IOException)6 Path (java.nio.file.Path)6 XmldbURI (org.exist.xmldb.XmldbURI)5 StringValue (org.exist.xquery.value.StringValue)5 InputStream (java.io.InputStream)4 PermissionDeniedException (org.exist.security.PermissionDeniedException)4 Txn (org.exist.storage.txn.Txn)4 EXistResource (org.exist.xmldb.EXistResource)4 AnyURIValue (org.exist.xquery.value.AnyURIValue)4 Resource (org.xmldb.api.base.Resource)4 XMLResource (org.xmldb.api.modules.XMLResource)4 URISyntaxException (java.net.URISyntaxException)3 CloseShieldInputStream (org.apache.commons.io.input.CloseShieldInputStream)3 Collection (org.exist.collections.Collection)3 DocumentImpl (org.exist.dom.persistent.DocumentImpl)3 LockedDocument (org.exist.dom.persistent.LockedDocument)3 BufferedImage (java.awt.image.BufferedImage)2 File (java.io.File)2