Unable to connect to container created by TestContainers in a SpringTest - spring-test

I'm using TestContainers to test a service class that will use mongodb. But Spring cannot connect to the mongodb created by the test container even I configured the DynamicPropertySource. It will just try to connect to my local mongo db instance.
Annotations for test class:
#Testcontainers
#SpringBootTest
#TestMethodOrder(MethodOrderer.OrderAnnotation::class)
Configuration
#Autowired lateinit var taskService: PersistentTaskService
companion object {
#Container
val mongoDbContainer: MongoDBContainer = MongoDBContainer("mongo:5.0.3")
#DynamicPropertySource
fun setUpProp(registry: DynamicPropertyRegistry) {
registry.add("spring.data.mongodb.uri", mongoDbContainer::getReplicaSetUrl)
}
}
How can I tell Spring to connect to the test container?

All right, I found out why.
The configuration above has no problem. The reason why Spring is still connecting to my local database is that the MongoDB configuration is hardcoded as a bean (in src/main).
I just removed the bean and opted for a configuration file instead.

Related

CqlSession cannot connect to Azure Cosmos DB Cassandra

I have this code
#Bean
public CqlSession getCqlSession() {
return CqlSession.builder()
.addContactPoint(new InetSocketAddress(cassandraHost, cassandraPort))
.withAuthCredentials(cassandraUsername, cassandraPassword)
.build();
}
The connection is failing with this exception:
Failed to instantiate [com.datastax.oss.driver.api.core.CqlSession]: Factory method 'getCqlSession' threw
exception; nested exception is com.datastax.oss.driver.api.core.AllNodesFailedException: Could not reach
any contact point, make sure you've provided valid addresses (showing first 1 nodes, use getAllErrors()
for more): Node(endPoint=tinyurl-cassandra.cassandra.cosmos.azure.com/52.230.23.170:10350, hostId=null,
hashCode=237f706): [com.datastax.oss.driver.api.core.DriverTimeoutException: [s0|control|id: 0xb89dacff,
L:/192.168.0.101:59158 - R:tinyurl-cassandra.cassandra.cosmos.azure.com/52.230.23.170:10350] Protocol
initialization request, step 1 (OPTIONS): timed out after 5000 ms]
I am new to Cassandra and have tried the following:
Validated that the credentials are okay.
Try with csqlsh - could not connect as well.
Check there's no firewall setup in my machine. Can telnet to host and port.
Can open Cassandra Shell from Azure Data Explorer.
What am I missing? I am new to this. Any help will be appreciated.
Looks like you are using the v.4x version of the Java Driver. The default load balancing in this driver mandates that you provide local data center, e.g:
CqlSession.builder().withSslContext(sc)
.addContactPoint(new InetSocketAddress(cassandraHost, cassandraPort)).**withLocalDatacenter("UK South")**
.withAuthCredentials(cassandraUsername, cassandraPassword).build();
You could take a look at this getting started sample for further reference: https://github.com/Azure-Samples/azure-cosmos-db-cassandra-java-getting-started-v4

Broaleaf 5.2 ROOT.war issue with Filters

I am trying to deploy Broadleaf demo site version 5.2.0 on external tomcat 8.5.16 with MYSQL as DB and standalone external Solr server running on port 8983.
I am able to access the admin application.
When I try deploying the ROOT.war, I get error
12-Aug-2017 16:33:52.733 SEVERE [localhost-startStop-1]
org.apache.catalina.core.StandardContext.filterStart Exception starting
filter [blDeviceResolverRequestFilter]
javax.naming.NameNotFoundException: Name [blDeviceResolver] is not bound
in this Context. Unable to find [blDeviceResolver].
I tried creating a bean so that it autowires correctly in
BroadleafDeviceResolverRequestFilter as
#Bean(name="blDeviceResolver")
public DeviceResolver getDeviceResolver() {
return new LiteDeviceResolver();
}
But the error is still the same and I am unable to run the demo application.
So the issues was that class BroadleafDeviceResolverRequestFilter was using
#Resource
private DeviceResolver deviceResolver;
But #Resource annotation is generic and means different things to Tomcat and Spring (Reference: Spring Boot WAR deployed in Tomcat 7 tries to perform weird automatic #Resource lookup)
I replaced #Resource with #Autowired and added a bean to com.community.core.config.CoreConfig
#Bean(name="blDeviceResolver")
public DeviceResolver getDeviceResolver() {
return new LiteDeviceResolver();
}
and my issue was resolved.

Connecting worker role with EF 6 to Azure sql database

