use of org.exist.util.MimeType in project exist by eXist-db.
the class MutableCollection method storeDocument.
@Override
public void storeDocument(final Txn transaction, final DBBroker broker, final XmldbURI name, final InputSource source, @Nullable MimeType mimeType, @Nullable final Date createdDate, @Nullable final Date lastModifiedDate, @Nullable final Permission permission, @Nullable final DocumentType documentType, @Nullable final XMLReader xmlReader) throws EXistException, PermissionDeniedException, SAXException, LockException, IOException {
if (mimeType == null) {
mimeType = MimeType.BINARY_TYPE;
}
if (mimeType.isXMLType()) {
// Store XML Document
final BiConsumer2E<XMLReader, IndexInfo, SAXException, EXistException> validatorFn = (xmlReader1, validateIndexInfo) -> {
validateIndexInfo.setReader(xmlReader1, null);
try {
xmlReader1.parse(source);
} catch (final SAXException e) {
throw new SAXException("The XML parser reported a problem: " + e.getMessage(), e);
} catch (final IOException e) {
throw new EXistException(e);
}
};
final BiConsumer2E<XMLReader, IndexInfo, SAXException, EXistException> parserFn = (xmlReader1, storeIndexInfo) -> {
try {
storeIndexInfo.setReader(xmlReader1, null);
xmlReader1.parse(source);
} catch (final IOException e) {
throw new EXistException(e);
}
};
storeXmlDocument(transaction, broker, name, mimeType, createdDate, lastModifiedDate, permission, documentType, xmlReader, validatorFn, parserFn);
} else {
// Store Binary Document
try (final InputStream is = source.getByteStream()) {
if (is == null) {
throw new IOException("storeDocument received a null InputStream when trying to store a Binary Document");
}
addBinaryResource(transaction, broker, name, is, mimeType.getName(), -1, createdDate, lastModifiedDate, permission);
}
}
}
use of org.exist.util.MimeType in project exist by eXist-db.
the class XMLDBStoreTask method execute.
@Override
public void execute() throws BuildException {
if (uri == null) {
throw new BuildException("you have to specify an XMLDB collection URI");
}
if ((fileSetList == null) && (srcFile == null)) {
throw new BuildException("no file set specified");
}
registerDatabase();
int p = uri.indexOf(XmldbURI.ROOT_COLLECTION);
if (p == Constants.STRING_NOT_FOUND) {
throw new BuildException("invalid uri: '" + uri + "'");
}
final String baseURI = uri.substring(0, p);
final String path;
if (p == (uri.length() - 3)) {
path = "";
} else {
path = uri.substring(p + 3);
}
Collection root = null;
try {
if (createCollection) {
root = DatabaseManager.getCollection(baseURI + XmldbURI.ROOT_COLLECTION, user, password);
root = mkcol(root, baseURI, XmldbURI.ROOT_COLLECTION, path);
} else {
root = DatabaseManager.getCollection(uri, user, password);
}
} catch (final XMLDBException e) {
final String msg = "XMLDB exception caught: " + e.getMessage();
if (failonerror) {
throw new BuildException(msg, e);
} else {
log(msg, e, Project.MSG_ERR);
return;
}
}
if (root == null) {
final String msg = "Collection " + uri + " could not be found.";
if (failonerror) {
throw new BuildException(msg);
} else {
log(msg, Project.MSG_ERR);
}
} else {
Resource res;
Collection col = root;
String relDir;
String prevDir = null;
if (srcFile != null) {
log("Storing " + srcFile.getName());
MimeType mime = getMimeTable().getContentTypeFor(srcFile.getName());
final String baseMimeType;
if (forceMimeType != null) {
baseMimeType = forceMimeType;
} else if (mime != null) {
baseMimeType = mime.getName();
} else {
baseMimeType = defaultMimeType;
}
if (type != null) {
if ("xml".equals(type)) {
mime = (baseMimeType != null) ? (new MimeType(baseMimeType, MimeType.XML)) : MimeType.XML_TYPE;
} else if ("binary".equals(type)) {
mime = (baseMimeType != null) ? (new MimeType(baseMimeType, MimeType.BINARY)) : MimeType.BINARY_TYPE;
}
}
// single file
if (mime == null) {
final String msg = "Cannot guess mime-type kind for " + srcFile.getName() + ". Treating it as a binary.";
log(msg, Project.MSG_ERR);
mime = (baseMimeType != null) ? (new MimeType(baseMimeType, MimeType.BINARY)) : MimeType.BINARY_TYPE;
}
final String resourceType = mime.isXMLType() ? XMLResource.RESOURCE_TYPE : BinaryResource.RESOURCE_TYPE;
if (targetFile == null) {
targetFile = srcFile.getName();
}
try {
log("Creating resource " + targetFile + " in collection " + col.getName() + " of type " + resourceType + " with mime-type: " + mime.getName(), Project.MSG_DEBUG);
res = col.createResource(targetFile, resourceType);
if (srcFile.length() == 0) {
// note: solves bug id 2429889 when this task hits empty files
} else {
res.setContent(srcFile);
((EXistResource) res).setMimeType(mime.getName());
col.storeResource(res);
}
if (permissions != null) {
setPermissions(res);
}
} catch (final XMLDBException e) {
final String msg = "XMLDB exception caught: " + e.getMessage();
if (failonerror) {
throw new BuildException(msg, e);
} else {
log(msg, e, Project.MSG_ERR);
}
}
} else {
for (final FileSet fileSet : fileSetList) {
log("Storing fileset", Project.MSG_DEBUG);
// using fileset
final DirectoryScanner scanner = fileSet.getDirectoryScanner(getProject());
scanner.scan();
final String[] includedFiles = scanner.getIncludedFiles();
final String[] includedDirs = scanner.getIncludedDirectories();
log("Found " + includedDirs.length + " directories and " + includedFiles.length + " files.\n");
final File baseDir = scanner.getBasedir();
if (includeEmptyDirs && createSubcollections) {
for (final String included : includedDirs) {
try {
log("Creating " + included + " ...\n");
// TODO : use dedicated function in XmldbURI
// check whether the relative file path contains file seps
p = included.lastIndexOf(File.separatorChar);
if (p != Constants.STRING_NOT_FOUND) {
relDir = included.substring(0, p);
// It's necessary to do this translation on Windows, and possibly MacOS:
relDir = relDir.replace(File.separatorChar, '/');
if (createSubcollections && ((prevDir == null) || (!relDir.equals(prevDir)))) {
// TODO : use dedicated function in XmldbURI
col = mkcol(root, baseURI, XmldbURI.ROOT_COLLECTION + path, relDir);
prevDir = relDir;
}
} else {
col = mkcol(root, baseURI, XmldbURI.ROOT_COLLECTION + path, included);
}
} catch (final XMLDBException e) {
final String msg = "XMLDB exception caught: " + e.getMessage();
if (failonerror) {
throw new BuildException(msg, e);
} else {
log(msg, e, Project.MSG_ERR);
}
}
}
}
for (final String included : includedFiles) {
try {
final File file = new File(baseDir, included);
log("Storing " + included + " ...\n");
// TODO : use dedicated function in XmldbURI
// check whether the relative file path contains file seps
p = included.lastIndexOf(File.separatorChar);
if (p != Constants.STRING_NOT_FOUND) {
relDir = included.substring(0, p);
// It's necessary to do this translation on Windows, and possibly MacOS:
relDir = relDir.replace(File.separatorChar, '/');
if (createSubcollections && ((prevDir == null) || (!relDir.equals(prevDir)))) {
// TODO : use dedicated function in XmldbURI
col = mkcol(root, baseURI, XmldbURI.ROOT_COLLECTION + path, relDir);
prevDir = relDir;
}
} else {
// No file separator found in resource name, reset col to the root collection
col = root;
}
MimeType currentMime = getMimeTable().getContentTypeFor(file.getName());
final String currentBaseMimeType;
if (forceMimeType != null) {
currentBaseMimeType = forceMimeType;
} else if (currentMime != null) {
currentBaseMimeType = currentMime.getName();
} else {
currentBaseMimeType = defaultMimeType;
}
if (type != null) {
if ("xml".equals(type)) {
currentMime = (currentBaseMimeType != null) ? (new MimeType(currentBaseMimeType, MimeType.XML)) : MimeType.XML_TYPE;
} else if ("binary".equals(type)) {
currentMime = (currentBaseMimeType != null) ? (new MimeType(currentBaseMimeType, MimeType.BINARY)) : MimeType.BINARY_TYPE;
}
}
if (currentMime == null) {
final String msg = "Cannot find mime-type kind for " + file.getName() + ". Treating it as a binary.";
log(msg, Project.MSG_ERR);
currentMime = (currentBaseMimeType != null) ? (new MimeType(currentBaseMimeType, MimeType.BINARY)) : MimeType.BINARY_TYPE;
}
final String resourceType = currentMime.isXMLType() ? XMLResource.RESOURCE_TYPE : BinaryResource.RESOURCE_TYPE;
log("Creating resource " + file.getName() + " in collection " + col.getName() + " of type " + resourceType + " with mime-type: " + currentMime.getName(), Project.MSG_DEBUG);
res = col.createResource(file.getName(), resourceType);
res.setContent(file);
((EXistResource) res).setMimeType(currentMime.getName());
col.storeResource(res);
if (permissions != null) {
setPermissions(res);
}
} catch (final XMLDBException e) {
final String msg = "XMLDB exception caught: " + e.getMessage();
if (failonerror) {
throw new BuildException(msg, e);
} else {
log(msg, e, Project.MSG_ERR);
}
}
}
}
}
}
}
use of org.exist.util.MimeType in project exist by eXist-db.
the class XMLDBGetMimeType method eval.
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
final String path = new AnyURIValue(args[0].itemAt(0).getStringValue()).toString();
if (path.matches("^[a-z]+://.*")) {
// external
final MimeTable mimeTable = MimeTable.getInstance();
final MimeType mimeType = mimeTable.getContentTypeFor(path);
if (mimeType != null) {
return new StringValue(mimeType.getName());
}
} else {
// database
try {
XmldbURI pathUri = XmldbURI.xmldbUriFor(path);
// relative collection Path: add the current base URI
pathUri = context.getBaseURI().toXmldbURI().resolveCollectionPath(pathUri);
// try to open the document and acquire a lock
try (final LockedDocument lockedDoc = context.getBroker().getXMLResource(pathUri, LockMode.READ_LOCK)) {
if (lockedDoc != null) {
return new StringValue(lockedDoc.getDocument().getMimeType());
}
}
} catch (final Exception e) {
logger.error(e.getMessage());
throw new XPathException(this, e);
}
}
return Sequence.EMPTY_SEQUENCE;
}
use of org.exist.util.MimeType in project exist by eXist-db.
the class XMLDBSetMimeType method getMimeTypeStoredResource.
/**
* Determine mimetype of currently stored resource. Copied from
* get-mime-type.
*/
private MimeType getMimeTypeStoredResource(XmldbURI pathUri) throws XPathException {
MimeType returnValue = null;
try {
// relative collection Path: add the current base URI
pathUri = context.getBaseURI().toXmldbURI().resolveCollectionPath(pathUri);
} catch (final XPathException ex) {
logger.debug("Unable to convert path {}", pathUri);
return returnValue;
}
try (final LockedDocument lockedDocument = context.getBroker().getXMLResource(pathUri, LockMode.READ_LOCK)) {
// try to open the document and acquire a lock
final DocumentImpl doc = lockedDocument == null ? null : lockedDocument.getDocument();
if (doc == null) {
throw new XPathException("Resource '" + pathUri + "' does not exist.");
} else {
final String mimetype = doc.getMimeType();
returnValue = MimeTable.getInstance().getContentType(mimetype);
}
} catch (final PermissionDeniedException ex) {
logger.debug(ex.getMessage());
}
return returnValue;
}
use of org.exist.util.MimeType in project exist by eXist-db.
the class GetData method eval.
@Override
public Sequence eval(final Sequence[] args, @Nonnull final RequestWrapper request) throws XPathException {
// if the content length is unknown or 0, return
if (request.getContentLength() <= 0) {
return Sequence.EMPTY_SEQUENCE;
}
InputStream isRequest = null;
Sequence result = Sequence.EMPTY_SEQUENCE;
try {
isRequest = request.getInputStream();
// was there any POST content?
if (isRequest != null && isRequest.available() > 0) {
// 1) determine if exists mime database considers this binary data
String contentType = request.getContentType();
if (contentType != null) {
// strip off any charset encoding info
if (contentType.indexOf(';') > -1) {
contentType = contentType.substring(0, contentType.indexOf(';'));
}
final MimeType mimeType = MimeTable.getInstance().getContentType(contentType);
if (mimeType != null && !mimeType.isXMLType()) {
// binary data
result = BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), isRequest);
}
}
if (result == Sequence.EMPTY_SEQUENCE) {
// 2) not binary, try and parse as an XML document, otherwise 3) return a string representation
// parsing will consume the stream so we must cache!
InputStream is = null;
FilterInputStreamCache cache = null;
try {
// 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)
cache = FilterInputStreamCacheFactory.getCacheInstance(() -> (String) context.getBroker().getConfiguration().getProperty(Configuration.BINARY_CACHE_CLASS_PROPERTY), isRequest);
is = new CachingFilterInputStream(cache);
// mark the start of the stream
is.mark(Integer.MAX_VALUE);
// 2) try and parse as XML
result = parseAsXml(is);
if (result == Sequence.EMPTY_SEQUENCE) {
// 3) not a valid XML document, return a string representation of the document
String encoding = request.getCharacterEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
try {
// reset the stream, as we need to reuse for string parsing after the XML parsing happened
is.reset();
result = parseAsString(is, encoding);
} catch (final IOException ioe) {
throw new XPathException(this, "An IO exception occurred: " + ioe.getMessage(), ioe);
}
}
} finally {
if (cache != null) {
try {
cache.invalidate();
} catch (final IOException ioe) {
LOG.error(ioe.getMessage(), ioe);
}
}
if (is != null) {
try {
is.close();
} catch (final IOException ioe) {
LOG.error(ioe.getMessage(), ioe);
}
}
}
}
// NOTE we do not close isRequest, because it may be needed further by the caching input stream wrapper
}
} catch (final IOException ioe) {
throw new XPathException(this, "An IO exception occurred: " + ioe.getMessage(), ioe);
}
return result;
}
Aggregations