maven/spring uploaded on jelastic having images problem, when uploaded by user? - java

I have uploaded my maven/spring project on jelastic and using following to save images:
ServletContext servletContext = request.getSession().getServletContext();
String absoluteFilesystemPath = servletContext.getRealPath("/");
byte[] fileData = file.getBytes();
String name=Trader.getImage();
if (fileData.length != 0) {
String fileName =login.getUserName()+".jpeg";
File f = new File(absoluteFilesystemPath+"\\img\\"+fileName);
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(fileData);
fileOutputStream.close();
}
It is working on localhost images are saved in img folder while on server it is saved on absolute path as name "img/xyz.jpeg"
i want to save it on
myproject/img/
It is saving on
myproject

Isn't your \ the wrong way? I'm going to guess that your localhost is Windows?
Jelastic is Linux based, so filesystem paths contain / not \. Maybe try
File(absoluteFilesystemPath+"/img/"+fileName);
Edit: according to File.separator vs Slash in Paths you might want to use File.separator instead for proper platform independence.

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.

Java - Japanese filenames garbled

I am running a standalone java process which writes data to multiple xlsx files in a parent target directory and upon completion, the entire target directory is zipped and uploaded to cloud and a download link is provided to the user. The xlsx file names and the name of the zip file is user defined and not possible to change.
The issue is with the names of the xlsx files created. If the filename selected by the user is Japanese, like
サイン色紙プレゼントCPN_第2.xlsx
the corresponding file that is created in the system is of the form:
??????????CPN_?2?.xlsx
The same files are being uploaded to cloud and user is seeing garbled file names. However, the Japanese name of the zip file is not garbled and is in Japanese only.
Following is the code sample for creating xlsx files:
String fileName = userGivenName + "_" + randomUUID + ".xlsx";
File file = new File(tmpParentDirectoryName, fileName);
FileOutputStream outputStream = new FileOutputStream(file);
workbook.write(outputStream);
In this case the absolute path of the xlsx file created is like :
/tmpDirectoryPath/??????????CPN_?2?_0c6b37ee-97c4-44d4-b80d-dfe5eafe0045.xlsx
Just like above there are multiple xlsx files created in the same tmpDirectory
Upon completion following is the code sample to create zip files and upload to cloud:
File[] files = getFilesInFolder(tmpDirectory);
if (ArrayUtils.isEmpty(files)) {
continue;
}
File zipFile = new File(targetDirectory, compressedFileName);
createZipFile(files, zipFile);
String url = uploadFile(compressedFileName, zipFile);
Following piece of code writes data to zip file:
public static void createZipFile(File[] files, File zipFile) {
if (ArrayUtils.isEmpty(files)) {
return;
}
byte[] buffer = new byte[1024];
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
try {
for (File file : files) {
FileInputStream fis = new FileInputStream(file);
try {
String fileName = URLDecoder.decode(file.getName(), "UTF-8");
ZipEntry zipEntry = new ZipEntry(fileName);
zos.putNextEntry(zipEntry);
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
} finally {
IOUtils.closeQuietly(fis);
}
}
} finally {
IOUtils.closeQuietly(zos);
}
}
The uploaded zip file has the correct Japanese name but the zip entries of the zip file have garbled xlsx filenames.
The standalone java process has following encoding options:
-Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8
Following is the output of the locale command:
locale
LANG=en_IN.UTF-8
LC_CTYPE="en_IN.UTF-8"
LC_NUMERIC="en_IN.UTF-8"
LC_TIME="en_IN.UTF-8"
LC_COLLATE="en_IN.UTF-8"
LC_MONETARY="en_IN.UTF-8"
LC_MESSAGES="en_IN.UTF-8"
LC_PAPER="en_IN.UTF-8"
LC_NAME="en_IN.UTF-8"
LC_ADDRESS="en_IN.UTF-8"
LC_TELEPHONE="en_IN.UTF-8"
LC_MEASUREMENT="en_IN.UTF-8"
LC_IDENTIFICATION="en_IN.UTF-8"
LC_ALL=
Can someone direct me as to what am I doing wrong here ? I want the same filenames to be uploaded as given by the user.
I was finally able to crack this.
The issue was with the system properties of the mesos slave that was executing the java process.
The process on the slave was started by a mesos master scheduler using a startup script. Due to this the default java locale properties were not being set up properly on the slave.
I added the following line to the start-up script of the slave:
export LANG=en_IN.UTF-8
Upon explicitly adding the locale property to the start-up script, was able to resolve the issue.

Inputstream is null, while loading a file from a file path in windows service

Im trying to read a file from a path.
This is my sample code;
String path = "repository"+ File.separator +"resources"+ File.separator +"api_templates";
String fileName = path + TEMPLATE_FILE_PREFIX + type + ".xml";
InputStream in = null;
try {
log.info("##############File path#############"+fileName);
in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
Here i get inputstream as null. I suspect the system could not load the file. But when i print my filepath, it correctly prints my file path.
This problem occurs only when i try to run my server as windows service, using "yajsw".
What might be the issue?
Edit:
My Sample wrapper-conf file;
#********************************************************************
# working directory
#********************************************************************
wrapper.working.dir=${my_home}
............
wrapper.java.additional.2 = -Xms256m
wrapper.java.additional.3 = -Xmx1024m
wrapper.java.additional.4 = -XX:MaxPermSize=256m
wrapper.java.additional.5 = -XX:+HeapDumpOnOutOfMemoryError
wrapper.java.additional.6 = -XX:HeapDumpPath=${my_home}\\repository\\logs\\heap-dump.hprof
wrapper.java.additional.7 = -Djava.endorsed.dirs=${my_home}\\lib\\endorsed;${java_home}\\jre\\lib\\endorsed
This is because of a classpath issue between resources and files. We can not use classloaders to access files. For that we need to use File, filereader, file input stream. After changing like this everything works fine;
InputStream in = new FileInputStream(filePath);

How to get the download file path on linux?

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).

how to reach a file in www directory from a servlet?

Using tomcat 6, i created a template inside www/templates/templatefile.html
how do I access it from a servlet ? i want to read the html file and parse it.
I tried getting the real path using request.getRealPath(request.getServletPath())
and from there to go to the templates directory but for some reason it still can't find the file.
Assuming that www is a folder in the public web content root, then you can use ServletContext#getRealPath() to convert a relative web path to an absolute disk file system path as follows:
String relativeWebPath = "/www/templates/templatefile.html";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
InputStream input = new FileInputStream(file);
// ...
Note that this won't work when the WAR is not expanded (Tomcat in default trim does it, but it can be configured not to do that). If all you want to end up is having an InputStream of it, then you'd rather like to use ServletContext#getResourceAsStream() instead.
String relativeWebPath = "/www/templates/templatefile.html";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// ...

Categories

Resources