I'm trying to set up a worker role to read and act based on data from Azure sql database.
I set the connection string like this:
public DBEntities(string connectionString) : base(connectionString) {}
Whenever I try to run the worker role localy I get the following error when querying the entities:
System.Data.Entity.Infrastructure.UnintentionalCodeFirstException: 'The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development.
To query the entities:
using (ctx = new CODDBEntities(_connectionString))
{
var result = ctx.entity.ToList().FindAll();
}
What am I doing wrong?
It seems that you're specifying the Database Initialization Strategies.
Try the Following:
public CODDBEntities()
{
Database.SetInitializer<CODDBEntities>(null);//Disable initializer
}
more info in here: http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx
Finnaly I got it. Using this article I understood that I was using the wrong connection string type. I needed to use the one starting like - metadata=res://*/..." while I just coiped the default connection string from the Azure portal.

Cassandra Cluster Recovery

I have a Spring Boot Application that uses Spring Data for Cassandra. One of the requirements is that the application will start even if the Cassandra Cluster is unavailable. The Application logs the situation and all its endpoints will not work properly but the Application does not shutdown. It should retry to connect to the cluster during this time. When the cluster is available the application should start to operate normally.
If I am able to connect during the application start and the cluster becomes unavailable after that, the cassandra java driver is capable of managing the retries.
How can I manage the retries during application start and still use Cassandra Repositories from Spring Data?
Thanx
It is possible to start a Spring Boot application if Apache Cassandra is not available but you need to define the Session and CassandraTemplate beans on your own with #Lazy. The beans are provided out of the box with CassandraAutoConfiguration but are initialized eagerly (default behavior) which creates a Session. The Session requires a connection to Cassandra which will prevent a startup if it's not initialized lazily.
The following code will initialize the resources lazily:
#Configuration
public class MyCassandraConfiguration {
#Bean
#Lazy
public CassandraTemplate cassandraTemplate(#Lazy Session session, CassandraConverter converter) throws Exception {
return new CassandraTemplate(session, converter);
}
#Bean
#Lazy
public Session session(CassandraConverter converter, Cluster cluster,
CassandraProperties cassandraProperties) throws Exception {
CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();
session.setCluster(cluster);
session.setConverter(converter);
session.setKeyspaceName(cassandraProperties.getKeyspaceName());
session.setSchemaAction(SchemaAction.NONE);
return session.getObject();
}
}
One of the requirements is that the application will start even if the Cassandra Cluster is unavailable
I think you should read this session from the Java driver doc: http://datastax.github.io/java-driver/manual/#cluster-initialization
The Cluster object does not connect automatically unless some calls are executed.
Since you're using Spring Data Cassandra (that I do not recommend since it has less feature than the plain Mapper Module of the Java driver ...) I don't know if the Cluster object or Session object are exposed directly to the users ...
For retry, you can put the cluster.init() call in a try/catch block and if the cluster is still unavaible, you'll catch an NoHostAvailableException according to the docs. Upon the exception, you can schedule a retry of cluster.init() later

How to Register Node app with Spring Cloud and Netflix's Eureka

I am trying hard to register my node app, with Netflix's Eureka , and after googling a lot, I am still looking for a solution . The max I can figure out is we have Prana but I got an issue which is still in the issue list of Prana (I guess it means my REST Template is not able to discover this app).
Sidecar , is another suggested solution , for which I am not getting any response . Apart from these two I have found a node module Eureka-Node-client , but none of them serve my purpose .
You can create a Sidecar application like you would create any spring-boot app:
#EnableSidecar
#SpringBootApplication
public class SideCarApplication {
public static void main(final String[] args) {
SpringApplication.run(SideCarApplication.class, args);
}
}
The important thing is that you have to configure it to correctly register your actual service. Your application.yml should look like this:
server:
port: 9999 -- the port your spring-boot sidecar is running
spring:
application:
name: nodeapplication -- the name will be your id in eureka
sidecar:
port: 8000 -- the node applications port
health-uri: http://localhost:8000/health.json -- the exposed health eindpoint of your node application
It is important to note that the healthpoint should return UP so your services status will be correct in eureka. The returned json for a healthy service :
{
"status":"UP"
}
If you are having trouble setting up a spring-boot app, use https://start.spring.io/ to configure a project. Sadly there isn't a sidecar option to tick, but you will get the idea. You can do the same from STS (Spring Tool Suite).
The maven dependency for Sidecar (with spring-cloud as a parent):
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-sidecar</artifactId>
</dependency>
Checkout eureka-js-client which can be directly used in the node application to register with eureka.
I used the npm generator-express-sidecar to generate a gradlew sidecar project with all the out-of-box configurations
Please refer to the reference link shared below
https://www.npmjs.com/package/generator-express-sidecar

Resources