2 * ============LICENSE_START==========================================
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
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.
19 * ============LICENSE_END=============================================
20 * ====================================================================
22 package org.onap.music.datastore;
24 import java.net.InetAddress;
25 import java.net.NetworkInterface;
26 import java.net.SocketException;
27 import java.util.ArrayList;
28 import java.util.Enumeration;
29 import java.util.HashMap;
30 import java.util.Iterator;
32 import org.onap.music.eelf.logging.EELFLoggerDelegate;
33 import org.onap.music.eelf.logging.format.AppMessages;
34 import org.onap.music.eelf.logging.format.ErrorSeverity;
35 import org.onap.music.eelf.logging.format.ErrorTypes;
36 import org.onap.music.exceptions.MusicQueryException;
37 import org.onap.music.exceptions.MusicServiceException;
38 import org.onap.music.main.MusicUtil;
39 import com.datastax.driver.core.Cluster;
40 import com.datastax.driver.core.ColumnDefinitions;
41 import com.datastax.driver.core.ColumnDefinitions.Definition;
42 import com.datastax.driver.core.ConsistencyLevel;
43 import com.datastax.driver.core.DataType;
44 import com.datastax.driver.core.KeyspaceMetadata;
45 import com.datastax.driver.core.Metadata;
46 import com.datastax.driver.core.PreparedStatement;
47 import com.datastax.driver.core.ResultSet;
48 import com.datastax.driver.core.Row;
49 import com.datastax.driver.core.Session;
50 import com.datastax.driver.core.TableMetadata;
51 import com.datastax.driver.core.exceptions.AlreadyExistsException;
52 import com.datastax.driver.core.exceptions.InvalidQueryException;
53 import com.datastax.driver.core.exceptions.NoHostAvailableException;
59 public class MusicDataStore {
61 private Session session;
62 private Cluster cluster;
69 public void setSession(Session session) {
70 this.session = session;
76 public Session getSession() {
83 public void setCluster(Cluster cluster) {
84 this.cluster = cluster;
89 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicDataStore.class);
94 public MusicDataStore() {
95 connectToCassaCluster();
103 public MusicDataStore(Cluster cluster, Session session) {
104 this.session = session;
105 this.cluster = cluster;
111 * @throws MusicServiceException
113 public MusicDataStore(String remoteIp) {
115 connectToCassaCluster(remoteIp);
116 } catch (MusicServiceException e) {
117 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
125 private ArrayList<String> getAllPossibleLocalIps() {
126 ArrayList<String> allPossibleIps = new ArrayList<String>();
128 Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
129 while (en.hasMoreElements()) {
130 NetworkInterface ni = (NetworkInterface) en.nextElement();
131 Enumeration<InetAddress> ee = ni.getInetAddresses();
132 while (ee.hasMoreElements()) {
133 InetAddress ia = (InetAddress) ee.nextElement();
134 allPossibleIps.add(ia.getHostAddress());
137 } catch (SocketException e) {
138 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.CONNCECTIVITYERROR, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
139 }catch(Exception e) {
140 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
142 return allPossibleIps;
146 * This method iterates through all available IP addresses and connects to multiple cassandra
149 private void connectToCassaCluster() {
150 Iterator<String> it = getAllPossibleLocalIps().iterator();
151 String address = "localhost";
152 logger.info(EELFLoggerDelegate.applicationLogger,
153 "Connecting to cassa cluster: Iterating through possible ips:"
154 + getAllPossibleLocalIps());
155 while (it.hasNext()) {
157 cluster = Cluster.builder().withPort(9042)
158 .withCredentials(MusicUtil.getCassName(), MusicUtil.getCassPwd())
159 .addContactPoint(address).build();
160 Metadata metadata = cluster.getMetadata();
161 logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster "
162 + metadata.getClusterName() + " at " + address);
163 session = cluster.connect();
166 } catch (NoHostAvailableException e) {
168 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.HOSTUNAVAILABLE, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
176 public void close() {
181 * This method connects to cassandra cluster on specific address.
185 private void connectToCassaCluster(String address) throws MusicServiceException {
186 cluster = Cluster.builder().withPort(9042)
187 .withCredentials(MusicUtil.getCassName(), MusicUtil.getCassPwd())
188 .addContactPoint(address).build();
189 Metadata metadata = cluster.getMetadata();
190 logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster "
191 + metadata.getClusterName() + " at " + address);
193 session = cluster.connect();
194 } catch (Exception ex) {
195 logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.CASSANDRACONNECTIVITY, ErrorSeverity.ERROR, ErrorTypes.SERVICEUNAVAILABLE);
196 throw new MusicServiceException(
197 "Error while connecting to Cassandra cluster.. " + ex.getMessage());
208 public DataType returnColumnDataType(String keyspace, String tableName, String columnName) {
209 KeyspaceMetadata ks = cluster.getMetadata().getKeyspace(keyspace);
210 TableMetadata table = ks.getTable(tableName);
211 return table.getColumn(columnName).getType();
219 * @return TableMetadata
221 public TableMetadata returnColumnMetadata(String keyspace, String tableName) {
222 KeyspaceMetadata ks = cluster.getMetadata().getKeyspace(keyspace);
223 return ks.getTable(tableName);
228 * Utility function to return the Java specific object type.
235 public Object getColValue(Row row, String colName, DataType colType) {
237 switch (colType.getName()) {
239 return row.getString(colName);
241 return row.getUUID(colName);
243 return row.getVarint(colName);
245 return row.getLong(colName);
247 return row.getInt(colName);
249 return row.getFloat(colName);
251 return row.getDouble(colName);
253 return row.getBool(colName);
255 return row.getMap(colName, String.class, String.class);
261 public boolean doesRowSatisfyCondition(Row row, Map<String, Object> condition) throws Exception {
262 ColumnDefinitions colInfo = row.getColumnDefinitions();
264 for (Map.Entry<String, Object> entry : condition.entrySet()) {
265 String colName = entry.getKey();
266 DataType colType = colInfo.getType(colName);
267 Object columnValue = getColValue(row, colName, colType);
268 Object conditionValue = MusicUtil.convertToActualDataType(colType, entry.getValue());
269 if (columnValue.equals(conditionValue) == false)
276 * Utility function to store ResultSet values in to a MAP for output.
281 public Map<String, HashMap<String, Object>> marshalData(ResultSet results) {
282 Map<String, HashMap<String, Object>> resultMap =
283 new HashMap<String, HashMap<String, Object>>();
285 for (Row row : results) {
286 ColumnDefinitions colInfo = row.getColumnDefinitions();
287 HashMap<String, Object> resultOutput = new HashMap<String, Object>();
288 for (Definition definition : colInfo) {
289 if (!definition.getName().equals("vector_ts"))
290 resultOutput.put(definition.getName(),
291 getColValue(row, definition.getName(), definition.getType()));
293 resultMap.put("row " + counter, resultOutput);
300 // Prepared Statements 1802 additions
302 * This Method performs DDL and DML operations on Cassandra using specified consistency level
304 * @param queryObject Object containing cassandra prepared query and values.
305 * @param consistency Specify consistency level for data synchronization across cassandra
307 * @return Boolean Indicates operation success or failure
308 * @throws MusicServiceException
309 * @throws MusicQueryException
311 public boolean executePut(PreparedQueryObject queryObject, String consistency)
312 throws MusicServiceException, MusicQueryException {
314 boolean result = false;
316 if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) {
317 logger.error(EELFLoggerDelegate.errorLogger, queryObject.getQuery(),AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
318 throw new MusicQueryException("Ill formed queryObject for the request = " + "["
319 + queryObject.getQuery() + "]");
321 logger.info(EELFLoggerDelegate.applicationLogger,
322 "In preprared Execute Put: the actual insert query:"
323 + queryObject.getQuery() + "; the values"
324 + queryObject.getValues());
325 PreparedStatement preparedInsert = null;
327 preparedInsert = session.prepare(queryObject.getQuery());
328 } catch(InvalidQueryException iqe) {
329 logger.error(EELFLoggerDelegate.errorLogger, iqe.getMessage());
330 throw new MusicQueryException(iqe.getMessage());
334 if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
335 logger.info(EELFLoggerDelegate.applicationLogger, "Executing critical put query");
336 preparedInsert.setConsistencyLevel(ConsistencyLevel.QUORUM);
337 } else if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) {
338 logger.info(EELFLoggerDelegate.applicationLogger, "Executing simple put query");
339 preparedInsert.setConsistencyLevel(ConsistencyLevel.ONE);
342 ResultSet rs = session.execute(preparedInsert.bind(queryObject.getValues().toArray()));
343 result = rs.wasApplied();
346 catch (AlreadyExistsException ae) {
347 logger.error(EELFLoggerDelegate.errorLogger, ae.getMessage(),AppMessages.SESSIONFAILED+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
348 throw new MusicServiceException(ae.getMessage());
350 catch (Exception e) {
351 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.SESSIONFAILED+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
352 throw new MusicQueryException("Executing Session Failure for Request = " + "["
353 + queryObject.getQuery() + "]" + " Reason = " + e.getMessage());
361 * This method performs DDL operations on Cassandra using consistency level ONE.
363 * @param queryObject Object containing cassandra prepared query and values.
365 * @throws MusicServiceException
366 * @throws MusicQueryException
368 public ResultSet executeEventualGet(PreparedQueryObject queryObject)
369 throws MusicServiceException, MusicQueryException {
371 if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) {
372 logger.error(EELFLoggerDelegate.errorLogger, "",AppMessages.QUERYERROR+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
373 throw new MusicQueryException("Ill formed queryObject for the request = " + "["
374 + queryObject.getQuery() + "]");
376 logger.info(EELFLoggerDelegate.applicationLogger,
377 "Executing Eventual get query:" + queryObject.getQuery());
378 PreparedStatement preparedEventualGet = session.prepare(queryObject.getQuery());
379 preparedEventualGet.setConsistencyLevel(ConsistencyLevel.ONE);
380 ResultSet results = null;
382 results = session.execute(preparedEventualGet.bind(queryObject.getValues().toArray()));
384 } catch (Exception ex) {
385 logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
386 throw new MusicServiceException(ex.getMessage());
393 * This method performs DDL operation on Cassandra using consistency level QUORUM.
395 * @param queryObject Object containing cassandra prepared query and values.
397 * @throws MusicServiceException
398 * @throws MusicQueryException
400 public ResultSet executeCriticalGet(PreparedQueryObject queryObject)
401 throws MusicServiceException, MusicQueryException {
402 if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) {
403 logger.error(EELFLoggerDelegate.errorLogger, "",AppMessages.QUERYERROR+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
404 throw new MusicQueryException("Error processing Prepared Query Object for the request = " + "["
405 + queryObject.getQuery() + "]");
407 logger.info(EELFLoggerDelegate.applicationLogger,
408 "Executing Critical get query:" + queryObject.getQuery());
409 PreparedStatement preparedEventualGet = session.prepare(queryObject.getQuery());
410 preparedEventualGet.setConsistencyLevel(ConsistencyLevel.QUORUM);
411 ResultSet results = null;
413 results = session.execute(preparedEventualGet.bind(queryObject.getValues().toArray()));
414 } catch (Exception ex) {
415 logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
416 throw new MusicServiceException(ex.getMessage());