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