I need to catch errors during authentication (like wrong parameters). I find nothing about it. I have isolted the procedure with threads. But with this bad way, the user can't understand what goes wrong
Below, my code:
public static boolean access(String db, String ip, String usr, String pwd){
Map<String, String> persistenceMap = new HashMap<>();
persistenceMap.put("hibernate.ogm.datastore.database", db);
persistenceMap.put("hibernate.ogm.datastore.host", ip);
persistenceMap.put("hibernate.ogm.datastore.username", usr);
persistenceMap.put("hibernate.ogm.datastore.password", pwd);
Thread mainThread = Thread.currentThread();
Thread logThread = new Thread(() -> {
Connection.EMF = Persistence.createEntityManagerFactory("ogm-jpa-mongo", persistenceMap);
Connection.EM = Connection.EMF.createEntityManager();
Connection.isOpen = true;
});
Thread timeOut = new Thread( () -> {
try{ Thread.sleep( 5000 ); }
catch(InterruptedException ex){ }
mainThread.interrupt();
});
logThread.start();
timeOut.start();
try{ logThread.join(); }
catch(InterruptedException ex){ return false; }
Connection.TM = com.arjuna.ats.jta.TransactionManager.transactionManager();
return Connection.isOpen;
}
The problem is that when I insert worng parameters, it is thrown a MongoSecurityException. But i can't catch it, I can only read it on the monitor-thread. Any ideas?
I believe this is a result of the way your version of Hibernate catches the MongoSecurityException. I believe the MongoSecurityException is caught inside a nested try catch block.
The correct answer here is to update your Hibernate version to the latest release. However, if you would like to see that exception I think you can do the following.
String message = "";
try {
logThread.join();
} catch(Throwable e) {
throw e;
} catch(Exception e) {
message = e.getMessage();
}
If that doesn't work you might be able to chain as follows.
String message = "";
try {
logThread.join();
} catch(Throwable e) {
e.getCause();
e.getCause().getCause();
e.getCause()..getCause().getCause();
}
Related
I'm just getting started with java development. My ex-colleagues write a code(Code 1). I recently faced the timeout exception.
Code 1:
public String deleteFiles(String DOMAIN0, String USER, String PASSWORD, String SRC_DIR, String DST_DIR, String ext, String ipAddress, String dstRoot) {
SmbConfig config = SmbConfig.builder()
.withMultiProtocolNegotiate(true)
.withSigningRequired(true)
.withDfsEnabled(true)
.build();
SMBClient client = new SMBClient(config);
try {
Connection connection = client.connect(ipAddress);
AuthenticationContext ac1 = new AuthenticationContext(USER, PASSWORD.toCharArray(), DOMAIN);
Session session1 = connection1.authenticate(ac1);
DiskShare share1 = (DiskShare) session1.connectShare(SRC_DIR);
if (DST_DIR.contains(".")) {
if (fileCheckExists) {
share1.rm(DST_DIR);
else {
boolean fileCheckExists = share1.folderExists(DST_DIR);
if (fileCheckExists) {
share1.rmdir(DST_DIR0, true);
catch (TimeoutException et) {
return "Error:" + et.getMessage();
catch (Exception ex) {
return "Error:" + ex.getMessage();
return "Completed";
}
I added a TimeoutException catch block, but eclipse show the error message(Unreachable catch block for TimeoutException. This exception is never thrown from the try statement body).
catch (TimeoutException et) {
return "Error:" + et.getMessage();
}
how to handle the timeout exception. Please suggust me.
I have my client trying to lookup a JMS server. Here is my class JmsTest.java:
public static void main(String[] aInArgs)
{
boolean bContinue = true;
try
{
// determine JmsTest configuration based on command line arguments.
JmsTest jmsTest = parseCommandLine(aInArgs);
// connect to the server.
//jmsTest.initializeConnection();
Thread jmsFaultClientThread = null;
jmsFaultClientThread = new Thread("RUN") {
#Override
public void run() {
try
{
System.out.println("jmsFaultClient starting...");
jmsTest.initializeConnection();
}
catch (Exception e)
{
System.out.println("Exception: " + e.toString());
}
System.out.println("jmsFaultClient started.");
}
};
jmsFaultClientThread.start();
And my method initializeConnection():
public void initializeConnection() throws Exception
{
try
{
Hashtable env = new Hashtable();
env.put(Context.SECURITY_PRINCIPAL, user );
env.put(Context.SECURITY_CREDENTIALS, password);
jndiContext = new InitialContext(env);
System.out.println("Initializing Topic (" + strName + ")...");
try
{
topicConnectionFactory = (TopicConnectionFactory) jndiContext.lookup(CONNECTION_FACTORY);
}
catch (Exception e)
{
topicConnectionFactory = getExternalFactory(jndiContext);
}
When I run jmsTest.initializeConnection() like this everything works, and the lookup is working. However, the problem is when it's run inside the thread it gets stuck without any exception or any error. It's just stuck.
In my logs i'm seeing:
System.out.println("Initializing Topic (" + strName + ")...");
Which is a log inside my try / catch, and nothing else.
In dependencies, I have 2 jars, contening javax\jms. With the first one it's work inside the thread, and with the second one it doesn't. But I don't know why my jar can "block" the thread.
UPDATE 1 :
#AnotherJavaprogrammer said me to print the error:
here is my lookup with print :
try
{
getLogger().debug("TRY context");
Context lInitialContext = (Context) jndiContext.lookup(JMS_CONTEXT);
lInitialContext.lookup("SAMConnectionFactory");
getLogger().debug("END trying context");
}
catch (Exception e)
{
getLogger().debug("Catch");
getLogger().debug("Exception", e);
}
The output from getLogger().debug("END trying context") never comes, and I don't see the getLogger().debug("Catch") one either. So it appears I'm really "stuck" inside the lookup(). I can't go further, and it doesn't throw an exception.
A project source code has a Java method for SQL handling. The method does work, but it uses a questionable workaround: try-catch block at the very end of the method for normal execution. What is the correct way to implement it?
public void run() {
if (running) {
return;
}
running = true;
while(null == Common.server || null == Common.database || !ConnectionsPool.isInitialized()) {
// Wait until the database is set before continuing...
try {
Thread.sleep(1000);
}
catch(Exception ex) {}
}
while(running) {
final Connections cs = ConnectionsPool.getConnections();
Connection c = null;
while(!entries.isEmpty()) {
if (null == c) {
c = cs.getConnection();
}
SQLLogEntry entry = entries.remove();
if (null != entry) {
try {
write(entry, c); //find usages
}
catch (SQLException ex) {
writeLogFile("Could not write entry to SQL", ex);
}
}
}
if (null != c) {
try {
c.commit();
}
catch (SQLException ex) {
writeLogFile("Could commit to SQL", ex);
try {
c.rollback();
}
catch (SQLException ex1) {
}
// log
final StringWriter err = new StringWriter();
ex.printStackTrace(new PrintWriter(err));
EditorTransactionUtil.writeLogFile(err.toString());
// for user
final String msg = "Exception: " + EditorUtil.getErrorMessage(ex.getMessage());
try {
SwingUtilities.invokeAndWait(() -> {
JOptionPane.showMessageDialog(null, msg);
});
}
catch (Throwable ex1) {
}
}
finally {
cs.returnConnection(c);
}
c = null;
}
synchronized(entries) {
try {
entries.wait(1000);
}
catch (InterruptedException ex) {
// This is a workaround to process this loop...
}
}
}
writeLogFile("SQLMsgLogger run loop stopping...");
}
Problems with this code start here.
If(running) return;
running=true;
This is clearly an attempt to make sure that only one thread executes. This is a wrong way to check concurrency. Second tread might kick in right when if check ended, but assignment didn't start yet. You need to use syncronizible interface.
As for the disposed try catch block - as Konrad pointed out it will not be executed without Thread.interrupt() call. It might be dead code left from previous versions.
I'm trying to make a call that might throw an exception due to server being down.
this is what i want to accomplish:
Server server = serverQueue.poll();
try {
if (server==null){return null}
server.makeConnection();
} catch (Exception e) {
// try another server
server = serverQueue.poll();
// now return to try block?
}
So i have 5 servers and maybe in later stage i'll add some more. So i want to connect to
anyone of them in this manner. How can i return to the try block? is there anything such as a statement like this below in java?:
Server server = serverQueue.poll();
outerBlock:
try {
if (server==null){return null}
server.makeConnection();
} catch (Exception e) {
// try another server
server = serverQueue.poll();
continue outerBlock;
}
Basically a loop:
Server server = serverQueue.poll();
boolean connected = false;
while (!connected) {
if (server == null) {
return null;
}
try {
server.makeConnection();
connected = true;
} catch (Exception e) {
// Presumably log something here, for management info
// try another server
server = serverQueue.poll();
}
}
Or to avoid the duplication:
Server server;
boolean connected = false;
while (!connected) {
server = serverQueue.poll();
if (server == null) {
return null;
}
try {
server.makeConnection();
connected = true;
} catch (Exception e) {
// Presumably log something here, for management info
}
}
You might consider isolating the "find a server" part of that into its own function.
You need to put your try block inside a simple loop, either while or for.
ou can use a for loop
Server server;
for(int i=0;i<=numberOFServers-1;i++){
server = serverQueue.poll();
try {
if (server==null){return null}
server.makeConnection();
} catch (Exception e) {
System.out.println("Server : " +i+ " could not establish connection");
}
}
I am trying to make a monitoring application for a FTP server using FTP4J(referred to as client in the code example).
It connects to a FTP, logs in, creates a file locally, uploads file, downloads file, validates the files are the same, cleans up files on ftp and locally and disconnects.
All this is already made but my question is how do I best log what has happened and break when an error is detected?
The simple solution I could think of was to make a Boolean that shows if previous steps where successful and only do next step if they where.
StringBuilder sb = new StringBuilder();
boolean noError = true;
// Connect to FTP
try {
client.connect(hostname, port);
} catch (Exception e) {
noError = false;
sb.append("failed to connect<br>");
}
//Logging in to FTP
if(noError) {
try {
client.login(username, password);
} catch (Exception e) {
noError = false;
sb.append("failed to login<br>");
}
}
...
// Close connection
if(client.isConnected()) {
try {
client.disconnect(true);
} catch (Exception e) {
sb.append("failed to disconnect<br>");
}
}
another solution I could think of was nested try/catch but that looked even worse, is there a better way of doing this?
The solution is simple: don't catch the exception. As soon as an exception is thrown and is not caught, the whole process will stop. Or catch it but transform it into your own exception with the appropriate error message, and throw this exception.
Side note: you should use a boolean and not a Boolean to store a non-nullable boolean value.
StringBuilder sb = new StringBuilder();
Boolean noError = true;
// Connect to FTP
try {
client.connect(hostname, port);
client.login(username, password);
} catch (ConnectException ce) {
sb.append("Couldn't connect: ");
sb.append(ce.getMessage);
} catch (LoginException le) {
sb.append("Couldn't login: ");
sb.append(le.getMessage);
} finally {
if(client.isConnected()) {
try {
client.disconnect(true);
} catch (Exception e) {
sb.append("failed to disconnect<br>");
}
}