How can I catch exceptions caused by following code?
try {
MongoCredential credential = MongoCredential.createCredential(
cu.getName(),
"admin",
cu.getPassword().toCharArray());
ServerAddress address = new ServerAddress("localhost", 27017);
mongoClient = new MongoClient(address, Arrays.asList(credential));
} catch (MongoSecurityException e) {
System.out.println("test");
}
I do get exceptions in stacktrace, but I'm not able to catch them though.
Mai 29, 2017 1:04:37 AM com.mongodb.diagnostics.logging.JULLogger log
INFORMATION: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Mai 29, 2017 1:04:37 AM com.mongodb.diagnostics.logging.JULLogger log
INFORMATION: Exception in monitor thread while connecting to server localhost:27017
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='root', source='admin', password=, mechanismProperties={}}
at com.mongodb.connection.SaslAuthenticator.wrapInMongoSecurityException(SaslAuthenticator.java:157)
at com.mongodb.connection.SaslAuthenticator.access$200(SaslAuthenticator.java:37)
at com.mongodb.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:66)
at com.mongodb.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:44)
at com.mongodb.connection.SaslAuthenticator.doAsSubject(SaslAuthenticator.java:162)
at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:44)
at com.mongodb.connection.DefaultAuthenticator.authenticate(DefaultAuthenticator.java:32)
at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:109)
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:46)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:116)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:113)
at java.lang.Thread.run(Unknown Source)
Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server localhost: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.sendSaslContinue(SaslAuthenticator.java:121)
at com.mongodb.connection.SaslAuthenticator.access$100(SaslAuthenticator.java:37)
at com.mongodb.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:63)
... 9 more
`
It seems you have an authentication problem:
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='root', source='admin', password=, mechanismProperties={}} at ...`
Looking at your code I see it's called MongoCredential.createCredential() which accepts 3 parameters (user, database and password).
Assuming that your credentials are correct I strongly suspect that admin is NOT your database name.
Related
I am working with java program connected with MongoDB when I run the program it will show an error but code is working.
MongoDB has a database called MongoDB and inside that, there is a collection called seatbooking with two columns(name,seatnumber).
This is my code:
MongoClient mongoClient = new MongoClient("localhost", 27017);
System.out.println("connection is established");
MongoDatabase mongoDatabase = mongoClient.getDatabase("MongoDB");
MongoCollection mongoCollection = mongoDatabase.getCollection("seatbooking");
Document document = new Document("name","shenal");
document.append("seatnumber",20);
mongoCollection.insertOne(document);
when I run this code my output is:
> Mar 09, 2020 12:41:36 PM
> com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster created
> with settings {hosts=[localhost:27017], mode=SINGLE,
> requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms',
> maxWaitQueueSize=500}
> **connection is established** Mar 09, 2020 12:41:36 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster
> description not yet available. Waiting for 30000 ms before timing out
> Mar 09, 2020 12:41:36 PM com.mongodb.diagnostics.logging.JULLogger log
> INFO: Opened connection [connectionId{localValue:1, serverValue:309}]
> to localhost:27017 Mar 09, 2020 12:41:36 PM
> com.mongodb.diagnostics.logging.JULLogger log INFO: Monitor thread
> successfully connected to server with description
> ServerDescription{address=localhost:27017, type=STANDALONE,
> state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 2,
> 2]}, minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216,
> logicalSessionTimeoutMinutes=30, roundTripTimeNanos=5168100} Mar 09,
> 2020 12:41:36 PM com.mongodb.diagnostics.logging.JULLogger log INFO:
> Opened connection [connectionId{localValue:2, serverValue:310}] to
> localhost:27017
The logging output doesn't show any result for the insertOne operation.
If you are using MongoDB Java Driver version prior to 4.0, there is no acknowledgement object returned. But, the version 4's insertOne method returns a InsertOneResult object. This is a new feature in 4.0 (in prior version's the method returned a void).
You can use the following code to check the insert's outcome as follows (with version 4.0):
try {
InsertOneResult insertResult = collection.insertOne(document);
System.out.println("Document inserted with ID: " + insertResult.getInsertedId());
}
catch(MongoWriteException e) {
// write failure happened, handle it here...
}
I'm working on my Telegram bot. I know, in my countries Telegram is locked, so I decide to connect to Telegram Bot API through proxy. When I try to run this code:
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.meta.ApiContext;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
public class SharperBotApp {
private static final String PROXY_HOST = "89.200.150.35";
private static final int PROXY_PORT = 37499;//TODO
public static void main(String[] args) {
ApiContextInitializer.init();
TelegramBotsApi botsApi = new TelegramBotsApi();
DefaultBotOptions botOptions = ApiContext.getInstance(DefaultBotOptions.class);
botOptions.setProxyHost(PROXY_HOST);
botOptions.setProxyPort(PROXY_PORT);
botOptions.setProxyType(DefaultBotOptions.ProxyType.SOCKS4);
try {
botsApi.registerBot(new SharperBot(botOptions));
} catch (TelegramApiRequestException e) {
e.printStackTrace();
}
}
}
I'm getting this stack trace:
Jun 12, 2019 11:56:51 AM org.apache.http.impl.execchain.RetryExec execute
INFO: Retrying request to {s}->https://api.telegram.org:443
Jun 12, 2019 11:56:51 AM org.apache.http.impl.execchain.RetryExec execute
INFO: I/O exception (java.net.SocketException) caught when processing request to {s}->https://api.telegram.org:443: Malformed reply from SOCKS server
Jun 12, 2019 11:56:51 AM org.apache.http.impl.execchain.RetryExec execute
INFO: Retrying request to {s}->https://api.telegram.org:443
Jun 12, 2019 11:56:52 AM org.apache.http.impl.execchain.RetryExec execute
INFO: I/O exception (java.net.SocketException) caught when processing request to {s}->https://api.telegram.org:443: Malformed reply from SOCKS server
Jun 12, 2019 11:56:52 AM org.apache.http.impl.execchain.RetryExec execute
INFO: Retrying request to {s}->https://api.telegram.org:443
org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException: Error removing old webhook
at org.telegram.telegrambots.util.WebhookUtils.clearWebhook(WebhookUtils.java:79)
at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:25)
at org.telegram.telegrambots.meta.TelegramBotsApi.registerBot(TelegramBotsApi.java:120)
at bot.SharperBotApp.main(SharperBotApp.java:24)
Caused by: org.telegram.telegrambots.meta.exceptions.TelegramApiException: Unable to execute deleteWebhook method
at org.telegram.telegrambots.bots.DefaultAbsSender.sendApiMethod(DefaultAbsSender.java:719)
at org.telegram.telegrambots.meta.bots.AbsSender.execute(AbsSender.java:47)
at org.telegram.telegrambots.util.WebhookUtils.clearWebhook(WebhookUtils.java:74)
... 3 more
Caused by: java.net.SocketException: Malformed reply from SOCKS server
at java.net.SocksSocketImpl.readSocksReply(SocksSocketImpl.java:129)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:459)
at java.net.Socket.connect(Socket.java:589)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:339)
at org.telegram.telegrambots.facilities.proxysocketfactorys.SocksSSLConnectionSocketFactory.connectSocket(SocksSSLConnectionSocketFactory.java:41)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:359)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:381)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:111)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.telegram.telegrambots.bots.DefaultAbsSender.sendHttpPostRequest(DefaultAbsSender.java:765)
at org.telegram.telegrambots.bots.DefaultAbsSender.sendMethodRequest(DefaultAbsSender.java:761)
at org.telegram.telegrambots.bots.DefaultAbsSender.sendApiMethod(DefaultAbsSender.java:716)
... 5 more
Process finished with exit code 0
I googled it and found that people advise to use proxy... But I've already done it! So I decided to use VPN. I installed windscribe on my laptop but then also got this exception. What should I try to do? Maybe, I'm doing something wrong? (There is Debian 9 installed on my laptop).
All you need is just to use tor proxy:
public class MyApplication {
public static void main(String[] args) {
System.getProperties().put("proxySet", true);
System.getProperties().put("socksProxyHost", 127.0.0.1);
System.getProperties().put("socksProxyPort", 9050);
}
}
But previously you should install tor service:
sudo apt-get install tor
I'm customizing couchbase sql importer open source code in maven project.
this is my code.
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder()
.socketConnectTimeout((int) TimeUnit.SECONDS.toMillis(45))
.connectTimeout(TimeUnit.SECONDS.toMillis(60))
.build();
cluster = CouchbaseCluster.create(env,"couchbase-dev.thisisdmg.com:8091");
bucket = cluster.openBucket(bucketName);
com.couchbase.client.java.query.Statement statement = select("*").from(i("sales_agent")).where("meta(t).id = 'appointments_appointment:1'").limit(50).offset(0);
JsonObject placeholderValues = JsonObject.create().put("age", 22);
for (N1qlQueryRow row : bucket.query(N1qlQuery.parameterized(statement, placeholderValues))) {
System.out.println(row);
}
When I send the query to server, I'm getting bellow error.
Mar 28, 2017 4:40:28 PM com.couchbase.client.core.endpoint.AbstractEndpoint$2 onSuccess
WARNING: [null][QueryEndpoint]: Could not connect to remote socket.
Mar 28, 2017 4:40:28 PM com.couchbase.client.core.endpoint.AbstractEndpoint$2 onSuccess
WARNING: [null][QueryEndpoint]: Could not connect to endpoint, retrying with delay 4096 MILLISECONDS:
com.couchbase.client.deps.io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection timed out: no further information: couchbase-dev.thisisdmg.com/5.9.216.200:8093
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
at com.couchbase.client.deps.io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:257)
at com.couchbase.client.deps.io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:291)
at com.couchbase.client.deps.io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:631)
at com.couchbase.client.deps.io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:566)
at com.couchbase.client.deps.io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:480)
at com.couchbase.client.deps.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:442)
at com.couchbase.client.deps.io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:131)
at com.couchbase.client.deps.io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
at java.lang.Thread.run(Thread.java:745)
Please help me, how can I fix this problem.
the following scala code seems to throw a java exception, but keeps on executing other lines of code :
object FirstMain {
def main(args: Array[String]): Unit = {
var mongoClient : MongoClient = MongoClients.create() // this is a java method
println("hello")
Thread.sleep(500)
println("hello2")
}
console output :
Feb 17, 2017 7:57:49 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Feb 17, 2017 7:57:50 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Exception in monitor thread while connecting to server localhost:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.AsynchronousSocketChannelStream$OpenCompletionHandler.failed(AsynchronousSocketChannelStream.java:253)
[...] // stacktrace
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
[...] // stacktrace
hello
hello2
I tried using a try/catch block to deal with the exception but I get the same output as inthe fist code snippet. The following code never prints "do something !" :
object FirstMain {
def main(args: Array[String]): Unit = {
try{
var mongoClient : MongoClient = MongoClients.create()
}
catch {
case e : MongoSocketOpenException => println("do Something")
}
println("hello")
Thread.sleep(500)
println("hello2")
}
}
Anyone knows how to catch exception thrown by async java code in scala ?
Thanks in advance for your help.
This has little to do with async or scala. The method you are calling is synchronous. It doesn't return a Future or other async type. The client you are creating is async but the method is not. The reason that you cannot catch the exception is because Mongo is likely already catching the exception and not letting it bubble up.
I am developing an API... and after requested several endpoints the server show me this message...
WARN: SQL Error: 0, SQLState: null Jun 24, 2016 9:51:45 PM
org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions ERROR:
HikariPool-1 - Connection is not available, request timed out after 10000ms. Jun
24, 2016 9:51:45 PM com.healthymama.utils.DEVLoggingFilter log INFO: 967 *
Server responded with a response on thread grizzly-http-server-2
The project is made with hibernate, mysql and Hikari... Could you help me? Thanks!
Here the configuration:
url = String.format("jdbc:mysql://%s:%s/%s?autoReconnect=true", host, port, bundle.getString("db.database"));
configuration
.setProperty("hibernate.order_updates", "true")
.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
.setProperty("hibernate.hbm2ddl.auto", "update")
.setProperty("hibernate.connection.provider_class", "com.zaxxer.hikari.hibernate.HikariConnectionProvider")
.setProperty("hibernate.hikari.dataSourceClassName", "com.mysql.jdbc.jdbc2.optional.MysqlDataSource")
.setProperty("hibernate.hikari.dataSource.url", url)
.setProperty("hibernate.hikari.dataSource.user", username)
.setProperty("hibernate.hikari.dataSource.password", password)
.setProperty("hibernate.hikari.dataSource.cachePrepStmts", "true")
.setProperty("hibernate.hikari.dataSource.prepStmtCacheSize", "250")
.setProperty("hibernate.hikari.dataSource.prepStmtCacheSqlLimit", "2048")
.setProperty("hibernate.hikari.minimumIdle", "5")
.setProperty("hibernate.hikari.minimumIdle", "5")
.setProperty("hibernate.hikari.maximumPoolSize", "10")
.setProperty("hibernate.hikari.idleTimeout", "30000")
.setProperty("hibernate.hikari.connectionTestQuery", "SELECT 1")
.setProperty("hibernate.hikari.connectionTimeout", "10000");