Well, I wrote some DAOs to call when I want to save the current state of
my bean. I am relying on the XML:DB-Api thus the code should work with
xindice as well. But I have not tried it with another database other
than eXist. Below you can see some sample code - SensorProfileDocument
was generated with XMLBeans.
Hope this is helpful,
Johannes
import org.apache.log4j.Logger;
import org.x52North.sps.v100.pm.SensorProfileDocument;
import org.xml.sax.ContentHandler;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.XMLResource;
/**
* DAO for persisting the profiles of the sensors registered at the
service in
* an XML database that implements the XMLDB:API.
*
* @author Johannes Echterhoff
*/
public class PMXMLdbSensorProfileDAO implements PMSensorProfileDAO {
private static Logger logger =
Logger.getLogger(PMXMLdbSensorProfileDAO.class);
/**
* Array containing username (index 0) and password (index 1) for
* authentication or null if authentication is not necessary.
*/
private String[] loginData;
/**
* URI to the collection that contains the SensorProfiles.
*/
private String spColUri;
/**
* true if authentication is necessary, else false.
*/
private boolean useAuthentication = true;
/**
* Creates a new PMXMLdbSensorProfileDAO that operates on the given
* collection and authenticates itself with the given login data.
*
* @param spColUri
* URI to the collection that contains the SensorProfiles.
* @param loginData
* Array containing username (index 0) and password (index
1) for
* authentication or null if authentication is not necessary.
*/
public PMXMLdbSensorProfileDAO(String spColUri, String[] loginData) {
this.spColUri = spColUri;
this.loginData = loginData;
if (loginData == null) {
useAuthentication = false;
}
}
/**
* @see
org.n52.sps.pm.PMSensorProfileDAO#deleteSensorProfileDocument(java.lang.String)
*/
public void deleteSensorProfileDocument(String id) throws Exception {
Collection spcol = null;
try {
if (this.useAuthentication)
spcol = DatabaseManager.getCollection(spColUri, loginData[0],
loginData[1]);
else
spcol = DatabaseManager.getCollection(spColUri);
XMLResource r = (XMLResource) spcol.createResource(id,
"XMLResource");
spcol.removeResource(r);
} catch (XMLDBException e) {
logger.debug(
"deleteSensorProfileDocument(): XMLDBException occurred. "
+ e.errorCode + " " + e.getMessage(), e);
throw e;
} finally {
if (spcol != null) {
spcol.close();
}
}
}
/**
* @see
org.n52.sps.pm.PMSensorProfileDAO#findSensorProfile(java.lang.String)
*/
public SensorProfileDocument findSensorProfile(String id) throws
Exception {
Collection spcol = null;
try {
if (this.useAuthentication)
spcol = DatabaseManager.getCollection(spColUri, loginData[0],
loginData[1]);
else
spcol = DatabaseManager.getCollection(spColUri);
XMLResource res = (XMLResource) spcol.getResource(id);
if (res == null)
return null;
SensorProfileDocument spd =
SensorProfileDocument.Factory.parse(res.getContentAsDOM());
return spd;
} catch (XMLDBException e) {
logger.debug("findSensorProfile(): XMLDBException occurred. "
+ e.errorCode + " " + e.getMessage(), e);
throw e;
} finally {
if (spcol != null) {
spcol.close();
}
}
}
/**
* @see
org.n52.sps.pm.PMSensorProfileDAO#saveSensorProfileDocument(org.x52North.sps.v100.pm.SensorProfileDocument)
*/
public void saveSensorProfileDocument(SensorProfileDocument
sensorprofile)
throws Exception {
Collection spcol = null;
try {
if (this.useAuthentication)
spcol = DatabaseManager.getCollection(spColUri, loginData[0],
loginData[1]);
else
spcol = DatabaseManager.getCollection(spColUri);
XMLResource r = (XMLResource) spcol.createResource(
sensorprofile.getSensorProfile().getSensorID().getStringValue(),
"XMLResource");
ContentHandler ch = r.setContentAsSAX();
sensorprofile.save(ch, null);
spcol.storeResource(r);
} catch (XMLDBException e) {
logger.debug("saveSensorProfileDocument(): XMLDBException
occurred. "
+ e.errorCode + " " + e.getMessage(), e);
throw e;
} finally {
if (spcol != null) {
spcol.close();
}
}
}
}
-----------------------------------------------------------------
In the DAOFactory I am retrieving the DAO.
-----------------------------------------------------------------
import java.util.Properties;
import java.util.StringTokenizer;
import org.apache.log4j.Logger;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.CollectionManagementService;
/**
* Factory that creates DAOs using the XMLDB:API for accessing the PMs
* ressources.
*
* @author Johannes Echterhoff
*/
public class PMXMLdbDAOFactory implements PMDAOFactory {
private static Logger logger = Logger.getLogger(PMXMLdbDAOFactory.class);
/**
* path relative to the root of the XML database that point to the
collection
* where the CapabilitiesBase information is stored.
*/
private String capbaseColPath = null;
/**
* true if the factory has been configured without failures, else false.
*/
private boolean configured = false;
/**
* URI to the XML database.
*/
private String databaseUri = null;
/**
* Password used for authentication.
*/
private String psswd;
/**
* path relative to the root of the XML database that point to the
collection
* where the SensorProfiles are stored.
*/
private String sensorprofilesColPath = null;
/**
* path relative to the root of the XML database that point to the
collection
* where the sensorML documents are stored.
*/
private String smlColPath = null;
/**
* true if authentication is necessary, else false.
*/
private boolean useAuthentication = true;
/**
* Username used for authentication.
*/
private String user;
/**
* Creates a new PMXMLdbDAOFactory. Configuration is performed with
* properties retrieved from PMInitParamContainer.
*/
public PMXMLdbDAOFactory() {
// initialise Factory
PMInitParamContainer initParams = PMInitParamContainer.getInstance();
try {
this.configureFactory(initParams.getPMDAOFactoryProperties());
} catch (Exception e) {
logger.debug("Could not configure factory.", e);
// TODO correct handling??
return;
}
}
/**
* Configures the factory.
*
* @param conf
* contain required configuration data.
* @throws Exception
* if the factory could not be configured.
*/
private void configureFactory(Properties conf) throws Exception {
// TODO howto automatically create the collections if they do not
exist
// yet?
String databaseDriver = conf.getProperty("pm.database.driver");
databaseUri = conf.getProperty("pm.database.uri");
capbaseColPath = conf.getProperty("pm.database.collections.capbase");
sensorprofilesColPath =
conf.getProperty("pm.database.collections.sensorprofiles");
smlColPath =
conf.getProperty("pm.database.collections.sensormldescriptions");
if (databaseUri.endsWith("/")) {
databaseUri = databaseUri.substring(0, databaseUri.length() - 1);
}
if (!capbaseColPath.startsWith("/")) {
capbaseColPath = "/".concat(capbaseColPath);
}
if (!sensorprofilesColPath.startsWith("/")) {
sensorprofilesColPath = "/".concat(sensorprofilesColPath);
}
if (!smlColPath.startsWith("/")) {
smlColPath = "/".concat(smlColPath);
}
user = conf.getProperty("pm.database.username");
psswd = conf.getProperty("pm.database.password");
// check whether authentication is necessary or not
if (user == null || user.length() == 0) {
logger.debug("Username not defined for accessing pm-database. "
+ "Using no authentication for accessing database.");
useAuthentication = false;
} else {
if (psswd == null) {
logger.debug("password was null: using '" + user
+ "' as username and '' as password.");
psswd = "";
} else {
logger.debug("using '" + user + "' as username and '" + psswd
+ "' as password.");
}
useAuthentication = true;
}
// check whether the database is accessible and the collections exist
// otherwise initialise collections if possible
Class c = Class.forName(databaseDriver);
Database database = (Database) c.newInstance();
DatabaseManager.registerDatabase(database);
Collection capbaseCol = null;
Collection profilesCol = null;
Collection smlCol = null;
try {
if (this.useAuthentication) {
capbaseCol = DatabaseManager.getCollection(databaseUri
+ capbaseColPath, user, psswd);
} else {
capbaseCol = DatabaseManager.getCollection(databaseUri
+ capbaseColPath);
}
if (capbaseCol == null) {
// capbaseCol does not exist -> try to initialise it
this.createCollection(databaseUri, capbaseColPath);
}
if (this.useAuthentication) {
profilesCol = DatabaseManager.getCollection(databaseUri
+ sensorprofilesColPath, user, psswd);
} else {
profilesCol = DatabaseManager.getCollection(databaseUri
+ sensorprofilesColPath);
}
if (profilesCol == null) {
// profilesCol does not exist -> try to initialise it
this.createCollection(databaseUri, sensorprofilesColPath);
}
if (this.useAuthentication) {
smlCol = DatabaseManager.getCollection(databaseUri + smlColPath,
user, psswd);
} else {
smlCol = DatabaseManager.getCollection(databaseUri +
smlColPath);
}
if (smlCol == null) {
// smlCol does not exist -> try to initialise it
this.createCollection(databaseUri, smlColPath);
}
} catch (XMLDBException e) {
logger.debug("configureFactory - XML:DB Exception occured "
+ e.errorCode + " " + e.getMessage(), e);
throw e;
} finally {
if (profilesCol != null) {
profilesCol.close();
}
if (capbaseCol != null) {
capbaseCol.close();
}
if (smlCol != null) {
smlCol.close();
}
}
// if everything is fine:
configured = true;
}
/**
* Creates a new collection in the given database with the given relative
* path.
*
* @param databaseUri
* uri to the root collection of the database. E.g. for a
remote
* eXist database: xmldb:exist://localhost:8080/exist/xmlrpc/db
* @param collPath
* relative path to the collection that shall be created, e.g.
* /sub1/sub2
* @throws XMLDBException
* if the collection could not be created.
*/
private void createCollection(String databaseUri, String collPath)
throws XMLDBException {
// TODO do the Collections that are created and accessed have to be
// closed??
Collection current;
if (this.useAuthentication) {
current = DatabaseManager.getCollection(databaseUri, user, psswd);
} else {
current = DatabaseManager.getCollection(databaseUri);
}
logger.debug("creating " + collPath);
CollectionManagementService mgtService;
Collection c = null;
String p = "", token;
StringTokenizer tok = new StringTokenizer(collPath, "/");
while (tok.hasMoreTokens()) {
token = tok.nextToken();
p = p + '/' + token;
if (this.useAuthentication) {
c = DatabaseManager.getCollection(databaseUri + p, user, psswd);
} else {
c = DatabaseManager.getCollection(databaseUri + p);
}
if (c == null) {
mgtService = (CollectionManagementService) current.getService(
"CollectionManagementService", "1.0");
current = mgtService.createCollection(token);
} else
current = c;
}
}
/**
* @see org.n52.sps.pm.PMDAOFactory#getCapBaseDAO()
*/
public PMCapBaseDAO getCapBaseDAO() {
if (this.useAuthentication)
return new PMXMLdbCapBaseDAO(databaseUri + capbaseColPath,
new String[] {user, psswd});
else
return new PMXMLdbCapBaseDAO(databaseUri + capbaseColPath, null);
}
/**
* @see org.n52.sps.pm.PMDAOFactory#getSensorMLDAO()
*/
public PMSensorMLDAO getSensorMLDAO() {
if (this.useAuthentication)
return new PMXMLdbSensorMLDAO(databaseUri + smlColPath, new
String[] {
user, psswd});
else
return new PMXMLdbSensorMLDAO(databaseUri + smlColPath, null);
}
/**
* @see org.n52.sps.pm.PMDAOFactory#getSensorProfileDAO()
*/
public PMSensorProfileDAO getSensorProfileDAO() {
if (this.useAuthentication)
return new PMXMLdbSensorProfileDAO(
databaseUri + sensorprofilesColPath, new String[] {user,
psswd});
else
return new PMXMLdbSensorProfileDAO(
databaseUri + sensorprofilesColPath, null);
}
/**
* @see org.n52.sps.pm.PMDAOFactory#getSensorProfileIDs()
*/
public String[] getSensorProfileIDs() throws Exception {
if (!configured)
throw new Exception("The Factory has not been configured yet");
// Collections should exist, because factory has been configured
// so do not test again
Collection profilesCol = null;
try {
if (this.useAuthentication)
profilesCol = DatabaseManager.getCollection(databaseUri
+ sensorprofilesColPath, user, psswd);
else
profilesCol = DatabaseManager.getCollection(databaseUri
+ sensorprofilesColPath);
String[] storedProfilesIDs = profilesCol.listResources();
if (storedProfilesIDs == null || storedProfilesIDs.length == 0)
return null;
else
return storedProfilesIDs;
} catch (XMLDBException e) {
logger.debug("XMLDBException occured " + e.errorCode + " "
+ e.getMessage(), e);
throw e;
} finally {
if (profilesCol != null) {
profilesCol.close();
}
}
}
}
-----------------------------------------------------------------
The properties file might look like this:
-----------------------------------------------------------------
# identifies the class which implements the XML:DB-Database-Interface
pm.database.driver=org.exist.xmldb.DatabaseImpl
# points to the root-collection of the database
# pm.database.uri + pm.database.collections.* must result in a valid
collection path
pm.database.uri=xmldb:exist://localhost:8080/exist/xmlrpc/db
# username and password to use for accessing collections
# leave empty or delete if the database does not support usernames and
passwords
pm.database.username=pm
pm.database.password=pm
# define the collection for storing the CapabilitiesBaseType
pm.database.collections.capbase=/sps/pm/capbase
# define the collection for storing SensorProfiles
pm.database.collections.sensorprofiles=/sps/pm/sensorprofiles
# define the collection for storing SensorML descriptions
pm.database.collections.sensormldescriptions=/sps/pm/sensorml
Alistair Young wrote:
That sounds like something that would work! Can you explain a bit
about the hardcoding? I don't think that would be a problem.
thanks,
Alistair
On 30 Mar 2006, at 14:54, Johannes Echterhoff wrote:
Hi.
I am using eXist to store and retrieve my XMLBeans-generated
objects. However, persisting is hardcoded - i.e. I call the methods
to store my beans explicitly in the code. Don't know if this is what
you want exactly.
Johannes
Alistair Young wrote:
thanks - I'll take a look at xindice
Alistair
On 30 Mar 2006, at 14:42, Alex Soto wrote:
no it is not possible directly. If you want a binder of xml that
also stores the data, you can use Castor, or XmlBeans + Xindice.
I suppose there is other ways but i only knows what i have
explained to you.
El dj 30 de 03 del 2006 a les 14:36 +0100, en/na Alistair Young va
escriure:
Is XMLBeans capable of persisting beans to the eXist XML database?
thanks,
Alistair
-------------------------------------------------------------------
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
<mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: [EMAIL PROTECTED]
<mailto:[EMAIL PROTECTED]>
La información contenida en el presente e-mail es confidencial y
está reservada para el uso exclusivo de su destinatario. Se
prohíbe estrictamente la distribución, copia o utilización de esta
información sin el previo permiso de su destinatario. Si usted no
fuera el destinatario, por favor notifíquelo inmediatamente al
remitente y elimine el presente mensaje de su sistema informático.
Information contained in this e-mail is confidential and is
intended for the use of the addressee only. Any dissemination,
distribution, copying or use of this communication without prior
permission of the addressee is strictly prohibited. If you are not
the intended addressee, please notify the sender immediately by
reply and then delete this message from your computer system.
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]