Resolve connection to influxDB in spring boot project - spring

I am trying to connect to an influxdb with my Spring Boot project which easily connects to a postgres db. This is my application-properties:
### Application server ###
server.port=8088
### DATABASE POSTGRES LOCAL ###
#spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:postgresql://localhost:5432/xxxxres
spring.datasource.username=xxxx
spring.datasource.password=xxxx
### INFLUX ###
spring.influx.url=https://xxxxxx.it:66xx3
spring.influx.user=admin
spring.influx.password=xxx
spring.influx.database=xxx
I have created some REST calls that work with postgres but I can't do the same on influx. My doubt is in the connection to the influx db.
This is my Influx Entity:
#Measurement(name = "M_M_TEST")
public class MMEntity {
#Column(name = "Time")
private Integer time;
#Column(name = "DUL5_L1_AUX_OTH_OTH_OTH.Active_Energy")
private Integer DUL5_L1_AUX_OTH_OTH_OTH_Active_Energy;
#Column(name = "DUL5_L1_AUX_OTH_OTH_OTH.Active_Power")
private Integer DUL5_L1_AUX_OTH_OTH_OTH_Active_Power;
}
This is my model:
#Measurement(name = "M_M_TEST")
public class MMModel {
private Integer time;
private Integer DUL5_L1_AUX_OTH_OTH_OTH_Active_Energy;
private Integer DUL5_L1_AUX_OTH_OTH_OTH_Active_Power;
//GETTER & SETTER
}
This is my Controller:
#Api(tags = { SwaggerTags.TAG_M_M_NAME })
#RequestMapping("/v1/basePath")
#RestController
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class MMController extends AbstractController{
private static final Logger logger = LoggerFactory.getLogger(MMController.class);
#Autowired
MMService mMService;
#ApiOperation(value = "Finds all values of MM")
#GetMapping("/M-M/all")
public List<MMModel> findAll() {
final String METHOD_NAME = "findAll()";
try {
startLog(METHOD_NAME);
final List<MonterotondoMarittimoEntity> result = monterotondoMarittimoService.findAll();
final List<MonterotondoMarittimoModel> response = ModelMapUtils.createObject(result,
MonterotondoMarittimoModel.class);
endLog(METHOD_NAME, response);
return response;
} catch (final Exception e) {
errorLog(METHOD_NAME, e);
throw e;
}
}
}
And this is my Service:
#Service
public class MonterotondoMarittimoService extends AbstractService {
#Autowired
InfluxDB influxDB;
#Value("${spring.influx.url}")
private String influxDBUrl;
#Value("${spring.influx.user}")
private String userName;
#Value("${spring.influx.password}")
private String password;
#Value("${spring.influx.database}")
private String database;
#Transactional
public List<MMEntity> findAll() {
final String METHOD_NAME = "findAll()";
startLog(METHOD_NAME);
List<MMEntity> result = new ArrayList<MMEntity>();
final Query query = new Query("SELECT * FROM M_M LIMIT 10", database);
QueryResult queryResult = influxDB.query(query);
InfluxDBResultMapper resultMapper = new InfluxDBResultMapper();
result = resultMapper.toPOJO(queryResult, MMEntity.class);
endLog(METHOD_NAME, result);
return result;
}
}
I want to get all the elements present in the table M_M with a findAll method.
But When I execute the method with my Swagger I get 500 error with this log ("org.influxdb.InfluxDBIOException: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target")
Is a class required to configure the connection to Influx?
What can I do to solve my problem?
Please, help me.

Related

How can we mock Objects/REST Call when using FeignClient in Spring Boot (Microservices)?

