Multiple tests with multiple throws - java

I would like to create a method that will test different things and throw an error depending on the issue (and then exit the program).
I am not really familiar with throwing exception... Is this method a good way to program it?
private static void testConnexions() throws IOException, Exception {
File file = null;
Socket socket;
try {
// Test access to the repository:
file = new File(pdfRepository);
if (!file.canRead())
throw new SecurityException();
if (!file.canWrite())
throw new SecurityException();
if (!file.exists())
throw new SecurityException();
if (!file.isDirectory())
throw new SecurityException();
// Connection to  Filenet:
connexion = new FilenetConnexion(filenetURI, objectStoreName,
stanza, dossierRacine, userName, password);
connexion.connect();
// Connection to a socket:
socket = new Socket(serveurCV, portCV);
// Initialize the JavaMail Session:
Properties props = System.getProperties();
if (serveurSMTP != null)
props.put("mail.smtp.host", serveurSMTP);
Session session = Session.getInstance(props, null);
} catch (SecurityException e) {
e.getMessage();
e.printStackTrace();
} catch (UnknownHostException e) {
e.getMessage();
e.printStackTrace();
} catch (IOException e) {
e.getMessage();
e.printStackTrace();
} catch (Exception e) {
e.getMessage();
e.printStackTrace();
}
}
I would like to catch a message detailed enough to know if the repository can't be written in, or if the System.getProperties() got an error, etc.
Thank you in advance for your help!
EDIT:
Here is the solution I chose among all your contributions, hoping it can help someone:
private static void testConnexions() {
File file = null;
Socket socket;
// Test access to the repository:
try {
file = new File(pdfRepository);
if (!file.canRead())
throw new SecurityException(pdfRepository + " can't be read.");
if (!file.canWrite())
throw new SecurityException(pdfRepository + " can't be written.");
if (!file.exists())
throw new SecurityException(pdfRepository + " doesn't exist.");
if (!file.isDirectory())
throw new SecurityException(pdfRepository + " isn't a folder.");
} catch (SecurityException e) {
logger.error(e.getMessage());
System.exit(1);
}
// Connection to  FileNet
try {
connexion = new FilenetConnexion(filenetURI, objectStoreName,
stanza, dossierRacine, userName, password);
connexion.connect();
} catch (Exception e) {
logger.error("Impossible to connect to FileNet. " + e.getMessage());
System.exit(2);
}
// Connection to FrontalSocket
try {
socket = new Socket(serveurCV, portCV);
} catch (UnknownHostException e) {
logger.error("Impossible to connect to FrontalSocket. " + e.getMessage());
System.exit(3);
} catch (IOException e) {
logger.error("Impossible to connect to FrontalSocket. " + e.getMessage());
System.exit(3);
}
// Initialize the JavaMail session
try {
Properties props = System.getProperties();
if (serveurSMTP != null)
props.put("mail.smtp.host", serveurSMTP);
else{
logger.error("The SMTP host name is null");
System.exit(4);
}
Session session = Session.getInstance(props, null);
} catch (Exception e) {
logger.error("Impossible to connect to SMTP server. " + e.getMessage());
System.exit(4);
}
}

You can do this several ways, choose which one fits your scenario best:
Throw different exceptions based on each error scenario. It is easy to subclass Exception and create the distinction this way.
Throw the same exception with a specific error message depending on the error scenario.
An example of case 1:
First define your own exceptions:
public class CannotReadException extends Exception {
// This is a separate class in your project
}
public class CannotWriteException extends Exception {
// This is a separate class in your project
}
Then throw and catch them:
try {
// Test access to the repository:
file = new File(pdfRepository);
if (!file.canRead())
throw new CannotReadException();
if (!file.canWrite())
throw new CannotWriteException();
...
} catch (CannotReadException e) {
// Do stuff for the specific error
} catch (CannotWriteException e) {
// Do stuff for the specific error
}
or, case 2:
try {
// Test access to the repository:
file = new File(pdfRepository);
if (!file.canRead())
throw new SecurityException( "cannot read" );
if (!file.canWrite())
throw new SecurityException( "cannot write" );
...
} catch (SecurityException e) {
// Get to your specific message using e.getMessage();
}

