Java exception does not propagate to Scala - java

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.

Related

MarkLogic Java API Exception Throwing Method

In Java API, No Exception is thrown, albeit erroneous transaction:
try {
…………………………………
logger.info("Delete Document " + uri);
docMgr.delete("rocky-mountains");
System.out.println("Deleted");
} catch (Exception e) {
logger.error("Exception : " + e.toString() );
}
Document rocky-mountains doesn’t exist, however, the API happily declares Deleted:
Jul 05, 2020 9:35:04 PM com.fc.allegro.DeleteDocument deleteDocument
INFO: Delete Document rocky-mountains
Jul 05, 2020 9:35:04 PM com.marklogic.client.impl.DocumentManagerImpl delete
INFO: Deleting rocky-mountains
Deleted
In Query Console, eval detects and throws error:
[1.0-ml] XDMP-DOCNOTFOUND: xdmp:document-delete("rocky-mountains") -- Document not found
As the lesser of two evils, DMSDK implies no document deleted but still doesn’t throw exception:
QueryBatcher batcher = dmManager.newQueryBatcher(new StructuredQueryBuilder().document("rocky-mountains"));
batcher.onUrisReady(new DeleteListener())
.onQueryFailure( exception -> exception.printStackTrace() );
Result:
Jul 05, 2020 9:52:07 PM com.marklogic.client.datamovement.impl.QueryBatcherImpl withForestConfig
INFO: (withForestConfig) Using forests on [localhost] hosts for "allegro"
Batch Deleted
INFO: Job complete, jobBatchNumber=1, jobResultsSoFar=0
I tried checked and unchecked exceptions, but to no avail.
Which MarkLogic Class and Method does enforce throwing exceptions and mitigate risk?
A query transaction via Java API:
Failure:
Success:
There is an important difference between running xdmp:document-delete and using Java API to delete a document. The Java API is a wrapper for the MarkLogic REST-API, which follows the rules for a RESTful API. One important rule of a RESTful API is that calls are expected to be idempotent. In short that means that you should be able to run the call twice and get same reply both times. That is why calls to insert, update, and delete don't throw errors if the document does or does not exist.
See also for instance: https://restfulapi.net/http-methods/#delete
I'd recommend using Data Services, or custom REST extensions if you want your app to be more strict.
HTH!

How to catch exceptions when connecting to MongoDB in Java?

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.

Thread is not getting stopped while polling using camel file poller

