[Zope-CVS] CVS: Packages/Moztop/moztop/content/lib - sitesmanager.js:1.1

Stephan Richter srichter@cbu.edu
Thu, 20 Mar 2003 11:04:21 -0500


Update of /cvs-repository/Packages/Moztop/moztop/content/lib
In directory cvs.zope.org:/tmp/cvs-serv2856/lib

Added Files:
	sitesmanager.js 
Log Message:
Moved SitesManager to lib/sitesmanager.js


=== Added File Packages/Moztop/moztop/content/lib/sitesmanager.js ===
/*****************************************************************************
*
* Copyright (c) 2002, 2003 Zope Corporation and Contributors.
* All Rights Reserved.
*
* This software is subject to the provisions of the Zope Public License,
* Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
* WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
******************************************************************************
Explorer library; here to manage Content Object Tree.


SitesManager API Methods:

  * connectSelectedSite - Connect to the selected site.

  * addSite - Add a site to the tree.  

  * getSelectedResource - Get the in the tree selected resource. 

  * openSelectedResource - Open resource views.

  * addResource - Add a resource to the selected container object.

  * deleteResource - Delete the selected resource.

$Id: sitesmanager.js,v 1.1 2003/03/20 16:04:20 srichter Exp $

******************************************************************************/

/* Some regular expressions to fix the case-sensitivity of Moz RDF */
var fixer1 = /rdf:rdf/g;
var fixer2 = /rdf:description/g;
var fixer3 = /rdf:seq/g;

function SitesManager () {
    /* A prototype to manage the sites database and datasources */

    // Initialization
    if( !(this instanceof SitesManager) ) 
	return new SitesManager( );
    DataSourceManager.call(this);
    
    // Grab appropriate Content Tree RDF datasource
    this.ds = new RDFDataSource(this.profileurl + "/moztop.rdf",null);
    
    // Define Content Type RDF datasource
    this.commontypesds = new RDFDataSource();
    this.commontypesds.parseFromString(commontypes_data,
				       "http://www.zope.org/rdf");

    dump(this.commontypesds.serializeToString());

    // DOM element id of the Explorer tree
    this.elementid = 'explorertree';
    
    // An array of all datasources that describe the content of a site.
    this.sitedatasources = new Array();
    
    /* Attach these (potentially empty) datasources */
    var tree = document.getElementById(this.elementid);
    tree.database.AddDataSource(this.ds.getRawDataSource());
    tree.database.AddDataSource(this.commontypesds.getRawDataSource());
    tree.builder.rebuild();		
}

/* Now subclass, then add methods */
SitesManager.prototype = new DataSourceManager();

/* Detect if this is an initial install.  If so, initialize. */
SitesManager.prototype.initializeProfileDatabases = function() {

    /* Are there databases in profile dir?  If so, log a message and return */
    var allres = this.ds.getAllResources();
    if (allres.hasMoreElements()) {
	logmanager.addMessage('Found existing moztop databases', 
			      'explorer.js, initExplorer', 
			      this.ds.serializeToString());
	return;
    }

    /* If we make it here, it means we need to create moztop databases */
    var rootnode = this.ds.getNode("urn:moztop:sites");
    var subitems = this.ds.getNode("urn:moztop:sites:subitems");
    subitems.makeSeq();
    rootnode.addTarget(this.subitemsprop,subitems);

    this.ds.save();
    logmanager.addMessage("Initialized moztop.rdf","explorer.js, initExplorer",
			  this.ds.serializeToString());

    return;
}

SitesManager.prototype.toggleNoSites = function() {
    return;
}

SitesManager.prototype.connectSelectedSite = function() {
    var selectedsite = this.getSelectedResource();

    if (! selectedsite) {
    	alert("Please select a site to connect to.");
	return;
    }

    var siteurl = selectedsite.getTarget(this.urlprop).getValue();

    /* If the site isn't already in the array, create a ds */
    id = this.sitedatasources.length
    var ds = this.sitedatasources[id];
    if (! ds) {
	var ds = new RDFDataSource();
	this.sitedatasources[id] = ds;
    }

    this.retrieveSiteContents(siteurl, ds);

    return;
}


