c5408951fae86f7ffb955904b6d809b56797c619
[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.bulk.BulkWriteError;
45 import com.mongodb.MongoBulkWriteException;
46 import com.mongodb.MongoClient;
47 import com.mongodb.MongoClientOptions;
48 import com.mongodb.MongoClientOptions.Builder;
49 import com.mongodb.MongoCredential;
50 import com.mongodb.ServerAddress;
51 import com.mongodb.client.MongoCollection;
52 import com.mongodb.client.MongoDatabase;
53 import com.mongodb.client.model.InsertManyOptions;
54
55 /**
56  * Service for using MongoDB
57  * 
58  * @author Guobiao Mo
59  *
60  */
61 @Service
62 public class MongodbService {
63
64         private final Logger log = LoggerFactory.getLogger(this.getClass());
65
66         @Autowired
67         private ApplicationConfiguration config;
68         private boolean dbReady = false;
69
70         @Autowired
71         private DbService dbService;
72
73         private MongoDatabase database;
74         private MongoClient mongoClient;
75         private Map<String, MongoCollection<Document>> mongoCollectionMap = new HashMap<>();
76         private InsertManyOptions insertManyOptions;
77
78         @PostConstruct
79         private void init() {
80                 Db mongodb = dbService.getMongoDB();
81
82                 String host = mongodb.getHost();
83
84                 Integer port = mongodb.getPort();
85                 if (port == null || port == 0) {
86                         port = 27017; //MongoDB default
87                 }
88
89                 String databaseName = mongodb.getDatabase();
90                 String userName = mongodb.getLogin();
91                 String password = mongodb.getPass();
92
93                 MongoCredential credential = null;
94                 if (StringUtils.isNoneBlank(userName) && StringUtils.isNoneBlank(password)) {
95                         credential = MongoCredential.createCredential(userName, databaseName, password.toCharArray());
96                 }
97
98                 Builder builder = MongoClientOptions.builder();
99                 builder.serverSelectionTimeout(30000);//server selection timeout, in milliseconds
100
101                 //http://mongodb.github.io/mongo-java-driver/3.0/driver/reference/connecting/ssl/
102                 if (config.isEnableSSL()) {
103                         builder.sslEnabled(Boolean.TRUE.equals(mongodb.getEncrypt()));// getEncrypt() can be null
104                 }
105                 MongoClientOptions options = builder.build();
106                 List<ServerAddress> addrs = new ArrayList<ServerAddress>();
107
108                 addrs.add(new ServerAddress(host, port)); // FIXME should be a list of address
109
110                 try {
111                         if (StringUtils.isNoneBlank(userName) && StringUtils.isNoneBlank(password)) {
112                                 credential = MongoCredential.createCredential(userName, databaseName, password.toCharArray());
113                                 List<MongoCredential> credentialList = new ArrayList<MongoCredential>();
114                                 credentialList.add(credential);
115                                 mongoClient = new MongoClient(addrs, credentialList, options);
116                         } else {
117                                 mongoClient = new MongoClient(addrs, options);
118                         }
119                 } catch (Exception ex) {
120                         dbReady = false;
121                         log.error("Fail to initiate MongoDB" + mongodb.getHost());
122                         return;
123                 }
124                 database = mongoClient.getDatabase(mongodb.getDatabase());
125
126                 insertManyOptions = new InsertManyOptions();
127                 insertManyOptions.ordered(false);
128
129                 dbReady = true;
130         }
131
132         @PreDestroy
133         public void cleanUp() {
134                 mongoClient.close();
135         }
136
137         public void saveJsons(TopicConfig topic, List<JSONObject> jsons) {
138                 if (dbReady == false)
139                         return;
140                 List<Document> documents = new ArrayList<>(jsons.size());
141                 for (JSONObject json : jsons) {
142                         //convert org.json JSONObject to MongoDB Document
143                         Document doc = Document.parse(json.toString());
144
145                         String id = topic.getMessageId(json); //id can be null
146                         if (id != null) {
147                                 doc.put("_id", id);
148                         }
149                         documents.add(doc);
150                 }
151
152                 String collectionName = topic.getName().replaceAll("[^a-zA-Z0-9]", "");//remove - _ .
153                 MongoCollection<Document> collection = mongoCollectionMap.computeIfAbsent(collectionName, k -> database.getCollection(k));
154
155                 try {
156                         collection.insertMany(documents, insertManyOptions);
157                 } catch (MongoBulkWriteException e) {
158                         List<BulkWriteError> bulkWriteErrors = e.getWriteErrors();
159                         for (BulkWriteError bulkWriteError : bulkWriteErrors) {
160                                 log.error("Failed record: {}", bulkWriteError);
161                         }
162                 }
163
164                 log.debug("saved text to topic = {}, batch count = {} ", topic, jsons.size());
165         }
166
167 }