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.be.dao.cassandra;
23 import java.util.List;
25 import javax.annotation.PreDestroy;
27 import org.apache.commons.lang3.tuple.ImmutablePair;
28 import org.openecomp.sdc.be.config.ConfigurationManager;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.springframework.stereotype.Component;
33 import com.datastax.driver.core.Cluster;
34 import com.datastax.driver.core.Session;
35 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
36 import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
37 import com.datastax.driver.core.policies.DefaultRetryPolicy;
38 import com.datastax.driver.core.policies.LoadBalancingPolicy;
39 import com.datastax.driver.core.policies.TokenAwarePolicy;
40 import com.datastax.driver.mapping.Mapper;
41 import com.datastax.driver.mapping.MappingManager;
43 import fj.data.Either;
45 @Component("cassandra-client")
46 public class CassandraClient {
47 private static Logger logger = LoggerFactory.getLogger(CassandraClient.class.getName());
49 private Cluster cluster;
50 private boolean isConnected;
52 public CassandraClient() {
55 List<String> cassandraHosts = null;
57 cassandraHosts = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
59 Long reconnectTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
60 .getCassandraConfig().getReconnectTimeout();
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();
74 } catch (Exception e) {
75 logger.info("** CassandraClient isn't connected to {}", cassandraHosts);
78 logger.info("** CassandraClient created");
81 private void setLocalDc(Cluster.Builder clusterBuilder) {
82 String localDataCenter = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
83 .getLocalDataCenter();
84 if (localDataCenter != null) {
85 logger.info("localDatacenter was provided, setting Cassndra clint to use datacenter: {} as local.",
87 LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(
88 DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
89 clusterBuilder.withLoadBalancingPolicy(tokenAwarePolicy);
92 "localDatacenter was provided, the driver will use the datacenter of the first contact point that was reached at initialization");
96 private void enableSsl(Cluster.Builder clusterBuilder) {
97 boolean ssl = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().isSsl();
99 String truststorePath = ConfigurationManager.getConfigurationManager().getConfiguration()
100 .getCassandraConfig().getTruststorePath();
101 String truststorePassword = ConfigurationManager.getConfigurationManager().getConfiguration()
102 .getCassandraConfig().getTruststorePassword();
103 if (truststorePath == null || truststorePassword == null) {
104 logger.error("ssl is enabled but truststorePath or truststorePassword were not supplied.");
106 System.setProperty("javax.net.ssl.trustStore", truststorePath);
107 System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
108 clusterBuilder.withSSL();
114 private void enableAuthentication(Cluster.Builder clusterBuilder) {
115 boolean authenticate = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
118 String username = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
120 String password = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
122 if (username == null || password == null) {
123 logger.error("authentication is enabled but username or password were not supplied.");
125 clusterBuilder.withCredentials(username, password);
134 * - key space to connect
137 public Either<ImmutablePair<Session, MappingManager>, CassandraOperationStatus> connect(String keyspace) {
138 if (cluster != null) {
140 Session session = cluster.connect(keyspace);
141 if (session != null) {
142 MappingManager manager = new MappingManager(session);
143 return Either.left(new ImmutablePair<Session, MappingManager>(session, manager));
145 return Either.right(CassandraOperationStatus.KEYSPACE_NOT_CONNECTED);
147 } catch (Throwable e) {
148 logger.debug("Failed to connect to keyspace [{}], error :", keyspace, e);
149 return Either.right(CassandraOperationStatus.KEYSPACE_NOT_CONNECTED);
152 return Either.right(CassandraOperationStatus.CLUSTER_NOT_CONNECTED);
155 public <T> CassandraOperationStatus save(T entity, Class<T> clazz, MappingManager manager) {
157 return CassandraOperationStatus.CLUSTER_NOT_CONNECTED;
160 Mapper<T> mapper = manager.mapper(clazz);
162 } catch (Exception e) {
163 logger.debug("Failed to save entity [{}], error :", entity, e);
164 return CassandraOperationStatus.GENERAL_ERROR;
166 return CassandraOperationStatus.OK;
169 public <T> Either<T, CassandraOperationStatus> getById(String id, Class<T> clazz, MappingManager manager) {
171 return Either.right(CassandraOperationStatus.CLUSTER_NOT_CONNECTED);
174 Mapper<T> mapper = manager.mapper(clazz);
175 T result = mapper.get(id);
176 if (result == null) {
177 return Either.right(CassandraOperationStatus.NOT_FOUND);
179 return Either.left(result);
180 } catch (Exception e) {
181 logger.debug("Failed to get by Id [{}], error :", id, e);
182 return Either.right(CassandraOperationStatus.GENERAL_ERROR);
186 public <T> CassandraOperationStatus delete(String id, Class<T> clazz, MappingManager manager) {
188 return CassandraOperationStatus.CLUSTER_NOT_CONNECTED;
191 Mapper<T> mapper = manager.mapper(clazz);
193 } catch (Exception e) {
194 logger.debug("Failed to delete by id [{}], error :", id, e);
195 return CassandraOperationStatus.GENERAL_ERROR;
197 return CassandraOperationStatus.OK;
200 public boolean isConnected() {
205 public void closeClient() {
209 logger.info("** CassandraClient cluster closed");