SitesManager.prototype.retrieveSiteContents = function(siteurl, ds) {
    /* Given a URL, retrieve the RDF and add it to the passed-in datasource */

    function handleError() {
	dump("\n in handleError");
	if (p.readyState == 2) {
	    if (p.status) {
		if (p.status== "401") {
		    alert("Invalid URL");
		    return;
		}
	    }
	}
    }

    function serializeResponse(e) {
	/* Local anonymous function for handling the async data */
	if (p.statusText) {
	    dump("\nhere\n");
	    
	    /* If p.ds is empty, we'll have to attach and rebuild */
	    var needsReload = false;
	    if (! p.ds.getAllResources()) {
		var needsReload = false;
	    }
	    
	    p.ds.refresh(true);
	    
	    var newrdf = p.responseText;
	    var newrdf = newrdf.replace(fixer1,"rdf:RDF");
	    var newrdf = newrdf.replace(fixer2,"rdf:Description");
	    var newrdf = newrdf.replace(fixer3,"rdf:Seq");
	    dump("\ngoober is " + newrdf);
	    
	    p.ds.parseFromString(newrdf,siteurl);
	    logmanager.addMessage("Retrieved remote contents.rdf",
				  "explorer.js, retrieveSiteContents",
				  p.ds.serializeToString());
	    
	    /* XXX: don't rebuild tree if you don't have to */
	    var tree=document.getElementById("explorertree");
	    tree.database.AddDataSource(p.ds.getRawDataSource());
	    tree.builder.rebuild();
	}
    }
	
    var p = new XMLHttpRequest();
    p.ds = ds;
    // p.onreadystatechange = handleError;
    p.onload = serializeResponse;
    p.open("GET", siteurl + "contents.rdf", false);
    p.send(null);
}


SitesManager.prototype.addSite = function(site_name, site_realm, site_url, 
					  site_username, site_password) {

    /* The realm is used in URNs while the name is for the display */
    var sc=this.ds.getNode("urn:moztop:sites")
               .getTarget(this.subitemsprop);
    var newsite=this.ds.getNode("urn:moztop:sites:" + site_realm);
    var siteres = this.ds.getNode("urn:moztop:resourcetypes:site");
    sc.addChild(newsite);


    // Now fill in the data for the new site
    newsite.addTarget(this.titleprop, site_name);
    newsite.addTarget(this.urlprop, site_url);
    newsite.addTarget(this.usernameprop, site_username);
    newsite.addTarget(this.passwordprop, site_password);
    newsite.addTarget(this.resourcetypeprop, siteres);

    // Prepare the area for pseudo-folders (Configurations, Content, etc.)
    var subitemsurn = "urn:moztop:sites:" + site_realm + ":subitems";
    var subitems = this.ds.getNode(subitemsurn);
    subitems.makeSeq();
    newsite.addTarget(this.subitemsprop,subitems);

    /* Now add the virtual folders which arc to this.commontypesds */
    var vfs = new Array ('Views', 'Configurations', 'Content', 'Bundles',
                         'Packages');
    for (var i = 0; i < vfs.length; i++) {

	/* vf is the current virtual folder */
	var vf = vfs[i];
	var vfurn = "urn:moztop:sites:" + site_realm + ":" + vf.toLowerCase();

	/* Create a new node for this virtual folder and append to subitems */
	var newvf = this.ds.getNode(vfurn);
	subitems.addChild(newvf);

	// XXX: get rid of the following line
	newvf.addTarget(this.titleprop,vf);

	/* Fill in the rest of the info for the virtual folder */
	newvf.addTarget(this.resourcetypeprop,
		"urn:moztop:resourcetypes:" + vf.toLowerCase());
    }

    /* Finally, create a site datasource and load the contents for this site */
    id = this.sitedatasources.length
    var ds = this.sitedatasources[id];
    if (! ds) {
	var ds = new RDFDataSource();
	this.sitedatasources[id] = ds;
    }
    this.retrieveSiteContents(site_url, ds);

    this.ds.save();
    return;
}


SitesManager.prototype.getSelectedResource = function() {
    /* Overwriting default implementation, since we need to look into the
       sitedatasources as well. */

    // get index of tree
    var tree = document.getElementById(this.elementid);
    var index = tree.view.selection.currentIndex;
    
    // get the selected resource
    if (index == -1) return false;
    var res = tree.view.getItemAtIndex(index).resource;
    
    // Try to find the node in the standard ds
    var rdf = this.ds.getNode(res.Value);
    
    // See whether the node could be possibly in sitedatasources.
    for (var i = 0; i < this.sitedatasources.length; i++) {
 	node = this.sitedatasources[i].getNode(res.Value);
 	if (node.propertyExists(this.titleprop)) 
 	    rdf = node;
    }    
    return rdf;
}


