jp.co.ctc_g.jse.data.mongo.showcase.config.MongoShowcaseContextConfig.java Source code

Java tutorial

Introduction

Here is the source code for jp.co.ctc_g.jse.data.mongo.showcase.config.MongoShowcaseContextConfig.java

Source

/*
 * Copyright (c) 2013 ITOCHU Techno-Solutions Corporation.
 *
 * 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 jp.co.ctc_g.jse.data.mongo.showcase.config;

import java.net.UnknownHostException;

import jp.co.ctc_g.jfw.core.internal.InternalException;
import jp.co.ctc_g.jfw.core.util.Maps;
import jp.co.ctc_g.jfw.core.util.Strings;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.auditing.IsNewAwareAuditingHandler;
import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mapping.context.MappingContextIsNewStrategyFactory;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.config.EnableMongoAuditing;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.core.mapping.event.AuditingEventListener;
import org.springframework.data.mongodb.core.mapping.event.LoggingEventListener;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;

/**
 * <p>
 * ????Spring????
 * </p>
 * @author ITOCHU Techno-Solutions Corporation.
 */
@Configuration
@EnableScheduling
@EnableMongoRepositories(basePackages = "jp.co.ctc_g.jse.data.mongo.showcase.integration.mongo")
@EnableMongoAuditing
public class MongoShowcaseContextConfig {

    /**
     * ?MongoDB???
     * 
     * 127.0.0.1
     */
    @Value("${mongo.host:127.0.0.1}")
    protected String host;

    /**
     * ?MongoDB???
     * 
     * 27017
     */
    @Value("${mongo.port:27017}")
    protected int port;

    /**
     * ?MongoDB???
     * 
     * ??
     */
    @Value("${mongo.username:}")
    protected String username;

    /**
     * ?MongoDB?
     * 
     * ??
     */
    @Value("${mongo.password:}")
    protected String password;

    /**
     * ?MongoDB??
     * 
     * 10
     */
    @Value("${mongo.connectionsPerHost:10}")
    protected int connectionsPerHost;

    /**
     * ?MongoDB????
     * 
     * 4
     */
    @Value("${mongo.threadsAllowedToBlockForConnectionMultiplier:4}")
    protected int threadsAllowedToBlockForConnectionMultiplier;

    /**
     * ?MongoDB???
     * 
     * 1000
     */
    @Value("${mongo.connectTimeout:1000}")
    protected int connectTimeout;

    /**
     * ?MongoDB????
     * 
     * 1500
     */
    @Value("${mongo.maxWaitTime:1500}")
    protected int maxWaitTime;

    /**
     * ?MongoDB???
     * 
     * true
     */
    @Value("${mongo.autoConnectRetry:true}")
    protected boolean autoConnectRetry;

    /**
     * ?MongoDB???
     * 
     * true
     */
    @Value("${mongo.socketKeepAlive:true}")
    protected boolean socketKeepAlive;

    /**
     * ?MongoDB???
     * 
     * true
     */
    @Value("${mongo.databaseName:}")
    protected String databaseName;

    /**
     * ??
     */
    public MongoShowcaseContextConfig() {
    }

    // -------------------- Mongo?

    /**
     * MongoDB???????
     * @return {@link MongoClient} ?
     */
    @Bean
    public MongoClient mongo() {
        try {
            return new MongoClient(new ServerAddress(host, port), options());
        } catch (UnknownHostException e) {
            throw new InternalException(MongoShowcaseContextConfig.class, "E-MONGO-CONFIG#0001",
                    Maps.hash("host", host).map("port", Integer.toString(port)), e);
        }
    }

    /**
     * MongoDB???MongoClientOptions?????
     * @return {@link MongoClientOptions} ?
     */
    @Bean
    public MongoClientOptions options() {
        return config().build();
    }

    /**
     * MongoDB? MongoDbFactory ?????
     * @return {@link SimpleMongoDbFactory} ?
     */
    @Bean
    public MongoDbFactory mongoDbFactory() {
        if (Strings.isEmpty(databaseName))
            throw new InternalException(MongoShowcaseContextConfig.class, "E-MONGO-CONFIG#0002");
        if (!Strings.isEmpty(username) && !Strings.isEmpty(password)) {
            return new SimpleMongoDbFactory(mongo(), databaseName, auth());
        } else {
            return new SimpleMongoDbFactory(mongo(), databaseName);
        }
    }

    /**
     * ??????
     * @return {@link UserCredentials} ?
     */
    @Bean
    public UserCredentials auth() {
        return new UserCredentials(username, password);
    }

    /**
     * MongoDB???????MongoOperations ?????
     * @return {@link MongoTemplate} ?
     */
    @Bean
    public MongoOperations mongoTemplate() {
        return new MongoTemplate(mongoDbFactory(), converter());
    }

    // ----------------------- MongoAuditing?
    @Bean
    public MongoMappingContext mappingContext() {
        return new MongoMappingContext();
    }

    @SuppressWarnings("unchecked")
    @Bean
    public AuditingEventListener auditingEventListener() {
        return new AuditingEventListener(auditingHandler());
    }

    @SuppressWarnings("rawtypes")
    @Bean
    public IsNewAwareAuditingHandler auditingHandler() {
        return new IsNewAwareAuditingHandler(support());
    }

    public MappingContextIsNewStrategyFactory support() {
        return new MappingContextIsNewStrategyFactory(mappingContext());
    }

    // --------------------- MongoLogging
    /**
     * ???MongoDB??????
     * @return
     */
    @Bean
    public LoggingEventListener logging() {
        return new LoggingEventListener();
    }

    // ---------------------- ?
    /**
     * MongoDB??????????????
     * @return {@link MongoClientOptions.Builder} 
     */
    protected MongoClientOptions.Builder config() {

        return MongoClientOptions.builder().connectionsPerHost(connectionsPerHost)
                .threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier)
                .connectTimeout(connectTimeout).maxWaitTime(maxWaitTime).autoConnectRetry(autoConnectRetry)
                .socketKeepAlive(socketKeepAlive);

    }

    /**
     * {@link MongoConverter}????????????
     * ????????null???
     * @return {@link MongoConverter} ?
     */
    protected MongoConverter converter() {
        return null;
    }

}