// dbXML imports
import org.xmldb.api.modules.XMLResource;
import org.xmldb.api.base.Resource;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.Collection;
import org.dbxml.client.xmldb.DatabaseImpl;
import org.dbxml.client.xmldb.services.DatabaseInstanceManager;
import org.dbxml.core.DBException;
import org.dbxml.client.xmldb.services.CollectionManager;
import org.dbxml.server.dbXMLException;

// xml imports
import org.w3c.dom.Node;
import org.w3c.dom.Document;	

public class DbxmlTest {
    public Document getDocument(String docID, String colName, String host,
				int port) {
	if(docID == null || colName == null || host == null ||
	   port == -1){
//	    logDebug("docID, colName, host or port == null");
	    return null;
	}
	// return value
	Document doc = null;
	
	Database dbxml = new DatabaseImpl();
/*
	try{
	    String naming = "http://" + host + ":" + port + "/NamingService";
	    logDebug("naming", naming);
	    dbxml.setProperty("dbxml.naming.ior", naming);
	} catch (XMLDBException ex){
	    logError("Error setting property for dbxml", ex);
	    throw new DOException(DOException.DBXML_ERROR);
	}
*/
	try{
	    DatabaseManager.registerDatabase(dbxml);
	} catch (XMLDBException ex){
//	    logError("Error registering database", ex);
	}
	Collection col = null;
	String colUri = "xmldb:dbxml://" + colName;
	try{
	    col = DatabaseManager.getCollection(colUri);
	} catch (XMLDBException ex){
//	    logError("Error getting collection " + colUri, ex);
	}
	
	XMLResource xmlRes = null;
	if(col != null){
	    try{
		xmlRes = (XMLResource)col.getResource(docID);
	    } catch (XMLDBException ex){
//		logError("Error getting resource from dbxml " + docID, ex);
	    }
	}
	Node node = null;
	if(xmlRes != null){
	    try{
		node = xmlRes.getContentAsDOM();
	    } catch (XMLDBException ex){
//		logError("Error getting dom from resource ", ex);
	    }
	}
	if(node != null){
	    doc = node.getOwnerDocument();
	}
	// close collection
	if(col != null){
	    try{
		xmlRes = null;
		col.close();
		DatabaseManager.deregisterDatabase(dbxml);
	    } catch (XMLDBException dbe){
//		logError("error closing collection", dbe);
	    }
	}
	return doc;
    }	


    public static void main(String[] args){
	DbxmlTest dbxml = new DbxmlTest();
	for(int i=0; i<5000; i++){
	    // insert your favourite document id
	    String docID = "18f51f_3Aeb2816ebed_3A-7fd5";
	    Document doc = dbxml.getDocument(docID, "/db/pta/fun/funPlan/", "", 1);
	    if(doc != null){
		System.out.println(i + " " + doc.getFirstChild().getNodeValue());
	    }
	}
    }
}






