Invalid mongo configuration, either uri or host/port/credentials must be specified - mongodb

I'm getting this exception :
Caused by: java.lang.IllegalStateException: Invalid mongo configuration, either uri or host/port/credentials must be specified
at org.springframework.boot.autoconfigure.mongo.MongoProperties.createMongoClient(MongoProperties.java:207)
at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration.mongo(MongoAutoConfiguration.java:73)
at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration$$EnhancerBySpringCGLIB$$15f9b896.CGLIB$mongo$1(<generated>)
at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration$$EnhancerBySpringCGLIB$$15f9b896$$FastClassBySpringCGLIB$$c0338f6a.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
at org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration$$EnhancerBySpringCGLIB$$15f9b896.mongo(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 25 common frames omitted
Here is my application.yml content :
spring:
data:
mongodb:
uri: mongodb://develop:d3VeL0p$#<my_host>:27017/SHAM
Here is my configuration class :
package com.me.service.testservice.config;
import com.mongodb.MongoClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
#Configuration
#EnableMongoRepositories(basePackages = {"com.me.service.testservice.repository"}, considerNestedRepositories = true)
public class SpringMongoConfiguration {
#Bean
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(new MongoClient("<my_host>"), "SHAM");
}
}
Now I'm getting this stack trace when starting without failing, it looks like user develop doesn't have the right to connect:
Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server phelbwlabect003.karmalab.net:27017. The full response is { "ok" : 0.0, "errmsg" : "Authentication failed.", "code" : 18, "codeName" : "AuthenticationFailed" }
at com.mongodb.connection.CommandHelper.createCommandFailureException(CommandHelper.java:170)
at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:123)
at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
at com.mongodb.connection.SaslAuthenticator.sendSaslStart(SaslAuthenticator.java:117)
at com.mongodb.connection.SaslAuthenticator.access$000(SaslAuthenticator.java:37)
at com.mongodb.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:50)
... 9 common frames omitted

You are mixing the uri style connection settings with the individual properties style settings.
Either use
spring:
data:
mongodb:
host: localhost
port: 27017
database: SHAM_TEST
username: develop
password: pass
Or
spring:
data:
mongodb:
uri:mongodb://develop:pass#localhost:27017/SHAM_TEST

If your project has more then one application.properties/application.yml file, sometime they both conflicts if one has URI and other has Host/Port/Credential.
This result in the error "Invalid mongo configuration, either uri or host/port/credentials must be specified"
To Avoid the conflict, make sure you either use URI or Host/Port/Credential in all.

The issue was authentication-database was missing.
Here is now the working configuration :
spring:
data:
mongodb:
host: <my_host>
username: develop
password: d3VeL0p$
port: 27017
database: SHAM
repositories:
enabled: true
authentication-database: admin

If you are using application.properties file to store your configuration, Use the following structure.
spring.data.mongodb.host = localhost
spring.data.mongodb.port = 27017
spring.data.mongodb.database = SHAM_TEST
spring.data.mongodb.username = develop
spring.data.mongodb.password = pass

This issue appears with mongo version 4.x,
spring or spring boot supports version 2.x only so when we try to connect with mongo 4 this error appears:
Downgrade your mongo from 4.x to 3.x or lower.
If not, then change these placeholders.
Change from :
spring.data.mongodb.host= localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database= your db name
spring.data.mongodb.username= something
spring.data.mongodb.password= ***
-to-
mongo.replica.hosts=localhost:27017
mongo.dbname= your db name
mongo.username= something
mongo.password= ***

Related

How do i disable elastic search and fall back to local filesystem storage in hibernate search 6

