How to get the download file path on linux? - java

I have finished developing a java web app using spring and hibernate. In my app, there's a download function. The function runs well on windows env. But when I deploy and run the app on linux env, using Tomcat as the server, the function return zero byte file. The file type is excel (xls). But the browser returns this as pdf file.
Download Function Failed:
Xls File Path on Linux:
and here is the code:
#RequestMapping("downloadXlsTemplate")
public String downloadTemplate(HttpServletRequest request, HttpServletResponse response) {
try {
String filename = "Template.xls";
File onLinux = new File("/opt/tomcat7/webapps/xls/" + filename);
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment; filename=" + filename);
response.setContentLength((int) onLinux.length());
InputStream inputStream = new FileInputStream(onLinux);
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while((bytes = inputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
inputStream.close();
responseOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I have tried various ways, but none were successful.
I will really appreciate any idea, help, or solution
Regards
Yunus

The problem you are facing is a file permission problem. The file is owned by 'root' and your tomcat runs on other user.
Try to move the files to a shared location where the tomcat user can access it. Try the /tmp location or any other shared location.

If it is permission issue, try using chmod unix command giving required permission on file .
e.g., chmod u+rwx
As a good practice, try to refer the file using relative path (using class path resource) instead of absolute path (so it is environment independent).

Related

How can I write a file in tomcat folder?

I have deployed my application in Apache Tomcat.
I have a folder(assets) to save the files. So want to write a file inside webapps/assets
I tried the following code for that
private String uploadedFiles(MultipartFile files) throws IOException {
String filePath = "../assets/users/image/" + files.getOriginalFilename();
File file = new File(filePath);
byte[] bytes = file.getBytes();
FileOutputStream out = new FileOutputStream(file);
out.write(bytes);
out.close();
But i am getting java.io.FileNotFoundException: ../assets/myfile.jpg (The system cannot find the path specified)
How can save this file?
Note: I want this kind of folder structure. Since I will save "../assets/myfile.png" in the database to access from the client application deployed in the same server.
You can get the tomcat home path with
System.getProperty( "catalina.base" );
You can then add to this your path, in your case /webapps/assets
Hope this helps :)
Maybe I am wrong, but you should give bytes from Multipart files !
And such of kind
../assets/users/image/
is wrong. I think, you should start with root folder, or use Paths.get() nio.

Vaadin Upload function

I'm interested in having a button which takes a pic from the user's computer and uploads it on my server.
I managed to solve the server uploading part, but I'm having difficulties in handling the path from the user computer. Vaadin Upload does not provide me full path, but I want it to be dynamic. Looking at the documentation, they use some temp location, but I don't know how to implement that.
public OutputStream receiveUpload(String filename,
String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Stream to write to
try {
// Open the file for writing.
file = new File("/tmp/uploads/" + filename);
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
new Notification("Could not open file<br/>",
e.getMessage(),
Notification.Type.ERROR_MESSAGE)
.show(Page.getCurrent());
return null;
}
return fos; // Return the output stream to write to
}
I'm expecting that when the File Chooser closes, I get some kind of file path or handler so I can put it on my server.
In the filename argument you will have the name of uploaded file.
The path of the file however is not sent to the server, this is one of the restrictions of web applications / web browsers.
With the code you use, you will have a copy of the uploaded file on your server in the tmp folder.
There is no way to directly access files on client computers through the web browser.

Export in standalone app not working while functionning in Eclipse

I'm working on a standalone app where results are exported in an excel sheet. I use Jxls for the export. All is working in Eclipse, but the exported jar just gives me a non-working sheet. Is it a problem with the output stream that doesn't write anything, or is it something with the absolute path? I'm a bit confused here.
The export is made with the required libraries packed in the jar.
The code of the exporting part :
private void exportDataDet(File file) throws ParseException, IOException, ParsePropertyException, InvalidFormatException {
String path = System.getProperty("user.home") + File.separator + "tempFile";
File IdGenreXLS = new File(path + ".xlsx");
List<ResultsDetails> detRes = generateResultsDetails();
try(InputStream is = IdGenre.class.getResourceAsStream("/xlsTemplates/IdGenre/IdGenre_20-29-et=12.xlsx")) {
try (OutputStream os = new FileOutputStream(IdGenreXLS)) {
Context context = new Context();
context.putVar("detRes", detRes);
JxlsHelper.getInstance().processTemplate(is, os, context);
}
}
Thanks for any suggestion.
Alright, the hypothesis that nothing was written on disk was the good one, as eventually nothing was written on disk.
A simple
os.flush();
at the end makes everything working. There's nothing for it but to close the input and output stream after.

Launching phantomjs as a local Resource when using an Executable Jar

Need a little bit of help with this one.
My goal is to have an executable jar file that takes a screen-capture of a webpage and works on both windows and linux machines. I have tried using html2image but the results from phantomjs were exponentially better.
I have code that looks like this:
RESOURCE_PATH = MyClass.class.getClassLoader().getResource("resources").getPath();
public static void main (String[] args) {
String url = args[1];
String outFilePath = args[0];
final String phantomjsHome = RESOURCE_PATH + "/phantomjs/";
ProcessBuilder pb = new ProcessBuilder(phantomjsHome + "phantomjs.exe", phantomjsRasterizeScript, url, outFilePath);
Process process = pb.start();
process.waitFor();
}
Now I have tests which assure me when I'm running this as a java application it works fine but when I build an executable jar I get an error. I have checked and double checked that the RESOURCE_FOLDER is pointing at the correct location. But when I run the jar using
java -jar MyProject.jar "google.png" "https://google.com"
I get a
java.io.Exception: Cannot run program "file:/C:/Users/Joe/MyProject.jar/resources/phantomjs.exe": CreateProcess error=2, The system cannot find file specified
By the way this is my first time asking a question on SO, so if you need additional info or have any suggestions or comments on phrasing comment with some feedback. Thank You!
UPDATE
After some more searching I found that an executable could not be executed from within the jar. I have created a method to copy the executable to outside the jar which seems to work.
private static String loadPhantomJS() {
String phantomJs = "phantomjs.exe";
try {
InputStream in = WebShot.class.getResourceAsStream("/resources/phantomjs/" + phantomJs);
File fileOut = new File(storePath + phantomJs);
OutputStream out = FileUtils.openOutputStream(fileOut);
IOUtils.copy(in, out);
in.close();
out.close();
return fileOut.getAbsolutePath();
} catch (Exception e) {
return "";
}
}
please note that this method only works for windows machines, change the file path for linux.
The above method works for Windows machines, note though that any file you want to run must also exist unpacked, outside the jar file. A similar method to loadPhantomJS can be used to unpack other resource files from the jar file. I used this method:
private static void makeLocalFile(String outPath, InputStream is) {
try {
InputStream is;
File fileOut = new File(outPath);
OutputStream out;
out = FileUtils.openOutputStream(fileOut);
IOUtils.copy(in, out);
in.close();
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
I get an InputStream from my resources using, MyClass.class.getResourceAsStream("jsFile.js"). The only way I was able to get it to work so far on linux is by actually installing phantomjs the linux instillation first. Will update this answer if/when I find a better solution.

How to read a file from remote system using java?

I have a file copied in one computer and I need to access the file from other computer.
I am not sure, which protocol or which technology to use for this?
Please provide me any hints for this..
Update:
I am using Ubuntu Linux system.
I used the code :
File f = new File("//192.168.1.157/home/renjith/picture.jpg");// 192.168.1.157 is the ip of the computer, where I have the picture file
Image image = ImageIO.read(f);
But it is giving an exception:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(ImageIO.java:1275)
I have shared renjith folder also.
There are any number of ways to access files on remote machines, but they virtually all depend on the remote machine having been set up to provide the file in some way first. If you with to access files via java, the easiest method would probably be to set up an HTTP server on the remote machine (this can be done pretty easily using Apache HTTP server on a variety of platforms) and then using Apache Commons HTTPClient on the client side java app. Further discussion of how to install these or configure them is generally beyond the scope of Stack Overflow and would at least require a more specific question
HTTP is an option. However, if these are Windows machines on the same LAN, it would be easier to expose the directory on the remote machine via a file share and access the file through a regular file path. Similarly, if these are Unix-like machines, you could use regular file paths if you're using NFS. FTP's yet another option.
if the remote computer is in the same network and on a shared folder to the computer where your java code is running then try this piece of code for accessing it
File file = new File("\\\\Comp-1\\FileIO\\Stop.txt");
here Comp-1 is the DNS name of the machine containing the file in the network!!!
You might try:
URL url = new URL("file://192.168.1.157/home/renjith/picture.jpg");
Image image = ImageIO.read(url);
You could try to mount that path first, and then load it. Do a :
subst x: \\192.168.1.157
and then:
File f = new File("x:\\home\\renjith\\picture.jpg");
Image image = ImageIO.read(f)
It should work.
Share the directory and access the file thruogh java code
try this one:
File f = new File("//10.22.33.122/images")
File[] files = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
// Specify the extentions of files to be included.
return name.endsWith(".bmp") || name.endsWith(".gif");
}
});
// get names of the files
String[] fileNamesArray = null;
for (int indx = 0; indx < files.length(); indx++) {
fileNamesArray[indx] = files[indx].getName();
}
return fileNamesArray;
Map your IP to network drive and try let us say the drive letter is X,
then code changes to File f = new File("x:\\home\\renjith\\picture.jpg");
Infact your file is already loaded in object f , try priting the value of the path f.getAbsolutePath() to console and see.. Actual error is with ImageIO
You can read from remote and write to remote using jcifs-1.3.15.jar jar in java but first you need to share location from remote system then it's possible.
try{
String strLine="";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("WORKGROUP", "username", "passwd"); // Authentication info here, domain can be null
// try (InputStream is = new SmbFile("smb://DESKTOP-0xxxx/usr/local/cache/abc.txt", auth).getInputStream()) {
try (InputStream is = new SmbFile("smb://xx.xx.xx.xxx/dina_share/abc.txt", auth).getInputStream()) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}
} catch (IOException e) {
e.printStackTrace();
}
String smbURL="smb://xx.xx.xx.xxx/dina_share/abcOther.txt";
SmbFileOutputStream fos = new SmbFileOutputStream(new SmbFile(smbURL,auth));
byte bytes[]="Wellcome to you".getBytes();
fos.write(bytes);
}catch(Exception e){
e.printStackTrace();
}

Categories

Resources