I am trying to set up a Spring Boot 2 project with Mongo DB but I the problem I am facing is that it keeps spinning up an embedded mongo DB even though I have configured to use external mongo
logs
2018-11-27 18:56:05.725 INFO 73687 --- [ Thread-2] o.s.b.a.mongo.embedded.EmbeddedMongo : note: noprealloc may hurt performance in many applications
2018-11-27 18:56:05.742 INFO 73687 --- [ Thread-2] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-11-27T18:56:05.741+0200 I CONTROL [initandlisten] MongoDB starting : pid=73690 port=50303 dbpath=/var/folders/pf/qp_pv2xn7xb7ysnltp6tc97cstys_v/T/embedmongo-db-c2738896-198f-4934-87c4-3bd773508af7 64-bit host=MBP15-N5AXG8WP
2018-11-27 18:56:05.742 INFO 73687 --- [ Thread-2] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-11-27T18:56:05.741+0200 I CONTROL [initandlisten] db version v3.5.5
2018-11-27 18:56:05.742 INFO 73687 --- [ Thread-2] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-11-27T18:56:05.741+0200 I CONTROL [initandlisten] git version: 98515c812b6fa893613f063dae568ff8319cbfbd
2018-11-27 18:56:05.742 INFO 73687 --- [ Thread-2] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-11-27T18:56:05.741+0200 I CONTROL [initandlisten] allocator: system
Config
#EnableReactiveMongoRepositories
public class MongoReactiveApplication {
#Value("${spring.data.mongodb.uri}")
private String mongoUri;
#Bean
public MongoClient mongoClient() {
return MongoClients.create(mongoUri);
}
}
yaml
spring.data.mongodb.uri: mongodb://localhost:27017/mongotest
How should I change configuration to use external mongo?
Adding these beans helped me to connect to my external mongo
#Value("${spring.data.mongodb.uri}")
private String mongoUri;
#Bean
public MongoClient mongoClient() {
return MongoClients.create(mongoUri);
}
#Bean
public ReactiveMongoTemplate reactiveMongoTemplate() {
return new ReactiveMongoTemplate(reactiveMongoDatabaseFactory());
}
#Bean
public ReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory() {
return new SimpleReactiveMongoDatabaseFactory(mongoClient(), "mongotest");
}
Try this
spring:
data:
mongodb:
uri: mongodb://localhost:27017/mongotest
Related
I am writing simple helloworld application in spring batch, and I'm trying to validate the JobParameters with custom implementation of JobParametersValidator.
public class ParameterValidator implements JobParametersValidator{
#Override
public void validate(JobParameters parameters) throws JobParametersInvalidException {
//String parameter = parameters.getParameters().get("outputText");
System.out.println("jobparameters are ............ " + parameters);
//System.out.println("parameter is " + parameter);
//if(!StringUtils.hasText(parameter)) {
throw new JobParametersInvalidException("Parameter is missing.........");
//}
}
}
But when I tried to Sysout the JobParameters inside the validate method, parameters return null.
Here is my console out.
2021-11-26 10:06:32.457 INFO 11912 --- [ restartedMain] com.pack.SpringBatchDemo2Application : Starting SpringBatchDemo2Application using Java 16.0.2 on DESKTOP-T1L7IA7 with PID 11912 (D:\Workspace\EclipseWorkspaceSpringPractise\SpringBatchDemo2\target\classes started by arepa in D:\Workspace\EclipseWorkspaceSpringPractise\SpringBatchDemo2)
2021-11-26 10:06:32.458 INFO 11912 --- [ restartedMain] com.pack.SpringBatchDemo2Application : No active profile set, falling back to default profiles: default
2021-11-26 10:06:32.536 INFO 11912 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-11-26 10:06:33.575 INFO 11912 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-11-26 10:06:33.784 INFO 11912 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-11-26 10:06:33.920 INFO 11912 --- [ restartedMain] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: POSTGRES
2021-11-26 10:06:34.262 INFO 11912 --- [ restartedMain] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2021-11-26 10:06:34.484 INFO 11912 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2021-11-26 10:06:34.539 INFO 11912 --- [ restartedMain] com.pack.SpringBatchDemo2Application : Started SpringBatchDemo2Application in 2.596 seconds (JVM running for 4.056)
2021-11-26 10:06:34.544 INFO 11912 --- [ restartedMain] o.s.b.a.b.JobLauncherApplicationRunner : Running default command line with: []
jobparameters are ............ {}
2021-11-26 10:06:34.713 INFO 11912 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-11-26 10:06:34.756 ERROR 11912 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
Here is my Job creation code.
#Component
public class HelloWorldJob {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
public Step step() {
Tasklet tasklet = (contribution, chunkContext) -> {
return RepeatStatus.FINISHED;
};
return this.stepBuilderFactory.get("step1")
.tasklet(tasklet).build();
}
#Bean
public Job job() {
return this.jobBuilderFactory.get("job1").start(step()).validator(new ParameterValidator()).build();
}
}
Here is my code for triggering jobs.
#Component
public class TriggerJobLauncher {
#Autowired
private JobLauncher launcher;
#Autowired
private Job job;
public void triggerJob() throws JobExecutionAlreadyRunningException,
JobRestartException,
JobInstanceAlreadyCompleteException,
JobParametersInvalidException {
JobParameters parameters = new JobParametersBuilder().addParameter("aa", new JobParameter("Hello World")).toJobParameters();
launcher.run(job, parameters);
}
}
I'm trying to configure my spring security application.
I want to create my own UserDetailsService.
For that i do something like this:
public class ApplicationUserService implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return this.someUser();
}
}
I got 2 ways to add this UserService to Spring Security
Add it to configuration class. Something like this:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
#Override
protected UserDetailsService userDetailsService() {
return applicationUserService;
}
}
Or add annotaion #Component, or #Service on my class.
Everything is working fine when i chose only 1 way, but i got an question: why when i trying to use both variants (add #Service and add #Bean to config) nothing is working?
I got no exceptions, error or something like this in console:
2021-09-11 17:26:16.755 INFO 15819 --- [ main] com.example.test.TestApplication : Starting TestApplication using Java 16.0.2 on aleksander-MS-7A71 with PID 15819 (/home/aleksander/programming/java/4fun/test/target/classes started by aleksander in /home/aleksander/programming/java/4fun/test)
2021-09-11 17:26:16.756 INFO 15819 --- [ main] com.example.test.TestApplication : No active profile set, falling back to default profiles: default
2021-09-11 17:26:17.402 INFO 15819 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-09-11 17:26:17.409 INFO 15819 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-09-11 17:26:17.409 INFO 15819 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.52]
2021-09-11 17:26:17.442 INFO 15819 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-09-11 17:26:17.442 INFO 15819 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 630 ms
2021-09-11 17:26:17.555 INFO 15819 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#6981f8f3, org.springframework.security.web.context.SecurityContextPersistenceFilter#38bb9d7a, org.springframework.security.web.header.HeaderWriterFilter#62db3891, org.springframework.security.web.authentication.logout.LogoutFilter#48528634, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#80bfdc6, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#78d6447a, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#5e65afb6, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#623dcf2a, org.springframework.security.web.session.SessionManagementFilter#2819c460, org.springframework.security.web.access.ExceptionTranslationFilter#6f49d153, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#60bbacfc]
2021-09-11 17:26:17.676 INFO 15819 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-09-11 17:26:17.682 INFO 15819 --- [ main] com.example.test.TestApplication : Started TestApplication in 1.215 seconds (JVM running for 1.794)
The way you've described the question, the application will definitely throw an exception unless you've defined the bean preference.
First case:
Basically, UserDetailsService is an interface and you've provided the implementation of it by declaring the bean as
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
#Override
protected UserDetailsService userDetailsService() {
return new ApplicationUserService();
}
}
Second case: You want to check the behaviour by declaring another bean using #Service or #Component annotation as following
#Service
public class ApplicationUserService implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return new UserDetails();
}
}
If you try to use the above cases together, it won't work. The case is very simple you are providing two beans of type UserDetailsService to the spring container and hence it won't be able to identify which one it should use.
If you want to check the behaviour with both the cases you've to set the priority for beans, so in that case you can mark one of the bean with #Primary annotation.
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Primary
#Bean
#Override
protected UserDetailsService userDetailsService() {
return new ApplicationUserService();
}
}
I am running a spring boot app version 2.1.4.RELEASE. The app is using hibernate 5.4.2.Final and postgresql driver version 42.2.5. Recently i tried to generate the DDL from hibernate in order to see the DDL, and I stumbled upon a error that is bugging me since days.
Using the PostgreSQL 11.2 version (Ubuntu 11.2-1.pgdg18.04+1)
Now when the app is booting it is running into that exception every time.
If i place a break point on the method
org.hibernate.engine.jdbc.env.internal.DefaultSchemaNameResolver.determineAppropriateResolverDelegate(Connection connection)
i see where the exception is occurring i.e. at the point
connection.getSchema();
there are helpful comments in this class
unfortunately Connection#getSchema is only available in Java 1.7 and above
and Hibernate still baselines on 1.6. So for now, use reflection and
leverage the Connection#getSchema method if it is available.
If the JDBC driver does not implement the Java 7 spec, but the JRE is Java 7
then the getSchemaMethod is not null but the call to getSchema() throws an java.lang.AbstractMethodError
well i am running version above 7 i.e. :
java -version
openjdk version "11" 2018-09-25
OpenJDK Runtime Environment 18.9 (build 11+28)
OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)
I am still running into the following exception on spring boot start i.e. !!!! EVEN BEFOR THE PART OF THE CODE (BEANS) ARE REACHED !!! that are supposed to generate the DDL i.e. the method createSchemaWithHibernate5(LocalSessionFactoryBean sessionFactory).
So that has something to do with the config or the connection type. When i place a breakpoint on then connection type i see it is of type
org.apache.commons.dbcp.PoolableConnection
well that one is extending from "DelegatingConnection" which DOES NOT implement the method getSchema() although it is extending the interface
java.sql.Connection
which does have the method getSchema().
I am not sure how this is supposed to work at all, since none of those are final or abstract classes.
I also see that there is another class called
org.postgresql.jdbc.PgConnection.
How can i force my app to use this one since i see this one indeed DOES implement the method getSchema().
Here is the exception i am running into:
2019-04-17 10:06:42.487 DEBUG tito-pc --- [ restartedMain] .i.f.i.DefaultIdentifierGeneratorFactory : Registering IdentifierGenerator strategy [enhanced-table] -> [org.hibernate.id.enhanced.TableGenerator]
2019-04-17 10:06:43.004 DEBUG tito-pc --- [ restartedMain] o.h.e.j.e.i.JdbcEnvironmentInitiator : Database ->
name : PostgreSQL
version : 11.2 (Ubuntu 11.2-1.pgdg18.04+1)
major : 11
minor : 2
2019-04-17 10:06:43.004 DEBUG tito-pc --- [ restartedMain] o.h.e.j.e.i.JdbcEnvironmentInitiator : Driver ->
name : PostgreSQL JDBC Driver
version : 42.2.5
major : 42
minor : 2
2019-04-17 10:06:43.005 DEBUG tito-pc --- [ restartedMain] o.h.e.j.e.i.JdbcEnvironmentInitiator : JDBC version : 4.2
2019-04-17 10:06:43.023 INFO tito-pc --- [ restartedMain] o.h.d.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL95Dialect
2019-04-17 10:06:43.053 DEBUG tito-pc --- [ restartedMain] o.h.e.j.e.s.IdentifierHelperBuilder : JDBC driver metadata reported database stores quoted identifiers in neither upper, lower nor mixed case
2019-04-17 10:06:54.515 DEBUG tito-pc --- [ restartedMain] o.h.e.j.e.i.DefaultSchemaNameResolver : Unable to use Java 1.7 Connection#getSchema
2019-04-17 10:06:59.058 DEBUG tito-pc --- [ restartedMain] o.h.e.j.e.i.JdbcEnvironmentImpl : Unable to resolve connection default schema
org.hibernate.HibernateException: Use of DefaultSchemaNameResolver requires Dialect to provide the proper SQL statement/command but provided Dialect [org.hibernate.dialect.PostgreSQL95Dialect] did not return anything from Dialect#getCurrentSchemaCommand
at org.hibernate.engine.jdbc.env.internal.DefaultSchemaNameResolver$SchemaNameResolverFallbackDelegate.resolveSchemaName(DefaultSchemaNameResolver.java:100)
at org.hibernate.engine.jdbc.env.internal.DefaultSchemaNameResolver.resolveSchemaName(DefaultSchemaNameResolver.java:76)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.determineCurrentSchemaName(JdbcEnvironmentImpl.java:311)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.<init>(JdbcEnvironmentImpl.java:266)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:114)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:175)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:118)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:473)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:84)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:689)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:615)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774)
.....
here is my persistence config:
#Profile("Development")
#Configuration
#EnableTransactionManagement
#Order(value=1)
public class PersistenceConfigDevelopment {
private static Logger logger = LogManager.getLogger(PersistenceConfigDevelopment.class.getName());
#Bean
#Primary
public org.apache.commons.dbcp.BasicDataSource dataSourceReadWrite1() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:5432/develpmentTestDb");
dataSource.setUsername("admin");
dataSource.setPassword("notABigSecret");
dataSource.setInitialSize(20);
dataSource.setMaxActive(-1);
return dataSource;
}
#Bean
#Primary
public org.springframework.orm.hibernate5.LocalSessionFactoryBean sessionFactory() {
org.springframework.orm.hibernate5.LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setHibernateProperties(hibernateProperties());
sessionFactory.setDataSource(this.dataSourceReadWrite1());
sessionFactory.setPackagesToScan("org.university.");
return sessionFactory;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory().getObject());
return txManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public Properties hibernateProperties() {
return new Properties() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL95Dialect");
setProperty("hibernate.chach.provider_class", "org.hibernate.cache.NoCacheProvider");
setProperty("hibernate.show_sql", "true");
setProperty("hibernate.hbm2ddl.auto", "create-drop");
setProperty("hibernate.cache.use_second_level_cache", "false");
setProperty("hibernate.cache.use_query_cache", "false");
// isolation level
setProperty("hibernate.connection.isolation", String.valueOf(Connection.TRANSACTION_SERIALIZABLE));
}
};
}
#Bean
public Boolean createSchemaWithHibernate5(LocalSessionFactoryBean sessionFactory) {
final PostgreSQL95Dialect dialect = new PostgreSQL95Dialect();
StandardServiceRegistry serviceRegistry = sessionFactory.getConfiguration().getStandardServiceRegistryBuilder()
.applySetting("hibernate.dialect", dialect)
.build();
Metadata metadata = new MetadataSources(serviceRegistry).buildMetadata();
new SchemaExport()
.setOutputFile("db-schema.hibernate5.ddl")
.create(EnumSet.of(TargetType.SCRIPT), metadata);
metadata.buildSessionFactory().close();
return Boolean.TRUE;
}
}
Because of this stackoverflow post i tried changing the drivers i.e.
Implementating Method org.postgresql.jdbc4.Jdbc4Connection.getSchema()
and tried using "postgresql" maven artifact instead of "org.postgresql" but that did not helped as well.
Any help is really appreciated.
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<!-- <version>${orgpostgresql.version}</version> -->
</dependency>
<!-- <dependency> -->
<!-- <groupId>postgresql</groupId> -->
<!-- <artifactId>postgresql</artifactId> -->
<!-- <version>${postgresql.version}</version> -->
<!-- </dependency> -->
update 17 April
I was able to get rid of the exception by using another data source i.e. PGSimpleDataSource that also changed the connector to PgConnection, but the DDL is still not being generated. I.e. the file db-schema.hibernate5.ddl is beeing generated but it is empty.
#Bean
#Primary
public PGSimpleDataSource dataSourceReadWrite1() {
PGSimpleDataSource dataSource = new PGSimpleDataSource();
dataSource.setUrl("jdbc:postgresql://localhost:5432/developmentTestDB");
dataSource.setUser("admin");
dataSource.setPassword("notABigSecret");
return dataSource;
}
I struggled with the same problem myself
11:16:07.675 [AWT-EventQueue-0] DEBUG org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator - Database ->
name : PostgreSQL
version : 10.18 (Ubuntu 10.18-0ubuntu0.18.04.1)
major : 10
minor : 18
11:16:07.675 [AWT-EventQueue-0] DEBUG org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator - Driver ->
name : PostgreSQL Native Driver
version : PostgreSQL 9.0 JDBC4 (build 801)
major : 9
minor : 0
11:16:07.675 [AWT-EventQueue-0] DEBUG org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator - JDBC version : 4.0
11:16:07.689 [AWT-EventQueue-0] INFO org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
11:16:07.709 [AWT-EventQueue-0] DEBUG org.hibernate.engine.jdbc.env.spi.IdentifierHelperBuilder - JDBC driver metadata reported database stores quoted identifiers in neither upper, lower nor mixed case
11:16:07.716 [AWT-EventQueue-0] DEBUG org.hibernate.engine.jdbc.env.internal.DefaultSchemaNameResolver - Unable to use Java 1.7 Connection#getSchema
11:16:07.718 [AWT-EventQueue-0] DEBUG org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl - Unable to resolve connection default schema
org.hibernate.HibernateException: Use of DefaultSchemaNameResolver requires Dialect to provide the proper SQL statement/command but provided Dialect [org.hibernate.dialect.PostgreSQLDialect] did not return anything from Dialect#getCurrentSchemaCommand
I had to update the drivers so that it showed
11:45:27.477 [AWT-EventQueue-0] DEBUG org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator - Driver ->
name : PostgreSQL JDBC Driver
version : 42.2.23
major : 42
minor : 2
And I had to change my dialect to
PostgreSQL10Dialect
I'm trying to save a basic document but despite connecting to mongodb successfully... It doesn't seem to want to save.
Spring logs
2018-10-03 00:17:25.998 INFO 10713 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2018-10-03 00:17:26.049 INFO 10713 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-10-03 00:17:26.106 INFO 10713 --- [ctor-http-nio-1] r.ipc.netty.tcp.BlockingNettyContext : Started HttpServer on /0:0:0:0:0:0:0:0:8080
2018-10-03 00:17:26.106 INFO 10713 --- [ restartedMain] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8080
2018-10-03 00:17:26.112 INFO 10713 --- [ restartedMain] c.l.s.ServiceLegalApplicationKt : Started ServiceLegalApplicationKt in 3.459 seconds (JVM running for 4.201)
2018-10-03 00:17:26.644 INFO 10713 --- [ntLoopGroup-2-2] org.mongodb.driver.connection : Opened connection [connectionId{localValue:3, serverValue:4}] to localhost:27017
application.properties
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=legal
spring.data.mongodb.repositories.type=reactive
spring.mongodb.embedded.version=4.0.2
basic interface and class
interface EventRepository: ReactiveMongoRepository<Event, String>
#Document
class Event(id: String, name: String)
trying a simple save function
#Service
class SomeService(val eventRepository: EventRepository)
{
fun save() = eventRepository.save(Event(UUID.randomUUID().toString(), "hey"))
}
Mono<Event> response = repository.save(Event(UUID.randomUUID().toString(), "hey"));
Changes in save method
fun save() = eventRepository.save(Event(UUID.randomUUID().toString(), "hey")).subscribe();
You have to invoke subscribe() method on Mono reference to see the logs or details.
To make you stream terminal with subscribe() operation and to get the Mono result at the same time - split into two separate operations:
Mono<String> myEvent = eventRepository.save(Event(UUID.randomUUID().toString(), "hey"));
myEvent.subscribe();
return myEvent;
You can also call .block() on the returned Reactive mono
Mono<Event> reactiveEvent = repository.save(); reactiveEvent.block()
Also read this
The CamelContextStartedEvent is called twice for the same camel context (camel-1). The issue might be the way I register the EventNotifier. You can reproduce the issue with Spring Initializr with Spring Boot 1.5.14, Spring Boot Camel Starter 2.21.1 and Spring Boot Web Starter.
See the logs:
2018-07-06 11:04:41.104 INFO 19092 --- [ main] o.a.camel.spring.SpringCamelContext : Apache Camel 2.21.1 (CamelContext: camel-1) is starting
2018-07-06 11:04:41.106 INFO 19092 --- [ main] o.a.c.m.ManagedManagementStrategy : JMX is enabled
2018-07-06 11:04:41.191 INFO 19092 --- [ main] o.a.camel.spring.SpringCamelContext : StreamCaching is not in use. If using streams then its recommended to enable stream caching. See more details at http://camel.apache.org/stream-caching.html
2018-07-06 11:04:41.193 INFO 19092 --- [ main] o.a.camel.spring.boot.RoutesCollector : Starting CamelMainRunController to ensure the main thread keeps running
2018-07-06 11:04:41.193 INFO 19092 --- [ main] o.a.camel.spring.SpringCamelContext : Total 0 routes, of which 0 are started
2018-07-06 11:04:41.194 INFO 19092 --- [ main] o.a.camel.spring.SpringCamelContext : Apache Camel 2.21.1 (CamelContext: camel-1) started in 0.090 seconds
2018-07-06 11:04:41.195 INFO 19092 --- [ main] c.e.bug.service.StartupEventNotifier : CamelContextStartedEvent for SpringCamelContext(camel-1) with spring id application:11223
2018-07-06 11:04:41.195 INFO 19092 --- [ main] c.e.bug.service.StartupEventNotifier : CamelContextStartedEvent for SpringCamelContext(camel-1) with spring id application:11223
2018-07-06 11:04:41.216 INFO 19092 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 11223 (http)
2018-07-06 11:04:41.221 INFO 19092 --- [ main] com.example.bug.BugApplication : Started BugApplication in 4.684 seconds (JVM running for 6.773)
The service that initializes the EventNotifier:
#Service
public class SchedulerService {
private final CamelContext camelContext;
private final StartupEventNotifier startupEventNotifier;
public SchedulerService(CamelContext camelContext, StartupEventNotifier startupEventNotifier) {
this.camelContext = camelContext;
this.startupEventNotifier = startupEventNotifier;
}
#PostConstruct
public void init() {
camelContext.getManagementStrategy().addEventNotifier(startupEventNotifier);
}
}
The EventNotifier:
#Component
public class StartupEventNotifier extends EventNotifierSupport {
private static final Logger logger = LoggerFactory.getLogger(StartupEventNotifier.class);
#Override
public void notify(EventObject event) throws Exception {
if (event instanceof CamelContextStartedEvent) {
logger.info("CamelContextStartedEvent for {}", event.getSource());
}
}
#Override
public boolean isEnabled(EventObject event) {
if (event instanceof CamelContextStartedEvent) {
return true;
}
return false;
}
}
application.yml:
camel:
springboot:
main-run-controller: true
server:
port: 11223
It is called twice, because it is registered twice. Once by you and once by Apache Camel. EventNotifier is registered automatically, if is found in Registry. Since your StartupEventNotifier is annotated as Component, it is part of Registry and Apache Camel registered it during CamelContext startup (You can see it in CamelAutoConfiguration line 424).
You have four options:
Remove your custom registration from SchedulerService.
Remove #Component annotation from StartupEventNotifier and register it with with camelContext.getManagementStrategy().addEventNotifier(new StartupEventNotifier())
Add duplicity check to your SchedulerService. Something like:
if (!context.getManagementStrategy().getEventNotifiers().contains(startupEventNotifier)){
context.getManagementStrategy().addEventNotifier(startupEventNotifier);
}
Register EventNotifier in #PostConstruct of RouteBuilder. It will be registered before automatic discovery is started and then it will be skipped in CamelAutoConfiguration (See line 422)