I am using Hibernate 6 with Amazons opensearch server in production. When i'm testing locally i don't want to use the opensearch server, instead i want to use local-filesystem to store the index files.
However i can't hibernate search to use local-filesystem even when i explicitly set it with jpaProperties.put("hibernate.search.backend.directory.type", "local-filesystem"); while at the same time not setting the property hibernate.search.backend.uris. Before all the hibernate search properties can be programmatically set i get the following error on startup:
default backend:
failures:
- HSEARCH400080: Unable to detect the Elasticsearch version running on the cluster: HSEARCH400007: Elasticsearch request failed: Connection refused: no further information
Request: GET with parameters {}
I have the following maven dependencies:
<dependency>
<groupId>org.hibernate.search</groupId>
<artifactId>hibernate-search-mapper-orm</artifactId>
<version>6.1.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.search</groupId>
<artifactId>hibernate-search-backend-elasticsearch-aws</artifactId>
<version>6.1.5.Final</version>
</dependency>
The following sets hibernate search and the lucene file destination path if using lucene only:
private Properties initializeJpaProperties() {
String luceneAbsoluteFilePath = useExternalElasticSearchServer ? null : setDefaultLuceneIndexBaseFilePath(); //Alleen relevant wanneer je geen elastic search gebruikt.
Properties jpaProperties = new Properties();
//---------------------------open search aws related-----------------------------------
if(useExternalElasticSearchServer) {
jpaProperties.put("hibernate.search.backend.aws.credentials.type", "static");
jpaProperties.put("hibernate.search.backend.aws.credentials.access_key_id", awsId);
jpaProperties.put("hibernate.search.backend.aws.credentials.secret_access_key", awsKey);
jpaProperties.put("hibernate.search.backend.aws.region", openSearchAwsInstanceRegion);
jpaProperties.put("hibernate.search.backend.aws.signing.enabled", true);
jpaProperties.put("hibernate.search.backend.uris", elasticSearchHostAddress);
}
//--------------------------------------------------------------------------------------------
jpaProperties.put("hibernate.search.automatic_indexing.synchronization.strategy", indexSynchronizationStrategy);
jpaProperties.put("hibernate.search.backend.request_timeout", requestTimeout);
jpaProperties.put("hibernate.search.backend.connection_timeout", elasticSearchConnectionTimeout);
jpaProperties.put("hibernate.search.backend.read_timeout", readTimeout);
jpaProperties.put("hibernate.search.backend.max_connections", maximumElasticSearchConnections);
jpaProperties.put("hibernate.search.backend.max_connections_per_route", maximumElasticSearchConnectionsPerRout);
// jpaProperties.put("hibernate.search.schema_management.strategy", schemaManagementStrategy);
jpaProperties.put("hibernate.search.backend.thread_pool.size", maxPoolSize);
jpaProperties.put("hibernate.search.backend.analysis.configurer", "class:config.EnhancedLuceneAnalysisConfig");
// jpaProperties.put("hibernate.search.backend.username", hibernateSearchUsername); //Alleen voor wanneer je elastic search lokaal draait
// jpaProperties.put("hibernate.search.backend.password", hibernateSearchPassword);
if(!useExternalElasticSearchServer) {
jpaProperties.put("hibernate.search.backend.directory.type", "local-filesystem");
jpaProperties.put("hibernate.search.backend.directory.root", luceneAbsoluteFilePath);
jpaProperties.put("hibernate.search.backend.lucene_version", "LUCENE_CURRENT");
jpaProperties.put("hibernate.search.backend.io.writer.infostream", true);
}
jpaProperties.put("hibernate.jdbc.batch_size", defaultBatchSize);
jpaProperties.put("spring.jpa.properties.hibernate.jdbc.batch_size", defaultBatchSize);
jpaProperties.put("hibernate.order_inserts", "true");
jpaProperties.put("hibernate.order_updates", "true");
jpaProperties.put("hibernate.batch_versioned_data", "true");
// log.info("The directory of the lucene index files is set to {}", luceneAbsoluteFilePath);
return jpaProperties;
}
private String setDefaultLuceneIndexBaseFilePath() {
String luceneRelativeFilePath = ServiceUtil.getOperatingSystemCompatiblePath("/data/lucene/indexes/default");
StringBuilder luceneAbsoluteFilePath = new StringBuilder(System.getProperty("user.dir"));
if(!StringUtils.isEmpty(luceneIndexBase)) {
luceneRelativeFilePath = ServiceUtil.getOperatingSystemCompatiblePath(luceneIndexBase);
String OSPathSeparator = ServiceUtil.getOperatingSystemFileSeparator();
if(luceneRelativeFilePath.toCharArray()[0] != OSPathSeparator.charAt(0))
luceneAbsoluteFilePath.append(OSPathSeparator);
luceneAbsoluteFilePath.append(luceneRelativeFilePath);
validateUserDefinedAbsolutePath(luceneRelativeFilePath);
}
else{
log.warn("No relative path value for property 'lucene-index-base' was found in application.properties, will use the default path '{}' instead.", luceneRelativeFilePath);
luceneAbsoluteFilePath.append(luceneRelativeFilePath);
}
return luceneAbsoluteFilePath.toString();
}
I know that i can disable hibernate search completely with hibernate.search.enabled set to false but i don't want that. I want to be able to switch to lucene only without having to remove all the ElasticSearch/OpenSearch dependencies from my POM.xml beforehand. How do i do this?
EDIT: I just found out that you can set the backend type with hibernate.search.backend.type. This setting is set to the value elasticsearch by default. I should also be able to set this value to lucene but when i do that i get the following error:
default backend:
failures:
- HSEARCH000501: Invalid value for configuration property 'hibernate.search.backend.type': 'lucene'. HSEARCH000579: Unable to resolve bean reference to type 'org.hibernate.search.engine.backend.spi.BackendFactory' and name 'lucene'. Failed to resolve bean from Hibernate Search's internal registry with exception: HSEARCH000578: No beans defined for type 'org.hibernate.search.engine.backend.spi.BackendFactory' and name 'lucene' in Hibernate Search's internal registry. Failed to resolve bean from bean manager with exception: HSEARCH000590: No configured bean manager. Failed to resolve bean from bean manager with exception: HSEARCH000591: Unable to resolve 'lucene' to a class extending 'org.hibernate.search.engine.backend.spi.BackendFactory': HSEARCH000530: Unable to load class 'lucene': Could not load requested class : lucene Failed to resolve bean using reflection with exception: HSEARCH000591: Unable to resolve 'lucene' to a class extending
'org.hibernate.search.engine.backend.spi.BackendFactory': HSEARCH000530: Unable to load class 'lucene': Could not load requested class : lucene
EDIT 2:
I tried the setting the following settings with no success as well.
jpaProperties.put("hibernate.search.default_backend", "lucene");
jpaProperties.put("hibernate.search.backends.lucene.type", "lucene");
jpaProperties.put("hibernate.search.backend.type", "lucene");
You need to set the backend type explicitly according to the environment:
jpaProperties.put("hibernate.search.backend.type", isProductionEnvironment() ? "elasticsearch" : "lucene");
And you also need to have the Lucene backend in your classpath:
<dependency>
<groupId>org.hibernate.search</groupId>
<artifactId>hibernate-search-backend-lucene</artifactId>
<version>${my-hibernate-search-version}</version>
</dependency>

