2 * ============LICENSE_START=======================================================
 
   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
 
  11 *     http://www.apache.org/licenses/LICENSE-2.0
 
  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=========================================================
 
  21 package org.onap.datalake.feeder.service.db;
 
  23 import java.util.ArrayList;
 
  24 import java.util.HashMap;
 
  25 import java.util.List;
 
  28 import javax.annotation.PostConstruct;
 
  29 import javax.annotation.PreDestroy;
 
  31 import org.apache.commons.lang3.StringUtils;
 
  32 import org.bson.Document;
 
  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.EffectiveTopic;
 
  38 import org.slf4j.Logger;
 
  39 import org.slf4j.LoggerFactory;
 
  41 import org.springframework.beans.factory.annotation.Autowired;
 
  42 import org.springframework.context.annotation.Scope;
 
  43 import org.springframework.stereotype.Service;
 
  45 import com.mongodb.bulk.BulkWriteError;
 
  46 import com.mongodb.MongoBulkWriteException;
 
  47 import com.mongodb.MongoClient;
 
  48 import com.mongodb.MongoClientOptions;
 
  49 import com.mongodb.MongoClientOptions.Builder;
 
  50 import com.mongodb.MongoCredential;
 
  51 import com.mongodb.MongoTimeoutException;
 
  52 import com.mongodb.ServerAddress;
 
  53 import com.mongodb.client.MongoCollection;
 
  54 import com.mongodb.client.MongoDatabase;
 
  55 import com.mongodb.client.model.InsertManyOptions;
 
  58  * Service for using MongoDB
 
  65 public class MongodbService implements DbStoreService {
 
  67         private final Logger log = LoggerFactory.getLogger(this.getClass());
 
  72         private ApplicationConfiguration config;
 
  73         private boolean dbReady = false;
 
  75         private MongoDatabase database;
 
  76         private MongoClient mongoClient;
 
  77         //MongoCollection is ThreadSafe
 
  78         private Map<String, MongoCollection<Document>> mongoCollectionMap = new HashMap<>();
 
  79         private InsertManyOptions insertManyOptions;
 
  81         public MongodbService(Db db) {
 
  88                 String host = mongodb.getHost();
 
  90                 Integer port = mongodb.getPort();
 
  91                 if (port == null || port == 0) {
 
  92                         port = 27017; //MongoDB default
 
  95                 String databaseName = mongodb.getDatabase();
 
  96                 String userName = mongodb.getLogin();
 
  97                 String password = mongodb.getPass();
 
  99                 MongoCredential credential = null;
 
 100                 if (StringUtils.isNoneBlank(userName) && StringUtils.isNoneBlank(password)) {
 
 101                         credential = MongoCredential.createCredential(userName, databaseName, password.toCharArray());
 
 104                 Builder builder = MongoClientOptions.builder();
 
 105                 builder.serverSelectionTimeout(30000);//server selection timeout, in milliseconds
 
 107                 //http://mongodb.github.io/mongo-java-driver/3.0/driver/reference/connecting/ssl/
 
 108                 if (config.isEnableSSL()) {
 
 109                         builder.sslEnabled(Boolean.TRUE.equals(mongodb.getEncrypt()));// getEncrypt() can be null
 
 111                 MongoClientOptions options = builder.build();
 
 112                 List<ServerAddress> addrs = new ArrayList<>();
 
 114                 addrs.add(new ServerAddress(host, port)); // FIXME should be a list of address
 
 117                         if (StringUtils.isNoneBlank(userName) && StringUtils.isNoneBlank(password)) {
 
 118                                 credential = MongoCredential.createCredential(userName, databaseName, password.toCharArray());
 
 119                                 List<MongoCredential> credentialList = new ArrayList<>();
 
 120                                 credentialList.add(credential);
 
 121                                 mongoClient = new MongoClient(addrs, credentialList, options);
 
 123                                 mongoClient = new MongoClient(addrs, options);
 
 125                 } catch (Exception ex) {
 
 127                         log.error("Fail to initiate MongoDB" + mongodb.getHost());
 
 130                 database = mongoClient.getDatabase(mongodb.getDatabase());
 
 132                 insertManyOptions = new InsertManyOptions();
 
 133                 insertManyOptions.ordered(false);
 
 139         public void cleanUp() {
 
 140                 config.getShutdownLock().readLock().lock();
 
 143                         log.info("mongoClient.close() at cleanUp.");
 
 146                         config.getShutdownLock().readLock().unlock();
 
 150         public void saveJsons(EffectiveTopic effectiveTopic, List<JSONObject> jsons) {
 
 151                 if (!dbReady)//TOD throw exception
 
 153                 List<Document> documents = new ArrayList<>(jsons.size());
 
 154                 for (JSONObject json : jsons) {
 
 155                         //convert org.json JSONObject to MongoDB Document
 
 156                         Document doc = Document.parse(json.toString());
 
 158                         String id = effectiveTopic.getTopic().getMessageId(json); //id can be null
 
 165                 String collectionName = effectiveTopic.getName().replaceAll("[^a-zA-Z0-9]", "");//remove - _ .
 
 166                 MongoCollection<Document> collection = mongoCollectionMap.computeIfAbsent(collectionName, k -> database.getCollection(k));
 
 169                         collection.insertMany(documents, insertManyOptions);
 
 170                 } catch (MongoBulkWriteException e) {
 
 171                         List<BulkWriteError> bulkWriteErrors = e.getWriteErrors();
 
 172                         for (BulkWriteError bulkWriteError : bulkWriteErrors) {
 
 173                                 log.error("Failed record: {}", bulkWriteError);
 
 175                 } catch (MongoTimeoutException e) {
 
 176                         log.error("saveJsons()", e);                    
 
 179                 log.debug("saved text to effectiveTopic = {}, batch count = {} ", effectiveTopic, jsons.size());