com.cloudbees.demo.beesshop.util.MongodbDBFactoryBean.java Source code

Java tutorial

Introduction

Here is the source code for com.cloudbees.demo.beesshop.util.MongodbDBFactoryBean.java

Source

/*
 * Copyright 2010-2013, the original author or authors
 *
 * 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.
 */
package com.cloudbees.demo.beesshop.util;

import com.mongodb.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * http://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html
 *
 * @author <a href="mailto:cleclerc@cloudbees.com">Cyrille Le Clerc</a>
 */
public class MongodbDBFactoryBean implements FactoryBean<DB>, InitializingBean {
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    private MongoClient mongoClient;
    private DB db;
    private String uri;

    @Override
    public void afterPropertiesSet() throws Exception {
        MongoClientURI mongoDbUri = new MongoClientURI(uri);
        logger.info("host=" + mongoDbUri.getHosts() + ",username=" + mongoDbUri.getUsername() + ",database="
                + mongoDbUri.getDatabase() + ",collection=" + mongoDbUri.getCollection());

        mongoClient = new MongoClient(mongoDbUri);
        db = mongoClient.getDB(mongoDbUri.getDatabase());
    }

    @Override
    public DB getObject() throws Exception {
        return db;
    }

    @Override
    public Class<?> getObjectType() {
        return DB.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }
}