I can suggest in this case to throw a user define exception and pass a message detailed enough to know the responsible for that error.
public class MyException extends Exception {
//override the needed methods.
}
then throw you own defined exception with a detaied message.
try {
// Test access to the repository:
file = new File(pdfRepository);
if (!file.canRead())
throw new MyException("The fine has no read permission");

Related

Java FTP transfer interrupted without error

I have a backup process by FTP, it works with org.apache.commons.net.ftp.FTPClient library.
I found that some file are partially uploaded and I did not found any upload error, sometimes just retrying I solved the problem.
This is my FTP connection code, I'm using passive mode and keepalive:
public FTPClient ftpConnect(){
FTPClient ftp = new FTPClient();
int retries=3;
int timeout=5000;
URL url;
try {
url = new URL(REMOTE_URL);
if(!url.getProtocol().equals("ftp"))
throw new MalformedURLException();
} catch (MalformedURLException e1) {
throw new SystemException("Invalid protocol");
}
ftp.setConnectTimeout(timeout);
ftp.setDataTimeout(timeout);
for (int i = 1; i <= retries; i++) {
try {
ftp.connect(url.getHost(),url.getPort()>0?url.getPort():21);
ftp.setSoTimeout(timeout);
ftp.enterLocalPassiveMode();
ftp.setKeepAlive(true);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new ConnectException("FTP server refused connection");
}
if(StringUtils.isNotBlank(url.getUserInfo())){
String[] arr=URLDecoder.decode(url.getUserInfo(), "UTF-8").split(":");
String user=arr[0];
String pass=arr.length>0?arr[1]:"";
if (!ftp.login(user,pass)) {
ftp.logout();
throw new SecurityException("FTP server login not valid");
}
}
ftp.changeWorkingDirectory(url.getPath());
break;
} catch (SocketException e ) {
log.error("Socket Error, retry nr {}",i);
if(i==retries) throw new SystemException("Socket error, max retries reached");
} catch (IOException e) {
throw new SystemException("Connection Error");
} catch (SecurityException e) {
throw new SystemException("Invalid authentication");
}
}
return ftp;
}
I would like to know how cand I solve this partial upload and above all how can I get an error in these cases.

How to handle throw exceptions inside finally block in java

In java, it is not recommended to throw exceptions inside finally section in try-chatch block due to hide the propagation of any unhandled throwable which was thrown in the try or catch block. This practice is a blocker level violation according to default sonar profile.
Sonar Error: Remove this throw statement from this finally block.
Please consider the following code snippet.
e.g.: close input stream inside the finally block, and handle possible exceptions might be occurred when closing the stream.
public void upload(File file) {
ChannelSftp c = (ChannelSftp) channel;
BufferedInputStream bis = new BufferedInputStream(file.toInputStream());
try {
String uploadLocation = Files.simplifyPath(this.fileLocation + "/" + file.getName());
c.put(bis, uploadLocation);
} catch (SftpException e) {
throw new IllegalTargetException("Error occurred while uploading " + e.getMessage());
} finally {
try {
bis.close();
} catch (IOException e) {
throw new UnsupportedOperationException("Exception occurred while closing Input stream " + e.getMessage());
}
}
}
It would be grateful if you can show the conventional way of handling these situations.
Best way to handle this problem is to use try-with-resource. But if someone want to close the connection manually and show the exception of the try or catch block without hiding, following code snippet is the solution.
public void upload(File file) throws IOException {
ChannelSftp c = (ChannelSftp) channel;
BufferedInputStream bis = new BufferedInputStream(file.toInputStream());
SftpException sftpException = null;
try {
String uploadLocation = Files.simplifyPath(this.fileLocation + "/" + file.getName());
c.put(bis, uploadLocation);
} catch (SftpException e) {
sftpException = e;
throw new IllegalTargetException("Error occurred while uploading " + e.getMessage());
} finally {
if (sftpException != null) {
try {
bis.close();
} catch (Throwable t) {
sftpException.addSuppressed(t);
}
} else {
bis.close();
}
}
}

Don't find my file.properties

