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