@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 '" + pathUri + "' has no mime-type, retrieve from document name.");
currentMimeType = mimeTable.getContentTypeFor(pathUri);
// if extension based lookup still fails
if (currentMimeType == null) {
throw new XPathException("Unable to determine mime-type from path '" + pathUri + "'.");
}