Files not found in JAR FIle - spring

I am trying to find a folder containning PDF's . Everything works when the backend and frontent is not a Jar file.
My question is how do you locate files ,if it is in a JAR, all I am recieving is a file not found exception
Tried adding the file to my resources folder but still nothing.
What am I missing?

This can be accomplished in a number of ways, here are a couple:
// get the resources as a URL
URL resource = getClass().getClassLoader().getResource(
"static/test/TrainingDocuments/SuperUser/2/PartnerInformation/PartnerInformation.pdf");
// get the resource as a classPathResource
ClassPathResource classPathResource = new ClassPathResource(
"static/test/TrainingDocuments/SuperUser/2/PartnerInformation/PartnerInformation.pdf");
// get the resource directly as a stream
InputStream resourceAsStream = getClass().getClassLoader()
.getResourceAsStream("static/test/TrainingDocuments/SuperUser/2/PartnerInformation/PartnerInformation.pdf");

Related

How to Read File from PersistentVolumeClaims in SpringBoot

I have "file.txt" in my OpenShift PersistentVolumeClaims.
My StorageClasses is NFS.
Is it possible to access and read "file.txt" from my spring-boot code?
(This spring-boot code will be deployed on OpenShift and I'll mount the PVC to the DeploymentConfigs)
If yes, how can I do that? (I'm confused in how to retrieve the file from persistent volume from inside the code)
Any help will be appreciated. Thanks.
What #larsks said in the comment is correct:
your application doesn't know or care about the fact that you're using
a persistent volume
However, I used:
Resource resource = new ClassPathResource("/pvc/mount/path/file.txt");
InputStream inputStream = resource.getInputStream();
and:
Resource resource = resourceLoader.getResource("/pvc/mount/path/file.txt");
InputStream inputStream = resource.getInputStream();
Both doesn't work.
Below is what I use in the end:
Path file = Paths.get("/pvc/mount/path/file.txt");
InputStream stream = Files.newInputStream(file);

Spring kafka not able to read truststore file from classpath

I am building an kafka consumer app which needs SASL_SSL config. Some how apache kafka is not recognizing truststore file located in classpath and looks like there is an open request to enhance it in kafka(KAFKA-7685).
In the mean time what would be the best way to solve this problem. Same app needs to deployed in PCF too so solution should work both during local windows based development and PCF (linux).
Any solution would be highly appreciated.
Here is the code which does file copy to java temp dir
String tempDirPath = System.getProperty("java.io.tmpdir");
System.out.println("Temp dir : " + tempDirPath);
File truststoreConf = ResourceUtils.getFile("classpath:Truststore.jks");
File truststoreFile = new File(tempDirPath + truststoreConf.getName());
FileUtils.copyFile(truststoreConf, truststoreFile);
System.setProperty("ssl.truststore.location", truststoreFile.getAbsolutePath());
You could use a ClassPathResource and FileCopyUtils to copy it from the jar to a file in a temporary directory in main() before creating the SpringApplication.
Root cause of this issue was resource filtering enabled. Maven during resource filtering corrupts the binary file. So if you have that enabled, disable it

Updating Tomcat WAR file on Windows

I have inherited a Maven/Tomcat(8.5) web application that is locally hosted on different machines. I am trying to get the application to update from a war file that is either stored locally (on a USB drive) or downloaded from AWS on Windows more reliably. On the Linux version, the software is able to upload the new war file via curl using the manager-script by doing the following:
String url = "http://admin:secret#localhost:8080/manager/text/deploy?path=/foo&update=true";
CommandRunner.executeCommand(new String[] { "curl", "--upload-file", war, url });
For Windows, the current current method tries to copy over the war file in the /webapps directory and has tomcat auto deploy the new war file after restarting either tomcat or the host machine. The problem is that the copied war file ends up being 0kb and there is nothing to deploy. This appears to happen outside of my install function because the file size after FileUtils.copyFile() for the /webapps/foo.war is the correct size.
I have tried to implement a PUT request for the manager-script roll from reading the Tomcat manager docs and another post:
File warfile = new File(request.getWar());
String warpath = warfile.getAbsolutePath().replace("\\", "/");
//closes other threads
App.terminate();
String url = "http://admin:secret#localhost:8080/manager/text/deploy?path=/foo&war=file:" + warpath + "&update=true";
HttpClient client = HttpClientBuilder.create().build();
HttpPut request;
try {
request = new HttpPut(url);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.err.println(result.toString());
} catch (Exception e){
LOGGER.info("war install failed");
throw new ServiceException("Unable to upload war file.", e);
}
However, the process still ends up with a 0kb war file to /webapps. The only error in my log is when tomcat tries to deploy the empty war. I have tried relaxing file read/write permissions in my tomcat installation and it doesn't seem to help. I also don't know if I can guarantee that all Windows installations will have access to curl if I try that implementation. Has anyone ran into similar issues?Thank you for the help!
Will, you are openning the file for sure but you are not writing anything to it, the result string is wrote to the stdout, so you got to replace System.err.println(result.toString()); with fr = new FileWriter(file); br = new BufferedWriter(fr); br.write(result);
and don't forget to close your resources at the end (br.close(); fr.close(); ) :)
PS: check if there are some informations to be filtered (headers or staff like that)

Cannot access pdf files in resources folder

i have a web app where i put some pdf files in the resources folder that are rendered to users when they click a download button, this is how i read the file
ClassLoader classloader = Thread.currentThread().getContextLoader();
File f = new File(classloader.getResource("pdf/report.pdf").getFile);
Then i render the file within a response, this works fine when i run it in eclipse.
But once i package it into a war file and deploy it using apache tomcat manager, i cannot access the file anymore it shows me a 500 ERROR that the specified access file is inaccessible.
If I understand your question correctly, then you need to get stream for the resource and serve response from that resource and not from the file. Classloader has function getResourceAsStream which should work with same parameter your are passing to getResource
ClassLoader classloader = Thread.currentThread().getContextLoader();
InputStream stream = classloader.getResourceAsStream("pdf/report.pdf")
// Copy resource stream to servlet response e.g. using Apache IOUTils
IOUtils.copy(stream, <servelet response stream>)
// Don't forget to close stream
Eclipse most like is resolving local file path which may not work in web applications environment in same way.
open your war file and check manually into "/WEB-INF/classes/" folder your file is exist into this folder or not.

How to get Relative Path in Spring web project

I am creating a spring web project where i am uploading a csv file and saving it to database. I need to keep the file in the relative path of the project so that it can be accessed through the url.for example: localhost:port/project_name/file_name
But I am getting the absolute path everytime using servlet context or URL.
Please help me out to get the relative path in spring controller.
You can save the file wherever you want. I particularly create a folder in the tomcat's directory and access it through the Java System Property System.getProperty("catalina.base");
Then to the url you can choose one of these possibilities:
Create a controller that serves the file.
Declare an Context in tomcat: option1 or option2
For example, I saved the file in:
System.getProperty("catalina.base")+File.separator+"mydata"+File.separator+filename;
I can create the controller:
#Controller
public class MyDataController {
#RequestMapping("/mydata/{filename}")
public String helloWorld(#PathVariable("filename") String filename) {
String path = System.getProperty("catalina.base")+File.separator+"mydata"+File.separator+filename;
return new FileSystemResource(new File(path));
}
}
or declare a context in tomcat create the file: [tomcat6directory]/conf/Catalina/localhost/appcontext#mydata.xml containing
<Context antiResourceLocking="false" privileged="true" path="/mydata" docBase="${catalina.base}/mydata" />

Resources