I am working on Micro-Services Project and a requirement came where the communication between 2 micro-services need to happen. So, I used FeignClient Interface Approach to get it done.
Here is the FeignClientInterface.java Class:
#AuthorizedFeignClient(name = "fcfhpickorders")
public interface FCFHPickOrderService {
#PutMapping(value = "/api/prescriptions/prescriptionCode", consumes = {"application/json", "application/merge-patch+json"})
public ResponseEntity<PrescriptionDTO> updatePrescriptionForBucketKey(
#NotNull #RequestBody PrescriptionDTO prescriptionDTO
);
}
Below is the function where I used the above declared function:
public Bucket setLinkedPrescriptionCode(Bucket bucket) {
if (bucket.getLinkedPrescriptionCode() != null) {
PrescriptionDTO prescription = new PrescriptionDTO();
prescription.setBucketKey(bucket.getBucketKey());
prescription.setPrescriptionCode(bucket.getLinkedPrescriptionCode());
ResponseEntity<PrescriptionDTO> prescriptionDTOResponseEntity = fcfhPickOrderService.updatePrescriptionForBucketKey(prescription);
if(prescriptionDTOResponseEntity.getStatusCode().isError()) {
bucket.setLinkedPrescriptionCode(null);
bucketRepository.save(bucket);
throw new ResourceNotFoundException("Prescription with " + bucket.getLinkedPrescriptionCode() + "Not Found");
}
}
return bucket;
}
I used the setLinkedPrescriptionCode(Bucket bucket) function while saving and updating an existing bucket. It worked fine.
I have some previously written test cases for creation and updation of bucket that are failing now because of the addition of the REST call.
#IntegrationTest
#ExtendWith(MockitoExtension.class)
#AutoConfigureMockMvc
#WithMockUser
class BucketResourceIT {
private static final String DEFAULT_BUCKET_KEY = "AAAAAAAAAA";
private static final String UPDATED_BUCKET_KEY = "BBBBBBBBBB";
private static final String DEFAULT_QR_CODE = "AAAAAAAAAA";
private static final String UPDATED_QR_CODE = "BBBBBBBBBB";
private static final String DEFAULT_LINKED_PRESCRIPTION_CODE = "AAAAAAAAAA";
private static final String UPDATED_LINKED_PRESCRIPTION_CODE = "BBBBBBBBBB";
private static final String ENTITY_API_URL = "/api/buckets";
private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";
private static Random random = new Random();
private static AtomicLong count = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));
#Autowired
private BucketRepository bucketRepository;
#Mock
private BucketRepository bucketRepositoryMock;
#Autowired
private BucketMapper bucketMapper;
#Mock
private BucketService bucketServiceMock;
#Autowired
private EntityManager em;
#Autowired
private MockMvc restBucketMockMvc;
private Bucket bucket;
#Mock
private FCFHPickOrderService fcfhPickOrderService;
public static Bucket createEntity(EntityManager em) {
Bucket bucket = new Bucket()
.bucketKey(DEFAULT_BUCKET_KEY)
.qrCode(DEFAULT_QR_CODE)
.linkedPrescriptionCode(DEFAULT_LINKED_PRESCRIPTION_CODE);
return bucket;
}
public static Bucket createUpdatedEntity(EntityManager em) {
Bucket bucket = new Bucket()
.bucketKey(UPDATED_BUCKET_KEY)
.qrCode(UPDATED_QR_CODE)
.linkedPrescriptionCode(UPDATED_LINKED_PRESCRIPTION_CODE);
return bucket;
}
#BeforeEach
public void initTest() {
bucket = createEntity(em);
}
#Test
#Transactional
void createBucket() throws Exception {
int databaseSizeBeforeCreate = bucketRepository.findAll().size();
// Create the Bucket
BucketDTO bucketDTO = bucketMapper.toDto(bucket);
restBucketMockMvc
.perform(
post(ENTITY_API_URL)
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(bucketDTO))
)
*.andExpect(status().isCreated());*
// Validate the Bucket in the database
List<Bucket> bucketList = bucketRepository.findAll();
assertThat(bucketList).hasSize(databaseSizeBeforeCreate + 1);
Bucket testBucket = bucketList.get(bucketList.size() - 1);
assertThat(testBucket.getBucketKey()).isEqualTo(DEFAULT_BUCKET_KEY);
assertThat(testBucket.getQrCode()).isEqualTo(DEFAULT_QR_CODE);
assertThat(testBucket.getLinkedPrescriptionCode()).isEqualTo(DEFAULT_LINKED_PRESCRIPTION_CODE);
}
#Test
#Transactional
void putNewBucket() throws Exception {
bucketRepository.saveAndFlush(bucket);
int databaseSizeBeforeUpdate = bucketRepository.findAll().size();
// Update the bucket
Bucket updatedBucket = bucketRepository.findById(bucket.getId()).get();
// Disconnect from session so that the updates on updatedBucket are not directly saved in db
em.detach(updatedBucket);
updatedBucket.bucketKey(UPDATED_BUCKET_KEY).qrCode(UPDATED_QR_CODE).linkedPrescriptionCode(UPDATED_LINKED_PRESCRIPTION_CODE);
BucketDTO bucketDTO = bucketMapper.toDto(updatedBucket);
restBucketMockMvc
.perform(
put(ENTITY_API_URL_ID, bucketDTO.getId())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(bucketDTO))
)
*.andExpect(status().isOk());*
// Validate the Bucket in the database
List<Bucket> bucketList = bucketRepository.findAll();
assertThat(bucketList).hasSize(databaseSizeBeforeUpdate);
Bucket testBucket = bucketList.get(bucketList.size() - 1);
assertThat(testBucket.getBucketKey()).isEqualTo(UPDATED_BUCKET_KEY);
assertThat(testBucket.getQrCode()).isEqualTo(UPDATED_QR_CODE);
assertThat(testBucket.getLinkedPrescriptionCode()).isEqualTo(UPDATED_LINKED_PRESCRIPTION_CODE);
}
How should I update the above tests in order to fix the Assertion Errors that I am receiving?
BucketResourceIT > createBucket() FAILED
java.lang.AssertionError at BucketResourceIT.java:133
BucketResourceIT > putNewBucket() FAILED
java.lang.AssertionError at BucketResourceIT.java:294