I try a lot of thinks to find the fail but i don't know how I can do it. my code is:
//DominioLlamadaRedSys.java
Properties d = new Properties();
InputStream entrada = null;
try {
entrada = new FileInputStream("prop/datosApp.properties");
d.load(entrada);
System.out.println(d.getProperty("TXD.endPointUrl"));
} catch (IOException ex) {
System.out.println("ERROR: "+ ex.getMessage());
} finally {
if (entrada != null) {
try {
entrada.close();
} catch (IOException e) {
}
}
}
I call the file inside a class in "com.rsi.secpay.dominio" and this always catch the same exception (don't find the file), I had try to quit "prop/" (just "datosApp.properties" ) with properties files like this:
If your prop package is in your classpath, you can get the stream using the classloader:
InputStream is = DominioLlamadaRedSys.class.getResourceAsStream("/prop/datosApp.properties");

Close current Java app until another send a signal

I want to know if is possible to close the current java app util another has done some task, my code is this:
private static void callJar(String jardir) throws IOException, InterruptedException {
// jardir contains the excecution command
Process p = Runtime.getRuntime().exec(jardir);
synchronized (p) {
// Here I want to wait for p for a signal but not when p has finished
// but waitFor() do the second
p.waitFor();
}
// If the other jar is correctly loaded, close this jar
System.exit(0);
}
The string jardir contains the excecution command that will start the other process that I will be listening, something like this:
jardir = "javaw -jar \\path\\to\\anotherjar.jar"
For now, callJar() opens this process and then close the current until the process that I started has been terminated. In other words, close A until B has been closed.
But what I want to do is to close A until B send a signal (B will continue to exist).
Is there a way to listen for a signal from the process that I started?
After searching for an answer, I finally found a solution, maybe this will work for someone so here is what I did:
Based on this answer and this site, I opted to create a communication between two Java apps using the java.net libraries.
In the process A, I have a method that create a server communication and just waits until it receive a message from process B...
private static boolean listen2ExternalProcess() {
ServerSocket server = null;
Socket serverSocked = null;
String line;
BufferedReader inputReader = null;
try {
server = new ServerSocket(3333);
serverSocked = server.accept();
inputReader = new BufferedReader(
new InputStreamReader(serverSocked.getInputStream()));
while (true) {
line = inputReader.readLine();
log.info("Client says: " + line);
if (line.equals("Kill yourself :D")) {
return true;
}
}
} catch (UnknownHostException e) {
log.error("Don't know about this, " + e);
return false;
} catch (IOException e) {
log.error("Couldn't get IO for the connection, " + e);
return false;
} finally {
try {
if(serverSocked != null) serverSocked.close();
if(inputReader != null) inputReader.close();
} catch (IOException ex) {
log.error("Couldn't get IO for the connection, " + ex);
return false;
}
}
}
this method will return true if the message has been received, then I can proceed to terminate process A.
In the process B, I have a method that just send a message to a socket when I need it...
public static void talk2ExternalProcess() {
Socket socket = null;
BufferedWriter outputWriter = null;
try {
socket = new Socket("localhost", 3333);
outputWriter = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
} catch (UnknownHostException e) {
log.error("Don't know about host: localhost, " + e);
} catch (IOException e) {
log.error("Couldn't get IO for the connection to localhost, " + e);
}
if (socket != null && outputWriter != null) {
try {
outputWriter.write("Kill yourself :D");
} catch (UnknownHostException e) {
log.error("Trying to connect to unkown host: " + e);
} catch (IOException e) {
log.error("IO Exception: " + e);
} finally {
try {
outputWriter.close();
socket.close();
} catch (IOException ex) {
log.error("IO Exception: " + ex);
}
}
} else {
log.warn("null socket or outputwriter");
}
}
finally, I just change the callJar method to something like this:
private static void callJar(String jardir) throws IOException {
Runtime.getRuntime().exec(jardir);
if (listen2ExternalProcess()) {
System.exit(0);
} else {
log.warn("Something went wrong...");
}
}
I would like to find an easier answer, but for now, this works for me.

DebugException in apache-commons-net

When i try to list files from my location using ftpClient.listFiles("folder"); it shows
org.eclipse.debug.core.DebugException: com.sun.jdi.ClassNotLoadedException: Type has not been loaded occurred while retrieving component type of array.
Can some one guide me what i am doing wrong.
I use apache-commons-net-3.3
My code is
FTPClientConfig ftpClientConfig = new FTPClientConfig(FTPClientConfig.SYST_NT);
FTPClient ftpClient = new FTPClient();
ftpClient.configure(ftpClientConfig);
ftpClient.connect(hostName, Integer.valueOf(portNumber));
ftpClient.enterLocalPassiveMode();
ftpClient.login(username, password);
// Error throws here
FTPFile[] files = ftpClient.listFiles("folder");
This Exception is thrown when a user gave a Wrong or Encrypted Username Or Password.
Apache is not throwing the correct exception.
public void ConnectToFtp(String serverAdd,String username,String password){
try {
ftpclient.connect(serverAdd);
boolean login = ftpclient.login(username,password);
reply = ftpclient.getReplyCode();
if(FTPReply.isPositiveCompletion(reply)){
System.out.println("Connected Success");
}else {
System.out.println("Connection Failed");
ftpclient.disconnect();
}
if (login) {
System.out.println("Connection established...");
FTPFile[] ftpFiles = ftpclient.listFiles();
for (FTPFile ftpFile : ftpFiles) {
if (ftpFile.getType() == FTPFile.DIRECTORY_TYPE) {
System.out.printf("FTPFile: %s; %s%n",
ftpFile.getName(),
FileUtils.byteCountToDisplaySize(ftpFile.getSize()));
}
}
}
boolean logout = ftpclient.logout();
if (logout) {
System.out.println("Connection close...");
} else {
System.out.println("Connection fail...");
}
} catch (SocketException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
ftpclient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Categories

Resources