Sync Integ to Master
[sdc.git] / test-apis-ci / src / main / java / org / openecomp / sdc / ci / tests / utils / cassandra / CassandraUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
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.openecomp.sdc.ci.tests.utils.cassandra;
22
23 import java.io.FileNotFoundException;
24 import com.datastax.driver.core.policies.*;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.List;
28 import org.javatuples.Pair;
29 import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
30 import org.openecomp.sdc.ci.tests.utils.Utils;
31 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 import com.datastax.driver.core.Cluster;
36 import com.datastax.driver.core.KeyspaceMetadata;
37 import com.datastax.driver.core.Metadata;
38 import com.datastax.driver.core.Row;
39 import com.datastax.driver.core.Session;
40 import com.datastax.driver.core.TableMetadata;
41 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
42 import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
43 import com.datastax.driver.core.policies.DefaultRetryPolicy;
44 import com.datastax.driver.core.policies.LoadBalancingPolicy;
45 import com.datastax.driver.core.policies.TokenAwarePolicy;
46 import com.datastax.driver.core.querybuilder.QueryBuilder;
47 import com.datastax.driver.core.querybuilder.Select;
48 import com.datastax.driver.core.querybuilder.Select.Where;
49
50 public final class CassandraUtils {
51     private static Logger logger = LoggerFactory.getLogger(CassandraUtils.class.getName());
52
53     protected static Cluster cluster = null;
54     protected static Session session;
55
56     public static void initConnection(String keyspace) throws FileNotFoundException {
57         List<String> cassandraHosts = new ArrayList<>();
58         try {
59             cassandraHosts.add(Utils.getConfig().getCassandraHost());
60             long reconnectTimeout = 30000;
61
62             logger.debug("creating cluster to hosts:{} with reconnect timeout:{}", cassandraHosts, reconnectTimeout);
63             Cluster.Builder clusterBuilder = Cluster.builder()
64                     .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectTimeout))
65                     .withRetryPolicy(DefaultRetryPolicy.INSTANCE);
66
67             cassandraHosts.forEach(host -> clusterBuilder.addContactPoint(host));
68             enableAuthentication(clusterBuilder);
69             enableSsl(clusterBuilder);
70             setLocalDc(clusterBuilder);
71
72             cluster = clusterBuilder.build();
73             session = cluster.connect(keyspace);
74         } catch (Exception e) {
75             logger.info("** CassandraClient isn't connected to {}", cassandraHosts);
76         }
77     }
78
79     private static void enableAuthentication(Cluster.Builder clusterBuilder) throws FileNotFoundException {
80         boolean authenticate = Utils.getConfig().getCassandraAuthenticate();
81         if (authenticate) {
82             String username = Utils.getConfig().getCassandraUsername();
83             String password = Utils.getConfig().getCassandraPassword();
84             if (username == null || password == null) {
85                 logger.error("authentication is enabled but username or password were not supplied.");
86             } else {
87                 clusterBuilder.withCredentials(username, password);
88             }
89
90         }
91     }
92
93     private static void enableSsl(Cluster.Builder clusterBuilder) throws FileNotFoundException {
94         boolean ssl = Utils.getConfig().getCassandraSsl();
95         if (ssl) {
96             String truststorePath = Utils.getConfig().getCassandraTruststorePath();
97             String truststorePassword = Utils.getConfig().getCassandraTruststorePassword();
98             if (truststorePath == null || truststorePassword == null) {
99                 logger.error("ssl is enabled but truststorePath or truststorePassword were not supplied.");
100             } else {
101                 System.setProperty("javax.net.ssl.trustStore", truststorePath);
102                 System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
103                 clusterBuilder.withSSL();
104             }
105         }
106     }
107
108
109     private static void setLocalDc(Cluster.Builder clusterBuilder) throws FileNotFoundException {
110         String localDataCenter = Utils.getConfig().getLocalDataCenter();
111         if (localDataCenter != null) {
112             logger.info("localDatacenter was provided, setting Cassndra clint to use datacenter: {} as local.", localDataCenter);
113             LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
114             clusterBuilder.withLoadBalancingPolicy(tokenAwarePolicy);
115         } else {
116             logger.info("localDatacenter was provided, the driver will use the datacenter of the first contact point that was reached at initialization");
117         }
118     }
119
120     public static void truncateTable(String keyspace, String tableName) throws FileNotFoundException {
121
122         if (session == null || session.isClosed()) {
123             initConnection(keyspace);
124         }
125
126         try (Cluster cluster = CassandraUtils.cluster){
127
128             if (session != null) {
129                 session.execute(QueryBuilder.truncate(keyspace, tableName));
130                 logger.debug("The table {}.{} was cleaned", keyspace, tableName);
131             } else {
132                 throw new RuntimeException("Keyspace " + keyspace + " not connected");
133             }
134         }
135     }
136
137     public static void close() {
138         if (cluster != null) {
139             cluster.close();
140         }
141     }
142
143     public static void truncateAllKeyspaces() throws FileNotFoundException {
144         // truncateAllTables(AuditingTypesConstants.ARTIFACT_KEYSPACE);
145         truncateAllTables(AuditingTypesConstants.AUDIT_KEYSPACE);
146     }
147
148     public static void truncateAllTables(String keyspace) throws FileNotFoundException {
149
150         if (session == null || session.isClosed()) {
151             initConnection(keyspace);
152         }
153         try {
154
155             if (session != null) {
156                 Metadata metadata = cluster.getMetadata();
157                 KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(keyspace);
158                 if (keyspaceMetadata != null) {
159                     Collection<TableMetadata> tables = keyspaceMetadata.getTables();
160                     tables.forEach(table -> {
161                         session.execute(QueryBuilder.truncate(table));
162                         logger.debug("Table trunceted - {}", table.getName());
163                     });
164                 }
165             } else {
166                 throw new RuntimeException("Keyspace " + keyspace + " not connected");
167             }
168
169         } finally {
170              if (cluster != null) {
171              cluster.close();
172              }
173         }
174     }
175
176     public static List<Row> fetchFromTable(String keyspace, String tableName, List<Pair<AuditingFieldsKeysEnum, String>> fields) throws FileNotFoundException {
177
178         List<Pair<String, String>> fieldsConverted = new ArrayList<>();
179
180 //              fields.forEach(pair -> {
181 //                      Pair<String, String> newPair = new Pair(pair.getValue0().getDisplayName(), pair.getValue1());
182 //                      fieldsConverted.add(newPair);
183 //              });
184
185         fields.forEach(pair -> {
186             Pair<String, String> newPair;
187             if (pair.getValue0() == AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL) {
188                 newPair = new Pair<String, String>("RESOURE_URL", pair.getValue1());
189
190             } else {
191                 newPair = new Pair<String, String>(pair.getValue0().getDisplayName(), pair.getValue1());
192             }
193             fieldsConverted.add(newPair);
194
195         });
196
197         return fetchFromTableQuery(keyspace, tableName, fieldsConverted);
198     }
199
200     public static List<Row> fetchFromTableQuery(String keyspace, String tableName, List<Pair<String, String>> fields)
201             throws FileNotFoundException {
202
203         if (session == null || session.isClosed()) {
204             initConnection(keyspace);
205         }
206         try {
207
208             if (session != null) {
209                 Select select = QueryBuilder.select().all().from(keyspace, tableName);
210                 if (fields != null) {
211                     // Set<Entry<AuditingFieldsKeysEnum, String>> entrySet =
212                     // fields.entrySet();
213                     // fields.
214                     boolean multiple = (fields.size() > 1) ? true : false;
215                     Where where = null;
216                     int size = 0;
217
218                     for (Pair<String, String> pair : fields) {
219                         ++size;
220                         if (size == 1) {
221                             where = select.where(QueryBuilder.eq(pair.getValue0(), pair.getValue1()));
222                         } else {
223                             where.and(QueryBuilder.eq(pair.getValue0(), pair.getValue1()));
224                         }
225                     }
226                     if (multiple) {
227                         select.allowFiltering();
228                     }
229
230                 }
231
232                 List<Row> rows = session.execute(select).all();
233                 for (Row row : rows) {
234                     logger.debug("{}", row);
235                 }
236                 return rows;
237             }
238         } finally {
239             // if (cluster != null) {
240             // cluster.close();
241             // }
242         }
243         return null;
244     }
245
246
247
248
249 }