Fail to upload file using ftp4j - java

I'm using ftp4j as FTP client.
FTPClient client = new FTPClient();
client.connect("86.22.11.178");
client.login("usr", "pwd");
client.changeDirectory("/dir");
client.upload(file);
It works fine at localhost, but it does not work when enclosed in a JSF web application deployed on a web server. I succeeded to do connect and login, when the code reaches to the upload command, it just skips on that and does nothing. No exception is been thrown.
There is full conectivity to the FTP server, it can't be a problem. I have also set chmod 777 permission on the files and they belong to the same owner.
This code worked on a Windows machine, could it be that machines running on Linux have different "rules"?

Your code seems to be correct. Try to find out the FTP error which its throws. Sometimes timeout may happens, which i faced!!!
import org.apache.commons.net.ftp.;
import java.io.;
/**
* This class is used to demonstrate the usage of the Jakarta Commons Net package
*/
public class TestFTP {
/** Creates a new instance of TestFTP */
public TestFTP() {
}
/**
* main - Unit test program
* #param args Command line arguments
*
*/
public static void main(String args[]) {
try {
String ftpHost = "157.227.38.131";
String ftpUserName = "firebird";
String ftpPassword = "tcs#12345";
String ftpRemoteDirectory = "/etc/vlp/uploaded_files";
String fileToTransmit = "c:\\temp\\VLPDYN18022010174439.an";
//Create a Jakarta Commons Net FTP Client object
FTPClient ftp = new FTPClient();
//A datatype to store responses from the FTP server
int reply;
//
//Connect to the server
//
ftp.connect(ftpHost);
//
// After connection attempt, you should check the reply code to verify success.
//
reply = ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)) {
try {
ftp.disconnect();
} catch (Exception e) {
System.err.println("Unable to disconnect from FTP server " +
"after server refused connection. "+e.toString());
}
throw new Exception ("FTP server refused connection.");
}
System.out.println("Connected to " + ftpHost + ". "+ftp.getReplyString());
//
//Try to login
//
if (!ftp.login(ftpUserName, ftpPassword)) {
throw new Exception ("Unable to login to FTP server " +
"using username "+ftpUserName+" " +
"and password "+ftpPassword);
}
System.out.println(ftp.getReplyString());
System.out.println("Remote system is " + ftp.getSystemName());
//
//Set our file transfer mode to either ASCII or Binary
//
//ftp.setFileType(FTP.ASCII_FILE_TYPE);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
//
//Change the remote directory
//
if (ftpRemoteDirectory != null && ftpRemoteDirectory.trim().length() > 0) {
System.out.println("Changing to FTP remote dir: " + ftpRemoteDirectory);
ftp.changeWorkingDirectory(ftpRemoteDirectory);
reply = ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)) {
throw new Exception ("Unable to change working directory " +
"to:"+ftpRemoteDirectory);
}
}
//
//Get the file that we will transfer and send it.
//
File f = new File(fileToTransmit);
System.out.println("Storing file as remote filename: " + f.getName());
boolean retValue=true;
try{
retValue = ftp.storeFile(f.getName(), new FileInputStream(f));
}catch(Exception e){e.printStackTrace();}
if (!retValue) {
throw new Exception ("Storing of remote file failed. ftp.storeFile() returned false.");
}
//Disconnect from the FTP server
//
try {
//ftp.logout();
ftp.disconnect();
} catch (Exception exc) {
System.err.println("Unable to disconnect from FTP server. " + exc.toString());
}
} catch (Exception e) {
System.err.println("Error: "+e.toString());
}
System.out.println("Process Complete.");
System.exit(0);
}
}

Related

Errors when creating java proxy client

