Changing restAPI URI - java

I have created an application in java with the name hello. my class is below
#Path("/test")
class TestAPI
{
#GET
#Path("/hi")
public String sayHi()
{
return "Hi I am Shweta";
}
}
I am accessing this application using
GET http://localhost:8080/hello/test/hi
Is there anyway I can remove hello from URI or I can replace the same without changing application.
If I need to access like http://localhost:8080/test/hi what changes I need to do? I am using maven.

Yes you can do it in your server.Say if you are using tomcat to deploy your application,Then go through its configuration file and change the context path to '/'.It will work.You just need to check where context path is defined in what ever server you are using and just replace the path with '/'.

Related

Get the Path of a resource from a spring boot aplication using servlet context

I have this structure, generated by spring boot
So I want to get a input stream of the file gastos.xlsx using sevletContext.
#Autowired
private ServletContext context;
#GetMapping("/grafico")
public ResponseEntity<String> exportExcelGrafico(HttpServletResponse response){
try{
//this path returns null. What is the real path to put here?
InputStream input = context.getResourceAsStream("src/main/resources/templates/gastos.xlsx");
//returns null
input = context.getResourceAsStream("/resources/templates/gastos.xlsx");
// Returns null
input = context.getResourceAsStream("/templates/gastos.xlsx");
}
catch(){
}
What would be the right path?
I didn't configure anything on my application.properties
What's in the src/main/resources folder of your Maven or Gradle project ends up in your jar, not in the web resources. And it should thus be loaded using the class loader, not using the servlet context:
MyClass.class.getResourceAsStream("/templates/gastos.xlsx")
Not sure why you put that file under templates, since... it's not a template.

Spring cloud config - Share file or his location

I have two applications :
one spriig boot config server
the another one a spring boot config client
The client side have to use a file named certificate.json.
I want to store this file in the server side so another microprogram and my client programm who need it can retrieve it from the server side.
I try that :
copy the file certificate.json to classpath:/config
add this line to the application.properties :
certificate.location: classpath:config/certificate.json
call the value from client programm by :
#Value("${certificate.location}")
private String certificateLocation;
But the value of certificateLocation is classpath:config/certificate.json. The value I want is the file location like : /home/user/project/scr/main/resources/config/certificate.json.
Or, are there a way to directly retrieve my file by URI, for example locahost:8889/... (8889 is my config server port).
EDIT 1:
I cannot use absolute path from the server because I'm not the one who run it.
Thank you in advance.
I'd do
#Value("${certificate.location}") private Resource certificateLocation;
that way, your location is already a Resource that you can load, call getURI(), getFile().getAbsolutePath() etc. Since your value is prefixed with classpath:, you would have a ClassPathResource instance, which you can use for lot of things.
The classpath is just a protocol part of the URL. You can use file or any other supported protocol. For example, file://home/user/project/scr/main/resources/config/certificate.json.
Try this url
spring.cloud.config.server.native.searchLocations
=file://${user.home}/CentralRepo/
SPRING_PROFILES_ACTIVE=native
I am also get this way using microservice
OP you need to create a web service and return certificate.json as the response. Then you can send and receive data by sending a GET or POST request to a URI like https://12.12.12.12:8080/getCertificate. Please see:
https://spring.io/guides/gs/rest-service/
As a side note, you should never expose your inner files to the internet because it's very unsecure and opens you up to pirating and hacking.
What I would do in this case is
Add configuration for static folder
#SpringBootApplication public class DemoStaticresourceApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(DemoStaticresourceApplication.class, args);
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**").addResourceLocations("file:/fileFolder/")
.setCachePeriod(0);
}
}
Place certificate.json in fileFolder and try http://localhost:8080/files/certificate.json and it will be served directly from file system for you.
And now every file you add in this folder will be served only if called using /files/ path

Custom path resolving static resources Spring

I am working on Spring Boot application. The general problem is the following: I've created REST API, a few controllers. However, I also have some static HTML files, located in "resources/static".
What I want to achieve, is to configure Spring resolvers so that I could access static content without appending ".html". On practise, I expect to access static HTML by path "ip:port/htmlPage" instead of "ip:port/htmlPage.html"
However, I don't want to create methods like this one:
#Controller
public class ViewMaster {
#RequestMapping("/home")
public String home() {
return "home";
}
So, properties like
spring.mvc.view.suffix=.html
not working for me. Any possibilities to avoid creation per page endpoint in a controller?
After reading your question i have tried a lot but unable to serve html from static folder without extention. What works for me is to create an #RequestMapping like this:
#RequestMapping(value="/static/{htmlName}")
String getStaticHtml(#PathVariable String htmlName){
return htmlName;
}
And moved html files to templates folder. So there is no need to create different end points to access html pages, just pass the name of html without extention and this will do the trick

Spring application URL in scheduled job

Is it possible to get the application URL in spring scheduled job (#Scheduled annotated)?
I want to create a job which sends an email with URL to specific page on the application, let's say on http://localhost:8080/appName/some/specific/url. The problem is that the part http://localhost:8080/ will be different in each environment (local,dev,production etc).
Is there any simple way to get a base URL in server-side method which is executed by spring scheduler?
I do that with a properties file. This tutorial tells you how you can do it.
The only complex part is you need a way to change the value the properties file is referencing for each of your different environments.
There is no direct way to get the base url within your scheduler. You may want to look at work arounds for this, like
Use a properties file to store url for each environment
Have a Configurartion bean which implements ServletContextAware. This bean would be automatically notified when a web context is initialised.
public class AppConfig implements ServletContextAware{
private String baseUrl;
public String getBaseUrl(){
return baseUrl;
}
public void setServletContext(ServletContext servletContext){
this.baseUrl=servletContext.getRealPath("/");
}
}

How to reach the WebContent folder from a web service method

I want to reach a file in WebContent folder from a method in a web service in the same project. For example:
#WebMethod
public String test() {
File configFile = new File("config.xml");
return configFile.getAbsolutePath();
}
It returns "/usr/share/glassfish3/glassfish/domains/domain1/config/config.xml". I want to get to a file in the directory "/usr/share/glassfish3/glassfish/domains/domain1/applications/my_project_name/" folder. How can I get to it?
The best way to do this that I use is:
Thread.currentThread().getContextClassLoader().getResource("myFile.txt").getPath()
This gives the path of any file myFile.txt placed in /WEB-INF/classes/ directory inside the WebContent folder of the WebApp.
In Eclipse JEE environment you need to keep the file myFile.txt, that you may want to read within the Web Service, in the src folder for it to be transported to the /WEB-INF/classes/ folder by the deployer.
From your code, I understand that yours is an JAXWS webservice.
In jaxws, you can get the HttpServletRequest, HttpServletResponse, ServletContext,
Have a private variable in your webservice class and annotate it in this way
#Resource
private WebServiceContext context;
And then in your method, you can get the ServletContext this way
ServletContext servletContext =
(ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
From servletContext, you can get the path.
Suppose if you need to get HttpServletRequest, you can get it in this way
HttpServletRequest request =
(HttpServletRequest) context.getMessageContext().get(MessageContext.SERVLET_REQUEST);
and you can get the context path of your app like
request.getContextPath() ;
Add the following parameter to your web service class:
#Context
ServletContext context;
Then, supposing your config.xml file is in the WebContent folder, you can get its absolute path by invoking the method context.getRealPath(String). Using your example code it would be:
#WebMethod
public String test() {
File configFile = new File(context.getRealPath("config.xml"));
return configFile.getAbsolutePath();
}
Or directly, without passing by a File object:
#WebMethod
public String test() {
return context.getRealPath("config.xml");
}

Categories