MongoDB工具类

package org.util;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


import org.apache.log4j.Logger;
import org.bson.Document;
import org.isli.deal.resolution.pojo.AreaInfo;


import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;


/**
 * MongoDB工具类
 * 
 * @author 
 *
 */
public class MongoDBUtil {


    private static final Logger LOGGER = Logger.getLogger(MongoDBUtil.class);
    private static final String COUNTRY = "country";
    private static final String PROVINCE = "province";
    private static final String CITY = "city";


    public MongoDBUtil() {


    }


    /**
     * 地址集合转换成List
     * 
     * @param serverAddress
     *            地址集合(localhost:27017,localhost:27018,localhost:27019)
     * @return
     */
    private static List<ServerAddress> getServerAddressList(
            String serverAddress) {
        List<ServerAddress> list = null;
        if (null != serverAddress && !"".equals(serverAddress)) {
            list = new ArrayList<ServerAddress>();
            // 分隔分号
            String[] addresss = serverAddress.split(Constant.SEMICOLON);
            if (null != addresss && addresss.length > 0) {
                ServerAddress server = null;
                for (String address : addresss) {
                    if (null != address && !"".equals(address)) {
                        // 分隔冒号
                        String[] ipPort = address.split(Constant.COLON);
                        server = new ServerAddress(ipPort[0],
                                Integer.parseInt(ipPort[1]));
                        list.add(server);
                    }
                }


            }
        }
        return list;
    }


    /**
     * 连接数据库
     * 
     * @return
     */
    private static MongoClient getMongoClient() {
        LOGGER.info("Connect to database successfully");
        MongoClient mongoClient = null;
        try {
            // 数据库地址
            String uri = SystemConfig.getString(Constant.MONGO_URI);
            mongoClient = new MongoClient(getServerAddressList(uri));
        } catch (Exception e) {
            e.printStackTrace();
        }


        return mongoClient;
    }


    /**
     * 插入数据
     * 
     * @param list
     *            json值集合
     * @return
     * @throws Exception
     */
    public int insertDB(List<String> list) throws Exception {
        LOGGER.info("[MongoDBUtil.insertDB] begin");
        int result = -1;
        MongoClient mongoClient = null;
        try {
            if (null != list && list.size() > 0) {
                mongoClient = getMongoClient();
                // 库名称
                MongoDatabase database = mongoClient
                        .getDatabase(SystemConfig.getString(Constant.MONGO_DB));
                // 文档名称
                MongoCollection<Document> collection = database.getCollection(
                        SystemConfig.getString(Constant.MONGO_COLLECTION));


                collection.insertMany(getDocuments(list));
                result = 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("[MongoDBUtil.insertDB]" + e.getMessage());
            throw e;
        } finally {
            if (mongoClient != null) {
                mongoClient.close();
                mongoClient = null;
            }
        }
        LOGGER.info("[MongoDBUtil.insertDB] end");


        return result;
    }


    @SuppressWarnings({ "rawtypes", "unchecked" })
    private List<Document> getDocuments(List<String> list) {
        List<Document> documents = new ArrayList<Document>();
        Document document = null;
        for (String json : list) {
            if (null == json || "".equals(json)) {
                continue;
            }
            Map map = JsonUtil.jsonToMap(json);
            if (null != map) {
                document = new Document();
                // 使用Iterator遍历Map
                Iterator<Map.Entry<String, Object>> entries = map.entrySet()
                        .iterator();
                while (entries.hasNext()) {
                    Map.Entry<String, Object> entry = entries.next();
                    if (null == entry) {
                        continue;
                    }
                    // 有多余的双引号,去掉
                    String entryKey = entry.getKey().replace("\"", "");
                    String entryValue = (entry.getValue() + "").replace("\"",
                            "");
                    String newEntryValue = "";
                    // null替换成""
                    if ("null".equals(entryValue)) {
                        newEntryValue = "";
                    } else {
                        newEntryValue = entryValue;
                    }


                    if (COUNTRY.equals(entryKey) || PROVINCE.equals(entryKey)
                            || CITY.equals(entryKey) || "id".equals(entryKey)
                            || "uuid".equals(entryKey)) {
                        continue;
                    } else if ("ip".equals(entryKey)) {
                        // 通过IP查出国家、省份、城市
                        // 保留一份
                        document.append(entryKey, newEntryValue);
                        AreaInfo area = new AddressUtil()
                                .getAddressByIp(newEntryValue);
                        if (null != area) {
                            document.append(COUNTRY, area.getCountry());
                            document.append(PROVINCE, area.getProvince());
                            document.append(CITY, area.getCity());
                        } else {
                            document.append(COUNTRY, "");
                            document.append(PROVINCE, "");
                            document.append(CITY, "");
                        }
                    } else if ("parseTime".equals(entryKey)
                            || "createTime".equals(entryKey)
                            || "updateTime".equals(entryKey)) {
                        /**
                         * 因为时间传递过来的为时间戳,下面做法是:保留一份时间戳,再增加字段格式化一份
                         */
                        // 时间戳格式化
                        String format = "";
                        if (!"".equals(newEntryValue)) {
                            format = DateTimeUtil
                                    .objectConvertFormatString(newEntryValue);
                        }
                        document.append(entryKey, DateTimeUtil.parse(format,
                                DateTimeUtil.FORMAT_YMDHMS));


                    } else {
                        if ("isSystemCode".equals(entryKey)
                                || "parseIsSuccess".equals(entryKey)) {
                            document.append(entryKey,
                                    Boolean.parseBoolean(newEntryValue));
                        } else {
                            document.append(entryKey, newEntryValue);
                        }


                    }


                }
                documents.add(document);
            }


        }


        return documents;
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值