02c80a458933b0ec591dd1263f705bc6c72523e0
[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.dto.TopicConfig;
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         private boolean dbReady = false;
66
67         @Autowired
68         private DbService dbService;
69
70         private MongoDatabase database;
71         private MongoClient mongoClient;
72         private Map<String, MongoCollection<Document>> mongoCollectionMap = new HashMap<>();
73
74         @PostConstruct
75         private void init() {
76                 Db mongodb = dbService.getMongoDB();
77
78                 String host = mongodb.getHost();
79
80                 Integer port = mongodb.getPort();
81                 if (port == null || port == 0) {
82                         port = 27017; //MongoDB default
83                 }
84
85                 String databaseName = mongodb.getDatabase();
86                 String userName = mongodb.getLogin();
87                 String password = mongodb.getPass();
88
89                 MongoCredential credential = null;
90                 if (StringUtils.isNoneBlank(userName) && StringUtils.isNoneBlank(password)) {
91                         credential = MongoCredential.createCredential(userName, databaseName, password.toCharArray());
92                 }
93
94                 Builder builder = MongoClientOptions.builder();
95                 builder.serverSelectionTimeout(30000);//server selection timeout, in milliseconds
96
97                 //http://mongodb.github.io/mongo-java-driver/3.0/driver/reference/connecting/ssl/
98                 if (config.isEnableSSL()) {
99                         builder.sslEnabled(Boolean.TRUE.equals(mongodb.getEncrypt()));// getEncrypt() can be null
100                 }
101                 MongoClientOptions options = builder.build();
102                 List<ServerAddress> addrs = new ArrayList<ServerAddress>();
103
104                 addrs.add(new ServerAddress(host, port)); // FIXME should be a list of address
105
106
107                 try {
108                         if(StringUtils.isNoneBlank(userName) && StringUtils.isNoneBlank(password))
109                         {
110                                 credential = MongoCredential.createCredential(userName, databaseName, password.toCharArray());
111                                 List<MongoCredential> credentialList = new ArrayList<MongoCredential>();
112                                 credentialList.add(credential);
113                                 mongoClient = new MongoClient(addrs, credentialList, options);
114                         }else
115                         {
116                                 mongoClient = new MongoClient(addrs, options);
117                         }
118                 }catch(Exception ex){
119                         dbReady = false;
120                         log.error("Fail to initiate MongoDB" + mongodb.getHost());
121                         return;
122                 }
123                 database = mongoClient.getDatabase(mongodb.getDatabase());
124                 dbReady = true;
125
126         }
127
128         @PreDestroy
129         public void cleanUp() {
130                 mongoClient.close();
131         }
132
133         public void saveJsons(TopicConfig topic, List<JSONObject> jsons) {
134                 if(dbReady == false)
135                         return;
136                 List<Document> documents = new ArrayList<>(jsons.size());
137                 for (JSONObject json : jsons) {
138                         //convert org.json JSONObject to MongoDB Document
139                         Document doc = Document.parse(json.toString());
140
141                         String id = topic.getMessageId(json); //id can be null
142                         if (id != null) {
143                                 doc.put("_id", id);
144                         }
145                         documents.add(doc);
146                 }
147
148                 String collectionName = topic.getName().replaceAll("[^a-zA-Z0-9]", "");//remove - _ .
149                 MongoCollection<Document> collection = mongoCollectionMap.computeIfAbsent(collectionName, k -> database.getCollection(k));
150                 collection.insertMany(documents);
151
152                 log.debug("saved text to topic = {}, batch count = {} ", topic, jsons.size());
153         }
154
155 }