001// Copyright 2013 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007// http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry5.internal.mongodb;
016
017import com.mongodb.DB;
018import com.mongodb.Mongo;
019import org.apache.tapestry5.ioc.services.ThreadCleanupListener;
020import org.apache.tapestry5.mongodb.MongoDB;
021import org.apache.tapestry5.mongodb.MongoDBSource;
022import org.slf4j.Logger;
023
024/**
025 * Default implementation for {@link org.apache.tapestry5.mongodb.MongoDB}
026 */
027public class MongoDBImpl implements MongoDB, ThreadCleanupListener
028{
029    private final Logger logger;
030
031        private final Mongo mongo;
032
033    private final String defaultDbName;
034    private final boolean consistentRequest;
035
036        private final boolean secureMode;
037        private final String dbUsername;
038        private final String dbPassword;
039
040    private DB db;
041
042    public MongoDBImpl(Logger logger,
043                   MongoDBSource mongoDBSource,
044           String defaultDbName, boolean consistentRequest,
045                   boolean secureMode, String dbUsername, String dbPassword)
046    {
047        this.logger = logger;
048
049        this.mongo = mongoDBSource.getMongo();
050
051        this.defaultDbName = defaultDbName;
052        this.consistentRequest = consistentRequest;
053
054                this.secureMode = secureMode;
055                this.dbUsername = dbUsername;
056                this.dbPassword = dbPassword;
057    }
058
059    public DB getDefaultMongoDb()
060    {
061        return buildDbSession(defaultDbName);
062    }
063
064    public DB getMongoDb(String dbname)
065    {
066                return buildDbSession(dbname);
067    }
068
069    public void threadDidCleanup()
070    {
071        if (consistentRequest)
072            db.requestDone();
073    }
074
075
076        private final DB buildDbSession(String dbname)
077        {
078                db = mongo.getDB(dbname);
079
080                if (consistentRequest)
081                {
082                        db.requestStart();
083                        db.requestEnsureConnection();
084                }
085
086                if (secureMode)
087                {
088                        db.authenticate(dbUsername, dbPassword.toCharArray());
089                }
090
091                return db;
092        }
093}