I am trying to create a web proxy client in java. I stole this guys code and modified it to create a server and now a client so that the user can just download and run the client to connect to the server. I would just like this to run on the terminal but my future plans are to add a gui.
This is the server. This works straight out of the box as in you enter the ip in firefox and it will run just fine. TLDR: It parses the URL and forwards the data from the client to the server and vice versa.
Request Handler.java
/*
-----------------------------------------------------------------------------------------------
STOLEN FROM THIS MAN ON GITHUB
https://github.com/stefano-lupo/Java-Proxy-Server/blob/master/src/RequestHandler.java
-----------------------------------------------------------------------------------------------
*/
import java.awt.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
public class RequestHandler implements Runnable {
/**
* Socket connected to client passed by Proxy server
*/
Socket clientSocket;
/**
* Read data client sends to proxy
*/
BufferedReader proxyToClientBr;
/**
* Send data from proxy to client
*/
BufferedWriter proxyToClientBw;
/**
* Thread that is used to transmit data read from client to server when using HTTPS
* Reference to this is required so it can be closed once completed.
*/
private Thread httpsClientToServer;
/**
* Creates a RequestHandler object capable of servicing HTTP(S) GET requests
* #param clientSocket socket connected to the client
*/
public RequestHandler(Socket clientSocket){
this.clientSocket = clientSocket;
try
{
this.clientSocket.setSoTimeout(2000);
proxyToClientBr = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
proxyToClientBw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
}
catch (IOException e)
{
System.out.println("Error on IO Exception");
e.printStackTrace();
}
}
/**
* Reads and examines the requestString and calls the appropriate method based
* on the request type.
*/
#Override
public void run() {
// Get Request from client
String requestString;
try{
requestString = proxyToClientBr.readLine();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error reading request from client");
return;
}
// Parse out URL
System.out.println("Request Received " + requestString);
// Get the Request type
String request = requestString.substring(0,requestString.indexOf(' '));
// remove request type and space
String urlString = requestString.substring(requestString.indexOf(' ')+1);
// Remove everything past next space
urlString = urlString.substring(0, urlString.indexOf(' '));
// Prepend http:// if necessary to create correct URL
if(!urlString.substring(0,4).equals("http")){
String temp = "http://";
urlString = temp + urlString;
}
// Check request type
if(request.equals("CONNECT")){
System.out.println("HTTPS Request for : " + urlString + "\n");
handleHTTPSRequest(urlString);
}
else
{
System.out.println("HTTP GET for : " + urlString + "\n");
sendNonCachedToClient(urlString);
}
}
/**
* Sends the contents of the file specified by the urlString to the client
* #param urlString URL ofthe file requested
*/
private void sendNonCachedToClient(String urlString){
try{
// Compute a logical file name as per schema
// This allows the files on stored on disk to resemble that of the URL it was taken from
int fileExtensionIndex = urlString.lastIndexOf(".");
String fileExtension;
// Get the type of file
fileExtension = urlString.substring(fileExtensionIndex, urlString.length());
// Get the initial file name
String fileName = urlString.substring(0,fileExtensionIndex);
// Trim off http://www. as no need for it in file name
fileName = fileName.substring(fileName.indexOf('.')+1);
// Remove any illegal characters from file name
fileName = fileName.replace("/", "__");
fileName = fileName.replace('.','_');
// Trailing / result in index.html of that directory being fetched
if(fileExtension.contains("/")){
fileExtension = fileExtension.replace("/", "__");
fileExtension = fileExtension.replace('.','_');
fileExtension += ".html";
}
fileName = fileName + fileExtension;
// Attempt to create File to cache to
boolean caching = true;
File fileToCache = null;
BufferedWriter fileToCacheBW = null;
try{
// Create File to cache
fileToCache = new File("cached/" + fileName);
if(!fileToCache.exists()){
fileToCache.createNewFile();
}
// Create Buffered output stream to write to cached copy of file
fileToCacheBW = new BufferedWriter(new FileWriter(fileToCache));
}
catch (IOException e){
System.out.println("Couldn't cache: " + fileName);
caching = false;
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("NPE opening file");
}
// Check if file is an image
if((fileExtension.contains(".png")) || fileExtension.contains(".jpg") ||
fileExtension.contains(".jpeg") || fileExtension.contains(".gif")){
// Create the URL
URL remoteURL = new URL(urlString);
BufferedImage image = ImageIO.read(remoteURL);
if(image != null) {
// Cache the image to disk
ImageIO.write(image, fileExtension.substring(1), fileToCache);
// Send response code to client
String line = "HTTP/1.0 200 OK\n" +
"Proxy-agent: ProxyServer/1.0\n" +
"\r\n";
proxyToClientBw.write(line);
proxyToClientBw.flush();
// Send them the image data
ImageIO.write(image, fileExtension.substring(1), clientSocket.getOutputStream());
// No image received from remote server
} else {
System.out.println("Sending 404 to client as image wasn't received from server"
+ fileName);
String error = "HTTP/1.0 404 NOT FOUND\n" +
"Proxy-agent: ProxyServer/1.0\n" +
"\r\n";
proxyToClientBw.write(error);
proxyToClientBw.flush();
return;
}
}
// File is a text file
else {
// Create the URL
URL remoteURL = new URL(urlString);
// Create a connection to remote server
HttpURLConnection proxyToServerCon = (HttpURLConnection)remoteURL.openConnection();
proxyToServerCon.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
proxyToServerCon.setRequestProperty("Content-Language", "en-US");
proxyToServerCon.setUseCaches(false);
proxyToServerCon.setDoOutput(true);
// Create Buffered Reader from remote Server
BufferedReader proxyToServerBR = new BufferedReader(new InputStreamReader(proxyToServerCon.getInputStream()));
// Send success code to client
String line = "HTTP/1.0 200 OK\n" +
"Proxy-agent: ProxyServer/1.0\n" +
"\r\n";
proxyToClientBw.write(line);
// Read from input stream between proxy and remote server
while((line = proxyToServerBR.readLine()) != null){
// Send on data to client
proxyToClientBw.write(line);
// Write to our cached copy of the file
if(caching){
fileToCacheBW.write(line);
}
}
// Ensure all data is sent by this point
proxyToClientBw.flush();
// Close Down Resources
if(proxyToServerBR != null){
proxyToServerBR.close();
}
}
// Close down resources
if(fileToCacheBW != null){
fileToCacheBW.close();
}
if(proxyToClientBw != null){
proxyToClientBw.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Handles HTTPS requests between client and remote server
* #param urlString desired file to be transmitted over https
*/
private void handleHTTPSRequest(String urlString){
// Extract the URL and port of remote
String url = urlString.substring(7);
String pieces[] = url.split(":");
url = pieces[0];
int port = Integer.valueOf(pieces[1]);
try{
// Only first line of HTTPS request has been read at this point (CONNECT *)
// Read (and throw away) the rest of the initial data on the stream
for(int i=0;i<5;i++){
proxyToClientBr.readLine();
}
// Get actual IP associated with this URL through DNS
InetAddress address = InetAddress.getByName(url);
// Open a socket to the remote server
Socket proxyToServerSocket = new Socket(address, port);
proxyToServerSocket.setSoTimeout(5000);
// Send Connection established to the client
String line = "HTTP/1.0 200 Connection established\r\n" +
"Proxy-Agent: ProxyServer/1.0\r\n" +
"\r\n";
proxyToClientBw.write(line);
proxyToClientBw.flush();
// Client and Remote will both start sending data to proxy at this point
// Proxy needs to asynchronously read data from each party and send it to the other party
//Create a Buffered Writer betwen proxy and remote
BufferedWriter proxyToServerBW = new BufferedWriter(new OutputStreamWriter(proxyToServerSocket.getOutputStream()));
// Create Buffered Reader from proxy and remote
BufferedReader proxyToServerBR = new BufferedReader(new InputStreamReader(proxyToServerSocket.getInputStream()));
// Create a new thread to listen to client and transmit to server
ClientToServerHttpsTransmit clientToServerHttps =
new ClientToServerHttpsTransmit(clientSocket.getInputStream(), proxyToServerSocket.getOutputStream());
httpsClientToServer = new Thread(clientToServerHttps);
httpsClientToServer.start();
// Listen to remote server and relay to client
try {
byte[] buffer = new byte[4096];
int read;
do {
read = proxyToServerSocket.getInputStream().read(buffer);
if (read > 0) {
clientSocket.getOutputStream().write(buffer, 0, read);
if (proxyToServerSocket.getInputStream().available() < 1) {
clientSocket.getOutputStream().flush();
}
}
} while (read >= 0);
}
catch (SocketTimeoutException e) {
}
catch (IOException e) {
e.printStackTrace();
}
// Close Down Resources
if(proxyToServerSocket != null){
proxyToServerSocket.close();
}
if(proxyToServerBR != null){
proxyToServerBR.close();
}
if(proxyToServerBW != null){
proxyToServerBW.close();
}
if(proxyToClientBw != null){
proxyToClientBw.close();
}
} catch (SocketTimeoutException e) {
String line = "HTTP/1.0 504 Timeout Occured after 10s\n" +
"User-Agent: ProxyServer/1.0\n" +
"\r\n";
try{
proxyToClientBw.write(line);
proxyToClientBw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
catch (Exception e){
System.out.println("Error on HTTPS : " + urlString );
e.printStackTrace();
}
}
/**
* Listen to data from client and transmits it to server.
* This is done on a separate thread as must be done
* asynchronously to reading data from server and transmitting
* that data to the client.
*/
class ClientToServerHttpsTransmit implements Runnable{
InputStream proxyToClientIS;
OutputStream proxyToServerOS;
/**
* Creates Object to Listen to Client and Transmit that data to the server
* #param proxyToClientIS Stream that proxy uses to receive data from client
* #param proxyToServerOS Stream that proxy uses to transmit data to remote server
*/
public ClientToServerHttpsTransmit(InputStream proxyToClientIS, OutputStream proxyToServerOS) {
this.proxyToClientIS = proxyToClientIS;
this.proxyToServerOS = proxyToServerOS;
}
#Override
public void run(){
try {
// Read byte by byte from client and send directly to server
byte[] buffer = new byte[4096];
int read;
do {
read = proxyToClientIS.read(buffer);
if (read > 0) {
proxyToServerOS.write(buffer, 0, read);
if (proxyToClientIS.available() < 1) {
proxyToServerOS.flush();
}
}
} while (read >= 0);
}
catch (SocketTimeoutException ste)
{
ste.printStackTrace();
}
catch (IOException e) {
System.out.println("Proxy to client HTTPS read timed out");
e.printStackTrace();
}
}
}
}
This is the client. It doesn't seem to work and I dont really understand why as it is just a modified version of the server.
Request Handler.java
/*
-----------------------------------------------------------------------------------------------
STOLEN FROM THIS MAN ON GITHUB
https://github.com/stefano-lupo/Java-Proxy-Server/blob/master/src/RequestHandler.java
-----------------------------------------------------------------------------------------------
*/
import java.awt.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
public class RequestHandler implements Runnable
{
/**
* Socket connected to client passed by Proxy server
*/
Socket clientSocket;
/**
* Read data client sends to proxy
*/
BufferedReader clientToClientBr;
/**
* Send data from proxy to client
*/
BufferedWriter clientToClientBw;
/**
* Thread that is used to transmit data read from client to server when using HTTPS
* Reference to this is required so it can be closed once completed.
*/
private Thread threads;
/**
* Creates a RequestHandler object capable of servicing HTTP(S) GET requests
* #param clientSocket socket connected to the client
*/
public RequestHandler(Socket clientSocket)
{
this.clientSocket = clientSocket;
try
{
this.clientSocket.setSoTimeout(2000);
clientToClientBr = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
clientToClientBw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
}
catch (IOException e)
{
System.out.println("Error on IO Exception");
e.printStackTrace();
}
}
/**
* Reads and examines the requestString and calls the appropriate method based
* on the request type.
*/
#Override
public void run()
{
// Get Request from client
String requestString;
try
{
requestString = clientToClientBr.readLine();
System.out.println(requestString);
sendToServer(requestString);
}
catch (IOException e)
{
e.printStackTrace();
System.out.println("Error reading request from client");
return;
}
}
private void sendToServer(String urlString) throws IOException
{
// Open a socket to the remote server
Socket proxyToServerSocket = new Socket("192.168.0.226", 8080);
proxyToServerSocket.setSoTimeout(5000);
// Client and Remote will both start sending data to proxy at this point
// Proxy needs to asynchronously read data from each party and send it to the other party
//Create a Buffered Writer betwen proxy and remote
BufferedWriter proxyToServerBW = new BufferedWriter(new OutputStreamWriter(proxyToServerSocket.getOutputStream()));
// Create Buffered Reader from proxy and remote
BufferedReader proxyToServerBR = new BufferedReader(new InputStreamReader(proxyToServerSocket.getInputStream()));
// Create a new thread to listen to client and transmit to server
ClientToServerHttpsTransmit clientToServerHttps = new ClientToServerHttpsTransmit(clientSocket.getInputStream(), proxyToServerSocket.getOutputStream());
threads = new Thread(clientToServerHttps);
threads.start();
// Listen to remote server and relay to client
try {
byte[] buffer = new byte[4096];
int read;
do
{
read = proxyToServerSocket.getInputStream().read(buffer);
if (read > 0)
{
clientSocket.getOutputStream().write(buffer, 0, read);
if (proxyToServerSocket.getInputStream().available() < 1)
{
clientSocket.getOutputStream().flush();
}
}
} while (read >= 0);
}
catch (SocketTimeoutException e) {
}
catch (IOException e) {
e.printStackTrace();
}
// Close Down Resources
if(proxyToServerSocket != null){
proxyToServerSocket.close();
}
if(proxyToServerBR != null){
proxyToServerBR.close();
}
if(proxyToServerBW != null){
proxyToServerBW.close();
}
if(clientToClientBw != null){
clientToClientBw.close();
}
}
}
/**
* Listen to data from client and transmits it to server.
* This is done on a separate thread as must be done
* asynchronously to reading data from server and transmitting
* that data to the client.
*/
class ClientToServerHttpsTransmit implements Runnable
{
InputStream proxyToClientIS;
OutputStream proxyToServerOS;
/**
* Creates Object to Listen to Client and Transmit that data to the server
* #param proxyToClientIS Stream that proxy uses to receive data from client
* #param proxyToServerOS Stream that proxy uses to transmit data to remote server
*/
public ClientToServerHttpsTransmit(InputStream proxyToClientIS, OutputStream proxyToServerOS)
{
this.proxyToClientIS = proxyToClientIS;
this.proxyToServerOS = proxyToServerOS;
}
#Override
public void run()
{
try
{
// Read byte by byte from client and send directly to server
byte[] buffer = new byte[4096];
int read;
do
{
read = proxyToClientIS.read(buffer);
if (read > 0)
{
proxyToServerOS.write(buffer, 0, read);
if (proxyToClientIS.available() < 1)
{
proxyToServerOS.flush();
}
}
} while (read >= 0);
}
catch (SocketTimeoutException ste)
{
ste.printStackTrace();
}
catch (IOException e)
{
System.out.println("Proxy to client HTTPS read timed out");
e.printStackTrace();
}
}
}
I think that the error is in the Request Handler for the Client as the error message I get on the client terminal is:
Wating for client to connect on port 8080
Got CONNECT www.youtube.com:443 HTTP/1.1
java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.net.SocketInputStream.read(SocketInputStream.java:127)
at ClientToServerHttpsTransmit.run(RequestHandler.java:186)
at java.lang.Thread.run(Thread.java:748)
and this is the error for the terminal on the server:
java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at RequestHandler.run(RequestHandler.java:75)
at java.lang.Thread.run(Thread.java:748)
Error reading request from client

Correct way to download ftp file from localhost

this is my code:
String serverAddress = "ftp://ftp.nasdaqtrader.com/symboldirectory/"; // ftp server address
int port = 21; // ftp uses default port Number 21
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(serverAddress, port);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE/FTP.ASCII_FILE_TYPE);
String remoteFilePath = "/nasdaqtraded.txt";
File localfile = new File(System.getProperty("user.dir")+"\\src\\test\\resources\\stocks.txt");
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localfile));
boolean success = ftpClient.retrieveFile(remoteFilePath, outputStream);
outputStream.close();
if (success) {
System.out.println("Ftp file successfully download.");
}
} catch (IOException ex) {
System.out.println("Error occurs in downloading files from ftp Server : " + ex.getMessage());
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
And i am running it from localhost so i can download a list of stocks from nasdaq site, problem is it gives me this error:
Error occurs in downloading files from ftp Server : ftp://ftp.nasdaqtrader.com/symboldirectory/: invalid IPv6 address
I understand that is because i am trying to download the file from localhost, is there any way around it?
I am just trying to download this file:
ftp://ftp.nasdaqtrader.com/symboldirectory/nasdaqtraded.txt
to my computer, that's it.
The FTPClient class's connect() method expects to be passed the hostname of the server to connect to.
As with all classes derived from SocketClient, you must first connect to the server with connect before doing anything, and finally disconnect after you're completely finished interacting with the server.
However, your code is passing in a URI, which is being misinterpreted as an IPv6 address (probaby because it contains a colon).
You should instead connect() to the hostname of the server.
String hostname = "ftp.nasdaqtrader.com";
int port = 21;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(hostname, port);
I had same issue and found this helpful
Read a file from NASDAQ FTP Server
Maven Dependencies:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
Java Code:
FTPClient ftpClient = new FTPClient();
ftpClient.setStrictReplyParsing(false);
int portNumber = 21;
String pass = "anonymous";
try {
// connect to NASDAQ FTP
ftpClient.connect("ftp.nasdaqtrader.com", portNumber);
ftpClient.login(pass, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
if (ftpClient.isConnected()) {
log.debug("connection successful");
ftpClient.changeWorkingDirectory("/SymbolDirectory");
String remoteFile = "nasdaqlisted.txt";
InputStream in = new BufferedInputStream(ftpClient.retrieveFileStream(remoteFile));
String text = IOUtils.toString(in, StandardCharsets.UTF_8.name());
if(text != null) {
log.debug("write successful; \n {}", text);
}
}
ftpClient.logout();
} catch (IOException e) {
log.error("connection failed", e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
log.error("failed to disconnect", e);
}
}

To transfer a file from one windows machine(Local) to another windows machine(Server)

I want to write a code which will transfer a file from one machine to another in Linux and Windows platforms.
I used ssh libraries (sftp connections) to transfer file to Linux machine.
Now, I wanted to do same for Windows machine. Can someone please help me with this?
Description: To transfer a file from one windows machine(Local) to another windows machine(Server).
Also, I checked with FTP libraries in java, but I wasn't able to create a directory outside the folder created/shared for ftp.
Below is my code I am using currently for ftp.
FTPClient ftpClient = new FTPClient();
FileInputStream inputStream = null;
try {
// pass directory path on server to connect
ftpClient.connect("172.30.17.17");
// pass username and password, returned true if authentication is
// successful
boolean login = ftpClient.login("Administrator", "Password1!");
if (login) {
System.out.println("Connection established...");
inputStream = new FileInputStream("C:/Demo/abcd.txt");
boolean uploaded = ftpClient.storeFile("uploadedFile3.txt",inputStream);
if (uploaded) {
System.out.println("File uploaded successfully !");
} else {
System.out.println("Error in uploading file !");
}
ftpClient.makeDirectory("C:/Demo1"); //Unable to create this here
System.out.println("Folder Created successfully !");
// logout the user, returned true if logout successfully
boolean logout = ftpClient.logout();
if (logout) {
System.out.println("Connection close...");
}
} else {
System.out.println("Connection fail...");
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}

FtpClient.login() returns false to existing user

I'm trying to connect into FTP server, the problem is that wehn I try to log into the server with specific user it returns false.
This is the link for the ftp website: https://url.publishedprices.co.il/
The user name is: DorAlon
The password should be empty
When I'm connecting through the website it's working, it works too when i'm connecting from FileZilla, but when I do so from Java it returns false for this user. There are several more users that logged in successfully to this server, and only this user doesn't work.
Here's my code:
String server = "url.retail.publishedprices.co.il";
int port = 21;
String pass = " ";
FtpClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
boolean a = ftpClient.login("xxx", "");
boolean b = ftpClient.login("yyy", "");
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
// Checking whether the client is connected - in that case we'll logout and disconnect from the server
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
In the end the boolean a holds false, and b holds true.
It's mean the connection with the server is okay and also the login, but for the specific user it doesn't work.
How could this be possible?
I would like for some help, Thanks.

how to use FTP File Upload in JSF?

I would like to use org.apache.commons.net.ftp.FTPClient in my JSF application. How client side (Web Browser) upload to my web application server for large file. Even if I use RichFaces File Upload or PrimeFaces File Upload, client browser can use HTTP Protocol. How can I support FTP Protocol to client browser? Could you provide the better way?
Cause : the application user cannot direct access to our Repository Server(SVN). Firstly, they have to upload the files to our application on Web AS. And then, the application checkin/chekout to RepositoryServer. The application user can upload the file which has 500M to 2G at least. That's why, I am thinking, how can I support FTP Protocol to browser client' to be faster. Otherwise, am I thinking wrong?
In order to be able to send a file to a FTP server, you obviously need a FTP client.
However, a webbrowser is a HTTP client, not a FTP client. This is a natural functional design limitation of the webbrowser. JSF look like a magician, but here it really can't do anything for you. It intercepts on HTTP requests/responses only.
Indeed, you're thinking wrong. Just stick to uploading the file the usual HTTP way. If you're absolutely positive that you need FTP for this for some reason, then your best bet is most likely homebrewing a Java Applet for this, but this would after all be plain clumsy.
First do HTTP upload through primefaces to a temporary directory. then through org.apache.commons.net.ftp.FTPClient or through sun.net.ftp.FtpClient upload to the required FTP Server.
Below is an example;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import sun.net.ftp.FtpClient;
/**
*
* #author fali
*/
public class FtpUtil {
public String server, username,password, remote, remotedir, local;
FtpClient ftp;
public static int BUFFER_SIZE = 10240;
public FtpUtil(){
server = "localhost";
username = "anonymous";
password = " ";
remotedir = "/incoming";
remote = "dvs.txt";
local = "C:\\dvs.txt";
}
protected void putFile() {
if (local.length() == 0) {
System.out.println("Please enter file name");
}
byte[] buffer = new byte[BUFFER_SIZE];
try {
File f = new File(local);
int size = (int) f.length();
System.out.println("File " + local + ": " + size + " bytes");
System.out.println(size);
FileInputStream in = new FileInputStream(local);
OutputStream out = ftp.put(remote);
int counter = 0;
while (true) {
int bytes = in.read(buffer);
if (bytes < 0)
break;
out.write(buffer, 0, bytes);
counter += bytes;
System.out.println(counter);
}
out.close();
in.close();
} catch (Exception ex) {
System.out.println("Error: " + ex.toString());
}
}
public String Upload(){
String result="";
try{
ftp = new FtpClient(server);
ftp.login(username, password);
System.out.println(ftp.welcomeMsg);
ftp.cd(remotedir);
putFile();
disconnect();
}catch(Exception ex){
System.out.println(ex);
result = "Error : "+ex;
}
return "";
}
protected void disconnect() {
if (ftp != null) {
try {
ftp.closeServer();
} catch (IOException ex) {
}
ftp = null;
}
}
}
In your managedbean/controller;
public String create() {
System.out.println("Request Button Clicked");
try {
// generate reference number
//current.setReferenceno(genReferenceNo());
// add to database
//getFacade().persist(current);
// upload to ftp
FtpUtil fu = new FtpUtil();
fu.Upload();
// show reference number
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("QueueCreated"));
JsfUtil.addSuccessMessage("Your Reference No. is :" + current.referenceno);
current = null;
// try {
// System.out.println("Redirecting");
// FacesContext.getCurrentInstance().getExternalContext().dispatch("/");
// } catch (Exception ex) {
// System.out.println(ex);
// }
return "";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
and some thing like this in your page;
<br />
<ppctu:commandButton action="#{appointmentController.create}" type="Submit" value="Request" />

Categories

Resources