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.*;
018import org.apache.tapestry5.ioc.annotations.Symbol;
019import org.apache.tapestry5.mongodb.MongoDBSource;
020import org.apache.tapestry5.mongodb.MongoDBSymbols;
021import org.slf4j.Logger;
022
023import java.net.UnknownHostException;
024import java.util.List;
025
026/**
027 * Default implementation for {@link org.apache.tapestry5.mongodb.MongoDBSource}
028 */
029public class MongoDBSourceImpl implements MongoDBSource
030{
031    private final Logger logger;
032
033    private final MongoClient mongoClient;
034
035
036    public MongoDBSourceImpl(Logger logger,
037            @Symbol(MongoDBSymbols.CONNECTIONS_PER_HOSTS) int connectionPerHost,
038            @Symbol(MongoDBSymbols.READ_PREFERENCE) ReadPreference readPreference,
039            @Symbol(MongoDBSymbols.WRITE_CONCERN) WriteConcern writeConcern,
040            List<ServerAddress> serverAddresses)
041    {
042        this.logger = logger;
043
044                MongoClientOptions options = new MongoClientOptions.Builder()
045                                .connectionsPerHost(connectionPerHost)
046                                .writeConcern(writeConcern).readPreference(readPreference)
047                                .build();
048
049        if (serverAddresses.isEmpty())
050                {
051                        try
052                        {
053                                mongoClient = new MongoClient(new ServerAddress(), options);
054                        }
055                        catch (UnknownHostException uhe)
056                        {
057                                throw new RuntimeException(uhe);
058                        }
059                }
060        else
061                {
062            mongoClient = new MongoClient(serverAddresses, options);
063                }
064    }
065
066    public MongoClient getMongo()
067    {
068        return this.mongoClient;
069    }
070}