ftp connection to determine if file is there - java

I am trying to check if the file exist in the FTP. When testing with one user it seems to be fine. But with the scenario of multiple users it seems to throw the below exception :
Exception in thread "main" sun.net.ftp.FtpProtocolException: Welcome message: 421.
Below is the code which we use to check if file is there and we have closed all the connection but still it throws sun.net.ftp.FtpProtocolException:Welcome message: 421.
public boolean getFtpFileExists(String fileUrl)
{
URL theURL = null;
InputStream inputStream = null;
FtpURLConnection ftpUrlConn = null;
boolean ftpFileExists = false;
try
{
theURL = new URL(fileUrl);
ftpUrlConn = (FtpURLConnection)theURL.openConnection();
inputStream = ftpUrlConn.getInputStream();//calling this method will throw a 'FileNotFoundException' if doesn't exist
ftpFileExists = true;
}
catch(FileNotFoundException fnfe)
{
ftpFileExists = false;
}
catch(Exception e)
{
System.out.println(e.toString());
ftpFileExists = false;//hmm, not sure really!
}
finally
{
//close inputStream & connection
if(inputStream != null)
{
try
{
inputStream.close();
}
catch(IOException ioe)
{
System.out.println("Error closing input stream: "+ioe.getMessage());
}
}
try
{
ftpUrlConn.close();
}
catch(Exception e)
{
System.out.println("Error closing ftpUrlConnection");
}
}
return ftpFileExists;
}
could anyone help me please?

Can you recreate the error that you get ?
at any case:
by the error MSG:
421: Service not available, closing control connection. This may be a
reply to any command if the service knows it must shut down.
It sounds like that maybe there's a configuration needs to be done at the FTPServer rather than a code error.

Related

File not found exception even after bufferedwriter close

New edit:
Now i found the cause, it is because there are two servers and it write into temp folder in 1st server and try to read from the 2nd one. But I still didn't find a solution for this unless write to Amazon S3 and read from there.
I tried to export csv with struts2 action. However if I tried to export 10 times i can only succeed once, all the others failed with File not found exception (if I refresh the link again, the file can be downloaded). Here is my code:
public String exportFile(String fileName) {
File exportFile = null;
try {
if (CollectionUtils.isEmpty(receipts)) {
return "";
}
exportFile = File.createTempFile(fileName, ".csv");
exportFile.deleteOnExit();
try (BufferedWriter fw = new BufferedWriter(new FileWriter(exportFile))) {
try {
fw.write("test");
} finally {
fw.close();
}
}
return exportFile.getPath();
} catch (Exception ex) {
logger.error("Error exporting report. ", ex.getMessage());
}
return "";
}
String getStreamFromPath(String filePath) {
try {
File downloadFile = new File(filePath);
fileInputStream = new FileInputStream(downloadFile);
return SUCCESS;
} catch (IOException e) {
log.error(e.getMessage(), e);
return ERROR;
}
}
This is really weird, when i test in another server it works totally fine. Any ideas?

Java FTP Upload Completed but not returning