Spring Cloud Gateway 500 when an instance is down

I have a Spring Cloud Gateway (eureka client) app that uses Spring Cloud Load Balancer (Spring Cloud version: Hoxton.SR6) and I have an instance of a spring boot app (spring boot 2.3 with enabled graceful shutdown, (eureka client).
When I shutdown a spring boot service and perform a request through the gateway then the gateway throws 500 error (connection refused), instead of 503. 503 appears after a 1-2 minutes.
Can anyone clarify if it is an expected behavior?
It seems that the problem comes from eureka-client (1.9.21 version in my case)
AtomicReference<Applications> localRegionApps isn't frequently updated
Thanks!
UPDATE:
I decided to check deeper this 500 error. The result is that my system (ubuntu) gives this error if the port is not used:
curl -v localhost:9722
Rebuilt URL to: localhost:9722/
Trying 127.0.0.1...
TCP_NODELAY set
connect to 127.0.0.1 port 9722 failed: Connection refused
Failed to connect to localhost port 9722: Connection refused
Closing connection 0
So I put in my application.yml:
spring:
cloud:
gateway:
routes:
- id: my_route
uri: http://localhost:9722/
Then when my request is routed to my_route and none of apps uses 9722 then I get an error:
io.netty.channel.AbstractChannel$AnnotatedConnectException: finishConnect(..) failed: Connection refused: localhost/127.0.0.1:9722
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
|_ checkpoint ⇢ org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter [DefaultWebFilterChain]
|_ checkpoint ⇢ org.springframework.boot.actuate.metrics.web.reactive.server.MetricsWebFilter [DefaultWebFilterChain]
|_ checkpoint ⇢ HTTP GET "/internal/mail/internal/health-check" [ExceptionHandlingWebHandler]
Stack trace:
Caused by: java.net.ConnectException: finishConnect(..) failed: Connection refused
at io.netty.channel.unix.Errors.throwConnectException(Errors.java:124)
at io.netty.channel.unix.Socket.finishConnect(Socket.java:251)
at io.netty.channel.epoll.AbstractEpollChannel$AbstractEpollUnsafe.doFinishConnect(AbstractEpollChannel.java:672)
at io.netty.channel.epoll.AbstractEpollChannel$AbstractEpollUnsafe.finishConnect(AbstractEpollChannel.java:649)
at io.netty.channel.epoll.AbstractEpollChannel$AbstractEpollUnsafe.epollOutReady(AbstractEpollChannel.java:529)
at io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:465)
at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:378)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:834)
It seems to be an unexpected exception, since it isn't possible to handle it using a circuit breaker or any gateway filter.
Is it possible to handle this error correctly? I would like to return 503 in this case
One of the easiest ways to map particular exception to particular HTTP status code is providing a custom bean of type org.springframework.boot.web.reactive.error.ErrorAttributes. Here is an example:
#Bean
public ErrorAttributes errorAttributes() {
return new CustomErrorAttributes(httpStatusExceptionTypeMapper);
}
public class CustomErrorAttributes extends DefaultErrorAttributes {
#Override
public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
Map<String, Object> attributes = super.getErrorAttributes(request, options);
Throwable error = getError(request);
MergedAnnotation<ResponseStatus> responseStatusAnnotation = MergedAnnotations
.from(error.getClass(), MergedAnnotations.SearchStrategy.TYPE_HIERARCHY).get(ResponseStatus.class);
HttpStatus errorStatus = determineHttpStatus(error, responseStatusAnnotation);
attributes.put("status", errorStatus.value());
return attributes;
}
private HttpStatus determineHttpStatus(Throwable error, MergedAnnotation<ResponseStatus> responseStatusAnnotation) {
if (error instanceof ResponseStatusException) {
return ((ResponseStatusException) error).getStatus();
}
return responseStatusAnnotation.getValue("code", HttpStatus.class).orElseGet(() -> {
if (error instanceof java.net.ConnectException) {
return HttpStatus.SERVICE_UNAVAILABLE;
}
return HttpStatus.INTERNAL_SERVER_ERROR;
}
}
}
hava a try to define your custom ErrorWebExceptionHandler.
see:
org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler
org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler
You should use Cloud Circuit Breaker.
For that:
Declare corresponding starter in your pom:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4j</artifactId>
</dependency>
Declare circuit breaker in application.yaml
spring:
cloud:
gateway:
routes:
- id: my_route
uri: http://localhost:9722/
filters:
- name: CircuitBreaker
args:
name: myCircuitBreaker
fallbackUri: forward:/inCaseOfFailureUseThis
Declare the endpoint which will be called in the case of failure (a connection error, for example)
#RequestMapping("/inCaseOfFailureUseThis")
public Mono<ResponseEntity<String>> inCaseOfFailureUseThis() {
return Mono.just(ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body("body for service failure case"));
}

