/**********************************************************************
Copyright (c) 2011 Andy Jefferson and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
...
**********************************************************************/
package org.datanucleus.store.mongodb;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.transaction.xa.XAResource;
import org.datanucleus.exceptions.NucleusDataStoreException;
import org.datanucleus.exceptions.NucleusException;
import org.datanucleus.store.StoreManager;
import org.datanucleus.store.connection.AbstractConnectionFactory;
import org.datanucleus.store.connection.AbstractManagedConnection;
import org.datanucleus.store.connection.ManagedConnection;
import org.datanucleus.store.connection.ManagedConnectionResourceListener;
import org.datanucleus.util.Localiser;
import org.datanucleus.util.NucleusLogger;
import org.datanucleus.util.StringUtils;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.ServerAddress;
/**
* Implementation of a ConnectionFactory for MongoDB.
* Accepts a URL of the form
* <pre>mongodb:[{server1}][/{dbName}][,{server2}[,{server3}]]</pre>
* Defaults to a server of "localhost" if nothing specified
* Defaults to a DB name of "DataNucleus" if nothing specified
*/
public class ConnectionFactoryImpl extends AbstractConnectionFactory
{
protected static final Localiser LOCALISER = Localiser.getInstance(
"org.datanucleus.store.mongodb.Localisation", MongoDBStoreManager.class.getClassLoader());
String dbName = "DataNucleus";
Mongo mongo;
/**
* Constructor.
* @param storeMgr Store Manager
* @param resourceType Type of resource (tx, nontx)
*/
public ConnectionFactoryImpl(StoreManager storeMgr, String resourceType)
{
super(storeMgr, resourceType);
// "mongodb:[server]"
String url = storeMgr.getConnectionURL();
if (url == null)
{
throw new NucleusException("You haven't specified persistence property 'datanucleus.ConnectionURL' (or alias)");
}
String remains = url.substring(7).trim();
if (remains.indexOf(':') == 0)
{
remains = remains.substring(1);
}
// Split into any replica sets
try
{
List<ServerAddress> serverAddrs = new ArrayList();
if (remains.length() == 0)
{
// "mongodb:"
serverAddrs.add(new ServerAddress());
}
else
{
StringTokenizer tokeniser = new StringTokenizer(remains, ",");
while (tokeniser.hasMoreTokens())
{
String token = tokeniser.nextToken();
String serverName = "localhost";
if (token.charAt(0) != '/')
{
// server name (and optional port)
int serverEndPos = remains.indexOf('/');
if (serverEndPos > 0)
{
serverName = token.substring(0, serverEndPos);
token = token.substring(serverEndPos);
}
else
{
serverName = token;
remains = "";
}
}
// Create a ServerAddress for this specification
ServerAddress addr = null;
int portSeparatorPos = serverName.indexOf(':');
if (portSeparatorPos > 0)
{
addr = new ServerAddress(serverName.substring(0, portSeparatorPos),
Integer.valueOf(serverName.substring(portSeparatorPos+1)).intValue());
}
else
{
addr = new ServerAddress(serverName);
}
serverAddrs.add(addr);
if (token.charAt(0) == '/' && token.length() > 1)
{
// database name
dbName = token.substring(1);
}
}
}
// Create the Mongo connection pool
if (NucleusLogger.CONNECTION.isDebugEnabled())
{
NucleusLogger.CONNECTION.debug(LOCALISER.msg("MongoDB.ServerConnect", dbName, serverAddrs.size(),
StringUtils.collectionToString(serverAddrs)));
}
if (serverAddrs.size() == 1)
{
mongo = new Mongo(serverAddrs.get(0));
}
else
{
mongo = new Mongo(serverAddrs);
}
}
catch (UnknownHostException e)
{
throw new NucleusDataStoreException("Unable to connect to mongodb", e);
}
catch (MongoException me)
{
throw new NucleusDataStoreException("Unable to connect to mongodb", me);
}
}
public void close()
{
mongo.close();
super.close();
}
/**
* Obtain a connection from the Factory. The connection will be enlisted within the {@link org.datanucleus.Transaction}
* associated to the <code>poolKey</code> if "enlist" is set to true.
* @param poolKey the pool that is bound the connection during its lifecycle (or null)
* @param transactionOptions Any options for then creating the connection
* @return the {@link org.datanucleus.store.connection.ManagedConnection}
*/
public ManagedConnection createManagedConnection(Object poolKey, Map transactionOptions)
{
return new ManagedConnectionImpl(transactionOptions);
}
public class ManagedConnectionImpl extends AbstractManagedConnection
{
Map options;
public ManagedConnectionImpl(Map options)
{
this.options = options;
}
public Object getConnection()
{
if (conn == null)
{
conn = mongo.getDB(dbName);
String userName = storeMgr.getConnectionUserName();
String password = storeMgr.getConnectionPassword();
if (!StringUtils.isWhitespace(userName))
{
boolean authenticated = false;
if (!((DB)conn).isAuthenticated())
{
authenticated = ((DB)conn).authenticate(userName, password.toCharArray());
if (!authenticated)
{
throw new NucleusDataStoreException("Authentication of the connection failed for datastore " +
dbName + " with user " + userName);
}
}
}
if (storeMgr.getBooleanProperty("datanucleus.readOnlyDatastore", false))
{
((DB)conn).setReadOnly(Boolean.TRUE);
}
}
((DB)conn).requestStart();
return conn;
}
public void release()
{
((DB)conn).requestDone();
super.release();
}
public void close()
{
if (conn == null)
{
return;
}
for (int i=0; i<listeners.size(); i++)
{
((ManagedConnectionResourceListener)listeners.get(i)).managedConnectionPreClose();
}
// DB db = (DB)conn;
for (int i=0; i<listeners.size(); i++)
{
((ManagedConnectionResourceListener)listeners.get(i)).managedConnectionPostClose();
}
}
public XAResource getXAResource()
{
return null;
}
}
}