SitesManager.prototype.openSelectedResource = function() {
    /* Opens the tab views for the selected resource */

    var rdf = this.getSelectedResource();

    // Grab the selected resource and its title
    var resourcetitle = rdf.getTarget(this.titleprop).getValue();
    
    // Find viewer container
    var outter = document.getElementById("active-contents-tabpanels");

    // Do not open resource if already opened.
    for (var i = 0; i < outter.childNodes.length; i++) {
	if (outter.childNodes[i].getAttribute('urn') == rdf.getValue())
	    return;
    }

    // Make an appropriate log entry
    logmanager.addMessage("Opening " + resourcetitle);

    // Retrieving resource type
    typeURN = rdf.getTarget(this.resourcetypeprop).getValue();
    type = this.commontypesds.getNode(typeURN);
    // XXX: The type registry should really have an attribute for this.
    typeViewerName = type.getTarget(
	"http://www.zope.org/rdf#styleid").getValue() + "viewer";

    // Creating resource viewer
    var viewer = document.createElement(typeViewerName);
    // Setting initialization attributes
    viewer.id = typeViewerName + "-" + new Date().getTime();
    viewer.setAttribute("urn", rdf.getValue());
    viewer.setAttribute("resourcetitle", resourcetitle);
    
    // Add new viewer to opened resources tabs
    outter.appendChild(viewer);
}


SitesManager.prototype.addResource = function(type, name) {
    /* Add a resource to the selected container object. */
    return;
}

SitesManager.prototype.deleteResource = function() {
    /* Delete a resource from the server and the RDF graph. */
    
    var urn = this.getSelectedResource();
    
    if (! urn) {
    	alert("Please select a resource to delete.");
	return;
    }
    
    var urn = urn.getValue();
    var selectedsite = this.ds.getNode(urn);
    var resourcetype = selectedsite.getTarget(
	this.resourcetypeprop).getValue();

    if (resourcetype != "urn:moztop:resourcetypes:site") {
	alert("You cannot delete a " + resourcetype);
	return;
    }

    /* XXX: Delete object from server */
    


    /* Only delete if you get a valid response back from the server */
    /* XXX: remove from array */
    this.ds.deleteRecursive(urn);
    this.ds.save();

    return;
}


SitesManager.prototype.DELETE = function(puturl, putcontent) {
    /* Deleting a resource on the server */
    var req = new XMLHttpRequest();

    function myfunc(e) {
	if (req.responseXML) {

	    var serializer = new XMLSerializer();
	    var resp = req.responseXML;
	    var str = serializer.serializeToString(d);

	    dump("\nmade it in PUT\n" + str + "\n");
	}
    }

    req.onload = myfunc;
    req.open("DELETE", puturl);
    req.setRequestHeader("Content-type", "text/plain");
    req.setRequestHeader("Host", "localhost");
    req.send(putcontent);

    return;
}    


SitesManager.prototype.PUT = function () {
    var puturl = "http://localhost:9700/fooboy3";
    var putcontent = "";

    var p = new XMLHttpRequest();
    var typeheader = "X-Zope-Type-Name"

    function myfunc (e) {
	if (p.responseXML) {

	    var s = new XMLSerializer();
	    var d = p.responseXML;
	    var str = s.serializeToString(d);

	    dump("\nmade it in PUT\n" + str + "\n");
	}
    }

    var x = document.implementation.createDocument("", "test", null);
    x.documentElement.appendChild(document.createElement("Foo"));
    x.documentElement.appendChild(document.createElement("Bar"));
    x.documentElement.firstChild.appendChild(
	document.createTextNode("My Stuff\nYeah"));

    var s = new XMLSerializer();
    str = s.serializeToString(x);

    p.onload = myfunc;
    p.open("PUT",puturl);
    p.setRequestHeader("Content-type", "text/xml");
    p.setRequestHeader("Host","localhost");
    p.setRequestHeader(typeheader, "PageTemplate");
    p.send(x);

    return;
}    

/* Initialize the Sites Manager */
function initSitesManager() {
    sitesmanager = SitesManager();
    sitesmanager.initializeProfileDatabases();
    return;
}