MongoDB auth failed in SPRINGBOOT , but anything work well in mongo SHELL, WHY?

Description:
I am unable to pass MongoDB authorization verification in springboot,but I can pass in the mongo shell environment.
I confirm that the password is correct in SpringBoot
It works well in Robo 3T client
Help:
Did I ignore any other operations?
Env: mongo shell
[dev#local ~]$ mongo 127.0.0.1:27017/wm-mongo -u wm-mongo -p SOh3TbYhx8ypJPxmt1oOfL
MongoDB shell version v3.4.20
connecting to: mongodb://127.0.0.1:27017/wm-mongo
MongoDB server version: 3.4.20
> show collections
ShuJuMoHeMessage
ShuJuMoHeReport
system.users
> db.ShuJuMoHeReport.find()
> db.ShuJuMoHeReport.count()
0
>
Env: Spring Boot
spring.data.mongodb.uri=mongodb://wm-mongo:SOh3TbYhx8ypJPxmt1oOfL#127.0.0.1:27017/wm-mongo
Caused by: com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='wm-mongo', source='wm-mongo', password=<hidden>, mechanismProperties={}}
at com.mongodb.internal.connection.SaslAuthenticator.wrapException(SaslAuthenticator.java:173)
at com.mongodb.internal.connection.SaslAuthenticator.access$300(SaslAuthenticator.java:40)
at com.mongodb.internal.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:70)
at com.mongodb.internal.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:47)
at com.mongodb.internal.connection.SaslAuthenticator.doAsSubject(SaslAuthenticator.java:179)
at com.mongodb.internal.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:47)
at com.mongodb.internal.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:151)
at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:64)
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:127)
at com.mongodb.internal.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:50)
at com.mongodb.internal.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:390)
at com.mongodb.internal.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:106)
at com.mongodb.internal.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:92)
at com.mongodb.internal.connection.DefaultServer.getConnection(DefaultServer.java:85)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:114)
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:451)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:415)
at com.mongodb.operation.CreateIndexesOperation.execute(CreateIndexesOperation.java:169)
at com.mongodb.operation.CreateIndexesOperation.execute(CreateIndexesOperation.java:70)
at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.execute(MongoClientDelegate.java:193)
at com.mongodb.client.internal.MongoCollectionImpl.executeCreateIndexes(MongoCollectionImpl.java:805)
at com.mongodb.client.internal.MongoCollectionImpl.createIndexes(MongoCollectionImpl.java:788)
at com.mongodb.client.internal.MongoCollectionImpl.createIndexes(MongoCollectionImpl.java:783)
at com.mongodb.client.internal.MongoCollectionImpl.createIndex(MongoCollectionImpl.java:768)
at org.springframework.data.mongodb.core.DefaultIndexOperations.lambda$ensureIndex$0(DefaultIndexOperations.java:135)
at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:535)
... 83 common frames omitted
Caused by: com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server 127.0.0.1:27017. The full response is { "ok" : 0.0, "errmsg" : "Authentication failed.", "code" : 18, "codeName" : "AuthenticationFailed" }
at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:179)
at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:293)
at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:255)
at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:83)
at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:33)
at com.mongodb.internal.connection.SaslAuthenticator.sendSaslContinue(SaslAuthenticator.java:134)
at com.mongodb.internal.connection.SaslAuthenticator.access$200(SaslAuthenticator.java:40)
at com.mongodb.internal.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:67)
... 106 common frames omitted

