if(docName != null && docName.length() == 0)
{docName = null;}
else if(docName != null)
{docName = new AnyURIValue(docName).toXmldbURI().toString();}
final Item item = args[2].itemAt(0);
String mimeType = MimeType.XML_TYPE.getName();
boolean binary = !Type.subTypeOf(item.getType(), Type.NODE);
if(getSignature().getArgumentCount() == 4) {
mimeType = args[3].getStringValue();
final MimeType mime = MimeTable.getInstance().getContentType(mimeType);
if (mime != null)
{binary = !mime.isXMLType();}
} else if (docName != null){
final MimeType mime = MimeTable.getInstance().getContentTypeFor(docName);
if (mime != null) {
mimeType = mime.getName();
binary = !mime.isXMLType();
}
}
Resource resource;
try {
if(Type.subTypeOf(item.getType(), Type.JAVA_OBJECT)) {
final Object obj = ((JavaObjectValue)item).getObject();
if(!(obj instanceof File)) {
logger.error("Passed java object should be a File");
throw new XPathException(this, "Passed java object should be a File");
}
resource = loadFromFile(collection, (File)obj, docName, binary, mimeType);
} else if(Type.subTypeOf(item.getType(), Type.ANY_URI)) {
try {
final URI uri = new URI(item.getStringValue());
resource = loadFromURI(collection, uri, docName, binary, mimeType);
} catch (final URISyntaxException e) {
logger.error("Invalid URI: " + item.getStringValue());
throw new XPathException(this, "Invalid URI: " + item.getStringValue(), e);
}
} else {
if(binary) {
resource = collection.createResource(docName, "BinaryResource");
} else {
resource = collection.createResource(docName, "XMLResource");
}
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(binary) {
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());
} else {
final ContentHandler handler = ((XMLResource)resource).setContentAsSAX();
handler.startDocument();
item.toSAX(context.getBroker(), handler, SERIALIZATION_PROPERTIES);
handler.endDocument();
}
} 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");