import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPFile;
import java.io.*;
public class FTPUpload{
public static boolean uploadfile(String server,String username,String Password,String source_file_path,String dest_dir){
FTPClient ftp=new FTPClient();
try {
int reply;
ftp.connect(server);
ftp.login(username, Password);
System.out.println("Connected to " + server + ".");
System.out.print(ftp.getReplyString());
reply = ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.err.println("FTP server refused connection.");
return false;
}
System.out.println("FTP server connected.");
InputStream input= new FileInputStream(source_file_path);
ftp.storeFile(dest_dir, input);
System.out.println( ftp.getReplyString() );
input.close();
ftp.logout();
} catch(Exception e) {
System.out.println("err");
e.printStackTrace();
return false;
} finally {
if(ftp.isConnected()) {
try {
ftp.disconnect();
} catch(Exception ioe) {
}
}
}
return true;
}
public static void main(String[] args) {
FTPUpload upload = new FTPUpload();
try {
upload.uploadfile("192.168.0.210","muruganp","vm4snk","/home/media/Desktop/FTP Upload/data.doc","/fileserver/filesbackup/Emac/");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Am using the above code to upload a file named "data.doc" in the server location 192.168.0.210.
The destination location of my server is fileserver/filesbackup/Emac/.
But I end up receiving the error "553 Could not create file" although the server gets connected successfully. I suspect that I am giving the destination format in a wrong way. Kindly let me know what has to be done to resolve the issue?
The problem is that you try to upload the file to a directory. You should rather specifiy the destination filename, not the destination directory.
Does it work when you try the same in another FTP client?
[Update]
Here is some (untested, since I don't have an FTP server) code that does the error handling better and in a shorter form.
package so3972768;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
public class FtpUpload {
private static void check(FTPClient ftp, String cmd, boolean succeeded) throws IOException {
if (!succeeded) {
throw new IOException("FTP error: " + ftp.getReplyString());
}
}
private static String today() {
return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
}
public void uploadfile(String server, String username, String Password, String sourcePath, String destDir) throws IOException {
FTPClient ftp = new FTPClient();
ftp.connect(server);
try {
check(ftp, "login", ftp.login(username, Password));
System.out.println("Connected to " + server + ".");
InputStream input = new FileInputStream(sourcePath);
try {
String destination = destDir;
if (destination.endsWith("/")) {
destination += today() + "-" + new File(sourcePath).getName();
}
check(ftp, "store", ftp.storeFile(destination, input));
System.out.println("Stored " + sourcePath + " to " + destination + ".");
} finally {
input.close();
}
check(ftp, "logout", ftp.logout());
} finally {
ftp.disconnect();
}
}
public static void main(String[] args) throws IOException {
FtpUpload upload = new FtpUpload();
upload.uploadfile("192.168.0.210", "muruganp", "vm4snk", "/home/media/Desktop/FTP Upload/data.doc", "/fileserver/filesbackup/Emac/");
}
}
Related
I want to create simple communicator with one server and few clients who could connect and send data to it. It works fine without any threads, with only one client, but once i try to incorporate concurrency it doesn't work. From client perspective there is some connection, I can send data, but there is no sign of receiving that data on server. Here is the server class:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class MyServerSocket implements Runnable
{
private ServerSocket serverSocket;
public MyServerSocket() throws Exception
{
Random generator = new Random();
this.serverSocket = new ServerSocket(generator.nextInt(65000 - 60000) + 60000, 50, InetAddress.getByName("192.168.0.105"));
}
public InetAddress getSocketIPAddress()
{
return this.serverSocket.getInetAddress();
}
public int getPort()
{
return this.serverSocket.getLocalPort();
}
public void run()
{
while (true)
{
System.out.println("Running a thread");
try
{
String data = null;
Socket client = this.serverSocket.accept();
String clientAddress = client.getInetAddress().getHostName();
System.out.println("Connection from: " + clientAddress);
System.out.println("Here I am");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String message = "";
while ((data = in.readLine()) != null && data.compareToIgnoreCase("quit") != 0)
{
message = ("\r\nMessage from " + clientAddress + ": " + data);
System.out.println(message);
out.write(message);
}
} catch (Exception e)
{
System.out.println("Something went wrong");
} finally
{
try
{
serverSocket.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Server main:
import java.lang.Thread;
public class Main
{
public static void main(String[] args)
{
try
{
MyServerSocket socket = new MyServerSocket();
Runnable runnable = new MyServerSocket();
System.out.println("Port number: " + socket.getPort() + " IP address: " + socket.getSocketIPAddress());
Thread thread = new Thread(runnable);
thread.start();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
Client class:
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class ClientSocket
{
private Socket socket;
private Scanner scanner;
ClientSocket(InetAddress serverAddress, int serverPort) throws Exception
{
this.socket = new Socket(serverAddress, serverPort);
this.scanner = new Scanner(System.in);
}
public void sendData() throws Exception
{
String data;
System.out.println("Please type in the message. If you want to terminate the connection, type Quit");
PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true);
do
{
data = scanner.nextLine();
out.println(data);
out.flush();
}while(data.compareToIgnoreCase("quit") != 0);
out.println();
}
}
Client main:
import java.net.InetAddress;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int port;
System.out.println("Provide port at which you will communicate with the server");
port = scanner.nextInt();
try
{
ClientSocket socket1 = new ClientSocket(InetAddress.getByName("192.168.0.105"), port);
socket1.sendData();
}catch(Exception e)
{
System.out.println("Could not connect to the server.");
}
}
}
Server somehow stops its working when is about to accept the client connection, while client works fine and seem to be connected to the server.
In server side, once you accept a client connection, you should new a thread to process this connection:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class MyServerSocket implements Runnable {
private ServerSocket serverSocket;
public MyServerSocket() throws Exception {
Random generator = new Random();
this.serverSocket = new ServerSocket(generator.nextInt(65000 - 60000) + 60000, 50, InetAddress.getByName("192.168.0.105"));
}
public InetAddress getSocketIPAddress() {
return this.serverSocket.getInetAddress();
}
public int getPort() {
return this.serverSocket.getLocalPort();
}
public void run() {
while (true) {
System.out.println("Running a thread");
try(Socket client = this.serverSocket.accept()) {
// new thread to process this client
new Thread(() -> {
try {
String data = null;
String clientAddress = client.getInetAddress().getHostName();
System.out.println("Connection from: " + clientAddress);
System.out.println("Here I am");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String message = "";
while (true) {
if (!((data = in.readLine()) != null && data.compareToIgnoreCase("quit") != 0)) break;
message = ("\r\nMessage from " + clientAddress + ": " + data);
System.out.println(message);
out.write(message);
}
} catch (IOException e) {
System.out.println("Something went wrong");
}
}).start();
} catch (Exception e) {
System.out.println("Something went wrong");
}
}
}
}
Ok, somehow I solved that problem, but still I need to understand how does it work:
Accepting connection inside try block, without finally block (nor try with resources) so socket is opened all the time.
Modified main method so there is no threads or runnable objects at all in it. The whole process is done within the class:
Code:
public class Main
{
public static void main(String[] args)
{
try
{
MyServerSocket socket = new MyServerSocket();
System.out.println("Port number: " + socket.getPort() + " IP address: " + socket.getSocketIPAddress());
socket.run();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
If anyone could point me out mistakes that are still in this final version of code I'll be grateful.
I'm trying to save image in FTP server. But it giving error like java.io.IOException: FTP error: 553 Could not create file.
I call the method
upload("xxx.xx.2.36","ftpuser","xxxxxpos",imageFile,"ftp://ftpuser#xxx.xx.2.36/Item/");
public static void check(FTPClient ftp, String cmd, boolean succeeded) throws IOException {
if (!succeeded) {
throw new IOException("FTP error: " + ftp.getReplyString());
}
}
/**
*
* #return
*/
private static String today() {
return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
}
public static void upload(String server, String username, String Password,
File imageFile, String destDir) {
FTPClient ftp = new FTPClient();
try {
ftp.connect(server);
check(ftp, "login", ftp.login(username, Password));
System.out.println("Connected to " + server + ".");
InputStream input = new FileInputStream(imageFile);
try {
String destination = destDir;
if (destination.endsWith("/")) {
destination += today()+"-"+imageFile.getName();
System.out.println("direc" +destination);
}
check(ftp, "store", ftp.storeFile(destination, input));
System.out.println("Stored " + imageFile + " to " + destination + ".");
} finally {
input.close();
}
check(ftp, "logout", ftp.logout());
}catch(Exception e){
e.printStackTrace();
}
finally {
try {
ftp.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
After ftp.storeFile(destination, input) it giving error
Please help to solve this.
i'm new to java programming and am using Apache commons net ftp to upload text files to my ftp server.
however, it seems that i can only upload the files on the same directory as my program .. when i set the file path to something like that : "C:\Users\Packard\Documents\ProjectsJava\FugeLessons\outputFile.txt" , it throws no errors, but when i check the ftp, there is nothing, like it has not been uploaded .
here is the code i'm using :
import org.apache.commons.net.ftp.FTPClient;
import java.io.FileInputStream;
import java.io.IOException;
public class ftp{
private final String host = "ftp.address.com";
private final String user = "user";
private final String pass = "pass";
public static void main(String[] args) {
ftp client = new ftp();
client.FtpUpload("C:\\Users\\Packard\\Documents\\ProjectsJava\\FugeLessons\\outputFile.txt");
}
public String FtpUpload(String filename){
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect(this.host);
client.login(this.user, this.pass);
fis = new FileInputStream(filename);
client.storeFile(filename, fis);
client.logout();
System.out.println("File " + filename + "\t uploaded successfully!");
} catch(IOException e){
error error = new error();
error.setVisible(true);
e.printStackTrace();
} finally {
try {
if ( fis != null) {
fis.close();
}
client.disconnect();
} catch(IOException e){
e.printStackTrace();
}
}
String ret = "success";
return ret;
}
}
what am i doing wrong ?
Thanks for your help!
You can use ftpClient method getReplyString() to get the error message. Below code can help.
boolean isSendSucces = ftpClient.storeFile(fileName, input );
if( isSendSuccess )
{
System.out.println("Sent File: " + fileName);
}
else
{
System.out.println("Problem is sending File: " + ftpClient.getReplyString());
}
I have a problem using sockets in Java: the server doesn't respond and no exception is thrown.
Server Code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
class Server {
public static void main(String args[]) {
final int time = 75;
//boolean CHAT_SESSION_ALIVE = false;
int port = 9999;
try {
System.out.println("Starting chat server using the port : " + port);
ServerSocket srvr = new ServerSocket(port);
Socket skt = srvr.accept();
System.out.println("Server has connected with client " + skt.getInetAddress());
//CHAT_SESSION_ALIVE = true;
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
if (in.ready()) {
String msg = in.readLine();
System.out.println("receive message: '" + msg + "'");
Thread.sleep(time);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
Thread.sleep(time);
String msg = new Scanner(System.in).nextLine();
System.out.println("Sending message: '" + msg + "'");
out.print(msg);
} catch (Exception e) {
System.out.println(e);
}
}
}
}).start();
//in.close();
//out.close();
//skt.close();
//srvr.close();
} catch (Exception e) {
System.out.print(e);
}
}
}
Client Code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
class Client {
public static void main(String args[]) {
final int time = 75;
//boolean CHAT_SESSION_ALIVE = false;
int port = 9999;
String hostIP = "127.0.0.1";
try {
Socket skt = new Socket(hostIP, port);
System.out.println("Client has connected with server " + hostIP + ":" + port);
//CHAT_SESSION_ALIVE = true;
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
if (in.ready()) {
String msg = in.readLine();
System.out.println("receive message: '" + msg + "'");
Thread.sleep(time);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
String msg = new Scanner(System.in).nextLine();
System.out.println("Sending message: '" + msg + "'");
out.print(msg);
Thread.sleep(time);
} catch (Exception e) {
System.out.println(e);
}
}
}
}).start();
//in.close();
//out.close();
//skt.close();
} catch (Exception e) {
System.out.print(e);
}
}
}
The server output:
Starting chat server using the port : 9999
Server has connected with client /127.0.0.1
The client output:
Client has connected with server 127.0.0.1:9999
simple message
Sending message: 'simple message'
Please explain why the server isn't working correctly.
Scanner.nextLine returns the line without the new line delim. The server is using BufferedReader.readLine, which expects a new line (or may block if it does not receive one). Solution: append the delimiter when sending messages. If using print, you must explicitly flush:
out.print(msg + "\n");
out.flush();//explicitly flush the stream
or use the println method to have it add the new line for you (and makes use of autoflush true flag passed to the PrintWriter constructor):
out.println(msg);//auto flushing
In both codes, put an out.flush() just right after the instanciation of PrintWriter out
The code below should allow the user to enter a URL and have it return the ip address of that website but it's not working.
The application is a console application. I had it working at one time but I don't know why it won't work now.
Here is the error i am getting when the users enters a website to get the ip address from
IOException: java.net.SocketException: Connection reset
HERE IS MY CLIENT CODE
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
String hostname = "localhost";
int port = 6052;
if (args.length > 0) {
hostname = args[0];
}
Socket clientSocket = null;
PrintWriter os = null;
BufferedReader is = null;
try {
clientSocket = new Socket(hostname, port);
os = new PrintWriter(clientSocket.getOutputStream(), true);
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + hostname);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + hostname);
}
if (clientSocket == null || os == null || is == null) {
System.err.println("Something is really wrong. ");
return;
}
try {
if (args.length != 2) {
System.out.print("Enter a www web address (must have www!) ");
BufferedReader br = new BufferedReader(new InputSreamReader(Sy.in))
String keyboardInput = br.readLine();
os.println(keyboardInput);
} else {
os.println(args[1]);
}
String responseLine = is.readLine();
System.out.println("The IP address of " + args[1] + "is" + responseLine);
} catch (UnknownHostException e) {
System.err.println("Trying to connect to host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
HERE IS MY SERVER CODE
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String args[]) {
int port = 6052;
Server server = new Server(port);
server.startServer();
}
ServerSocket echoServer = null;
Socket clientSocket = null;
int numConnections = 0;
int port;
public Server(int port) {
this.port = port;
}
public void stopServer() {
System.out.println("Server working hold on a min.");
System.exit(0);
}
public void startServer() {
try {
echoServer = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Server is now started and is waiting for Clients.");
while (true) {
try {
clientSocket = echoServer.accept();
numConnections++;
new Thread(new ServerConnection(clientSocket, numConnections,
this)).start();
} catch (IOException e) {
System.out.println(e);
}
}
}
}
class ServerConnection implements Runnable {
private static BufferedReader is;
private static PrintStream os;
private static Socket clientSocket;
private static int id;
private static Server server;
public ServerConnection(Socket clientSocket, int id, Server server) {
this.clientSocket = clientSocket;
this.id = id;
this.server = server;
System.out.println( "Connection " + id + " established with: " + clientSocket );
try {
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
}
public void run() {
String line;
try {
boolean serverStop = false;
line = is.readLine();
System.out.println( "Received " + line + " from Connection " + id + "." );
InetAddress hostAddress = InetAddress.getByName(line);
String IPaddress = hostAddress.getHostAddress();
os.println(IPaddress);
is.close();
os.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
With no arguments, host will be localhost, user will be propted for a website. ArrayOutOfBoundsException because you didn't check the arguments.
With one argument, it is the host. Passing a site will not work because the site won't work as expected.
Running with two arguments, it works if the first argument is localhost.