Updates to Callback Api and Connection
[music.git] / musictrigger / src / MusicTrigger.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
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  * 
19  * ============LICENSE_END=============================================
20  * ====================================================================
21  */
22
23 import java.util.Arrays;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Iterator;
27
28 import javax.ws.rs.core.HttpHeaders;
29 import javax.ws.rs.core.MediaType;
30
31 import org.apache.cassandra.config.ColumnDefinition;
32 import org.apache.cassandra.db.Clustering;
33 import org.apache.cassandra.db.Mutation;
34 import org.apache.cassandra.db.partitions.Partition;
35 import org.apache.cassandra.db.rows.Cell;
36 import org.apache.cassandra.db.rows.Row;
37 import org.apache.cassandra.db.rows.Unfiltered;
38 import org.apache.cassandra.db.rows.UnfilteredRowIterator;
39 import org.apache.cassandra.triggers.ITrigger;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 import com.sun.jersey.api.client.Client;
44 import com.sun.jersey.api.client.ClientResponse;
45 import com.sun.jersey.api.client.WebResource;
46
47 public class MusicTrigger implements ITrigger {
48
49         private static final Logger logger = LoggerFactory.getLogger(MusicTrigger.class);
50
51         
52     public Collection<Mutation> augment(Partition partition)
53     {
54         boolean isDelete = false;
55         logger.info("Step 1: "+partition.partitionLevelDeletion().isLive());
56         if(partition.partitionLevelDeletion().isLive()) {
57                 
58         } else {
59             // Partition Level Deletion
60                 isDelete = true;
61         }
62         logger.info("MusicTrigger isDelete: " + isDelete);
63         String ksName = partition.metadata().ksName;
64         String tableName = partition.metadata().cfName;
65         logger.info("MusicTrigger Table: " + tableName);
66         boolean isInsert = checkQueryType(partition);
67         org.json.simple.JSONObject obj = new org.json.simple.JSONObject();
68         
69         
70         String operation = null;
71         if(isDelete)
72                 operation = "delete";
73         else if(isInsert)
74                 operation = "insert";
75         else
76                 operation = "update";
77         
78         
79         obj.put("operation", operation);
80         obj.put("keyspace", ksName);
81         obj.put("table_name", tableName);
82         obj.put("full_table", ksName+"."+tableName);
83         obj.put("primary_key", partition.metadata().getKeyValidator().getString(partition.partitionKey().getKey()));
84         
85         //obj.put("message_id", partition.metadata().getKeyValidator().getString(partition.partitionKey().getKey()));
86         try {
87             UnfilteredRowIterator it = partition.unfilteredIterator();
88             while (it.hasNext()) {
89                 Unfiltered un = it.next();
90                 Clustering clt = (Clustering) un.clustering();  
91                 Iterator<Cell> cells = partition.getRow(clt).cells().iterator();
92                 Iterator<ColumnDefinition> columns = partition.getRow(clt).columns().iterator();
93
94                 while(columns.hasNext()){
95                     ColumnDefinition columnDef = columns.next();
96                     Cell cell = cells.next();
97                     String data = new String(cell.value().array()); // If cell type is text
98                     logger.info("Inside triggers loop: "+columnDef.toString()+" : "+data);
99                     obj.put(columnDef.toString(), data);
100                 }
101             }
102         } catch (Exception e) {
103
104         }
105         logger.info("Sending response: "+obj.toString());
106         try {
107             notifyMusic(obj.toString());
108         } catch(Exception e) {
109             e.printStackTrace();
110             logger.error("Notification failed..."+e.getMessage()s);
111         }
112         return Collections.emptyList();
113     }
114     
115     private boolean checkQueryType(Partition partition) { 
116         UnfilteredRowIterator it = partition.unfilteredIterator();
117         while (it.hasNext()) {
118             Unfiltered unfiltered = it.next();
119             Row row = (Row) unfiltered;
120             if (isInsert(row)) {
121                 return true;
122             }
123         }
124         return false;
125     }
126
127     private boolean isInsert(Row row) {
128         return row.primaryKeyLivenessInfo().timestamp() != Long.MIN_VALUE;
129     }
130        
131         private void notifyMusic(String request) {
132                 System.out.println("notifyMusic...");
133                 Client client = Client.create();
134                 WebResource webResource = client.resource("http://localhost:8080/MUSIC/rest/v2/admin/callbackOps");
135                         
136                 JSONObject data = new JSONObject();
137                 data.setData(request);
138                 
139                 ClientResponse response = webResource.accept("application/json").type("application/json")
140                 .post(ClientResponse.class, data);
141                 
142                 if(response.getStatus() != 200){
143                         System.out.println("Exception...");
144         }
145                 response.getHeaders().put(HttpHeaders.CONTENT_TYPE, Arrays.asList(MediaType.APPLICATION_JSON));
146                 response.bufferEntity();
147                 String x = response.getEntity(String.class);
148                 System.out.println("Response: "+x);
149                 
150         }
151
152         /*public Collection<Mutation> augment(Partition partition) {
153                 
154                 String tableName = partition.metadata().cfName;
155         System.out.println("Table: " + tableName);
156
157         JSONObject obj = new JSONObject();
158         obj.put("message_id", partition.metadata().getKeyValidator().getString(partition.partitionKey().getKey()));
159
160         
161             try {
162                 UnfilteredRowIterator it = partition.unfilteredIterator();
163                 while (it.hasNext()) {
164                     Unfiltered un = it.next();
165                     Clustering clt = (Clustering) un.clustering();  
166                     Iterator<Cell> cls = partition.getRow(clt).cells().iterator();
167                 Iterator<ColumnDefinition> columns = partition.getRow(clt).columns().iterator();
168
169                     while(cls.hasNext()){
170                         Cell cell = cls.next();
171                         String data = new String(cell.value().array()); // If cell type is text
172                         System.out.println(cell + " : " +data);
173                         
174                     }
175                     while(columns.hasNext()){
176                     ColumnDefinition columnDef = columns.next();
177                     Cell cell = cls.next();
178                     String data = new String(cell.value().array()); // If cell type is text
179                     obj.put(columnDef.toString(), data);
180                 }
181                 }
182             } catch (Exception e) {
183             }
184             
185             System.out.println(obj.toString());
186
187         return Collections.emptyList();
188         }*/
189         
190 }