java jar file reading image file - java

i have stand alone application, which has one of the module to sent out emails. This application packaged as executable JAR containing all the resource files including images.
I am using spring for sending email, which contains following code for inline:
Spring code is using org.springframework.core.io.FileSystemResource
//IN-LINE ATTCHEMENTS
if (null != msg.getInlineAttachments() && msg.getInlineAttachments().size() > 0) {
for (Map.Entry<String, File> e : msg.getInlineAttachments().entrySet()) {
if (log.isTraceEnabled()) {
log.trace("Conntent-ID:" + e.getKey() + ", Resource:" + e.getValue());
}
try {
helper.addInline(e.getKey(), new FileSystemResource(e.getValue()));
} catch (Exception e1) {
log.error(e1);
}
}
}
File image is passed to above code using following:
ClassPathResource res = new ClassPathResource("./images/" + name);
if (log.isTraceEnabled()) {
log.trace(res.getFile().getAbsolutePath());
}
file = res.getFile();
Note:
Application works fine when executed in development environment in eclipse, because it is exploded format, non-jar.
Exception:
java.io.FileNotFoundException: class path resource [images/app_logo.png]
cannot be resolved to absolute file path because it does not reside in the file system:
jar:file:/C:/TEMP/app-1.0/app-1.0.jar!/images/app_logo.png

You need to handle the image as a Stream instead of a File. Files are concept that are only valid in a filesystem, but you are trying to access something inside of a Jar which isn't a filesystem.

Only option left out is copy image files into temp folder, and reference from there...

Related

FileNotFoundException while getting file from resources folder using getResource()

I need to get this file from the resources folder in the File object, not in InputSream.
I am using below code, working file on eclipse but FoleNotFoundException on the server. )Using AWS EC2)
Code:
URL res = ResidentHelperService.class.getClassLoader().getResource("key.pem");
System.out.println("resource path2 :" + res);
File privateKeyFile = Paths.get(res.toURI()).toFile();
After printing path looks like:
:jar:file:/home/centos/myproject/microservices/user-service/target/user-service-0.0.1-SNAPSHOT.jar!/BOOT-INF/lib/project-common-utility-0.0.1-SNAPSHOT.jar!/key.pem
I have added dependency on the common jar to user service pom.
Please help me to get the file from resources of a common project.
If you have your file in resources folder, the easiest way to access it from the code is probably to use org.springframework.util.ResourceUtils class that Spring provides:
try {
final File file = ResourceUtils.getFile("classpath:key.pem");
....
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Perhaps this way can help you with your issue.

Packaged Jar unable to read files from mapped network drive (Windows)

I have a Spring Boot application which reads files in folders on a mapped network drive, i.e. m:/PRODUCTION
The problem is, when I execute the jar file, my debugging output shows that no files exist in the folder, even though the folder is full of a files.
I have IntelliJ installed on the same machine, and if I run the application from it's source code, it works absolutely fine.
The method I have that reads filename to an array is;
private File[] getFilesInPath(String path) {
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null) {
Arrays.sort(listOfFiles, Comparator.comparingLong(File::lastModified));
}
return listOfFiles;
}
Then, I call this function from a number of places in the application, here's an example;
public void manuallyProcessAttritionData(List<Line> lines) {
Handler handler = new AttritionHandler().setLines(lines).setService(this);
String pathToProcess = dataFolder + attritionFolder;
log.debug("Processing path: " + pathToProcess);
File[] listOfFiles = getFilesInPath(pathToProcess);
if (listOfFiles != null) {
log.debug("Number of files to process: " + listOfFiles.length);
for (File file : listOfFiles) {
handler.processFile(file);
}
} else {
log.debug("No files to process");
}
}
The output from running the above is;
Processing ATTRITION data...
Processing path: m:/PRODUCTION
No files to process
...Finished processing ATTRITION data
I've confirmed the path is correct, running the following commands from the command line works fine and there are files in the result;
cd m:\PRODUCTION
M:\PRODUCTION>
Does anyone know of a reason why the folder can be read perfectly find from the application running in IntelliJ, but not when packaged as a JAR file?
Looks like your development account Intellij has access to this drive where as the account which started this spring-boot doesn't have access to it.
I would suggest using full path instead of a mapped network path.
There should be no difference in running the code from intelliJ or running it from the built jar. But there may be other factors comming into play. Maybe you run intelliJ with a different user than the jvm that runs the jar? I propose the following steps to resolve the issue:
1. Use the Path Class to avoid platform specific problems (eg. file separators)
Instead of
new File("path/to/my/directory");
you should use
Paths.get("path", "to", "my", "directory").toFile()
or
Paths.get("path/to/my/directory").toFile()
2. Check the file attributes
Use the code below to investigate if the directory exists, if you have the correct permissions etc.
Path directory = Paths.get("e:/TEMP");
System.out.println("Absolute Path of directory: " + directory.toAbsolutePath());
System.out.println("Directory exists: " + directory.toFile().exists());
System.out.println("Directory is a directory: " + directory.toFile().isDirectory());
System.out.println("Directory isReadable: " + directory.toFile().canRead());
System.out.println("Directory isWriteable: " + directory.toFile().canWrite());
this should output something like:
Absolute Path of directory: e:\TEMP
Directory exists: true
Directory is a directory: true
Directory isReadable: true
Directory isWriteable: true

Jar classpath resources read failing which is triggerred from other executable jar

