It seems that my code won't work after learning that the machine that I'll be pointing the upload path to is a Linux box.
My use case is, a user logs in to the web app, chooses a file to upload, then click upload button. Is it possible to do this direct from the Java code to the Linux server using appropriate ssh or scp libraries if there is any?
EDIT: Here's my current code.
#Override
public void fileTransfer(File uploadedFile, String fileName, String pathTemp) {
File destFile = new File( pathTemp + File.separator + fileName);
try{
FileUtils.copyFile(uploadedFile, destFile);
String getTempFile = destFile.toString();
String tempPath = getTempFile.replace("\\", "\\\\");
File tempFile = new File(tempPath); // 1st file
String tempFileName = tempFile.getName();
String fileSave = getUploadPathSave().replace("\\", "\\\\");
tempFile.renameTo(new File(fileSave + tempFileName));
} catch (IOException ex) {
System.out.println("Could not copy file " + fileName);
ex.printStackTrace();
}
}
If your app is deployed at one place only (not mass distribution), the easiest way would be:
create samba share on linux machine
map samba share to logical drive on windows machine
do usual file copy with java functions.
attention: renameTo will not work between drives. You'll need to copy input stream to output stream or, better, use apache commons-io functions for that.
There are different possibilities:
If you can create a shared directory in linux and mount it under windows (see Samba. Then you can write to that directory like a local directory. File will go to the linux server.
Use a library like Jsch to upload the file from windows server to linux server.
There are certain things you can do:
1-> If you can program your linux server, then you can make a program that listens to user request on a port, and stores data in file. Then you can send you files to that port of server.
2-> The other way is you can use some sort of script to create ssh-connection to server and then you can just add file through ssh, but here your java program will not be useful.
I personally use my own program to share files between 2 machines in same network.
You can use it,if it will be useful for you: https://github.com/RishabhRD/xshare
Related
I have a file on S3 which I am downloading using a s3 handler. It gets downloaded to the cloud desktop (where my code is located). I have used the following to get the path:
String home = System.getProperty("user.home");
File file = new File(home+"/Downloads/" + fileName + ".txt");
I want the file to be downloaded to the local machine instead of the cloud desktop. Is there a way to route the file from cloud desktop to local? What can be done to get the file on the local machine instead? Any ideas?
I have installed wkhtmltopdf utility and its accessible via mac terminal. But when I'm trying to access it via java code, I get the following error
Cannot run program "wkhtmltopdf": error=2, No such file or directory
I am using this wrapper of wkhtmltopdf https://github.com/jhonnymertz/java-wkhtmltopdf-wrapper
Same code is perfectly running fine in windows system. So i believe issue is something related to tomcat not able to access the wkhtmltopdf utility.
Here is the code that i am using,
Pdf pdf = new Pdf();
pdf.addPage(serverBasePath + "/htmlview", PageType.url);
// Save the PDF
pdf.saveAs(filePath + "\\" + filename);
You need to tell java-wkhtmltopdf-wrapper were the actual program is on the disk. Try this:
WrapperConfig wc = new WrapperConfig("C:\\Program Files\\wkhtmltopdf\\wkhtmltopdf.exe");
Pdf pdf = new Pdf(wc);
...
pdf.saveAs(...);
File dir = new File(System.getProperty("user.home")+"\\Desktop\\" + svc);
dir.mkdir();
File f;
f = new File(System.getProperty("user.home")+"\\Desktop\\" + svc
+ "\\" + logFile + "_" + System.currentTimeMillis()
+ ".txt");
I am using this code to store the files in the user(client) machine.But it is storing the files in the server machine.Can anyone help me on this? I have deployed my war file in unix server.
Saving a file on a client machine from software running on a server is not as simple as that.
Servers do not have direct access to the file system of any client - it would be very insecure if that were the case.
The simplest way to do this is by making the server return a web page with a link which the user can click to download the file.
You could also do something more complicated, for example write an applet that downloads the file (using some file transfer protocol) and saves it in the local file system. The applet would need to have the appropriate permissions (by default, applets cannot access the local file system).
Seems like this code is part of a Web Application Server Side. In this case System.getProperty("user.home") will return Server's home directory.
I am trying to read a file which is in the remote linux server. But I do not know how to get the inputstream of the file using java.
How can this be done?
Assuming that by "remote linux server" you mean "remote linux shell", you should use an ssh library like JSch. You can find a file download example here.
Maybe SSHJ can help you? https://github.com/shikhar/sshj
Features of the library include:
reading known_hosts files for host key verification
publickey, password and keyboard-interactive authentication
command, subsystem and shell channels
local and remote port forwarding
scp + complete sftp version 0-3 implementation
Assuming you have a working connection to the server and access to the file, you can create a File object with the URI of the file:
File f = new File(uri);
FileInputStream fis = new FileInputStream(f);
The URI should be the URI to the file, for example "file://server/path/to/file".
See also the Javadoc for File(URI) .
It depends on how is the file available. Is it by HTTP, FTP, SFTP or through a server you wrote yourself ?
If your want to get the file through HTTP, you can use this :
HttpURLConnection connec = (HttpURLConnection)new URL("http://host/file").openConnection();
if(connec.getResponseCode() != connec.HTTP_OK)
{
System.err.println("Not OK");
return;
}
System.out.println("length = " + connec.getContentLength());
System.out.println("Type = " + connec.getContentType());
InputStream in = connec.getInputStream();
//Now you can read the file content with in
There is also Jsch library which is very good for SFTP / SCP
You can use any ssh java lib, as was mentioned in other answers, or mount directory with file as NFS share folder. After mounting you can use usual java API to acsess file.
Example
I am using java webservice (on tomcat).
I have the following code that handles image upload:
public String uploadPicture( long xId,
int pictureIndex,
String imageData )
{
File imageFile = new File( new String( "D:\\" + xId + "_" + pictureIndex ) );
try
{
FileOutputStream fos = new FileOutputStream( imageFile );
byte[] encodedImage = Base64.decode( imageData );
fos.write( encodedImage );
fos.close();
return imageFile.getPath();
}
catch( FileNotFoundException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch( Base64DecodingException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch( IOException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
I specify the path as D:\ since it is on the local PC.
But I need to update it the the path on the server where it will be deployed - then should change it to ~\picDir? something like that?
The webservice url: http://192.168.0.11:8080/XWebService/services/XWebService
will be updated to domain instead of the 192.168.0.11
What should be the URL to get the image? (E.g. if the picture folder is: ~\picDir)
If target server will run Linux/Unix, then proper path should be something like /usr/share/myapp. '~\' is totally wrong, I guess you meant '~/' which will point to home folder of current user. This should be avoided since you might run web server as different users with different home directories. Usually, on each environment (developer machine, demo, live server) you should have such place for storing configuration and data needed by an application.
File System location of your pictures has nothing to do with the URL under which photos will be located. It depends on Web Server (Tomcat, Jetty, JBoss, etc.) which will run your application and your application itself. For instance, you can configure your Tomcat server to map domain www.myapp.com to /var/lib/tomcat6/webapps/myapp/ directory. Servlet which will publish images might take them from configuration dir mentioned in 1. = /usr/share/myapp/picDir. If the servlet can be accessed via /pictures?picId=1 then you will find them under www.myapp.com/pictures?picId=1. However, if you just want to put static images inside your *.war file to be accessed by the browser, put them in root directory of your *.war file.
To summarize:
Choose (and tell us) your application server
Use some configuration directory for all environments and configure your server to be able to see it
Configure your server for desired domain
You should read more about context of *.war files and how the file itself is being organised.
Understanding URLs and context on example of Tomcat
Assuming that:
On your local machine desired servlet is located under: http://localhost:8080/myapp/utils/myservlet.html
Your app is packed as myapp.war
Remote Tomcat has IP 2.2.2.2 and is running on port 8080
When you deploy your myapp.war to remote Tomcat into webapps directory (/var/lib/tomcat6/webapps) it will get unpacked and you will be able to see your servlet under http://2.2.2.2:8080/myapp/utils/myservlet.html. By configuring your application in Tomcat's server.xml you can add domain name and reduce unnecessary "myapp" part called context, effectively leaving URL in form of http://www.myapp.com/utils/myservlet.html. This is what you want in production environment. This topic is explained in Tomcat's documentation, please refer to it.
Accessing File System resources from web application
If you would like to save or get any file from your server, please keep in mind that client (Web Browser) has no idea about underlying disk structure. The browser uses request-response communication pattern which (in terms of upload/download) can be handled by server like this:
upload - grab some byte content from Request and save it as a file on server file system
download - read some byte content from server file system and stream it as a Response
As you can see in both cases server file system is internal concern of the server itself. You can save it anywhere you want. You can read bytes from whatever location. That is why it's good to have MYAPP_CONF (mentioned in comments) to store and read those files always from some predefined directory.