mongoDB async driver java - unable to connect with authentication

Recently we've updated our mongoDB with port 35489 and also with authentication and roles to the database.
I've granted readWrite and readWriteAnyDatabase roles for a user and can successfully connect from our c# coding from mentioning it from the web.config
My web.config:
<add key="MongoConnectionString" value="mongodb://readWriteUser:********#192.168.1.225:35489/admin" />
Now, my problem is I'm uanble to connect to mongoDB from java async driver and it is throwing an exception like
Exception
Exception in monitor thread while connecting to server localhost:35489 com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='AdminAllDatabases', source='admin', password=, mechanismProperties={}} at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:61) at com.mongodb.connection.DefaultAuthenticator.authenticate(DefaultAuthenticator.java:32) at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:99) at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:44) at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115) at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127) at java.lang.Thread.run(Unknown Source) Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server localhost:35489. The full response is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication failed." } at com.mongodb.connection.CommandHelper.createCommandFailureException(CommandHelper.java:170) at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:123) at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32) at com.mongodb.connection.SaslAuthenticator.sendSaslContinue(SaslAuthenticator.java:99) at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:58) ... 6 common frames omitted
My async java driver code:
public static final String DEFAULT_URI = "mongodb://readWriteUser:******#localhost:35489/";
public static synchronized ConnectionString getConnectionString()
{
if (connectionString == null)
{
connectionString = new ConnectionString(DEFAULT_URI);
}
return connectionString;
}
public static synchronized MongoClient getMongoClient()
{
if (mongoClient == null)
{
mongoClient = MongoClients.create(getConnectionString());
}
return mongoClient;
}
we've tried with both localhost and ip address, but nothing seems to work.
Can anyone suggest me the right way to do this?

