f5ee5b7904a0b0c1de7df89ea79e6fff96d2616d
[dcaegen2/services.git] /
1 /*
2 * ============LICENSE_START=======================================================
3 * ONAP : DATALAKE
4 * ================================================================================
5 * Copyright 2019 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.List;
25
26 import javax.annotation.PostConstruct;
27 import javax.annotation.PreDestroy;
28  
29 import org.json.JSONObject;
30 import org.onap.datalake.feeder.config.ApplicationConfiguration;
31 import org.onap.datalake.feeder.domain.Db;
32 import org.onap.datalake.feeder.domain.Topic;
33 import org.onap.datalake.feeder.dto.TopicConfig;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 import org.springframework.beans.factory.annotation.Autowired;
38 import org.springframework.stereotype.Service;
39
40 import com.couchbase.client.java.Bucket;
41 import com.couchbase.client.java.Cluster;
42 import com.couchbase.client.java.CouchbaseCluster;
43 import com.couchbase.client.java.document.JsonDocument;
44 import com.couchbase.client.java.document.JsonLongDocument;
45 import com.couchbase.client.java.document.json.JsonObject; 
46
47 import rx.Observable;
48 import rx.functions.Func1;
49
50 /**
51  * Service to use Couchbase
52  * 
53  * @author Guobiao Mo
54  *
55  */
56 @Service
57 public class CouchbaseService {
58
59         private final Logger log = LoggerFactory.getLogger(this.getClass());
60
61         @Autowired
62         ApplicationConfiguration config;
63
64         @Autowired
65         private DbService dbService;
66         
67         Bucket bucket;
68         private boolean isReady = false;
69
70         @PostConstruct
71         private void init() {
72         // Initialize Couchbase Connection
73         try {
74             Db couchbase = dbService.getCouchbase();
75             Cluster cluster = CouchbaseCluster.create(couchbase.getHost());
76             cluster.authenticate(couchbase.getLogin(), couchbase.getPass());
77             bucket = cluster.openBucket(couchbase.getDatabase());
78             log.info("Connect to Couchbase {}", couchbase.getHost());
79             // Create a N1QL Primary Index (but ignore if it exists)
80             bucket.bucketManager().createN1qlPrimaryIndex(true, false);
81             isReady = true;
82         }
83         catch(Exception ex)
84         {
85             isReady = false;
86         }
87         }
88
89         @PreDestroy
90         public void cleanUp() { 
91                 bucket.close();
92         } 
93
94         public void saveJsons(TopicConfig topic, List<JSONObject> jsons) { 
95                 List<JsonDocument> documents= new ArrayList<>(jsons.size());
96                 for(JSONObject json : jsons) {
97                         //convert to Couchbase JsonObject from org.json JSONObject
98                         JsonObject jsonObject = JsonObject.fromJson(json.toString());   
99
100                         long timestamp = jsonObject.getLong(config.getTimestampLabel());//this is Kafka time stamp, which is added in StoreService.messageToJson()
101
102                         //setup TTL
103                         int expiry = (int) (timestamp/1000L) + topic.getTtl()*3600*24; //in second
104                         
105                         String id = getId(topic, json);
106                         JsonDocument doc = JsonDocument.create(id, expiry, jsonObject);
107                         documents.add(doc);
108                 }
109                 try {
110                         saveDocuments(documents);
111                 }catch(Exception e) {
112                         log.error("error saving to Couchbase.", e);
113                 }
114                 log.debug("saved text to topic = {}, this batch count = {} ", topic, documents.size()); 
115         }
116
117         public String getId(TopicConfig topic, JSONObject json) {
118                 //if this topic requires extract id from JSON
119                 String id = topic.getMessageId(json);
120                 if(id != null) {
121                         return id;
122                 }
123                 
124                 String topicStr= topic.getName();               
125                 //String id = topicStr+":"+timestamp+":"+UUID.randomUUID();
126
127                 //https://forums.couchbase.com/t/how-to-set-an-auto-increment-id/4892/2
128                 //atomically get the next sequence number:
129                 // increment by 1, initialize at 0 if counter doc not found
130                 //TODO how slow is this compared with above UUID approach?
131                 JsonLongDocument nextIdNumber = bucket.counter(topicStr, 1, 0); //like 12345 
132                 id = topicStr +":"+ nextIdNumber.content();
133                 
134                 return id;
135         }
136          
137         //https://docs.couchbase.com/java-sdk/2.7/document-operations.html
138         private void saveDocuments(List<JsonDocument> documents) { 
139                 Observable
140             .from(documents)
141             .flatMap(new Func1<JsonDocument, Observable<JsonDocument>>() {
142                 @Override
143                 public Observable<JsonDocument> call(final JsonDocument docToInsert) {
144                     return bucket.async().insert(docToInsert);
145                 }
146             })
147             .last()
148             .toBlocking()
149             .single();          
150         }
151
152 }