<commit_before>/*
 *  eXist Open Source Native XML Database
 *  Copyright (C) 2001-03 <NAME>
 *  <EMAIL>
 *  http://exist.sourceforge.net
 *  
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *  
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *  
 *  $Id$
 */
package org.exist.xquery.functions.xmldb;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;

import org.exist.dom.QName;
import org.exist.util.MimeTable;
import org.exist.util.MimeType;
import org.exist.util.serializer.SAXSerializer;
import org.exist.xmldb.EXistResource;
import org.exist.xquery.Cardinality;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.JavaObjectValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.StringValue;
import org.exist.xquery.value.Type;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.XMLResource;

/**
 * @author wolf
 */
public class XMLDBStore extends XMLDBAbstractCollectionManipulator {

	public final static FunctionSignature signatures[] = {
		new FunctionSignature(
			new QName("store", XMLDBModule.NAMESPACE_URI, XMLDBModule.PREFIX),
			"Store a new resource into the database. The first " +
			"argument denotes the collection where the resource should be stored. " +
			"The collection can be either specified as a simple collection path, " +
			"an XMLDB URI, or a collection object as returned by the collection or " +
			"create-collection functions. The second argument is the name of the new " +
			"resource. The third argument is either a node, an xs:string, a Java file object or an xs:anyURI. " +
			"A node will be serialized to SAX. It becomes the root node of the new " +
			"document. If the argument is of type xs:anyURI, the resource is loaded " +
			"from that URI. The functions returns the path to the new document as an xs:string or " + 
			" - if the document could not be stored - the empty sequence.",
			new SequenceType[] {
				new SequenceType(Type.ITEM, Cardinality.EXACTLY_ONE),
				new SequenceType(Type.STRING, Cardinality.ZERO_OR_ONE),
				new SequenceType(Type.ITEM, Cardinality.EXACTLY_ONE)},
			new SequenceType(Type.STRING, Cardinality.ZERO_OR_ONE)),
		new FunctionSignature(
			new QName("store", XMLDBModule.NAMESPACE_URI, XMLDBModule.PREFIX),
			"Store a new resource into the database. The first " +
			"argument denotes the collection where the resource should be stored. " +
			"The collection can be either specified as a simple collection path, " +
			"an XMLDB URI, or a collection object as returned by the collection or " +
			"create-collection functions. The second argument is the name of the new " +
			"resource. The third argument is either a node, an xs:string, a Java file object or an xs:anyURI. " +
			"A node will be serialized to SAX. It becomes the root node of the new " +
			"document. If the argument is of type xs:anyURI, the resource is loaded " +
			"from that URI. The final argument $d is used to specify a mime-type.  If the mime-type " +
			"is something other than 'text/xml' or 'application/xml', the resource will be stored as " +
			"a binary resource. The functions returns the path to the new document as an xs:string or " +
			"- if the document could not be stored - the empty sequence.",
			new SequenceType[] {
				new SequenceType(Type.ITEM, Cardinality.EXACTLY_ONE),
				new SequenceType(Type.STRING, Cardinality.ZERO_OR_ONE),
				new SequenceType(Type.ITEM, Cardinality.EXACTLY_ONE),
				new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE)
			},
			new SequenceType(Type.STRING, Cardinality.ZERO_OR_ONE))
	};

	/**
	 * @param context
	 * @param signature
	 */
	public XMLDBStore(XQueryContext context, FunctionSignature signature) {
		super(context, signature);
	}

	/* (non-Javadoc)
	 * @see org.exist.xquery.Expression#eval(org.exist.dom.DocumentSet, org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
	 */
	public Sequence evalWithCollection(Collection collection, Sequence args[],
		Sequence contextSequence)
		throws XPathException {
		String docName = args[1].getLength() == 0 ? null : args[1].getStringValue();
		if(docName != null && docName.length() == 0)
			docName = null;
		
        String mimeType = "text/xml";
		boolean binary = true;
		if(getSignature().getArgumentCount() == 4) {
			mimeType = args[3].getStringValue();
			binary = !("text/xml".equals(mimeType) || "application/xml".equals(mimeType));
		} else if (docName != null){
		    MimeType mime = MimeTable.getInstance().getContentTypeFor(docName);
            if (mime != null) {
                mimeType = mime.getName();
                binary = !mime.isXMLType();
            }
        }
		
		Item item =
			args[2].itemAt(0);
		Resource resource;
		try {
			if(Type.subTypeOf(item.getType(), Type.JAVA_OBJECT)) {
				Object obj = ((JavaObjectValue)item).getObject();
				if(!(obj instanceof File))
					throw new XPathException(getASTNode(), "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 {
					URI uri = new URI(item.getStringValue());
					resource = loadFromURI(collection, uri, docName, binary, mimeType);
				} catch (URISyntaxException e) {
					throw new XPathException(getASTNode(), "Invalid URI: " + item.getStringValue(), e);<commit_msg>Now that default type is text/xml the boolean binary variable should be false by default (done with Wolf's guidance :-))<commit_after>/*
 *  eXist Open Source Native XML Database
 *  Copyright (C) 2001-03 <NAME>
 *  <EMAIL>
 *  http://exist.sourceforge.net
 *  
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *  
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *  
 *  $Id$
 */
package org.exist.xquery.functions.xmldb;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;

import org.exist.dom.QName;
import org.exist.util.MimeTable;
import org.exist.util.MimeType;
import org.exist.util.serializer.SAXSerializer;
import org.exist.xmldb.EXistResource;
import org.exist.xquery.Cardinality;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.JavaObjectValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.StringValue;
import org.exist.xquery.value.Type;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.XMLResource;

/**
 * @author wolf
 */
public class XMLDBStore extends XMLDBAbstractCollectionManipulator {

	public final static FunctionSignature signatures[] = {
		new FunctionSignature(
			new QName("store", XMLDBModule.NAMESPACE_URI, XMLDBModule.PREFIX),
			"Store a new resource into the database. The first " +
			"argument denotes the collection where the resource should be stored. " +
			"The collection can be either specified as a simple collection path, " +
			"an XMLDB URI, or a collection object as returned by the collection or " +
			"create-collection functions. The second argument is the name of the new " +
			"resource. The third argument is either a node, an xs:string, a Java file object or an xs:anyURI. " +
			"A node will be serialized to SAX. It becomes the root node of the new " +
			"document. If the argument is of type xs:anyURI, the resource is loaded " +
			"from that URI. The functions returns the path to the new document as an xs:string or " + 
			" - if the document could not be stored - the empty sequence.",
			new SequenceType[] {
				new SequenceType(Type.ITEM, Cardinality.EXACTLY_ONE),
				new SequenceType(Type.STRING, Cardinality.ZERO_OR_ONE),
				new SequenceType(Type.ITEM, Cardinality.EXACTLY_ONE)},
			new SequenceType(Type.STRING, Cardinality.ZERO_OR_ONE)),
		new FunctionSignature(
			new QName("store", XMLDBModule.NAMESPACE_URI, XMLDBModule.PREFIX),
			"Store a new resource into the database. The first " +
			"argument denotes the collection where the resource should be stored. " +
			"The collection can be either specified as a simple collection path, " +
			"an XMLDB URI, or a collection object as returned by the collection or " +
			"create-collection functions. The second argument is the name of the new " +
			"resource. The third argument is either a node, an xs:string, a Java file object or an xs:anyURI. " +
			"A node will be serialized to SAX. It becomes the root node of the new " +
			"document. If the argument is of type xs:anyURI, the resource is loaded " +
			"from that URI. The final argument $d is used to specify a mime-type.  If the mime-type " +
			"is something other than 'text/xml' or 'application/xml', the resource will be stored as " +
			"a binary resource. The functions returns the path to the new document as an xs:string or " +
			"- if the document could not be stored - the empty sequence.",
			new SequenceType[] {
				new SequenceType(Type.ITEM, Cardinality.EXACTLY_ONE),
				new SequenceType(Type.STRING, Cardinality.ZERO_OR_ONE),
				new SequenceType(Type.ITEM, Cardinality.EXACTLY_ONE),
				new SequenceType(Type.STRING, Cardinality.EXACTLY_ONE)
			},
			new SequenceType(Type.STRING, Cardinality.ZERO_OR_ONE))
	};

	/**
	 * @param context
	 * @param signature
	 */
	public XMLDBStore(XQueryContext context, FunctionSignature signature) {
		super(context, signature);
	}

	/* (non-Javadoc)
	 * @see org.exist.xquery.Expression#eval(org.exist.dom.DocumentSet, org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
	 */
	public Sequence evalWithCollection(Collection collection, Sequence args[],
		Sequence contextSequence)
		throws XPathException {
		String docName = args[1].getLength() == 0 ? null : args[1].getStringValue();
		if(docName != null && docName.length() == 0)
			docName = null;
		
        String mimeType = "text/xml";
		boolean binary = false;
		if(getSignature().getArgumentCount() == 4) {
			mimeType = args[3].getStringValue();
			binary = !("text/xml".equals(mimeType) || "application/xml".equals(mimeType));
		} else if (docName != null){
		    MimeType mime = MimeTable.getInstance().getContentTypeFor(docName);
            if (mime != null) {
                mimeType = mime.getName();
                binary = !mime.isXMLType();
            }
        }
		
		Item item =
			args[2].itemAt(0);
		Resource resource;
		try {
			if(Type.subTypeOf(item.getType(), Type.JAVA_OBJECT)) {
				Object obj = ((JavaObjectValue)item).getObject();
				if(!(obj instanceof File))
					throw new XPathException(getASTNode(), "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 {
					URI uri = new URI(item.getStringValue());
					resource = loadFromURI(collection, uri, docName, binary, mimeType);
				} catch (URISyntaxException e) {
					throw new XPathException(getASTNode(), "Invalid URI: " + item.getStringValue(), e);
{'fraction_non_alphanumeric': 0.10139058679706602, 'fraction_numerical': 0.003514669926650367, 'mean_word_length': 3.894913986537023, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 27}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7315886', 'n_tokens_mistral': 4257, 'n_tokens_neox': 3858, 'n_words': 1300}