2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.ci.tests.utils.cassandra;
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;
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;
50 public final class CassandraUtils {
51 private static Logger logger = LoggerFactory.getLogger(CassandraUtils.class.getName());
53 protected static Cluster cluster = null;
54 protected static Session session;
56 public static void initConnection(String keyspace) throws FileNotFoundException {
57 List<String> cassandraHosts = new ArrayList<>();
59 cassandraHosts.add(Utils.getConfig().getCassandraHost());
60 long reconnectTimeout = 30000;
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);
67 cassandraHosts.forEach(host -> clusterBuilder.addContactPoint(host));
68 enableAuthentication(clusterBuilder);
69 enableSsl(clusterBuilder);
70 setLocalDc(clusterBuilder);
72 cluster = clusterBuilder.build();
73 session = cluster.connect(keyspace);
74 } catch (Exception e) {
75 logger.info("** CassandraClient isn't connected to {}", cassandraHosts);
79 private static void enableAuthentication(Cluster.Builder clusterBuilder) throws FileNotFoundException {
80 boolean authenticate = Utils.getConfig().getCassandraAuthenticate();
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.");
87 clusterBuilder.withCredentials(username, password);
93 private static void enableSsl(Cluster.Builder clusterBuilder) throws FileNotFoundException {
94 boolean ssl = Utils.getConfig().getCassandraSsl();
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.");
101 System.setProperty("javax.net.ssl.trustStore", truststorePath);
102 System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
103 clusterBuilder.withSSL();
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);
116 logger.info("localDatacenter was provided, the driver will use the datacenter of the first contact point that was reached at initialization");
120 public static void truncateTable(String keyspace, String tableName) throws FileNotFoundException {
122 if (session == null || session.isClosed()) {
123 initConnection(keyspace);
126 try (Cluster cluster = CassandraUtils.cluster){
128 if (session != null) {
129 session.execute(QueryBuilder.truncate(keyspace, tableName));
130 logger.debug("The table {}.{} was cleaned", keyspace, tableName);
132 throw new RuntimeException("Keyspace " + keyspace + " not connected");
137 public static void close() {
138 if (cluster != null) {
143 public static void truncateAllKeyspaces() throws FileNotFoundException {
144 // truncateAllTables(AuditingTypesConstants.ARTIFACT_KEYSPACE);
145 truncateAllTables(AuditingTypesConstants.AUDIT_KEYSPACE);
148 public static void truncateAllTables(String keyspace) throws FileNotFoundException {
150 if (session == null || session.isClosed()) {
151 initConnection(keyspace);
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());
166 throw new RuntimeException("Keyspace " + keyspace + " not connected");
170 if (cluster != null) {
176 public static List<Row> fetchFromTable(String keyspace, String tableName, List<Pair<AuditingFieldsKeysEnum, String>> fields) throws FileNotFoundException {
178 List<Pair<String, String>> fieldsConverted = new ArrayList<>();
180 // fields.forEach(pair -> {
181 // Pair<String, String> newPair = new Pair(pair.getValue0().getDisplayName(), pair.getValue1());
182 // fieldsConverted.add(newPair);
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());
191 newPair = new Pair<String, String>(pair.getValue0().getDisplayName(), pair.getValue1());
193 fieldsConverted.add(newPair);
197 return fetchFromTableQuery(keyspace, tableName, fieldsConverted);
200 public static List<Row> fetchFromTableQuery(String keyspace, String tableName, List<Pair<String, String>> fields)
201 throws FileNotFoundException {
203 if (session == null || session.isClosed()) {
204 initConnection(keyspace);
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();
214 boolean multiple = (fields.size() > 1) ? true : false;
218 for (Pair<String, String> pair : fields) {
221 where = select.where(QueryBuilder.eq(pair.getValue0(), pair.getValue1()));
223 where.and(QueryBuilder.eq(pair.getValue0(), pair.getValue1()));
227 select.allowFiltering();
232 List<Row> rows = session.execute(select).all();
233 for (Row row : rows) {
234 logger.debug("{}", row);
239 // if (cluster != null) {