Good day. I have imported org.apache.commons.net.ftp.FTP to my project and I faced some issues when upload the zip file to FTP.
When it uploads small file(<100MB), it works fine. But when it comes to larger file (>500MB), it will stops there, without returning and execute the remaining operation, even it the file is transferred to the server.
And how the function / FTP acknowledge when the transfer is done? Is there anyway to check it?
public class zipFTP
{
public boolean uploadFile(String ht, String usr, String ps, String fpath, String uploadloc)
{
FTPClient client = new FTPClient();
FileInputStream fis = null;
writeLog nLog = new writeLog();
String channel = "FTP";
boolean completed = false;
//client.setBufferSize(1048576);
client.setControlKeepAliveReplyTimeout(300);
//System.out.println(client.getBufferSize());
try
{
nLog.writeToLog(dumptoFTP.filename, channel, "Uploading...");
client.connect(ht);
client.login(usr, ps);
client.enterLocalPassiveMode();
client.setFileType(FTP.BINARY_FILE_TYPE);
fis = new FileInputStream(fpath);
completed = client.storeFile(uploadloc, fis);
//client.completePendingCommand(); //to complete the transaction entirely
if(completed)
{
if (dumptoFTP.isSysLog)
System.out.println("File uploaded");
nLog.writeToLog(dumptoFTP.filename, channel, "File uploaded");
}
fis.close();
}
catch (IOException e)
{
e.printStackTrace();
if (dumptoFTP.isSysLog)
System.out.println("Upload failed");
nLog.writeToLog(dumptoFTP.filename, channel, "Upload failed");
nLog.writeToLog(dumptoFTP.filename, channel, e.toString());
}
finally
{
try
{
if(client.isConnected())
{
client.logout();
client.disconnect();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
return completed;
}
}
Ended up, setBufferSize() does the trick

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.

Where and when should I use the close() method to avoid IOException in ObjectInputStream?

I'm trying to read an object from client program over tcp. As you can see in this line I created objectInput:
ObjectInputStream objectInput = new ObjectInputStream(incoming.getInputStream());
And then read my input from the other program. It used to work fine until i made minor changes to clean up the program. Personally Assume I added
objectInput.clsoe();
My question is, After reading the object should I close the objectInputStream or Keep remain without close? Should I close it straight away after using it or at the end of if block or at the end of program? What are the effect of the close? By the way I have read the close documentation.
Here is the error:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2280)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2749)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:779)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:279)
at Server.ClientWorker.run(MyCollectionServer.java:116)
at java.lang.Thread.run(Thread.java:680)
Here is my code:
public static void main(String[] args) {
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(port);
}
catch (IOException e)
{
e.printStackTrace();
}
while(true)
{
ClientWorker w;
try
{
w = new ClientWorker(serverSocket.accept());
Thread t = new Thread(w);
t.start();
}
catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
}
class ClientWorker implements Runnable
{
.....
private Socket incoming;
public ClientWorker(Socket incoming)
{
myList = new ArrayList<PureAlbum>();
loadList();
this.incoming = incoming;
}
.....
public synchronized void run()
{
else if(request.compareTo("AddAlbum")==0)
{
try
{
ObjectInputStream objectInput = new ObjectInputStream(incoming.getInputStream()); //This is the line mentioned in the error
PureAlbum object = (PureAlbum) objectInput.readObject();
if(object instanceof CDAlbum)
{
CDAlbum a = (CDAlbum) object;
myList.add(a);
System.out.println("Artist = " + a.getArtist());
}
else if(object instanceof Client.au.edu.uow.Collection.DVDAlbum)
{
myList.add((DVDAlbum) object);
}
else
{
System.err.println("Warning : The object to add to database is unknown! "+ object.getClass() + "*");
System.exit(0);
}
}
catch (UnknownHostException e)
{
System.err.println("Can not read the host name");
e.printStackTrace();
}
catch (IOException e)
{
System.err.println("Can not read the FILE name"); //This exception has been called
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
Your code fragment is pretty long, so I will try to give you a general answer and it will hopefully help you.
The typical patterns of usage of stream.close() prior to java 7 are:
InputStream in = null;
try {
InputStream in = .....; // create your input stream;
// use input stream
} catch (IOException e) {
// do what you need here
} finally {
if (in != null) {
in.close();
}
}
or simply declare the method as throws IOException and then write:
InputStream in = null;
try {
InputStream in = .....; // create your input stream;
// use input stream
} finally {
if (in != null) {
in.close();
}
}
Pay atention that this example does not contain catch section.
Starting from java 7 we can enjoy the new facilities of the language:
try (
InputStream in = .....; // create your input stream;
) {
// use input stream
}
You even do not have to call close() at all. All resources defined into header of try block that implement interface Closable will be closed automatically.
This line of stack trace shows that the exception is occurring when you are initializing the ObjectInputStream, not when you are closing.
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:279)
The most likely cause is that the remote client did not open an ObjectOutputStream. It might have written some other kind of data, or it might have closed its output stream or simply exited.
You should close the Stream when you have completed your reading or writing.
here in this case , you should close the InputStream when you have read the file completely and you no longer require to read file from stream.
In Short , You should close the Stream when its work is over.
It may be in the end of program or after if loop....depends on your use case.
Hope this will help.
I am doing it this way (different example):
private void readFile() throws Exception {
FileInputStream fis = null;
ObjectInputStream ois = null;
Object aux = null;
try {
fis = new FileInputStream("lib.dat");
ois = new ObjectInputStream(fis);
do {
aux = ois.readObject();
if (aux instanceof MyObject)
this.myObjectInstance.add((MyObject) aux);
} while (true);
} catch (EOFException e) {
ois.close();
}
}
This way I am sending any relevant "Error" Exception upstairs to be handled, and once the EndOfFileException is launched this is specifically captured to close the stream properly.
The object has to be defined outside the Try block to be accessible from the Catch block.
The close() method could as well throw an IOException and this can't be caught by our Try block, this would have to be passed by the generic "throw Exception" of readFile() method.

File download in httpclient using java?

My code is,
import java.io.*;
import java.net.*;
public class DownloadHttp
{
public static void main(String a[])
{
DownloadHttp d = new DownloadHttp();
String addr = "http://www.gmail.com";
String file = "D:/venkatesh/Software/download1.html";
d.download(addr,file);
}
public void download(String address, String localFileName) {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
// Get the URL
URL url = new URL(address);
// Open an output stream to the destination file on our local filesystem
out = new BufferedOutputStream(new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
// Get the data
byte[] buffer = new byte[1024];
int numRead;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
}
// Done! Just clean up and get out
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException ioe) {
// Shouldn't happen, maybe add some logging here if you are not
// fooling around ;)
}
}
}
}
Here I wants download specific file using httpClient using java.
It produces:
"java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)" as error.
How to resolve it, help me, thanks in advance.
I believe it is a network problem. Have you tried to access the url directly or are you behind a firewall?
Recompiled your code on my machine, it works perfectly well. I'm able to fetch files from the web.
Check if your web-browser can download the file for you (make sure it's not a network problem)
One thing to notice though, in your finally block you might want to close the streams separately. So if anything goes wrong with the input stream, the output stream will still be closed.
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ignored) {}
try {
if (out != null) {
out.close();
}
} catch (Exception ignored) {}
}
I think you are using a proxy when connecting to internet.
Set these in the code and then retry.
System.setProperty("http.proxyHost", *Proxy-IP*);
System.setProperty("http.proxyPort", *Proxy-Port*);

Categories

Resources