You are viewing a plain text version of this content. The canonical link for it is here.
Posted to cvs@cocoon.apache.org by st...@apache.org on 2002/07/01 01:29:22 UTC
cvs commit: xml-cocoon2/src/scratchpad/src/org/apache/cocoon/components/source/impl XMLDBSource.java XMLDBSourceFactory.java
stephan 2002/06/30 16:29:22
Added: src/scratchpad/src/org/apache/cocoon/components/source/impl
XMLDBSource.java XMLDBSourceFactory.java
Log:
Tried to refactoring the XMLDB source and source factory.
It should solves the issue of
http://marc.theaimsgroup.com/?l=xml-cocoon-dev&m=102529069023501&w=2
Also the classes don't use deprecated interfaces anymore.
Revision Changes Path
1.1 xml-cocoon2/src/scratchpad/src/org/apache/cocoon/components/source/impl/XMLDBSource.java
Index: XMLDBSource.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The end-user documentation included with the redistribution, if any, must
include the following acknowledgment: "This product includes software
developed by the Apache Software Foundation (http://www.apache.org/)."
Alternately, this acknowledgment may appear in the software itself, if
and wherever such third-party acknowledgments normally appear.
4. The names "Apache Cocoon" and "Apache Software Foundation" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
apache@apache.org.
5. Products derived from this software may not be called "Apache", nor may
"Apache" appear in their name, without prior written permission of the
Apache Software Foundation.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This software consists of voluntary contributions made by many individuals
on behalf of the Apache Software Foundation and was originally created by
Stefano Mazzocchi <st...@apache.org>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.cocoon.components.source.impl;
import org.apache.avalon.excalibur.xml.XMLizable;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.component.ComponentManager;
import org.apache.avalon.framework.component.ComponentSelector;
import org.apache.avalon.framework.component.Composable;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.cocoon.xml.IncludeXMLConsumer;
import org.apache.cocoon.serialization.Serializer;
import org.apache.excalibur.source.Source;
import org.apache.excalibur.source.SourceException;
import org.apache.excalibur.source.SourceValidity;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.ErrorCodes;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.Service;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.ResourceIterator;
import org.xmldb.api.modules.XMLResource;
import org.xmldb.api.modules.XPathQueryService;
import org.xml.sax.InputSource;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
/**
* This class implements the xmldb:// pseudo-protocol and allows to get XML
* content from an XML:DB enabled XML database.
*
* @author <a href="mailto:gianugo@apache.org">Gianugo Rabellino</a>
* @author <a href="mailto:vgritsenko@apache.org">Vadim Gritsenko</a>
* @author <a href="mailto:stephan@apache.org">Stephan Michels</a>
* @version CVS $Id: XMLDBSource.java,v 1.1 2002/06/30 23:29:22 stephan Exp $
*/
public class XMLDBSource extends AbstractLogEnabled implements Composable, Source,XMLizable {
/** Component manager */
private ComponentManager manager;
/** The requested URL */
protected String url;
/** The part of URL after # sign */
protected String query = null;
/** The System ID */
protected String systemId;
/** Static Strings used for XML Collection representation */
protected static final String URI = "http://apache.org/cocoon/xmldb/1.0";
// FIXME (VG): Should not be this more generic? Say, "xmldb"?
protected static final String PREFIX = "collection";
/** Root element <collections> */
protected static final String COLLECTIONS = "collections";
protected static final String QCOLLECTIONS = PREFIX + ":" + COLLECTIONS;
protected static final String RESOURCE_COUNT_ATTR = "resources";
protected static final String COLLECTION_COUNT_ATTR = "collections";
// protected static final String COLLECTION_BASE_ATTR = "base";
/** Element <collection> */
protected static final String COLLECTION = "collection";
protected static final String QCOLLECTION = PREFIX + ":" + COLLECTION;
/** Element <resource> */
protected static final String RESOURCE = "resource";
protected static final String QRESOURCE = PREFIX + ":" + RESOURCE;
protected static final String NAME_ATTR = "name";
/** Root element <results> */
protected static final String RESULTSET = "results";
protected static final String QRESULTSET = PREFIX + ":" + RESULTSET;
protected static final String QUERY_ATTR = "query";
protected static final String RESULTS_COUNT_ATTR = "resources";
/** Element <result> */
protected static final String RESULT = "result";
protected static final String QRESULT = PREFIX + ":" + RESULT;
protected static final String RESULT_DOCID_ATTR = "docid";
protected static final String RESULT_ID_ATTR = "id";
protected static final String CDATA = "CDATA";
/**
* The constructor.
*
* @param environment the Cocoon Environment.
* @param url the URL being queried.
* @param driver the XML:DB driver class name.
*/
public XMLDBSource(String url) {
int start;
if ((start = url.indexOf('#')) != -1) {
this.url = url.substring(0, start);
this.query = url.substring(start + 1);
} else {
this.url = url;
}
}
/**
* Pass the ComponentManager to the composer. The Composable implementation
* should use the specified ComponentManager to acquire the components it needs for execution
*
* @param manager The ComponentManager which this Composable uses
*
* @throws ComponentException
*/
public void compose(ComponentManager manager) throws ComponentException {
this.manager = manager;
}
/**
* Get an InputSource for the given URL. Shamelessly stolen
* from SitemapSource.
*/
public InputStream getInputStream()
throws IOException, SourceException {
ComponentSelector serializerSelector = null;
Serializer serializer = null;
try {
serializerSelector = (ComponentSelector) this.manager.lookup(Serializer.ROLE + "Selector");
serializer = (Serializer)serializerSelector.select("xml");
ByteArrayOutputStream os = new ByteArrayOutputStream();
serializer.setOutputStream(os);
this.toSAX(serializer);
return new ByteArrayInputStream(os.toByteArray());
} catch (ComponentException cme) {
throw new SourceException("could not lookup pipeline components", cme);
} catch (Exception e) {
throw new SourceException("Exception during processing of " + this.getSystemId(), e);
} finally {
if (serializer != null) serializerSelector.release(serializer);
if (serializerSelector != null) this.manager.release(serializerSelector);
}
}
/**
* Override this method to set the Content Length
*
*/
public long getContentLength() {
return -1;
}
/**
* Override this method to set the Last Modification date
*
*/
public long getLastModified() {
return 0;
}
/**
* Get the Validity object. This can either wrap the last modification
* date or the expires information or...
* If it is currently not possible to calculate such an information
* <code>null</code> is returned.
*/
public SourceValidity getValidity() {
return null;
}
/**
* Refresh the content of this object after the underlying data
* content has changed.
*/
public void discardValidity() {
}
/**
* The mime-type of the content described by this object.
* If the source is not able to determine the mime-type by itself
* this can be null.
*/
public String getMimeType() {
return "text/xml";
}
/**
* Get the value of a parameter.
* Using this it is possible to get custom information provided by the
* source implementation, like an expires date, HTTP headers etc.
*/
public String getParameter(String name) {
return null;
}
/**
* Get the value of a parameter.
* Using this it is possible to get custom information provided by the
* source implementation, like an expires date, HTTP headers etc.
*/
public long getParameterAsLong(String name) {
return 0;
}
/**
* Get parameter names
* Using this it is possible to get custom information provided by the
* source implementation, like an expires date, HTTP headers etc.
*/
public Iterator getParameterNames() {
return new EmptyIterator();
}
class EmptyIterator implements Iterator {
public boolean hasNext() { return false; }
public Object next() { return null; }
public void remove() {}
}
/**
* Stream SAX events to a given ContentHandler. If the requested
* resource is a collection, build an XML view of it.
*/
public void toSAX(ContentHandler handler) throws SAXException {
if (url.endsWith("/"))
this.collectionToSAX(handler);
else
this.resourceToSAX(handler);
}
private void resourceToSAX(ContentHandler handler) throws SAXException {
final String col = url.substring(0, url.lastIndexOf('/'));
final String res = url.substring(url.lastIndexOf('/') + 1);
try {
Collection collection = DatabaseManager.getCollection(col);
if (collection == null) {
throw new SAXException("Document " + url + " not found");
}
XMLResource xmlResource = (XMLResource) collection.getResource(res);
if (xmlResource == null) {
throw new SAXException("Document " + url + " not found");
}
if (query != null) {
// Query resource
if (getLogger().isDebugEnabled()) {
getLogger().debug("Querying resource " + res + " from collection " +
url + "; query= " + this.query);
}
queryToSAX(handler, collection, res);
} else {
// Return entire resource
if (getLogger().isDebugEnabled()) {
getLogger().debug("Obtaining resource " + res + " from collection " + col);
}
xmlResource.getContentAsSAX(handler);
}
collection.close();
} catch (XMLDBException xde) {
String error = "Unable to fetch content. Error "
+ xde.errorCode + ": " + xde.getMessage();
getLogger().debug(error, xde);
throw new SAXException(error, xde);
}
}
private void collectionToSAX(ContentHandler handler) throws SAXException {
AttributesImpl attributes = new AttributesImpl();
try {
Collection collection = DatabaseManager.getCollection(url);
if (collection == null) {
throw new SAXException("Collection " + url + " not found");
}
if (query != null) {
// Query collection
if (getLogger().isDebugEnabled()) {
getLogger().debug("Querying collection " + url + "; query= " + this.query);
}
queryToSAX(handler, collection, null);
} else {
// List collection
if (getLogger().isDebugEnabled()) {
getLogger().debug("Listing collection " + url);
}
final String ncollections = Integer.toString(collection.getChildCollectionCount());
final String nresources = Integer.toString(collection.getResourceCount());
attributes.addAttribute("", RESOURCE_COUNT_ATTR,
RESOURCE_COUNT_ATTR, "CDATA", nresources);
attributes.addAttribute("", COLLECTION_COUNT_ATTR,
COLLECTION_COUNT_ATTR, "CDATA", ncollections);
// attributes.addAttribute("", COLLECTION_BASE_ATTR,
// COLLECTION_BASE_ATTR, "CDATA", url);
handler.startDocument();
handler.startPrefixMapping(PREFIX, URI);
handler.startElement(URI, COLLECTIONS, QCOLLECTIONS, attributes);
// Print child collections
String[] collections = collection.listChildCollections();
for (int i = 0; i < collections.length; i++) {
attributes.clear();
attributes.addAttribute("", NAME_ATTR, NAME_ATTR, CDATA, collections[i]);
handler.startElement(URI, COLLECTION,
QCOLLECTION, attributes);
handler.endElement(URI, COLLECTION, COLLECTION);
}
// Print child resources
String[] resources = collection.listResources();
for (int i = 0; i < resources.length; i++) {
attributes.clear();
attributes.addAttribute("", NAME_ATTR, NAME_ATTR, CDATA, resources[i]);
handler.startElement(URI, RESOURCE,
QRESOURCE, attributes);
handler.endElement(URI, RESOURCE, RESOURCE);
}
handler.endElement(URI, COLLECTIONS, QCOLLECTIONS);
handler.endPrefixMapping(PREFIX);
handler.endDocument();
}
collection.close();
} catch (XMLDBException xde) {
String error = "Collection listing failed. Error " + xde.errorCode + ": " + xde.getMessage();
getLogger().debug(error, xde);
throw new SAXException(error, xde);
}
}
private void queryToSAX(ContentHandler handler, Collection collection, String resource)
throws SAXException {
AttributesImpl attributes = new AttributesImpl();
try {
XPathQueryService service =
(XPathQueryService) collection.getService("XPathQueryService", "1.0");
ResourceSet resultSet = (resource == null) ?
service.query(query) : service.queryResource(resource, query);
attributes.addAttribute("", QUERY_ATTR, QUERY_ATTR, "CDATA", query);
attributes.addAttribute("", RESULTS_COUNT_ATTR,
RESULTS_COUNT_ATTR, "CDATA", Long.toString(resultSet.getSize()));
handler.startDocument();
handler.startPrefixMapping(PREFIX, URI);
handler.startElement(URI, RESULTSET, QRESULTSET, attributes);
IncludeXMLConsumer includeHandler = new IncludeXMLConsumer(handler);
// Print search results
ResourceIterator results = resultSet.getIterator();
while (results.hasMoreResources()) {
XMLResource result = (XMLResource)results.nextResource();
final String id = result.getId();
final String documentId = result.getDocumentId();
attributes.clear();
if (id != null) {
attributes.addAttribute("", RESULT_ID_ATTR, RESULT_ID_ATTR,
CDATA, id);
}
if (documentId != null) {
attributes.addAttribute("", RESULT_DOCID_ATTR, RESULT_DOCID_ATTR,
CDATA, documentId);
}
handler.startElement(URI, RESULT, QRESULT, attributes);
result.getContentAsSAX(includeHandler);
handler.endElement(URI, RESULT, RESULT);
}
handler.endElement(URI, RESULTSET, QRESULTSET);
handler.endPrefixMapping(PREFIX);
handler.endDocument();
} catch (XMLDBException xde) {
String error = "Query failed. Error " + xde.errorCode + ": " + xde.getMessage();
getLogger().debug(error, xde);
throw new SAXException(error, xde);
}
}
public void recycle() {
this.url = null;
this.query = null;
}
public String getSystemId() {
return url;
}
}
1.1 xml-cocoon2/src/scratchpad/src/org/apache/cocoon/components/source/impl/XMLDBSourceFactory.java
Index: XMLDBSourceFactory.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The end-user documentation included with the redistribution, if any, must
include the following acknowledgment: "This product includes software
developed by the Apache Software Foundation (http://www.apache.org/)."
Alternately, this acknowledgment may appear in the software itself, if
and wherever such third-party acknowledgments normally appear.
4. The names "Apache Cocoon" and "Apache Software Foundation" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
apache@apache.org.
5. Products derived from this software may not be called "Apache", nor may
"Apache" appear in their name, without prior written permission of the
Apache Software Foundation.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This software consists of voluntary contributions made by many individuals
on behalf of the Apache Software Foundation and was originally created by
Stefano Mazzocchi <st...@apache.org>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.cocoon.components.source.impl;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.excalibur.source.Source;
import org.apache.excalibur.source.SourceException;
import org.apache.excalibur.source.SourceFactory;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.XMLDBException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* This class implements the xmldb:// pseudo-protocol and allows to get XML
* content from an XML:DB enabled XML database.
*
* @author <a href="mailto:gianugo@rabellino.it">Gianugo Rabellino</a>
* @author <a href="mailto:stephan@apache.org">Stephan Michels</a>
* @version CVS $Id: XMLDBSourceFactory.java,v 1.1 2002/06/30 23:29:22 stephan Exp $
*/
public final class XMLDBSourceFactory
extends AbstractLogEnabled
implements SourceFactory, Configurable {
/** The driver implementation class */
protected String driver;
/** A Map containing the driver list */
protected HashMap driverMap;
/**
* Configure the instance.
*/
public void configure(final Configuration conf)
throws ConfigurationException {
if (conf != null) {
driverMap = new HashMap();
Configuration[] xmldbConfigs = conf.getChildren("driver");
String type = null;
String clazz = null;
for (int i = 0; i < xmldbConfigs.length; i++) {
type = xmldbConfigs[i].getAttribute("type");
driver = xmldbConfigs[i].getAttribute("class");
driverMap.put(type, driver);
if (getLogger().isDebugEnabled()) {
getLogger().debug("Initializing XML:DB connection, using driver " + driver);
}
try {
Class c = Class.forName(driver);
DatabaseManager.registerDatabase((Database)c.newInstance());
} catch (XMLDBException xde) {
String error = "Unable to connect to the XMLDB database. Error "
+ xde.errorCode + ": " + xde.getMessage();
getLogger().debug(error, xde);
throw new ConfigurationException(error, xde);
} catch (Exception e) {
getLogger().error("There was a problem setting up the connection");
getLogger().error("Make sure that your driver is available");
throw new ConfigurationException("Problem setting up the connection to XML:DB: "
+ e.getMessage(), e);
}
}
} else {
throw new ConfigurationException("XMLDB configuration not found");
}
}
/**
* Get a <code>Source</code> object.
* @param parameters This is optional.
*/
public Source getSource(String location, Map parameters)
throws MalformedURLException, IOException, SourceException {
int start = location.indexOf(':') + 1;
int end = location.indexOf(':', start);
if (start == -1 || end == -1) {
if (this.getLogger().isWarnEnabled()) {
this.getLogger().warn("Mispelled XML:DB URL. " +
"The syntax is \"xmldb:databasetype://host/collection/resource\"");
throw new MalformedURLException("Mispelled XML:DB URL. " +
"The syntax is \"xmldb:databasetype://host/collection/resource\"");
}
}
String type = location.substring(start, end);
driver = (String)driverMap.get(type);
if (driver == null) {
this.getLogger().error("Unable to find a driver for the \"" +
type + " \" database type, please check the configuration");
throw new SourceException("Unable to find a driver for the \"" +
type + " \" database type, please check the configuration");
}
return new XMLDBSource(location);
}
}
----------------------------------------------------------------------
In case of troubles, e-mail: webmaster@xml.apache.org
To unsubscribe, e-mail: cocoon-cvs-unsubscribe@xml.apache.org
For additional commands, e-mail: cocoon-cvs-help@xml.apache.org