How to get Relative Path in Spring web project - spring

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" />

Related

spring boot read property value from file content (not property file)

Is there a way to inject the value of a property from file content?
In my case i want to read a public certificate:
#ConstructorBinding
#ConfigurationProperties(prefix = "certificate")
#Value
public class Certificate {
String publicKey;
}
The certificate is in a file with content like
-----BEGIN CERTIFICATE-----
MIIC3DCCAcSgAwIBAgIGAYYWvEf6MA0GCSqGSIb3DQEBCwUAMC8xLTArBgNVBAMM
JDhjOGVmNjQxLTEwMGEtNDUxMi1iOTFhLWM3Mzc5NDcwMTdjMzAeFw0yMzAyMDMx
...
4/eJiZvtUhlPTZAeBCbmwHhLFufMRrYtOje/JLDcXFUhF4Ypb6BITbbWijJ7oMqP
1Amyt3eKiVhFdIVk1U4gp19wda4oeKP+5gaPTvAlYrN+EWdC1lUDRBipcM5zioFk
CwELjzRA2Dzg059g93NN7Q==
-----END CERTIFICATE-----
Currently i have 2 ways to load this as property:
load it in env variable with shell CERTIFICATE_PUBLIC_KEY="$(cat ./certs/device-cert.pem)" - need to run before
change the file to a property file beginning with certificate.publicKey=
and adding "\n" at every line end and adding it as additional property source
Is there a way to load the file content directly into a property on start?
At the moment i don't want to loose the Spring Boot Property feature - because it is really flexible.
If not possible i can of course just load the file and use its content.
It is possible with Spring. You can add the following option to your application properties file:
spring:
config:
import: configtree:/specify_the_path_where_your_file_is_located/
Then you should put your public key file to that location and give a name to this file according to your desired configuration properties:
certificate.publicKey
And you're done here! During application startup the content of that file will be injected to that property and will be both accesible from your configuration properties or from Environment bean

Spring Cloud Config Server ResourceController does not map request with useDefaultLabel when path contains slashes

I have a simple Spring Cloud Config Server project (using spring-cloud-config-server-4.0.0)
With a default branch property set
spring.cloud.config.server.git.default-label
This works without a label:
GET http://localhost:8888/myAppName/myProfiles/test.txt?useDefaultLabel
This does not (path includes slash):
GET http://localhost:8888/myAppName/myProfiles/path/test.txt?useDefaultLabel
Throws the following Exception:
RefNotFoundException: Ref path cannot be resolved
...
at org.springframework.cloud.config.server.resource.ResourceController.retrieve(ResourceController.java:107)
It resolves to the wrong controller endpoint:
#GetMapping("/{name}/{profile}/{label}/**")
instead of
#GetMapping(value = "/{name}/{profile}/{path:.*}", params = "useDefaultLabel")
To my understanding this should work because of this change: https://github.com/spring-cloud/spring-cloud-config/issues/824
I've tried without success:
Encoding the slash
Assigning something ("true") to the useDefaultLabel request parameter

How to upload to SFTP user's Home directory using Spring Integration

I'm trying to upload a file via SFTP using Spring Integration (version 4.1.2).
Does anyone know how to configure the sftp:outbound-channel-adapter so that the file gets uploaded automatically to user's home directory without indicating the full directory path in the remote-directory's attribute (ex: remote-directory="/home/sftp_user")?
The solution is that the remote-directory must be set as an empty string.
Please note that the following won't work as it fails the XML model validation:
<sftp:outbound-channel-adapter
...
remote-directory=""
...
/>
I ended up reading the remote-directory from a configuration property which I set as an empty string.

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.

Laravel location of created files

I'm attempting to modify a text file stored on the server using Larvel's File::put(filelocation,filecontents)
but I can't figure out what location this is relative to on the server. If I have a file "somestuff.json" within my LaravelApp/public folder, what location string do I use for a parameter to File::put() ?
File name for File::methods() is not relative you have to give the full file path:
File::put('/var/www/LaravelApp/public/somestuff.json', $filecontents);
But Laravel has some helpers to help you with this:
File::put(public_path().'/somestuff.json', $filecontents);
Also:
base_path(); // the base of your application LaravelApp/
app_path(); // Your LaravelApp/app
They are all in the file vendor/laravel/framework/src/Illuminate/Support/helpers.php.

Resources