With reference to the link: How do I read a resource file from a Java jar file?
I am trying using your code base and trying to read content of sample.csv which is residing in my project directory src/main/resources. I am unable to read the content, it says can not read file. Output:
[Can not read file: sample.csv]
//This is added within your while loop after this check /* If it is a directory, then skip it. */
I mean when file is detected then next is my below code snippet added to read the file content
if(entry.getName().contains("sample.csv")) {
File f1 = new File("sample.csv");
if(f1.canRead()) {
List<String> lines = Files.readAllLines(f1.toPath());
System.out.println("Lines in file: "+lines.size());
} else {
System.out.println("Can not read file: "+entry.getName());
}
}
Can anyone educate me what I am doing wrong here, how can I make it working?
My requirement is this:
(My micro-service) Service.jar imports Parser.jar library in its pom.xml
(My library) - Parser.jar has FnmaUtils-3.2-fieldMapping.csv file in src/main/resources directory
There is a FnmaUtils class that loads the FnmaUtils-3.2-fieldMapping.csv within its constructor, this class is part of Parser.jar - Here I am trying to read the content FnmaUtils-3.2-fieldMapping.csv, this step is keep failing with below error, tried all possible options shown in [How do I read a resource file from a Java jar file?
public FnmaUtils() {
String mappingFileUrl = null;
try {
Resource resource = new ClassPathResource("FnmaUtils-3.2-fieldMapping.csv");
mappingFileUrl = resource.getFile().getPath();
loadFnmaTemplate(mappingFileUrl);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("Error loading fnma template file ", e);
}
}
Getting error:
java.io.FileNotFoundException: class path resource [`FnmaUtils-3.2-fieldMapping.csv`] cannot be resolved to absolute file path because it does not reside in the file system: `jar:file:/home/ravibeli/.m2/repository/com/xxx/mismo/util/fnma-parser32/2018.1.0.0-SNAPSHOT/fnma-parser32-2018.1.0.0-SNAPSHOT.jar!/FnmaUtils-3.2-fieldMapping.csv`
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:218)
at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:52)
at com.xxx.fnma.util.FannieMaeUtils.<init>(FannieMaeUtils.java:41)
at com.xxx.fnma.processor.FNMA32Processor.<init>(FNMA32Processor.java:54)
at com.xxx.fnma.processor.FNMA32Processor.<clinit>(FNMA32Processor.java:43)
What is going wrong here?
Try
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
Be sure the resource is in your classpath.

folder is created in eclipse home not in web application

I have create folder (i.e uploads ) in web application. I want to create one more folder inside "uploads" folder at runtime depends one the username of user. for this i have write below code. This code is creating folder and file but the location is different that i expected.
the location that i am getting is in eclipse location not web application location
D:\PAST\RequiredPlugins\JUNO\eclipse\uploads\datto\adhar.PNG
then i am getting error in FileOutStream that "system can't find the location specified."
public String getFolderName(String folderName, MultipartFile uploadPhoto)
throws ShareMeException {
File uploadfFile = null;
try {
File file = new File("uploads\\" + folderName);
if (!file.exists()) {
file.mkdir();
}
uploadfFile = new File(file.getAbsoluteFile()
+ "\\"+uploadPhoto.getOriginalFilename());
if (uploadfFile.exists()) {
throw new ShareMeException(
"file already exist please rename it");
} else {
uploadfFile.createNewFile();
FileOutputStream fout = new FileOutputStream(uploadfFile);
fout.write(uploadPhoto.getBytes());
fout.flush();
fout.close();
}
} catch (IOException e) {
throw new ShareMeException(e.getMessage());
}
return uploadfFile.getAbsolutePath();
}
i want to save uploaded file in web app "uploads" folder
Your filename is not absolute: uploads\folderName is resolved against the current directory, which the Eclipse launcher sets to JUNO\eclipse.
You should introduce an application variable like APP_HOME and resolve any data directory (including upload) against this variable.
Also, I suggest not to name anything (neither files nor directories) on your filesystem after user-entered input: you are asking for troubles (unicode characters in the user name) and especially security holes (even in combination with the unicode thing). If you really want to use the filesystem, keep the filename anonymous (1.data, 2.data, ...) and keep metadata inside some database.
You can do something on below lines in your webapp:-
String folderPath= request.getServletContext().getRealPath("/");
File file = new File (folderPath+"upload");
file.mkdir();

Java getDeskTop issue

Having a issue with getDeskTop().open / .edit(file) in that it is working properly on development drive by opening the file but when I move the application (jar) to another drive I get no error and no response. The paths are hardcoded "/home/temp/" + file, the application creates folders on start, basically the application is a personal version system serializes file contents to XML, when selected it deserializes then writes the file to a temp folder then calls getDeskTop().open(file). The confusing part is that I also call getDeskTop().open(file) on the VersionControl.xml that the app creates and it works properly, checked the path vars to the file and they are correct. Here is the basic call, I get the path vars from a JTable cell:
case 2 :
File fr = new File((String) jt.getModel().getValueAt(tmpRow, 2));
javaxt.io.File ft = new javaxt.io.File((String)jt.getModel().getValueAt(tmpRow, 2));
//JOptionPane.showMessageDialog(null, fr.toString());
if (!AppVars.getIllegalExt().contains(ft.getExtension())) {
try {
Desktop.getDesktop().edit(fr);
} catch (IOException e1) {
e1.printStackTrace();
}
}
break;
It seems somehow I am missing a reference, the "Make" configuration is to extract dependencies into the jar.

Categories

Resources