Don't have access to Spring boot controller, but have access to index.html - spring

I have a Spring Boot project, what I deployed on remote server. When I call http://109.206.178.66:8080/proxynator/ - I can see an index.html, but when I call rest controller by url http://109.206.178.66:8080/proxynator/countries - I have an error 404 whith
Description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
It's strangely, because when I start this project on my local machine, all working right. Project structure is:
Line from catalina.out file:
SEVERE [http-nio-8080-exec-19] org.apache.tomcat.util.descriptor.web.WebXmlParser.parseWebXml Parse error in application web.xml file at [file:/opt/tomcat/webapps/proxynator/WEB-INF/web.
My controller:
#RestController
class MainController(val proxyRepo: ProxyRepo, val countryRepo:
CountryRepo) {
#GetMapping("/countries")
fun findCountries(): List<Country> = countryRepo.findAll()
#GetMapping("/proxies")
#ResponseBody
fun findProxies(#RequestParam countryid: Int): List<Proxy> =
proxyRepo.findAllByCountryid(countryid)
}
UPD
I added configuration class on the root package
#Configuration
open class RestConfiguration {
#Bean
open fun mainController():MainController
= MainController()
}
But it does not working. I don't understand, why I can see index.html by irl http://109.206.178.66:8080/proxynator/, but can't get access to my controllers. When I package my project I have some files:
Any advice?

your api access url is wrong access using http://109.206.178.66:8080/countries this is the correct path for your rest mapping, not http://109.206.178.66:8080/proxynator/countries

To solve this problem I was edit my Application class.
#SpringBootApplication
#EnableAutoConfiguration
open class Application: SpringBootServletInitializer(){
#Override
override fun configure(application: SpringApplicationBuilder?):
SpringApplicationBuilder {
return super.configure(application)
}
}
fun main(args: Array<String>) {
SpringApplication.run(Application::class.java, *args)
}
I was override configure method, and all is working!
Hope it will save time for anybody!

Related

Spring Batch is looking for source files during deployment

I am developing Spring batch application on Spring Boot. Batch process is based on fire and forget, which means migration process is triggered by Http GET method and doesn't wait for result. There are 6 (six) csv files which containes migration data and these data must be processed and transferred to DB. Source files path is provided by application.yml file. Batch config (template) looks like as follows:
#Configuration
public class BeginCureBtachConfig {
#Value("$batch-files.begincure-source")
private String dataSourceFilePath;
#Autowired
IteamReader<BeginCure> itemReader;
#Autowired
ItemProcessor<BeginCure, BeginCure> itemProcessor;
#Bean Job beginCureJob(JobBuilderFactory jbFactory, StepBuilderDactory stp, ItemWriter<BeginCure> begnCure {
//// code goes here
}
#Bean
public FlatFileItemReader<BeginCure> beginCureItemReader() {
FlatFileItemReader<BeginCure> ffReader = new FlatFileItemReader<>();
ffReader.setResource(new FileSystemResource(dataSourceFilePath));
ffReader.setLineMapper(lineMapper());
return ffReader;
}
#Bean
public LineMapper<BeginCure> lineMapper () {
//..
}
}
The problem is when project is deployed on openshift, batch looks for files even migratin is not triggered.
In the code, I think this part of code giving some error ffReader.setResource(new FileSystemResource(dataSourceFilePath));
Is there any workaround or solution? Did anybody have this kind of problem?
Thank you in advance^^

Getting 404 Not Found for basic spring rest api tutorial - 'hello world'

I am trying to create a rest api web application that can be eventually deployed into a container environment. I downloaded quite a few tutorials from spring.io to other websites as well but each time I use the exact repos I get a 404 error for the simple request.
To simplify it further I reduced it to 2 classes in one package:
project hierarchy
Main class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
Controller Class:
#RestController
#RequestMapping("/")
public class RESTController {
private final AtomicLong counter = new AtomicLong();
private static final String template = "Hello, %s!";
/*
* REST API Test Methods
*/
#RequestMapping( "/greeting" )
public String greeting() {
return "It's working...!";
}
And of course the actual request:
http://localhost:8080/test_rest_api/greeting
HTTP Status 404 – Not Found
Type Status Report
Message /test_rest_api/greeting
Description The origin server did not find a current representation for the target resource or is not
willing to disclose that one exists.
Apache Tomcat/8.5.43
That is running on server by Run As - ; if I select Run as java application and select springboot the following error occurs:
java.lang.IllegalArgumentException: Sources must not be empty at
org.springframework.util.Assert.notEmpty(Assert.java:467)
I finally figured it out and it was a stupid mistake. I added the name of the project as part of the domain of the request url.
http://localhost:8080/test_rest_api/greeting
vs
http://localhost:8080/greeting

Loading React Pages from Spring Controller

I have this code in my Spring Boot Application
#RestController
public class SampleController {
public SampleController() {
File file = new File("restresources");
System.out.println("File -> "+ file.getAbsolutePath());
}
#GetMapping(value = "/sample")
public String sampleText(HttpServletRequest request){
System.out.println("Sample Text");
return "Sample Text";
}
#RequestMapping()
public String acceptAny(){
return "ASDasdasdasdasd";
}
}
The acceptAny Method accepts any url hit from browser? But I have react files in my public folder too. So, when I hit localhost:8090/, instead of loading react index.html, it loads acceptAny() method.
How can I load react index.html instead of invoking this acceptAny() method or is there any method for loading React index.html from Controller itself?
Any help is highly appreciated!
first of all you have remove method acceptAny is hasn't any useful duties.
Than you should build your reactjs project and copy build files in resources/public or resources/static, than run project and open in browser localhost:8090/

SpringBoot/Kotlin: Multipart MaxUploadSizeExceededException handler does not fire

Please excuse any horrible mistakes, I literally picked up Kotlin fully and some Spring about a week ago, due to a project requirement. I am trying to create a simple RESTful API with an endpoint that can accept a file via Multipart. Later on, there will be a few pages outside the API that will display HTML, I am using Koreander for that. From what I can see, and based on Java tutorials, exception handling should work like this.
For the API, my defined exception handler for MaxUploadSizeExceededException, however, does not fire at all. My application.kt:
#SpringBootApplication
#EnableConfigurationProperties(StorageProperties::class)
class JaApplication {
#Bean fun koreanderViewResolver(): ViewResolver = KoreanderViewResolver()
}
fun main(args: Array<String>) {
runApplication<JaApplication>(*args)
}
My controller:
#RestController
#RequestMapping("/api")
#EnableAutoConfiguration
class APIController {
#PostMapping(
value = "/convert",
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)
)
fun convert(#RequestParam("file") multipartFile: MultipartFile): Result {
return Result(status = 0, message = "You have uploaded: ${multipartFile.getOriginalFilename()}.")
}
}
#ControllerAdvice
class ExceptionHandlers {
#ExceptionHandler(MultipartException::class)
fun handleException(e: MultipartException): String = Result(status = 1, message = "File is too large.")
}
}
When I am attempting to post a large file via curl, I get a JSON reply:
curl -F 'file=#path-to-large-file' http://localhost:8080/api/convert
{"timestamp":"2018-11-27T15:47:31.907+0000","status":500,"error":"Internal Serve
r Error","message":"Maximum upload size exceeded; nested exception is java.lang.
IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$Siz
eLimitExceededException: the request was rejected because its size (4294967496)
exceeds the configured maximum (529530880)","path":"/api/convert"}
Is it possible that Tomcat does not pass this exception to Spring? If yes, how may I go about catching this? It also works if I can set the size to unlimited and check for file size at upload time, though I would need to do that before the server starts receiving the file, and I assume by the time I get to the /api/convert endpoint, it is too late.
Thanks for any help.
Found the issue. I'm posting it for anyone else who might have the same issue in the future.
#ControllerAdvice
class ExceptionHandlers():ResponseEntityExceptionHandler() {
#ExceptionHandler(MaxUploadSizeExceededException::class)
fun handleException(e: MultipartException, request:WebRequest): ResponseEntity<Any> {
return handleExceptionInternal(e, Result(message = "File is too large."), HttpHeaders(), HttpStatus.PAYLOAD_TOO_LARGE, request)
}
}

Amazon Web Services - Deploy Spring Boot Application

I have a spring boot application that I am deploying onto EB (Elastic Beanstalk) AWS. The app works fine locally, however, I get a 404 on all pages I try to access on the deployed version. Also, I can't access any of the static content under the static folder either. All REST endpoints work fine.
My project structure is as follows
-- src
-- main
-- kotlin
-- resources
-- static
-- css
-- fonts
-- images
-- js
-- templates (contains html files)
I've tried defining option_settings in a .config file under a .ebextensions folder
option_settings
aws:elasticbeanstalk:container:java:staticfiles:
/public/: WEB-INF/classes/static
/static/: WEB-INF/classes/staticenter code here
I've also tried adding the following to my spring configuration class
#Configuration open class MvcConfig : WebMvcConfigurerAdapter() {
override fun addViewControllers(registry: ViewControllerRegistry) {
registry.addViewController("/").setViewName("homepage")
registry.addViewController("/index").setViewName("homepage")
registry.addViewController("/home").setViewName("homepage")
registry.addViewController("/homepage").setViewName("homepage")
registry.addViewController("/login").setViewName("login")
registry.addViewController("/products").setViewName("productsList")
registry.addViewController("/productdetail").setViewName("productDetail")
}
#Bean
open fun viewResolver(): ViewResolver {
val bean = InternalResourceViewResolver()
bean.setPrefix("/templates/")
bean.setSuffix(".html")
return bean
}
override fun addResourceHandlers(registry: ResourceHandlerRegistry?) {
// Register resource handler for all static folders
registry!!.addResourceHandler("/resources/**").addResourceLocations("classpath:/statics/")
.setCacheControl(CacheControl.maxAge(2, TimeUnit.HOURS).cachePublic())
}
#Bean
open fun errorPageFilter(): ErrorPageFilter {
return ErrorPageFilter()
}
#Bean
open fun disableSpringBootErrorFilter(filter: ErrorPageFilter): FilterRegistrationBean {
val filterRegistrationBean = FilterRegistrationBean()
filterRegistrationBean.filter = filter
filterRegistrationBean.isEnabled = false
return filterRegistrationBean
}
I am deploying onto tomcat8 that sits behind an Apache proxy server.
My EB settings are correct as I tried to deploy a simpler application onto the instance, which worked fine.
Please let me know if there are any further details I need to provide
The issue was related to the resourceHandler, the classpath it self was never added to the resource handler, even though servlet logging was indicating it was.
Spring by default maps the following paths
classpath:META-INF/resources/
classpath:resources/
classpath:static/
classpath:public/
needed to add the /** to the mapping. The solution was to modify the code to the following
override fun addResourceHandlers(registry: ResourceHandlerRegistry?) {
registry!!.addResourceHandler("/**", "/static/**")
.addResourceLocations("classpath:/templates/", "classpath:/static/").setCacheControl(CacheControl.maxAge(2,TimeUnit.HOURS).cachePublic())
}
#Bean
open fun viewResolver(): ViewResolver {
val bean = InternalResourceViewResolver()
bean.setSuffix(".html")
return bean
}

Resources