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.
Related
sonar issue
private void getGtcj(String gtcjStatusValue, String strArchiveReqd) throws Exception {
XPathHelper activationConfigParser = null;
try {
activationConfigParser = ConfigUtil.getInstance().getConfigParser(new URL((V21Constants.FILE
+ System.getProperty(V21Constants.USER_DIR) + "/vServe21/config/ActivationParameters.xml")));
} catch (Exception e) {
log.error(e.getMessage());
}
StringBuffer useGTCJSolution = new StringBuffer();
useGTCJSolution.append(XPathConstants.ACTIVATION_CONFIG_ACTIVATION_PARAM)
.append("/parameter[#name = '").append(XPathConstants.TAG_NAME_USE_GTCJ_SOLUTION)
.append("']");
String useGTCJSolutionStr = activationConfigParser.evaluateXPath(useGTCJSolution.toString());
log.debug("useGTCJSolutionStr value:" + useGTCJSolutionStr);
if (useGTCJSolutionStr != null && useGTCJSolutionStr.trim().equalsIgnoreCase(V21Constants.YES)
&& (gtcjStatusValue.equalsIgnoreCase(Statuses.ACTIVATION_SUCCESS)
|| gtcjStatusValue.equalsIgnoreCase(Statuses.ROLLBACK_SUCCESS)
|| gtcjStatusValue.equalsIgnoreCase("Rollback Failure"))) {
log.debug("No need to archive and send response from here.");
} else {
log.debug("inside GTCJSolution for GTCJ orders...Archiving and sending response xml");
if (strArchiveReqd != null && "Yes".equalsIgnoreCase(strArchiveReqd)) {
archiveXML(responseFileName, V21Constants.VIF_ARCHIVE_RESPONSE_XML_PATH);
}
// sending the response XML
response = new Response();
response.sendResponseXML(properties, responseXml, bNBSConnectivityFlag, queueName, address);
}
}
I figured out there should be a finally block after catch, but I don't know what to add inside the finally block. Or is there any other solution?
When you create the variable activationCOnfigParser you're in a try/Catch block. You can bypass this error :
private void getGtcj(String gtcjStatusValue, String strArchiveReqd) throws Exception {
XPathHelper activationConfigParser = null;
try {
activationConfigParser = ConfigUtil.getInstance().getConfigParser(new URL((V21Constants.FILE
+ System.getProperty(V21Constants.USER_DIR) + "/vServe21/config/ActivationParameters.xml")));
} catch (Exception e) {
actionConfigParser = <DEFAULT VALUE>
log.error(e.getMessage());
}
In catch block there is that you can replace with a value that actionConfigParser has to assuming in case of exception.
I am trying to recieve SNMP v3 traps from a device, using Adventnet.
When getting a trap I see the following AdventNet exception thrown:
Exception while constructing message after receiving PDU. Dropping this PDU received from xxx.xxx.xxx.xxx. com.adventnet.snmp.snmp2.SnmpException: Parse Header: Incorrect Scoped data
If I monitor the traps using NG-Soft browser the traps are recieved correctly.
Here is my code:
private void initV3Parameters(NEData neData) throws InterruptedException
{
logger.debug("in.");
try
{
logger.debug(".in");
SnmpAPI m_api = new SnmpAPI();
m_api.setDebug( true );
SnmpSession m_session = new SnmpSession(m_api);
m_session.addSnmpClient(this);
UDPProtocolOptions m_udpOpt = new UDPProtocolOptions();
m_udpOpt.setRemoteHost(neData.m_szIpAddress);
m_session.setProtocolOptions(m_udpOpt);
try
{
m_session.open();
String message="Succes to bind port: "+session.getLocalPort();
logger.info(message);
System.out.println(message);
}
catch (Exception ex)
{
String message = "Failed to open session - Port in use or permission denied. \n Message- "+ ex.getMessage() + "\n Will exit from Trap process. ";
logger.error(message, ex);
System.err.println(message);
throw new RuntimeException(message);
}
SnmpEngineEntry engineentry = new SnmpEngineEntry(neData.m_szIpAddress, m_udpOpt.getRemotePort());
SnmpEngineTable enginetable = m_api.getSnmpEngine();
enginetable.addEntry(engineentry);
try
{
engineentry.discoverSnmpEngineID(m_session,10000,3);
}
catch (Exception e)
{
logger.error("Failed to discover snmp EngineID. " + e.getMessage());
printToLog("failed",neData);
return;
}
USMUserEntry entry = new USMUserEntry(neData.usmUser.getBytes(), engineentry.getEngineID());
entry.setAuthProtocol(Integer.parseInt(neData.authProtocol));
entry.setAuthPassword(neData.authPassword.getBytes());
entry.setPrivProtocol(Integer.parseInt(neData.privProtocol));
entry.setPrivPassword(neData.privPassword.getBytes());
byte[] authKey = USMUtils.password_to_key(entry.getAuthProtocol(),
neData.authPassword.getBytes(),
neData.authPassword.getBytes().length,
engineentry.getEngineID());
entry.setAuthKey(authKey);
byte[] privKey = USMUtils.password_to_key(entry.getAuthProtocol(),
neData.privPassword.getBytes(),
neData.privPassword.getBytes().length,
engineentry.getEngineID());
entry.setPrivKey(privKey);
entry.setEngineEntry(engineentry);
entry.setSecurityLevel(Snmp3Message.AUTH_PRIV);
SecurityProvider provider = m_api.getSecurityProvider();
USMUserTable userTable = (USMUserTable) provider.getTable(3);
userTable.addEntry(entry);
entry.timeSynchronize(m_session, m_udpOpt);
printToLog("success",neData);
}
catch (Exception exp)
{
logger.error(exp.getMessage()+" for ip = "+neData.m_szIpAddress,exp);
discoveredDeque.put(neData);
printToLog("failed",neData);
}
}
I've also tried Using High-Level API
USMUtils.init_v3_parameters(
neData.usmUser,
null,
Integer.valueOf(neData.authProtocol),
neData.authPassword,
neData.privPassword,
udpOptions,
session,
false,
Integer.valueOf(neData.privProtocol));
In this case I see the trap using public void debugPrint (String debugOutput)
and no exception is throwing.
But there is nothing in the callback
Any advice will be welcome!!!
It turns out that there was a problem with the time synchronization of the device that sends the traps and my code worked perfectly fine.
probably NG-Soft doesn't care from time sync...
I attach my code here in case any of you will need it in the future...
private SnmpSession session;
/**
* Create a listener for trap version 1-2
*/
public void trapsListener ()
{
logger.debug(".in");
SnmpAPI api = new SnmpAPI();
// api.setDebug( true );
session = new SnmpSession(api);
session.addSnmpClient(this);
UDPProtocolOptions udpOpt = new UDPProtocolOptions();
udpOpt.setLocalPort(TRAP_PORT);
session.setProtocolOptions(udpOpt);
try
{
session.open();
String message="Succes to bind port: "+session.getLocalPort();
logger.info(message);
System.out.println(message);
}
catch (Exception ex)
{
String message = "Failed to open session - Port in use or permission denied. \n Message- "+ ex.getMessage() + "\n Will exit from Trap process. ";
logger.error(message, ex);
System.err.println(message);
throw new RuntimeException(message);
}
}
/**
* For each new device
* 1) discover the snmp engineID
* 2) create SnmpEngineEntry and add it to SnmpEngineTable
* 3) create USMUserEntry and add it to USMUserTable
* 4) performs time synchronization
**/
private void initV3Parameters(Device data) throws InterruptedException
{
logger.debug("in.");
try
{
UDPProtocolOptions udpOptions = new UDPProtocolOptions();
udpOptions.setLocalPort(TRAP_PORT);
udpOptions.setRemoteHost(data.getIpAddress());
USMUtils.init_v3_parameters(
data.getUsmUser(),
null,// null means that the SNMPv3 discovery will be activated
Integer.valueOf(data.getAuthProtocol()),
data.getAuthPassword(),
data.getPrivPassword(),
udpOptions,
session,
false,
Integer.valueOf(data.getPrivProtocol()));
printToLog("secsses",data);
}
catch (SnmpException exp) {
logger.error(exp.getMessage()+" for ip = "+data.getIpAddress(),exp);
printToLog("failed",data);
}
}
I have a problem with while getting offline messages from ejabberd server 18.01 via smack library.
I have a connector method
private static AbstractXMPPConnection connectToServer(String serverHost, Integer port, String userName, String userPassword) {
DomainBareJid xmppDomain = null;
try {
xmppDomain = JidCreate.domainBareFrom(serverHost);
} catch (XmppStringprepException e) {
System.out.println("XMPP Domain initialization exception " + e.getMessage());
return null;
}
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setXmppDomain(xmppDomain)
.setHost(serverHost)
.setPort(port)
.setDebuggerEnabled(true)
.setSendPresence(false)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.build();
AbstractXMPPConnection connection = new XMPPTCPConnection(config);
try {
connection.connect().login(userName, userPassword);
return connection;
} catch (XMPPException | SmackException | IOException | InterruptedException e) {
System.out.println("Something went wrong while connection to server: " + e.getMessage());
connection.disconnect();
return null;
}
}
and offline messages receiver
private XMPPConnection connection;
#Override
public void run() {
connection = Connector.getInstance();
if (connection != null) {
System.out.println("Start listening messages in the background");
String offlineMessageOffline = "Offline message is %s from %s";
OfflineMessageManager offlineMessageManager = new OfflineMessageManager(connection);
try {
if (offlineMessageManager.supportsFlexibleRetrieval()) {
offlineMessageManager.getMessages()
.forEach(message -> {
System.out.println(String.format(offlineMessageOffline, message.getBody(), message.getFrom()));
});
// offlineMessageManager.deleteMessages();
}
} catch (SmackException.NoResponseException | XMPPException.XMPPErrorException |
SmackException.NotConnectedException | InterruptedException e) {
System.out.println(String.format("Error while getting offline messages from server: by the reason %s", e.getMessage()));
}
try {
connection.sendStanza(new Presence(Presence.Type.available));
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
ChatManager chatManager = ChatManager.getInstanceFor(connection);
IncomingChatMessageListener listener = (entityBareJid, message, chat) -> {
System.out.println(String.format("Incoming message is %s from %s", message.getBody(), message.getFrom()));
};
chatManager.addIncomingListener(listener);
} else {
System.out.println("Connection has not been established. Please try to choose option 1");
}
}
I start running message listener at the background. I see that database has an offline message and in the dubug node I see that offlineMessageManager.getMessageCount() returns the proper number of offline messages but method offlineMessageManager.getMessages() returns noting. The smack version is 4.2.3 but earlier version has the same problem
UPDATED
I found a workaround because it doesn't look like a obvious solution
public class ListenMessagesFromServerCommand implements Runnable {
private XMPPConnection connection;
#Override
public void run() {
connection = Connector.getInstance();
if (connection != null) {
System.out.println("Start listening messages in the background");
String offlineMessageOffline = "Offline message is %s from %s";
OfflineMessageManager offlineMessageManager = new OfflineMessageManager(connection);
try {
if (offlineMessageManager.supportsFlexibleRetrieval() && offlineMessageManager.getMessageCount() > 0) {
List<String> messagesNodes = offlineMessageManager.getHeaders().stream()
.map(OfflineMessageHeader::getStamp)
.collect(Collectors.toList());
offlineMessageManager.getMessages(messagesNodes)
.forEach(message -> {
System.out.println(String.format(offlineMessageOffline, message.getBody(), message.getFrom()));
});
offlineMessageManager.deleteMessages();
}
} catch (SmackException.NoResponseException | XMPPException.XMPPErrorException |
SmackException.NotConnectedException | InterruptedException e) {
System.out.println(String.format("Error while getting offline messages from server: by the reason %s", e.getMessage()));
}
try {
connection.sendStanza(new Presence(Presence.Type.available));
} catch (SmackException.NotConnectedException | InterruptedException e) {
System.out.println("Error sending presence available type " + e.getMessage());
}
ChatManager chatManager = ChatManager.getInstanceFor(connection);
IncomingChatMessageListener listener = (entityBareJid, message, chat) -> {
System.out.println(String.format("Incoming message is %s from %s", message.getBody(), message.getFrom()));
};
chatManager.addIncomingListener(listener);
} else {
System.out.println("Connection has not been established. Please try to choose option 1");
}
}
}
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();
}
What is the correct procedure to follow when an exception is thrown on an FTP Client in Java i.e. does the FTP session stay active or does it automatically 'quit' when an exception is thrown?
So I have this:
public boolean testHost(Host host, String path) {
boolean success = false;
try {
FTPClient ftp = new FTPClient();
ftp.setRemoteHost(host.getIpaddress());
ftp.connect();
ftp.login(host.getUsername(), host.getPassword());
success = ftp.connected();
if (success && path != null){
ftp.chdir(path);
}
ftp.quit();
} catch (UnknownHostException e) {
LOG.info("Host IPAddress cannot be reached on " + host.getIpaddress());
success = false;
} catch (IOException e) {
e.printStackTrace();
success = false;
} catch (FTPException e) {
success = false;
}
return success;
}
The quit command doesnt get hit when any of the exceptions get called - is this a problem? Could there potentially be 100's of active connections open to the FTP Client if this method keeps getting hit? Or am I worrying about nothing?
Move your ftp.quit() statement so it is just above the return statement
Like this:
public boolean testHost(Host host, String path) {
boolean success = false;
try {
FTPClient ftp = new FTPClient();
ftp.setRemoteHost(host.getIpaddress());
ftp.connect();
ftp.login(host.getUsername(), host.getPassword());
success = ftp.connected();
if (success && path != null){
ftp.chdir(path);
}
} catch (UnknownHostException e) {
LOG.info("Host IPAddress cannot be reached on " + host.getIpaddress());
success = false;
} catch (IOException e) {
e.printStackTrace();
success = false;
} catch (FTPException e) {
success = false;
}
ftp.quit();
return success;
}
Since none of your catches terminate the method, execution will continue to the ftp.quit() statement and finally return with the success result.
Optionally, you can use the finally clause at the end of the try and put the ftp.quit() statement in that.
AFAIK the choice is preferential.