Builder Pattern and Dependecy Injection - how to fix problem

I wanted to create a class based on the builder pattern. Using the static method build. Which would return a properly built object based on initial validation checking whether a given object exists in the database.
#Component
#Data
#Builder
public class GetBookedSeatsRequest {
#Autowired
private MovieRepository movieRepository;
#Autowired
public CinemaRepository cinemaRepository;
#Autowired
public PropertiesMovieRepository propertiesMovieRepository;
private String cinemaName;
private String movieName;
private String movieRoom;
#JsonFormat(pattern="yyyy-MM-dd; HH:mm:ss",shape = JsonFormat.Shape.STRING)
private LocalDateTime localDateTime;
private List<Integer> wantedSeats;
public GetBookedSeatsRequest build(ReservationModel reservationModel) throws CinemaNotFoundException, MovieNotFoundException, PropertyMovieNotFoundException {
boolean cinemaExist = cinemaRepository.existsByCinemaName(reservationModel.getCinemaName());
if (!cinemaExist) {
throw new CinemaNotFoundException("Cinema doesn't exist");
}
boolean movieExist = movieRepository.existsByMovieName(reservationModel.getMovieName());
if (!movieExist) {
throw new MovieNotFoundException("Movie doesn't exist");
}
boolean roomExist = movieRepository.existsByMovieRoom(reservationModel.getMovieRoom());
if (!roomExist) {
throw new MovieNotFoundException("Movie Romm doesn't exist");
}
boolean existData = propertiesMovieRepository.existsByStartTimeOfTheMovie(reservationModel.getDateAndTime());
if (!existData) {
throw new PropertyMovieNotFoundException("This data doesn't exist");
}
// boolean existSeats = movieRepository.existsBySeating(reservationModel.getSeatsToBooked());
// if (!existSeats) {
// throw new MovieNotFoundException("This seats doesn't exist");
// }
GetBookedSeatsRequest correct = GetBookedSeatsRequest.builder()
.cinemaName(reservationModel.getCinemaName())
.movieName(reservationModel.getMovieName())
.movieRoom(reservationModel.getMovieRoom())
.localDateTime(reservationModel.getDateAndTime())
.wantedSeats(reservationModel.getSeatsToBooked())
.build();
return correct;
}
}
#Data
#AllArgsConstructor
public class ReservationModel {
private String cinemaName;
private String movieName;
private String movieRoom;
#JsonFormat(pattern="yyyy-MM-dd; HH:mm:ss",shape = JsonFormat.Shape.STRING)
private LocalDateTime dateAndTime;
private List<Integer> seatsToBooked;
}
But I still got some erros. What am I doing wrong, I am learing Spring Boot. Thanks for help
Description:
Parameter 3 of constructor in com.cinema.booking.aop.GetBookedSeatsRequest required a bean of type 'java.lang.String' that could not be found.
Action:
Consider defining a bean of type 'java.lang.String' in your configuration.