Why does database initialization fail with "ERROR: improper qualified name (too many dotted names)"?

I'm using Scala 2.10 and Slick 2.10-1.0.1 with plain queries.
I tried to init a lazy evaluating database with Tomcat at localhost. For query evaluation I use PostgreSQL on port 5432.
As I tried to compile I got following error message:
ERROR org.quartz.core.JobRunShell - Job DEFAULT.MissionLifecycleManager threw an unhandled Exception: org.postgresql.util.PSQLException: ERROR: improper qualified name (too many dotted names)
Position: 16
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102) ~[postgresql-9.1-901.jdbc4.jar:na]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835) ~[postgresql-9.1-901.jdbc4.jar:na]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257) ~[postgresql-9.1-901.jdbc4.jar:na]
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500) ~[postgresql-9.1-901.jdbc4.jar:na]
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388) ~[postgresql-9.1-901.jdbc4.jar:na]
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:381) ~[postgresql-9.1-901.jdbc4.jar:na]
at scala.slick.jdbc.StatementInvoker.results(StatementInvoker.scala:34) ~[slick_2.10-1.0.1.jar:1.0.1]
at scala.slick.jdbc.StatementInvoker.elementsTo(StatementInvoker.scala:17) ~[slick_2.10-1.0.1.jar:1.0.1]
....
This is the code of my initialisation:
import com.weiglewilczek.slf4s.Logging
import scala.slick.driver.PostgresDriver._
import scala.slick.session.Database
import Database.threadLocalSession
import scala.slick.jdbc.{GetResult, StaticQuery => Q}
import scala.slick.driver.PostgresDriver.simple._
object SQLUtilities extends Logging with ServiceInjector {
lazy val db = init()
private def init() = {
info("Connecting to postgres database at localhost") //writes in a log file
val qe = Database.forURL("jdbc:postgresql://localhost:5432", "user", "pass", driver = "org.postgresql.Driver")
info("Connected to database")
qe
}
}
Obviously, something went wrong. So I think, my database initiallisation is not correct. Do I have forgotten some parameters? Are my parameters correct at all?
An another - not so fatal - question: If I have a body where I want to log something at the beginning and at the end of a method - let's say always the same log message, but different bodys - as a sign that I started and leaved this method... Is there a proper way to do this than this example here in init()?
Specify a database in your connection string "jdbc:postgresql://localhost:5432/somedatabase".
See http://jdbc.postgresql.org/documentation/head/connect.html