[SDC-29] rebase continue work to align source
[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 com.datastax.driver.core.*;
24 import com.datastax.driver.core.querybuilder.QueryBuilder;
25 import com.datastax.driver.core.querybuilder.Select;
26 import com.datastax.driver.core.querybuilder.Select.Where;
27
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 java.io.FileNotFoundException;
36 import java.util.ArrayList;
37 import java.util.Collection;
38 import java.util.List;
39
40 public final class CassandraUtils {
41         private static Logger logger = LoggerFactory.getLogger(CassandraUtils.class.getName());
42
43         protected static Cluster cluster = null;
44         protected static Session session;
45
46         protected static void initConnection(String keyspace) throws FileNotFoundException {
47
48                 String cassandraHost = Utils.getConfig().getCassandraHost();
49                 Boolean cassandraAuthenticate = Utils.getConfig().getCassandraAuthenticate();
50                 String cassandraUsername = Utils.getConfig().getCassandraUsername();
51                 String cassandraPassword = Utils.getConfig().getCassandraPassword();
52                 Boolean cassandraSsl = Utils.getConfig().getCassandraSsl();
53                 String cassandraTruststorePath = Utils.getConfig().getCassandraTruststorePath();
54                 String cassandraTruststorePassword = Utils.getConfig().getCassandraTruststorePassword();
55                 /*
56                  * String cassandraAuditKeySpace=
57                  * Utils.getConfig().getCassandraAuditKeySpace(); String
58                  * cassandraArtifactKeySpace=
59                  * Utils.getConfig().getCassandraArtifactKeySpace();
60                  */
61
62                 Cluster.Builder clusterBuilder = Cluster.builder().addContactPoint(cassandraHost);
63                 if (cassandraAuthenticate) {
64                         // authantication
65                         clusterBuilder.withCredentials(cassandraUsername, cassandraPassword);
66                 }
67
68                 if (cassandraSsl) {
69                         // ssl
70                         System.setProperty("javax.net.ssl.trustStore", cassandraTruststorePath);
71                         System.setProperty("javax.net.ssl.trustStorePassword", cassandraTruststorePassword);
72                         clusterBuilder.withSSL();
73                 }
74
75                 cluster = clusterBuilder.build();
76                 session = cluster.connect(keyspace);
77
78         }
79
80         public static void truncateTable(String keyspace, String tableName) throws FileNotFoundException {
81
82                 if (session == null || session.isClosed()) {
83                         initConnection(keyspace);
84                 }
85
86                 try {
87
88                         if (session != null) {
89                                 session.execute(QueryBuilder.truncate(keyspace, tableName));
90                                 logger.debug("The table {}.{} was cleaned",keyspace,tableName);
91                         } else {
92                                 throw new RuntimeException("Keyspace " + keyspace + " not connected");
93                         }
94                 } finally {
95                         // if (cluster != null) {
96                         // cluster.close();
97                         // }
98                 }
99         }
100
101         public static void close() {
102                 if (cluster != null) {
103                         cluster.close();
104                 }
105         }
106
107         public static void truncateAllKeyspaces() throws FileNotFoundException {
108                 // truncateAllTables(AuditingTypesConstants.ARTIFACT_KEYSPACE);
109                 truncateAllTables(AuditingTypesConstants.AUDIT_KEYSPACE);
110         }
111
112         public static void truncateAllTables(String keyspace) throws FileNotFoundException {
113
114                 if (session == null || session.isClosed()) {
115                         initConnection(keyspace);
116                 }
117                 try {
118
119                         if (session != null) {
120                                 Metadata metadata = cluster.getMetadata();
121                                 KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(keyspace);
122                                 if (keyspaceMetadata != null) {
123                                         Collection<TableMetadata> tables = keyspaceMetadata.getTables();
124                                         tables.forEach(table -> {
125                                                 session.execute(QueryBuilder.truncate(table));
126                                                 logger.debug("Table trunceted - {}", table.getName());
127                                         });
128                                 }
129                         } else {
130                                 throw new RuntimeException("Keyspace " + keyspace + " not connected");
131                         }
132
133                 } finally {
134                         // if (cluster != null) {
135                         // cluster.close();
136                         // }
137                 }
138         }
139
140         public static List<Row> fetchFromTable(String keyspace, String tableName,
141                         List<Pair<AuditingFieldsKeysEnum, String>> fields) throws FileNotFoundException {
142
143                 List<Pair<String, String>> fieldsConverted = new ArrayList<>();
144
145 //              fields.forEach(pair -> {
146 //                      Pair<String, String> newPair = new Pair(pair.getValue0().getDisplayName(), pair.getValue1());
147 //                      fieldsConverted.add(newPair);
148 //              });
149                 
150                 fields.forEach(pair ->{
151                         Pair<String, String> newPair;
152                         if(pair.getValue0() == AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL ){
153                         newPair = new Pair<String, String>("RESOURE_URL", pair.getValue1());
154                         
155                 }else{
156                         newPair = new Pair<String, String>(pair.getValue0().getDisplayName(), pair.getValue1());
157                 }
158                 fieldsConverted.add(newPair);
159                         
160                 });
161
162                 return fetchFromTableQuery(keyspace, tableName, fieldsConverted);
163         }
164
165         public static List<Row> fetchFromTableQuery(String keyspace, String tableName, List<Pair<String, String>> fields)
166                         throws FileNotFoundException {
167
168                 if (session == null || session.isClosed()) {
169                         initConnection(keyspace);
170                 }
171                 try {
172
173                         if (session != null) {
174                                 Select select = QueryBuilder.select().all().from(keyspace, tableName);
175                                 if (fields != null) {
176                                         // Set<Entry<AuditingFieldsKeysEnum, String>> entrySet =
177                                         // fields.entrySet();
178                                         // fields.
179                                         boolean multiple = (fields.size() > 1) ? true : false;
180                                         Where where = null;
181                                         int size = 0;
182
183                                         for (Pair<String, String> pair : fields) {
184                                                 ++size;
185                                                 if (size == 1) {
186                                                         where = select.where(QueryBuilder.eq(pair.getValue0(), pair.getValue1()));
187                                                 } else {
188                                                         where.and(QueryBuilder.eq(pair.getValue0(), pair.getValue1()));
189                                                 }
190                                         }
191                                         if (multiple) {
192                                                 select.allowFiltering();
193                                         }
194
195                                 }
196
197                                 List<Row> rows = session.execute(select).all();
198                                 for (Row row : rows) {
199                                         logger.debug("{}", row);
200                                 }
201                                 return rows;
202                         }
203                 } finally {
204                         // if (cluster != null) {
205                         // cluster.close();
206                         // }
207                 }
208                 return null;
209         }
210         //
211         // public static void main(String[] args) throws FileNotFoundException {
212         // Map<AuditingFieldsKeysEnum, String> map = new HashMap<>();
213         // map.put(AuditingFieldsKeysEnum.AUDIT_ACTION, "Access");
214         // map.put(AuditingFieldsKeysEnum.AUDIT_STATUS, "200");
215         // // CassandraUtils.truncateTable("sdcartifact", "resources");
216         //// CassandraUtils.truncateAllTables("sdcaudit");
217         // CassandraUtils.fetchFromTable("sdcaudit", "useraccessevent", map );
218         // }
219
220 }