Hibernate does not create proxy within #DataJpaTest

I have a very simple test that tests the spring data repository that works ok in normal runtime. I really don't think it should be this difficult to do this, but I do not understand what I am doing wrong, please help.
When I try to test this repository I start receiving errors that say something like:
Caused by: org.hibernate.HibernateException: Generation of
HibernateProxy instances at runtime is not allowed when the configured
BytecodeProvider is 'none'; your model requires a more advanced
BytecodeProvider to be enabled. at
org.hibernate.bytecode.internal.none.DisallowedProxyFactory.getProxy(DisallowedProxyFactory.java:37)
at
org.hibernate.tuple.entity.AbstractEntityTuplizer.createProxy(AbstractEntityTuplizer.java:746)
at
org.hibernate.persister.entity.AbstractEntityPersister.createProxy(AbstractEntityPersister.java:5049)
It appears that hibernate can not create a proxy for entity classes, because it for some reason has been assigned a DisallowedProxyFactory implementation for proxy factory. So I added this configs:
spring.jpa.properties.hibernate.enhancer.enableDirtyTracking=true
spring.jpa.properties.hibernate.enhancer.enableLazyInitialization=true
But now I simply receive this error instead:
Caused by: java.lang.IllegalStateException: Cannot apply class
transformer without LoadTimeWeaver specified at
org.springframework.orm.jpa.persistenceunit.SpringPersistenceUnitInfo.addTransformer(SpringPersistenceUnitInfo.java:83)
So I added #EnableLoadTimeWeaving to the test class, and now I receive this error
Caused by: java.lang.IllegalStateException: ClassLoader
[jdk.internal.loader.ClassLoaders$AppClassLoader] does NOT provide an
'addTransformer(ClassFileTransformer)' method. Specify a custom
LoadTimeWeaver or start your Java virtual machine with Spring's agent:
-javaagent:spring-instrument-{version}.jar
The initial test set up:
#DataJpaTest
#Transactional
#Import({RdsPersistenceConfigration.class})
class DivisionRepositoryTest {
#Autowired
private DivisionRepository repository;
#Test
#Sql(scripts = "classpath:sql/division-repository-test.sql")
void crudOperations() {
// test case logic
}
}
Division entity:
#Entity
#Getter
#Setter
#NoArgsConstructor
#Table(name = "division")
public class Division {
private transient static final int HASH_CODE = Division.class.hashCode();
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "division_name", nullable = false)
private String divisionName;
#OneToMany(mappedBy = "division", fetch = FetchType.LAZY)
private Set<Branch> branches = new HashSet<>();
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "tenant_id", nullable = false)
private Tenant tenant;
public void setTenant(Tenant tenant) {
if (tenant != null) {
this.tenant = tenant;
tenant.addDivision(this);
} else {
if (this.tenant != null) this.tenant.removeDivision(this);
this.tenant = tenant;
}
}
#Transient
public void addBranch(Branch branch) {
if (branch != null) {
if (branch.getDivision() != this) {
branch.getDivision().removeBranch(branch);
}
branches.add(branch);
}
}
#Transient
public void removeBranch(Branch branch) {
if (branch != null) {
branches.remove(branch);
}
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Division division = (Division) o;
return Objects.equals(id, division.id);
}
#Override
public int hashCode() {
return Division.HASH_CODE;
}
}
Repository:
public interface DivisionRepository extends JpaRepository<Division, Integer> {
Page<Division> findAll(Pageable pageable);
}
Rds Persistence config class
#Configuration
#PropertySource("classpath:application-liquibase.properties")
#EntityScan("com.nflp.processingapplication.main.modules.persistence.sql")
public class RdsPersistenceConfigration {
}
Updated test after suggestion from #M. Denium
#DataJpaTest
#Transactional
#TestPropertySource(properties = "spring.liquibase.change-log=classpath:db/changelog/changelog.master.xml")
class DivisionRepositoryTest {
#Autowired
private DivisionRepository repository;
Ok, I finally found the solution, the reason was in something I did not even suspect, my application uses spring native to create optimized production builds, apparently it has somehow intervened with the development build process of the application. For now, I have just removed it from my application.
Later on I will probably try to separate the development build.gradle from the production one.

How to reference a properties value inside the schema attribute of an entity?

There is an entity :
#Entity
#Table(name = "ITMMASTER" , schema = "TOMCTB")
public class Article {
#Id
#Column(name = "ITMREF_0")
private String code_article;
#Column(name = "ACCCOD_0")
private String acccod;
public String getCode_article() {
return code_article;
}
public void setCode_article(String code) {
this.code_article = code;
}
public String getAcccod() {
return acccod;
}
public void setAcccod(String acccod) {
this.acccod = acccod;
}
}
I want to make the schema attribute to be dynamic depending on a properties file property value , for example : env.schema = TOMEXPL.
How to achieve that ?
I didn't tried it but I guess this should work.
public class DynamicNamingStrategy extends DefaultNamingStrategy {
#Value("db.table.name")
private String name;
#Override
public String tableName(String tableName) {
return name;
}
...
}
SessionFactory sessionFactory;
Configuration config = new AnnotationConfiguration()
.configure("hibernate.cfg.xml")
.setNamingStrategy( new DynamicNamingStrategy() );
sessionFactory = config.buildSessionFactory();
session = sessionFactory.openSession();

Couchbase 5 bucket password setting

I am trying to write a sample in order to learn couchbase. I am trying to use it with spring boot and it’s crud repositories .
So I have downloaded latest docker image but the point is: i could not find the password of the bucket. The couchbase console allows only user creation but in spring, there is no equivalent of this usage like a username/password. It allows only bucketName and password which does not seem compatible with couchbase 5.
Am I missing anything here or is spring not compatible with couchbase 5? If spring is not compatible, which version of couchbase is ok?
Thx
Spring Data Couchbase is compatible with Couchbase Server 5.0. You can achieve the same auth as 4.x by creating a user with the same name as the bucket, then just use that bucket name and password from Spring Data if it's prior to 3.0/Kay.
The docs should cover this and if there's anything confusing there, please click the "feedback" button and offer what could be improved!
https://developer.couchbase.com/documentation/server/5.0/security/security-authorization.html
https://developer.couchbase.com/documentation/server/5.0/security/concepts-rba-for-apps.html
https://developer.couchbase.com/documentation/server/5.0/security/security-resources-under-access-control.html
I faced the same issue. I started debugging by getting into AbstractCouchbaseConfiguration and there i found
public abstract class AbstractCouchbaseConfiguration
extends AbstractCouchbaseDataConfiguration implements CouchbaseConfigurer {
....//some other configuration
#Override
#Bean(name = BeanNames.COUCHBASE_CLUSTER_INFO)
public ClusterInfo couchbaseClusterInfo() throws Exception {
return couchbaseCluster().clusterManager(getBucketName(), getBucketPassword()).info();
}
What i did is created a bucket with the same name as of my couchbase user.
couchbase username : userdetail
couchbase password : ******
bucket name : userdetail
Couchbase driver supports connection to Couchbase 5 buckets using username/password. Problem is that spring-data-couchbase is not developed fast enough to cover all the new features Couchbase introduces. So, we need to help Spring to use a new bucket connection, doing it by overriding Couchbase cluster instantiation method of spring-data-couchbase configuration base class - org.springframework.data.couchbase.config.AbstractCouchbaseConfiguration. This is the method we are looking at :
#Override
#Bean(name = BeanNames.COUCHBASE_CLUSTER_INFO)
public ClusterInfo couchbaseClusterInfo() throws Exception {
return couchbaseCluster().clusterManager(getBucketName(), getBucketPassword()).info();
}
as we can see, it's not using username, just bucket and password, so in our configuration we will override it as following :
#Override
#Bean(name = BeanNames.COUCHBASE_CLUSTER_INFO)
public ClusterInfo couchbaseClusterInfo() throws Exception {
return couchbaseCluster().authenticate(couchbaseUsername, couchbasePassword).clusterManager().info();
}
that's it. Here is the full code of my spring-data-couchbase configuration :
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.cluster.ClusterInfo;
import com.couchbase.client.java.env.CouchbaseEnvironment;
import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.couchbase.config.AbstractCouchbaseConfiguration;
import org.springframework.data.couchbase.config.BeanNames;
import org.springframework.data.couchbase.repository.config.EnableCouchbaseRepositories;
import javax.inject.Inject;
import java.security.KeyStore;
import java.util.List;
/**
* #author by avoinovan
*/
#Configuration
#EnableCouchbaseRepositories
public class ModelConfig extends AbstractCouchbaseConfiguration {
private final static int DEFAULT_HTTP_PORT = 8091;
private final static int DEFAULT_HTTP_SSL_PORT = 18091;
private final static int DEFAULT_CARRIER_PORT = 11210;
private final static int DEFAULT_CARRIER_SSL_PORT = 11207;
private final static long DEFAULT_KEEP_ALIVE_INTERVAL = 30000;
private final static int DEFAULT_SOCKET_CONNECT_TIMEOUT_MS = 5000;
private final static long DEFAULT_CONNECT_TIMEOUT_MS = 5000;
private final static long DEFAULT_MANAGEMENT_TIMEOUT_MS = 75000;
private final static long DEFAULT_DISCONNECT_TIMEOUT_MS = 25000;
private final static String PROPERTY_KEEP_ALIVE_INTERVAL_MS = "couchbase.keep_alive_interval_ms";
private final static String PROPERTY_SOCKET_CONNECT_TIMEOUT_MS = "couchbase.socket_connect_timeout_ms";
private final static String PROPERTY_CONNECT_TIMEOUT_MS = "couchbase.connect_timeout_ms";
private final static String PROPERTY_MANAGEMENT_TIMEOUT_MS = "couchbase.management_timeout_ms";
private final static String PROPERTY_DISCONNECT_TIMEOUT_MS = "couchbase.disconnect_timeout_ms";
private final static String PROPERTY_SSL_ENABLED = "couchbase.ssl.enabled";
private final static String PROPERTY_SSL_KEYSTORE_FILE = "couchbase.ssl.keystore.file";
private final static String PROPERTY_SSL_KEYSTORE_PASSWORD = "couchbase.ssl.keystore.password";
private final static String PROPERTY_SSL_TRUSTSTORE_FILE = "couchbase.ssl.truststore.file";
private final static String PROPERTY_SSL_TRUSTSTORE_PASSWORD = "couchbase.ssl.truststore.password";
private final static String PROPERTY_BOOTSTRAP_HTTP_ENABLED = "couchbase.bootstrap.http.enabled";
private final static String PROPERTY_BOOTSTRAP_HTTP_PORT = "couchbase.bootstrap.http.port";
private final static String PROPERTY_BOOTSTRAP_HTTP_SSL_PORT = "couchbase.bootstrap.http.ssl.port";
private final static String PROPERTY_BOOTSTRAP_CARRIER_ENABLED = "couchbase.bootstrap.carrier.enabled";
private final static String PROPERTY_BOOTSTRAP_CARRIER_PORT = "couchbase.bootstrap.carrier.port";
private final static String PROPERTY_BOOTSTRAP_CARRIER_SSL_PORT = "couchbase.bootstrap.carrier.ssl.port";
#Value("#{'${spring.couchbase.bootstrap-hosts}'.split(',')}")
private List<String> couchbaseBootstrapHosts;
#Value("${spring.couchbase.bucket.name}")
private String bucketName;
#Value("${spring.couchbase.password}")
private String couchbasePassword;
#Value("${spring.couchbase.username}")
private String couchbaseUsername;
private final Environment environment;
private final ResourceLoader resourceLoader;
#Inject
public ModelConfig(final Environment environment,
final ResourceLoader resourceLoader) {
this.environment = environment;
this.resourceLoader = resourceLoader;
}
protected List<String> getBootstrapHosts() {
return couchbaseBootstrapHosts;
}
protected String getBucketName() {
return bucketName;
}
protected String getBucketPassword() {
return couchbasePassword;
}
protected CouchbaseEnvironment getEnvironment() {
return DefaultCouchbaseEnvironment.builder()
.keepAliveInterval(environment.getProperty(PROPERTY_KEEP_ALIVE_INTERVAL_MS,
Long.class,
DEFAULT_KEEP_ALIVE_INTERVAL))
// timeout settings
.socketConnectTimeout(environment.getProperty(PROPERTY_SOCKET_CONNECT_TIMEOUT_MS,
Integer.class,
DEFAULT_SOCKET_CONNECT_TIMEOUT_MS))
.connectTimeout(environment.getProperty(PROPERTY_CONNECT_TIMEOUT_MS,
Long.class,
DEFAULT_CONNECT_TIMEOUT_MS))
.managementTimeout(environment.getProperty(PROPERTY_MANAGEMENT_TIMEOUT_MS,
Long.class,
DEFAULT_MANAGEMENT_TIMEOUT_MS))
.disconnectTimeout(environment.getProperty(PROPERTY_DISCONNECT_TIMEOUT_MS,
Long.class,
DEFAULT_DISCONNECT_TIMEOUT_MS))
// port and ssl
.sslEnabled(environment.getProperty(PROPERTY_SSL_ENABLED, Boolean.class, false))
.bootstrapHttpEnabled(environment.getProperty(PROPERTY_BOOTSTRAP_HTTP_ENABLED,
Boolean.class,
Boolean.TRUE))
.bootstrapHttpDirectPort(environment.getProperty(PROPERTY_BOOTSTRAP_HTTP_PORT,
Integer.class,
DEFAULT_HTTP_PORT))
.bootstrapHttpSslPort(environment.getProperty(PROPERTY_BOOTSTRAP_HTTP_SSL_PORT,
Integer.class,
DEFAULT_HTTP_SSL_PORT))
.bootstrapCarrierEnabled(environment.getProperty(PROPERTY_BOOTSTRAP_CARRIER_ENABLED,
Boolean.class,
Boolean.TRUE))
.bootstrapCarrierDirectPort(environment.getProperty(PROPERTY_BOOTSTRAP_CARRIER_PORT,
Integer.class,
DEFAULT_CARRIER_PORT))
.bootstrapCarrierSslPort(environment.getProperty(PROPERTY_BOOTSTRAP_CARRIER_SSL_PORT,
Integer.class,
DEFAULT_CARRIER_SSL_PORT))
// keystore and trust store
.sslKeystore(createKeyStore(environment, resourceLoader))
.sslTruststore(createTrustStore(environment, resourceLoader))
.build();
}
#Override
#Bean(name = BeanNames.COUCHBASE_CLUSTER_INFO)
public ClusterInfo couchbaseClusterInfo() throws Exception {
return couchbaseCluster().authenticate(couchbaseUsername, couchbasePassword).clusterManager().info();
}
/**
* Return the {#link Bucket} instance to connect to.
*
* #throws Exception on Bean construction failure.
*/
#Override
#Bean(destroyMethod = "close", name = BeanNames.COUCHBASE_BUCKET)
public Bucket couchbaseClient() throws Exception {
//#Bean method can use another #Bean method in the same #Configuration by directly invoking it
return couchbaseCluster().openBucket(getBucketName());
}
private KeyStore createKeyStore(final Environment environment, final ResourceLoader resourceLoader) {
return loadKeyStore(environment, resourceLoader, PROPERTY_SSL_KEYSTORE_FILE, PROPERTY_SSL_KEYSTORE_PASSWORD);
}
private KeyStore createTrustStore(final Environment environment, final ResourceLoader resourceLoader) {
return loadKeyStore(environment, resourceLoader, PROPERTY_SSL_TRUSTSTORE_FILE, PROPERTY_SSL_TRUSTSTORE_PASSWORD);
}
private KeyStore loadKeyStore(final Environment environment,
final ResourceLoader resourceLoader,
final String fileProperty,
final String passwordProperty) {
String file = environment.getProperty(fileProperty);
String password = environment.getProperty(passwordProperty);
if (file != null) {
Resource resource = resourceLoader.getResource(file);
if (resource != null) {
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(resource.getInputStream(), password == null ? null : password.toCharArray());
return keyStore;
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
}
return null;
}
}

Resources