Webservice uploaded image url - java

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.

Related

Azure : Image Magick gives 0kb output?

I have integrated Image magick with a Java WebApp and have deployed it on Azure App Service. On azure , I am getting 0kb as output image for a image while the same image gets converted fine on my local machine.
I am using im4java for integration with Image Magick.
Below is the code:
public void compressImage(String imageSource, String destinationPath) throws IOException, InterruptedException,
IM4JavaException {
ConvertCmd cmd = getCommand();
// create the operation, add images and operators/options
IMOperation op = new IMOperation();
op.strip();
op.interlace();
op.addRawArgs(compressionRawArguments);
op.gaussianBlur(compressionGaussianBlur);
op.quality(compressedImageQuality);
op.addImage(imageSource); // source file
op.addImage(destinationPath); // destination file
// execute the operation
cmd.run(op);
}
Both imageSource and destination are temp files created using java. I have checked that imageSource file has correct size but after running this code, the destination file is always 0 Kb.
Please advise what could I be doing wrong?
Answering my own question so that It might be helpful for fellow developers who might face this problem.
Azure App Service normally has Windows Server VMs. You can check the OS of your server in web container logs.
Image Magick for windows does not allow conversion of remote http
image urls while for Unix System, it allows so. My Local machine is
MAC So it was working correctly on my local system.
2 Solutions to this problem that I found:
Either you use a linux VM on Azure
In your application, download the image URL to a temp file and
supply the absolute path of that temp file to image magick for
conversion.
I have tried both and are both working.

File upload from a web-based application to a linux server

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

How to store files in client machine?

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.

Deployment in tomcat

i am getting a problem
i have deployed a war file, when i run localy through tomcat it works fine but when i run on another system by giveing my system ip and then project folder e.g
http:\192.168.0.145\DllTest it loads the applet but when i click on a button to load the functionality it is throwing an exception
Exception in thread "AWT-EventQueue-3" java.lang.UnsatisfiedLinkError: Expecting an absolute path of the library: http:\192.168.0.145:8080\DllTest\lib\jinvoke.dll
while it is working fine localy but not in another system. Please tell me what is the problem.
Is it a rights issue or something else.
You cannot load a DLL on an external host. It has to be an absolute disk file system -as the exception message already hints. Your best bet is to download it manually, create a temp file and load it instead.
File dllFile = File.createTempFile("jinvoke", ".dll");
InputStream input = new URL(getCodeBase(), "lib/jinvoke.dll").openStream();
OuptutStream output = new FileOutputStream(dllFile);
// Write input to output and close streams the usual Java IO way.
// Then load it using absolute disk file system path.
System.loadLibrary(dllFile.getAbsolutePath());
dllFile.deleteOnExit();

Eclipse FileInputStream with local development and remote file

I'm developing a java web app on my local PC that uses a file on the deployment server. I have to do something like this to get it to work both locally during development and on the server when deployed. Is this standard practice? Or is there a way in Eclipse using linked folders and files to specify the file the same as it is referenced on the server?
InputStream in = null;
try {
in = new FileInputStream("/EBWEB/www/homepages/path/to/file/STKCore.properties");
} catch (java.io.FileNotFoundException ex) {
in = new FileInputStream("W:/internal/www/homepages/path/to/file/STKCore.properties");
}
W: is how I have the remote server mapped using Samba in Windows XP on my PC.
You can put your properties file in your war and open it with a getResourceAsStream().

Categories