I am trying to implement simple file polling from one folder to another using camel 2.14 version. I have used pollEnrich with basic timer to poll every 30 seconds. But whenever I tried to stop the tomcat 7.0 server I am getting the logs as:
Catalina.logs
SEVERE: The web application [/CamelPoller] appears to have started a thread named [Camel (camel-1) thread #0 - timer://myTimer] but has failed to stop it. This is very likely to create a memory leak.
Aug 14, 2015 2:50:06 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/CamelPoller] appears to have started a thread named [Camel (camel-1) thread #1 - file://D:/Input] but has failed to stop it. This is very likely to create a memory leak.
FilePollerDemo.java
public class FilePollerDemo {
public FilePollerDemo() {
CamelContext context = new DefaultCamelContext();
try {
context.addRoutes(new RouteBuilder() {
public void configure() {
from("timer://myTimer?period=30000")
.pollEnrich("file://D:/Input?fileName=test.txt")
.to("file://D:/Output");
}
});
context.start();
// context.stop();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
I have commented out the context.stop(), because if I am using it, the file polling is not happening or if I used like this :
context.start();
thread.sleep(30000);
context.stop();
then the poller run only for once.
Please help me I am new to camel.

MongoDB Java API com.mongodb.DBPortPool gotError

I'm currently working on a project using the MongoDB Java API. I have been working on this project for a while, but have recently come across an issue that I cannot resolve. I am trying to make a database system that is fault tolerant. To simulate a database crashing, I have my program connect to a Mongodb server that I have made, execute a simple read or write, and then shut down the database server. I had originally thought that this would cause certain methods that I am calling to throw a MongoException that I could catch and then recover from the database crash. However, I am getting a strange stack trace that says I am throwing an EOFException, among other things. Below is the stack trace itself.
Mar 04, 2013 8:06:15 PM com.mongodb.DBPortPool gotError
WARNING: emptying DBPortPool to polaris.cs.wcu.edu/152.30.5.5:12345 b/c of error
java.io.EOFException
at org.bson.io.Bits.readFully(Bits.java:48)
at org.bson.io.Bits.readFully(Bits.java:33)
at org.bson.io.Bits.readFully(Bits.java:28)
at com.mongodb.Response.<init>(Response.java:40)
at com.mongodb.DBPort.go(DBPort.java:124)
at com.mongodb.DBPort.call(DBPort.java:74)
at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:282)
at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:256)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:289)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:274)
at com.mongodb.DBCursor._check(DBCursor.java:368)
at com.mongodb.DBCursor._hasNext(DBCursor.java:459)
at com.mongodb.DBCursor.hasNext(DBCursor.java:484)
at edu.wcu.cs.capstone.view.AbstractViewEngine.getView(AbstractViewEngine.java:57)
at edu.wcu.cs.capstone.transaction.ServerTransactionManager.getView(ServerTransactionManager.java:52)
at edu.wcu.cs.capstone.transaction.ServerTransactionManager.run(ServerTransactionManager.java:183)
at java.lang.Thread.run(Thread.java:722)
Caught exception
Mar 04, 2013 8:06:15 PM com.mongodb.DBPortPool gotError
WARNING: emptying DBPortPool to polaris.cs.wcu.edu/152.30.5.5:12345 b/c of error
java.io.IOException: couldn't connect to [polaris.cs.wcu.edu/152.30.5.5:12345] bc:java.net.ConnectException: Connec
at com.mongodb.DBPort._open(DBPort.java:214)
at com.mongodb.DBPort.go(DBPort.java:107)
at com.mongodb.DBPort.call(DBPort.java:74)
at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:282)
at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:256)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:289)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:274)
at com.mongodb.DBCursor._check(DBCursor.java:368)
at com.mongodb.DBCursor._hasNext(DBCursor.java:459)
at com.mongodb.DBCursor.hasNext(DBCursor.java:484)
at edu.wcu.cs.capstone.view.AbstractViewEngine.getView(AbstractViewEngine.java:61)
at edu.wcu.cs.capstone.transaction.ServerTransactionManager.getView(ServerTransactionManager.java:52)
at edu.wcu.cs.capstone.transaction.ServerTransactionManager.run(ServerTransactionManager.java:183)
at java.lang.Thread.run(Thread.java:722)
DB is down.
Exception in thread "Thread-3" java.lang.NullPointerException
at edu.wcu.cs.capstone.transaction.ServerTransactionManager.run(ServerTransactionManager.java:184)
at java.lang.Thread.run(Thread.java:722)
The Caught Exception and DB is down. are print statements I am using to verify I am catching certain exceptions. Here is the relevant code:
public View getView(Mongo mongo, Query query) throws MongoException,
EOFException {
String connected = "";
try {
connected = mongo.getConnectPoint();
} catch (Exception e) {
throw new MongoException("Error.");
}
System.out.println("Connected: " + connected);
DB db = mongo.getDB(query.getServer());
List<DBObject> viewList = new ArrayList<DBObject>();
DBCollection collection = db.getCollection(query.getCollection());
DBCursor cursor = collection.find(query.getQuery(), excludeID);
try {
cursor.hasNext();
} catch (Exception e) {
System.out.println("Caught exception");
}
while (cursor.hasNext()) {
viewList.add(cursor.next());
}
return new View(viewList);
}
As you can see, the error is occurring when I call cursor.hasNext(). I am also actually still catching the exception that is being thrown because of the Caught exception. However, I am still getting a stack trace as if it was not being caught. I am suspicious that this has something to do with the DBPortPoolgotError() method, but I have looked at the code for this method, and cannot determine what it is actually doing or even how it is being called. (GrepCode link)
As stated above, I thought the behavior for this type of code would have been to throw a MongoException when a call on that specific Mongo object failed because the database was no longer active. Any help that anyone could provide would be greatly appreciated!
this happens due to the driver loosing connection. Here is an issue on the mongo bug tracker referring to it https://jira.mongodb.org/browse/JAVA-481
I had the same issue. It was because I restarted mongod without restart my java server (tomcat in my case). Restarting tomcat solved this issue because the mongo driver was lost

InvalidName exception in jacorb

I am using Jacorb for corba implementation. I have started the NS on port 900.
When I am trying to start the server I am getting following exception
D:\eclipse_workspace\WorkSpace\corba\bin>jaco hello.MyServer -DORBInitRef.NameService=jacorb::localhost:900
org.jacorb.orb.ORB
Feb 14, 2013 4:00:07 PM org.jacorb.config.JacORBConfiguration <init>
WARNING: no properties found for configuration jacorb
Feb 14, 2013 4:00:07 PM org.jacorb.orb.ORBSingleton <init>
INFO: created ORBSingleton
Exception in thread "main" org.omg.CORBA.ORBPackage.InvalidName: IDL:omg.org/CORBA/ORB/InvalidName:1.0
at org.jacorb.orb.ORB.resolve_initial_references(ORB.java:1371)
at hello.MyServer.main(MyServer.java:15)
Code is as following
public static void main(String[] args) throws Exception{
Properties props = new Properties();
props.setProperty("ORBInitRef","NameService=jacorb::localhost:900");
System.out.println(System.getProperty("org.omg.CORBA.ORBClass"));
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, props);
org.omg.CORBA.Object o = orb.resolve_initial_references("NameService");
NamingContextExt nc = NamingContextExtHelper.narrow( o );
}
Could someone tell whats the problem here?
The NameService reference has to be either a reference to a file containing an IOR, e.g., file://tmp/NS_Ref or an URL, e.g., http://www.testme.not/NS_Ref or just a corbaloc/corbaname URL, e.g., corbaloc:iiop:1.2#host1:3075/NameService
The last one is most common. You can shorten it, for example, to corbaloc::localhost:900/NameService
More information to corbaloc could be found at http://www.ciaranmchale.com/corba-explained-simply/the-corbaloc-and-corbaname-urls.html

Categories

Resources