35426afb0f16999595f98b0dfce8f39d5d9ca59f
[dcaegen2/services.git] /
1 /*
2 * ============LICENSE_START=======================================================
3 * ONAP : DATALAKE
4 * ================================================================================
5 * Copyright 2018 China Mobile
6 *=================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 *     http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
19 */
20
21 package org.onap.datalake.feeder.service;
22
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27
28 import javax.annotation.PostConstruct;
29 import javax.annotation.PreDestroy;
30
31 import org.apache.commons.lang3.StringUtils;
32 import org.bson.Document;
33
34 import org.json.JSONObject;
35 import org.onap.datalake.feeder.config.ApplicationConfiguration;
36 import org.onap.datalake.feeder.domain.Db;
37 import org.onap.datalake.feeder.domain.Topic;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 import org.springframework.beans.factory.annotation.Autowired;
42 import org.springframework.stereotype.Service;
43
44 import com.mongodb.MongoClient;
45 import com.mongodb.MongoClientOptions;
46 import com.mongodb.MongoClientOptions.Builder;
47 import com.mongodb.MongoCredential;
48 import com.mongodb.ServerAddress;
49 import com.mongodb.client.MongoCollection;
50 import com.mongodb.client.MongoDatabase;
51
52 /**
53  * Service for using MongoDB
54  * 
55  * @author Guobiao Mo
56  *
57  */
58 @Service
59 public class MongodbService {
60
61         private final Logger log = LoggerFactory.getLogger(this.getClass());
62
63         @Autowired
64         private ApplicationConfiguration config;
65
66         @Autowired
67         private DbService dbService;
68
69         private MongoDatabase database;
70         private MongoClient mongoClient;
71         private Map<String, MongoCollection<Document>> mongoCollectionMap = new HashMap<>();
72
73         @PostConstruct
74         private void init() {
75                 Db mongodb = dbService.getMongoDB();
76
77                 String host = mongodb.getHost();
78
79                 Integer port = mongodb.getPort();
80                 if (port == null || port == 0) {
81                         port = 27017; //MongoDB default
82                 }
83
84                 String databaseName = mongodb.getDatabase();
85                 String userName = mongodb.getLogin();
86                 String password = mongodb.getPass();
87
88                 MongoCredential credential = null;
89                 if (StringUtils.isNoneBlank(userName) && StringUtils.isNoneBlank(password)) {
90                         credential = MongoCredential.createCredential(userName, databaseName, password.toCharArray());
91                 }
92
93                 Builder builder = MongoClientOptions.builder();
94                 builder.serverSelectionTimeout(30000);//server selection timeout, in milliseconds
95
96                 //http://mongodb.github.io/mongo-java-driver/3.0/driver/reference/connecting/ssl/
97                 if (config.isEnableSSL()) {
98                         builder.sslEnabled(Boolean.TRUE.equals(mongodb.getEncrypt()));// getEncrypt() can be null
99                 }
100                 MongoClientOptions options = builder.build();
101
102                 if (credential == null) {
103                         mongoClient = new MongoClient(new ServerAddress(host, port), options);
104                 } else {
105                         mongoClient = new MongoClient(new ServerAddress(host, port), credential, options);
106                 }
107                 database = mongoClient.getDatabase(databaseName);
108         }
109
110         @PreDestroy
111         public void cleanUp() {
112                 mongoClient.close();
113         }
114
115         public void saveJsons(Topic topic, List<JSONObject> jsons) {
116                 List<Document> documents = new ArrayList<>(jsons.size());
117                 for (JSONObject json : jsons) {
118                         //convert org.json JSONObject to MongoDB Document
119                         Document doc = Document.parse(json.toString());
120
121                         String id = topic.getMessageId(json); //id can be null
122                         if (id != null) {
123                                 doc.put("_id", id);
124                         }
125                         documents.add(doc);
126                 }
127
128                 String collectionName = topic.getName().replaceAll("[^a-zA-Z0-9]", "");//remove - _ .
129                 MongoCollection<Document> collection = mongoCollectionMap.computeIfAbsent(collectionName, k -> database.getCollection(k));
130                 collection.insertMany(documents);
131
132                 log.debug("saved text to topic = {}, topic total count = {} ", topic, collection.countDocuments());
133         }
134
135 }