After searching out all the possible solutions I'm posting this out.
My spring boot application was running fine few days ago. I was able to deploy it on tomcat and also export the war and deploy it on my application server. But suddenly it is showing blank page on deployment. What could be the possible reasons?
In pom.xml I've all the dependencies:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sdigital</groupId>
<artifactId>cheapTravelTicket</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name></name>
<description>cheap Travel Ticket</description>
<!-- Default from spring boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- Web Application -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring data jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Spring Webservices -->
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.4.01</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.w3c/dom -->
<dependency>
<groupId>org.w3c</groupId>
<artifactId>dom</artifactId>
<version>2.3.0-jaxb-1.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/sax/sax -->
<dependency>
<groupId>sax</groupId>
<artifactId>sax</artifactId>
<version>2.0.1</version>
</dependency>
<!-- Embedded Tomcat -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- Slug generator -->
<dependency>
<groupId>com.github.slugify</groupId>
<artifactId>slugify</artifactId>
<version>2.1.7</version>
</dependency>
<!-- Common String -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<!-- Apache Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- JSTL for JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>provided</scope>
</dependency>
<!-- Need this to compile JSP -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- Need this to compile JSP,
tomcat-embed-jasper version is not working, no idea why -->
<dependency>
<groupId>org.eclipse.jdt.core.compiler</groupId>
<artifactId>ecj</artifactId>
<version>4.6.1</version>
<scope>provided</scope>
</dependency>
<!-- Optional, test for static content, bootstrap CSS-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.jcabi/jcabi-xml -->
<dependency>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-xml</artifactId>
<version>0.18.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Spring boot maven support -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application class is as follows:
package com.sdigital;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.sdigital.cache.ExpiringMap;
/**
* The Class CTTApplication.
*/
#SpringBootApplication
public class CTTApplication {
/**
* The main method.
*boots the application
*
*/
public static void main(String[] args) {
SpringApplication.run(CTTApplication.class, args);
}
#Bean
public Map<String, Object> getCache(){
Map<String, Object> map = ExpiringMap.builder()
.maxSize(200)
.expiration(12, TimeUnit.HOURS)
.build();
return map;
}
}
ServletInitializer
package com.sdigital;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
// TODO: Auto-generated Javadoc
/**
* The Class ServletInitializer.
*/
public class ServletInitializer extends SpringBootServletInitializer {
/* (non-Javadoc)
* SpringApplication Builder
*/
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CTTApplication.class);
}
}
Controller
package com.sdigital.controller;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.sdigital.bus.distribution.domain.ConnectionRequest;
import com.sdigital.cache.SearchCache;
import com.sdigital.domain.JourneyRequest;
import com.sdigital.domain.TimeTableRequest;
import com.sdigital.domain.XmlUrl;
import com.sdigital.domain.XmlUrlSet;
import com.sdigital.model.BusProvider;
import com.sdigital.model.City;
import com.sdigital.model.CustomForm;
import com.sdigital.model.Route;
import com.sdigital.model.SeoConfig;
import com.sdigital.model.SiteMap;
import com.sdigital.repositories.BusProviderRepository;
import com.sdigital.repositories.CityRepository;
import com.sdigital.repositories.RouteRepository;
import com.sdigital.repositories.SeoConfigRepository;
import com.sdigital.repositories.SiteMapRepository;
import com.sdigital.repositories.StationConfigRepository;
import com.sdigital.service.AppService;
import com.sdigital.utils.CTTConstant;
import com.sdigital.utils.CommonUtils;
#Controller
#SessionAttributes({"searchRequest", "searchBusRequest"})
public class AppController {
#Autowired
private AppService appServc;
#Autowired
private StationConfigRepository strepo;
#Autowired
private RouteRepository rtrepo;
#Autowired
private CityRepository ctrepo;
#Autowired
private BusProviderRepository busrepo;
#Autowired
private SeoConfigRepository repo;
#Autowired
private SearchCache searchCache;
#Autowired
private SiteMapRepository siteMap;
#RequestMapping("/")
public ModelAndView home(){
//List<Route> cttPopular = rtrepo.findOneByPopularType(CTTConstant.CTT_POPULAR_TYPE);
List<City> cttPopular = ctrepo.findAllByOrderByPriorityAsc();
List<Route> popular = rtrepo.findByPopularType(CTTConstant.POPULAR_TYPE);
ModelAndView model = new ModelAndView("index");
model.addObject("cttPopular", cttPopular);
model.addObject("popular", popular);
SeoConfig seoCon = repo.findByPageType(3);
model.addObject("title", seoCon.getPageTitle());
model.addObject("meta_title", seoCon.getMetaTitle());
model.addObject("meta_description", seoCon.getMetaDescription());
model.addObject("meta_keywords", seoCon.getMetaKeywords());
model.addObject("seo_url", seoCon.getSeoUrl());
model.addObject("description", seoCon.getDescription());
model.addObject("desc1", seoCon.getDesc1());
model.addObject("desc2", seoCon.getDesc2());
model.addObject("desc3", seoCon.getDesc3());
List<City> topCities = ctrepo.findTop10ByOrderByPriorityAsc();
List<Route> topRoutes = rtrepo.findTop10ByOrderByPriorityAsc();
model.addObject("topCities", topCities);
model.addObject("topRoutes", topRoutes);
List<BusProvider> topBusProviders = busrepo.findTop10ByPublishOrderByPriorityAsc(true);
model.addObject("topBusProviders", topBusProviders);
return model;
}
#RequestMapping(value = "/book")
public ModelAndView portalBook(#ModelAttribute("journeyRequest") JourneyRequest journeyRequest) throws URISyntaxException {
ModelAndView m = null;
m = appServc.getView(journeyRequest);
return m;
}
#RequestMapping(value="/search")
public ModelAndView portalSearch(#ModelAttribute("searchRequest") TimeTableRequest searchRequest,
#RequestParam(name="sort_by", required = false) String sortBy,
#RequestParam(name="s", required = false) String start,
#RequestParam(name="orig", required = false) String originuic,
#RequestParam(name="dest", required = false) String destinationuic, HttpSession session){
/*System.out.println("*** Session data ***");
Enumeration<String> e = session.getAttributeNames();
while (e.hasMoreElements()){
String s = e.nextElement();
System.out.println(s);
System.out.println("**" + session.getAttribute(s));
}*/
if(originuic!=null && destinationuic!=null){
searchRequest.setChildren(0);
searchRequest.setRailcards(null);
searchRequest.setTravelclass("standard");
searchRequest.setRetdatetime(null);
searchRequest.setAdults(1);
searchRequest.setDestinationuic(destinationuic);
searchRequest.setOriginuic(originuic);
searchRequest.setReturnjry(false);
searchRequest.setOutdatetime(CommonUtils.getFormatedDate(CTTConstant.DEFAULT_SEARCH_FORMAT, new Date()));
searchRequest.setOutsearchTime(CommonUtils.getCurrentUTCTimeSearchable(false));
}
ModelAndView m = appServc.getView(searchRequest, sortBy, start);
List<City> topCities = ctrepo.findTop10ByOrderByPriorityAsc();
List<Route> topRoutes = rtrepo.findTop10ByOrderByPriorityAsc();
m.addObject("topCities", topCities);
m.addObject("topRoutes", topRoutes);
List<BusProvider> topBusProviders = busrepo.findTop10ByPublishOrderByPriorityAsc(true);
m.addObject("topBusProviders", topBusProviders);
m.addObject("currentDate", CommonUtils.getFormatedDate(CTTConstant.DEFAULT_SEARCH_FORMAT, new Date()));
return m;
}
#ModelAttribute("searchRequest")
public TimeTableRequest createFormModelAttribute(HttpSession session) {
TimeTableRequest req = (TimeTableRequest)session.getAttribute("searchRequest");
if(req!=null)
return req;
TimeTableRequest req1 = new TimeTableRequest();
req1.setAdults(1);
req1.setOutdatetime(CommonUtils.getFormatedDate(CTTConstant.DEFAULT_SEARCH_FORMAT, new Date()));
req1.setOutsearchTime(CommonUtils.getCurrentUTCTimeSearchable(false));
req1.setRetsearchTime(CommonUtils.getCurrentUTCTimeSearchable(true));
return req1;
}
#RequestMapping(value="/bus-search")
public ModelAndView portalSearch(#ModelAttribute("searchBusRequest") ConnectionRequest searchRequest,
#RequestParam(name="sort_by", required = false) String sortBy,
#RequestParam(name="s", required = false) String start,
#RequestParam(name="orig", required = false) String originuic,
#RequestParam(name="dest", required = false) String destinationuic, HttpSession session){
if(originuic!=null && destinationuic!=null){
searchRequest.setChildren1(0);
searchRequest.setRetdatetime(null);
searchRequest.setAdults1(1);
searchRequest.setDestinationuic1(destinationuic);
searchRequest.setOriginuic1(originuic);
searchRequest.setReturnjry(false);
searchRequest.setCurrency("EUR");
searchRequest.setDatetime(CommonUtils.getFormatedDate(CTTConstant.DEFAULT_SEARCH_FORMAT, new Date()));
}
ModelAndView m = appServc.getView(searchRequest, sortBy, start);
List<City> topCities = ctrepo.findTop10ByOrderByPriorityAsc();
List<Route> topRoutes = rtrepo.findTop10ByOrderByPriorityAsc();
m.addObject("topCities", topCities);
m.addObject("topRoutes", topRoutes);
List<BusProvider> topBusProviders = busrepo.findTop10ByPublishOrderByPriorityAsc(true);
m.addObject("topBusProviders", topBusProviders);
m.addObject("currentDate", CommonUtils.getFormatedDate(CTTConstant.DEFAULT_SEARCH_FORMAT, new Date()));
return m;
}
#ModelAttribute("searchBusRequest")
public ConnectionRequest createFormModelAttribute() {
return new ConnectionRequest();
}
#ModelAttribute("journeyRequest")
public JourneyRequest createFormModelAttribute1() {
return new JourneyRequest();
}
#RequestMapping(value="/{seo:.+}")
public ModelAndView portalLocation(#PathVariable("seo") String seo, HttpServletResponse response, #RequestParam(name="status", required = false) String status){
ModelAndView m = appServc.getView(seo, response, status);
List<City> topCities = ctrepo.findTop10ByOrderByPriorityAsc();
List<Route> topRoutes = rtrepo.findTop10ByOrderByPriorityAsc();
m.addObject("topCities", topCities);
m.addObject("topRoutes", topRoutes);
List<BusProvider> topBusProviders = busrepo.findTop10ByPublishOrderByPriorityAsc(true);
m.addObject("topBusProviders", topBusProviders);
return m;
}
#RequestMapping(value="/{seo1}/{seo2:.+}")
public ModelAndView portalChildLocation(#PathVariable("seo1") String seo1, #PathVariable("seo2") String seo2, HttpServletResponse response, #RequestParam(name="status", required = false) String status){
ModelAndView m = appServc.getView(seo1+"/"+seo2, response, status);
List<City> topCities = ctrepo.findTop10ByOrderByPriorityAsc();
List<Route> topRoutes = rtrepo.findTop10ByOrderByPriorityAsc();
m.addObject("topCities", topCities);
m.addObject("topRoutes", topRoutes);
List<BusProvider> topBusProviders = busrepo.findTop10ByPublishOrderByPriorityAsc(true);
m.addObject("topBusProviders", topBusProviders);
return m;
}
#ResponseBody
#RequestMapping(value="/schedular/trains")
public boolean portalSchedularToUpdateTrains(){
appServc.updateTrainsForCityToCity();
return true;
}
#RequestMapping(value = "/robots.txt")
#ResponseBody
public String getRobots(HttpServletRequest request) {
return "User-agent: * \n Disallow: /";
}
#RequestMapping(value = "/sitemap.xml", method = RequestMethod.GET)
#ResponseBody
public XmlUrlSet getSiteMap(HttpServletRequest request) {
XmlUrlSet xmlUrlSet = new XmlUrlSet();
create(xmlUrlSet, "", "1.0", request);
List<SiteMap> seoUrls = siteMap.findByPublish(1);
for(SiteMap sUrl : seoUrls){
create(xmlUrlSet, "/"+sUrl.getSeoUrl(), null, request);
}
return xmlUrlSet;
}
private void create(XmlUrlSet xmlUrlSet, String link, String priority, HttpServletRequest request) {
String rootUrl = request.getScheme() + "://" + request.getServerName() + request.getContextPath();
xmlUrlSet.addUrl(new XmlUrl(rootUrl + link, priority));
}
#RequestMapping(value="/information/rail-cards")
public ModelAndView railCardInfo(){
ModelAndView model = new ModelAndView("railinfo");
return model;
}
#RequestMapping(value="/form/post")
public String formPost(#ModelAttribute("addRequest") CustomForm addRequest){
String r = appServc.addData(addRequest);
return r;
}
#ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception ex) {
ModelAndView m = new ModelAndView("exception");
List<City> topCities = ctrepo.findTop10ByOrderByPriorityAsc();
List<Route> topRoutes = rtrepo.findTop10ByOrderByPriorityAsc();
m.addObject("topCities", topCities);
m.addObject("topRoutes", topRoutes);
List<BusProvider> topBusProviders = busrepo.findTop10ByPublishOrderByPriorityAsc(true);
m.addObject("topBusProviders", topBusProviders);
m.addObject("searchRequest", new TimeTableRequest());
return m;
}
}
Adding my answer in case anyone else faces same issue.
Problem was with the context path. Updated the context path in project properties in eclipse. then ran clean and build. Most important part was to remove the server configuration and again ran it on tomcat, it worked.
Since I was not clearing the server configurations from eclipse updated context path was not picking up.
Related
I am trying to implement Bucket4J rate limiter in Netflix Zuul Api Gateway. I have added Interceptor for Rate Limiting the requests using WebMvcConfigurer.
package com.rajkumar.apiigateway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.rajkumar.apiigateway.ratelimit.interceptor.RateLimitInterceptor;
#SpringBootApplication
#EnableZuulProxy
public class ApiiGatewayApplication implements WebMvcConfigurer{
#Autowired
#Lazy
RateLimitInterceptor rateLimitInterceptor;
public static void main(String[] args) {
new SpringApplicationBuilder(ApiiGatewayApplication.class)
.run(args);
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(rateLimitInterceptor)
.addPathPatterns("/api/service_1/throttling/users");
}
}
And Interceptor for rate limiting looks like
package com.rajkumar.apiigateway.ratelimit.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.rajkumar.apiigateway.ratelimit.service.RateLimitService;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.ConsumptionProbe;
#Component
public class RateLimitInterceptor implements HandlerInterceptor {
private static final String HEADER_API_KEY = "X-API-KEY";
private static final String HEADER_LIMIT_REMAINING = "X-RATE-LIMIT-REMAINING";
private static final String HEADER_RETRY_AFTER = "X-RATE-LIMIT-RETRY-AFTER-SECONDS";
#Autowired
RateLimitService rateLimitService;
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String apiKey = request.getHeader(HEADER_API_KEY);
if(apiKey == null || apiKey.isEmpty()) {
response.sendError(HttpStatus.OK.value(), HEADER_API_KEY+" request header is mandatory");
return false;
}
Bucket tokenBucket = rateLimitService.resolveBucket(request.getHeader(HEADER_API_KEY));
ConsumptionProbe probe = tokenBucket.tryConsumeAndReturnRemaining(1);
if(probe.isConsumed()) {
response.addHeader(HEADER_LIMIT_REMAINING, Long.toString(probe.getRemainingTokens()));
return true;
}
response.addHeader(HEADER_RETRY_AFTER, Long.toString(probe.getNanosToWaitForRefill()/1000000000));
response.sendError(HttpStatus.TOO_MANY_REQUESTS.value(),"You have exceeded your request limit");
return false;
}
}
and other dependent component
package com.rajkumar.apiigateway.ratelimit.service;
import java.util.concurrent.TimeUnit;
import org.springframework.stereotype.Component;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.rajkumar.apiigateway.ratelimit.RateLimit;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Bucket4j;
#Component
public class RateLimitService {
private LoadingCache<String, Bucket> cache = Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.MINUTES)
.build(this::newBucket);
public Bucket resolveBucket(String apiKey) {
return cache.get(apiKey);
}
private Bucket newBucket(String apiKey) {
RateLimit plan = RateLimit.resolvePlanFromApiKey(apiKey);
Bucket bucket = Bucket4j.builder()
.addLimit(plan.getLimit())
.build();
return bucket;
}
}
package com.rajkumar.apiigateway.ratelimit;
import java.time.Duration;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Refill;
public enum RateLimit {
FREE(2L),
BASIC(4L),
PROFESSIONAL(10L);
private Long tokens;
private RateLimit(Long tokens) {
this.tokens = tokens;
}
public static RateLimit resolvePlanFromApiKey(String apiKey) {
if(apiKey==null || apiKey.isEmpty()) {
return FREE;
}
else if(apiKey.startsWith("BAS-")) {
return BASIC;
}
else if(apiKey.startsWith("PRO-")) {
return PROFESSIONAL;
}
return FREE;
}
public Bandwidth getLimit() {
return Bandwidth.classic(tokens, Refill.intervally(tokens, Duration.ofMinutes(1)));
}
}
and pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.rajkumar</groupId>
<artifactId>apii-gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apii-gateway</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR8</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<!-- <version>2.5.5</version> -->
</dependency>
<dependency>
<groupId>com.github.vladimir-bukhtoyarov</groupId>
<artifactId>bucket4j-core</artifactId>
<version>4.10.0</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
and application.properties
server.port = 8080
spring.application.name = api-gateway
#routing for service 1
zuul.routes.service_1.path = /api/service_1/**
zuul.routes.service_1.url = http://localhost:8081/
#routing for service 2
zuul.routes.service_2.path = /api/service_2/**
zuul.routes.service_2.url = http://localhost:8082/
When I am trying to hit api gateway (http://localhost:8080/api/service_1/throttling/users): it is not passing through the interceptor. Any help is appreciated.
Thanks in advance.
I wrote a web service to connect to an URL which has custom params.
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.client.utils.URIBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
#RestController
public class ServiceNowController {
private static final Logger logger = LoggerFactory.getLogger(ServiceNowController.class);
#CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
#RequestMapping(method = RequestMethod.GET, value = "/incident", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> retriveAllIncidents(HttpServletRequest request) throws UnsupportedEncodingException {
logger.info("ServiceNowController -> retrieveAllIncidents(): Invoked");
RestTemplate restTemplate = new RestTemplate();
ArrayList<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
messageConverters.add(converter);
restTemplate.setMessageConverters(messageConverters);
String mainUrl = "<url>";
final String sysparm_query = "param1";
final String sysparm_display_value = "param2";
final String decoded_sysparam_query = URLDecoder.decode(sysparm_query, StandardCharsets.UTF_8.toString());
System.out.println(decoded_sysparam_query);
try {
URIBuilder builder = new URIBuilder(mainUrl);
builder.addParameter(sysparm_query, decoded_sysparam_query);
builder.addParameter(sysparm_display_value, sysparm_display_value);
String finalUrl = builder.toString();
System.out.println(finalUrl);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "<authorization token>");
headers.setAccept(Arrays.asList(MediaType.ALL));
HttpEntity<String> entity = new HttpEntity<String>(headers);
String urlString = "< url with params >";
String encodedUrl = URLEncoder.encode(urlString, StandardCharsets.UTF_8.toString());
String decodedUrl = URLDecoder.decode(encodedUrl.toString(), StandardCharsets.UTF_8.toString());
ResponseEntity<Object> results = restTemplate.exchange(decodedUrl, HttpMethod.GET, null, Object.class);
return results;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
}
Main class
package com.dell.servicenowapis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
#SpringBootApplication
public class ServicenowapisApplication {
public static void main(String[] args) {
SpringApplication.run(ServicenowapisApplication.class, args);
}
#Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
POM.XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.dell</groupId>
<artifactId>servicenowapis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>servicenowapis</name>
<description>Service Now API</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
When I try to run it, I get this stack trace.
org.springframework.core.annotation.AnnotationConfigurationException: Attribute 'proxyBeanMethods' in annotation [org.springframework.boot.SpringBootConfiguration] is declared as an #AliasFor nonexistent attribute 'proxyBeanMethods' in annotation [org.springframework.context.annotation.Configuration].; nested exception is java.lang.NoSuchMethodException: org.springframework.context.annotation.Configuration.proxyBeanMethods()
at org.springframework.core.annotation.AnnotationUtils$AliasDescriptor.<init>(AnnotationUtils.java:2089)
at org.springframework.core.annotation.AnnotationUtils$AliasDescriptor.from(AnnotationUtils.java:2056)
at org.springframework.core.annotation.AnnotationUtils.getAttributeAliasNames(AnnotationUtils.java:1726)
at org.springframework.core.annotation.AnnotationUtils.isSynthesizable(AnnotationUtils.java:1685)
at org.springframework.core.annotation.AnnotationUtils.synthesizeAnnotation(AnnotationUtils.java:1468)
at org.springframework.core.annotation.AnnotationUtils.synthesizeAnnotationArray(AnnotationUtils.java:1572)
at org.springframework.core.annotation.AnnotationUtils.getAnnotations(AnnotationUtils.java:231)
at org.springframework.core.type.classreading.AnnotationAttributesReadingVisitor.visitEnd(AnnotationAttributesReadingVisitor.java:76)
at org.springframework.asm.ClassReader.readAnnotationValues(ClassReader.java:2020)
at org.springframework.asm.ClassReader.accept(ClassReader.java:676)
at org.springframework.asm.ClassReader.accept(ClassReader.java:527)
at org.springframework.ide.eclipse.core.java.classreading.JdtConnectedMetadataReader.<init>(JdtConnectedMetadataReader.java:45)
at org.springframework.ide.eclipse.core.java.classreading.JdtMetadataReaderFactory.getMetadataReader(JdtMetadataReaderFactory.java:53)
at org.springframework.ide.eclipse.core.java.classreading.CachingJdtMetadataReaderFactory.getMetadataReader(CachingJdtMetadataReaderFactory.java:38)
at org.springframework.ide.eclipse.beans.core.internal.model.BeansJavaConfig.registerBean(BeansJavaConfig.java:368)
at org.springframework.ide.eclipse.beans.core.internal.model.BeansJavaConfig$2.call(BeansJavaConfig.java:229)
at org.springframework.ide.eclipse.beans.core.internal.model.BeansJavaConfig$2.call(BeansJavaConfig.java:1)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoSuchMethodException: org.springframework.context.annotation.Configuration.proxyBeanMethods()
at java.lang.Class.getDeclaredMethod(Unknown Source)
at org.springframework.core.annotation.AnnotationUtils$AliasDescriptor.<init>(AnnotationUtils.java:2082)
... 22 more
Where am I making mistakes? How to fix this?
Although the pom looks OK to me, there is a chance that its a clash of old and new spring versions.
Note that proxyBeanMethods is added in spring boot 2.2.
Please open up the generated artifact without actually run it with tools like WinRar and check the BOOT-INF/lib folder.
Make sure you don't have older spring/spring-boot versions there.
The problem seems to be here. You are instantiating a bean for RestTemplate in main class and in the web service again you are creating a new object for the same. Try removing the bean definition
Remove the below lines
#Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
enter image description herei ran my program without java-based config with web.xml. when i use java-based config my postman don't see any query and return error 404.
I thought this problem is due to beans. placed everywhere anotation.
package com.lesson3.hometask.Controller;
import com.google.gson.Gson;
import com.lesson3.hometask.Model.Storage;
import com.lesson3.hometask.Service.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
#Controller
#Component
public class StorageController{
private Service service;
#Autowired
public StorageController(Service service) {
this.service = service;
}
#RequestMapping(method = RequestMethod.POST, value = "/storageSave")
public #ResponseBody
String save(HttpServletRequest req) throws IOException {
return service.save(readValuesPostman(req), Integer.parseInt(req.getParameter("id"))).toString();
}
#RequestMapping(method = RequestMethod.GET, value = "/storageFind")
public #ResponseBody
String findById(HttpServletRequest req) throws IOException {
return service.findById(Storage.class, Integer.parseInt(req.getParameter("id"))).toString();
}
#RequestMapping(method = RequestMethod.DELETE, value = "/storageDelete")
public #ResponseBody
String delete(HttpServletRequest req) throws IOException {
service.delete(Storage.class, Integer.parseInt(req.getParameter("id")));
return service.findById(Storage.class, Integer.parseInt(req.getParameter("id"))).toString();
}
#RequestMapping(method = RequestMethod.PUT, value = "/storageUpdate")
public #ResponseBody
String update(HttpServletRequest req) throws IOException {
service.update(readValuesPostman(req));
return readValuesPostman(req).toString();
}
private Storage readValuesPostman(HttpServletRequest req) throws IOException {
Storage storage;
try(BufferedReader reader = req.getReader()) {
Gson gson = new Gson();
storage = gson.fromJson(reader, Storage.class);
}
return storage;
}
}
package com.lesson3.hometask.Model;
import javax.persistence.*;
import java.util.Arrays;
#Entity
#Table(name = "STORAGE")
public class Storage {
#Id
#SequenceGenerator(name = "STORAGE_SEQ", sequenceName = "STORAGE_ID_SEQ", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "STORAGE_SEQ")
#Column(name = "ID")
private int id;
#Column(name = "FORMATS_SUPPORTED")
private String formatsSupported;
#Column(name = "STORAGE_COUNTRY")
private String storageCountry;
#Column(name = "STORAGE_MAX_SIZE")
private Long storageMaxSize;
public Storage() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFormatsSupported() {
return formatsSupported;
}
public void setFormatsSupported(String formatsSupported) {
this.formatsSupported = formatsSupported;
}
public String getStorageCountry() {
return storageCountry;
}
public void setStorageCountry(String storageCountry) {
this.storageCountry = storageCountry;
}
public long getStorageMaxSize() {
return storageMaxSize;
}
public void setStorageMaxSize(Long storageMaxSize) {
this.storageMaxSize = storageMaxSize;
}
#Override
public String toString() {
return "Storage{" +
"id=" + id +
", formatsSupported='" + formatsSupported + '\'' +
", storageCountry='" + storageCountry + '\'' +
", storageMaxSize=" + storageMaxSize +
'}';
}
}
package config;
import com.lesson3.hometask.DAO.DAO;
import com.lesson3.hometask.Service.Service;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
#ComponentScan({"com"})
#EnableWebMvc
public class AppContext implements WebMvcConfigurer {
#Bean(name = "service")
public Service service(){
return new Service();
}
#Bean(name = "DAO")
public DAO dao(){
return new DAO();
}
}
package config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class Initializer implements WebApplicationInitializer {
// Указываем имя нашему Servlet Dispatcher для мапинга
private static final String DISPATCHER_SERVLET_NAME = "dispatcher";
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
// Регистрируем в контексте конфигурационный класс, который мы создадим ниже
ctx.register(AppContext.class);
servletContext.addListener(new ContextLoaderListener(ctx));
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet(DISPATCHER_SERVLET_NAME, new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Spring1.3</groupId>
<artifactId>Spring1.3</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>18.3.0.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugin</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
postman return error 404 = "The origin server did not find a current representation for the target resource or is not
willing to disclose that one exists".
Exception at org.springframework.beans.factory.BeanCreationException:Error
creating bean with name'myDBAuthenticationService': Injection of autowired dependencies failed; nested exception is Org.springframework.beans.factory.BeanCreationException:Could not autowire field: private org.o7planning.springmvcshopp
AdminController.java
package org.o7planning.springmvcshoppingcart.controller;
import java.util.List;
import org.o7planning.springmvcshoppingcart.dao.OrderDAO;
import org.o7planning.springmvcshoppingcart.dao.ProductDAO;
import org.o7planning.springmvcshoppingcart.model.OrderDetailInfo;
import org.o7planning.springmvcshoppingcart.model.OrderInfo;
import org.o7planning.springmvcshoppingcart.model.PaginationResult;
import org.o7planning.springmvcshoppingcart.model.ProductInfo;
import org.o7planning.springmvcshoppingcart.validator.ProductInfoValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import
org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
#Controller
// Enable Hibernate Transaction.
#Transactional
// Need to use RedirectAttributes
#EnableWebMvc
public class AdminController {
#Autowired
private OrderDAO orderDAO;
#Autowired
private ProductDAO productDAO;
#Autowired
private ProductInfoValidator productInfoValidator;
// Configurated In ApplicationContextConfig.
#Autowired
private ResourceBundleMessageSource messageSource;
#InitBinder
public void myInitBinder(WebDataBinder dataBinder) {
Object target = dataBinder.getTarget();
if (target == null) {
return;
}
System.out.println("Target=" + target);
if (target.getClass() == ProductInfo.class) {
dataBinder.setValidator(productInfoValidator);
// For upload Image.
dataBinder.registerCustomEditor(byte[].class, new
ByteArrayMultipartFileEditor());
}
}
// GET: Show Login Page
#RequestMapping(value = { "/login" }, method = RequestMethod.GET)
public String login(Model model) {
return "login";
}
#RequestMapping(value = { "/accountInfo" }, method = RequestMethod.GET)
public String accountInfo(Model model) {
UserDetails userDetails = (UserDetails)
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
System.out.println(userDetails.getPassword());
System.out.println(userDetails.getUsername());
System.out.println(userDetails.isEnabled());
model.addAttribute("userDetails", userDetails);
return "accountInfo";
}
#RequestMapping(value = { "/orderList" }, method = RequestMethod.GET)
public String orderList(Model model, //
#RequestParam(value = "page", defaultValue = "1") String pageStr) {
int page = 1;
try {
page = Integer.parseInt(pageStr);
} catch (Exception e) {
}
final int MAX_RESULT = 5;
final int MAX_NAVIGATION_PAGE = 10;
PaginationResult<OrderInfo> paginationResult //
= orderDAO.listOrderInfo(page, MAX_RESULT, MAX_NAVIGATION_PAGE);
model.addAttribute("paginationResult", paginationResult);
return "orderList";
}
// GET: Show product.
#RequestMapping(value = { "/product" }, method = RequestMethod.GET)
public String product(Model model, #RequestParam(value = "code",
defaultValue = "") String code) {
ProductInfo productInfo = null;
if (code != null && code.length() > 0) {
productInfo = productDAO.findProductInfo(code);
}
if (productInfo == null) {
productInfo = new ProductInfo();
productInfo.setNewProduct(true);
}
model.addAttribute("productForm", productInfo);
return "product";
}
// POST: Save product
#RequestMapping(value = { "/product" }, method = RequestMethod.POST)
// Avoid UnexpectedRollbackException (See more explanations)
#Transactional(propagation = Propagation.NEVER)
public String productSave(Model model, //
#ModelAttribute("productForm") #Validated ProductInfo productInfo,
//
BindingResult result, //
final RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
return "product";
}
try {
productDAO.save(productInfo);
} catch (Exception e) {
// Need: Propagation.NEVER?
String message = e.getMessage();
model.addAttribute("message", message);
// Show product form.
return "product";
}
return "redirect:/productList";
}
#RequestMapping(value = { "/order" }, method = RequestMethod.GET)
public String orderView(Model model, #RequestParam("orderId") String
orderId) {
OrderInfo orderInfo = null;
if (orderId != null) {
orderInfo = this.orderDAO.getOrderInfo(orderId);
}
if (orderInfo == null) {
return "redirect:/orderList";
}
List<OrderDetailInfo> details =
this.orderDAO.listOrderDetailInfos(orderId);
orderInfo.setDetails(details);
model.addAttribute("orderInfo", orderInfo);
return "order";
}
}
POM.XML
<properties>
<java-version>1.8</java-version>
</properties>
<repositories>
<!-- Repository for ORACLE JDBC Driver -->
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Servlet API -->
<!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -
->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- Jstl for jsp page -->
<!-- http://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- JSP API -->
<!-- http://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!-- Apache Commons FileUpload -->
<!-- http://mvnrepository.com/artifact/commons-fileupload/commons-
fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- Spring dependencies -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -
->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework/spring-web --
>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework/spring-orm --
>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<!-- Spring Security Artifacts - START -->
<!--
http://mvnrepository.com/artifact/org.springframework.security/spring-
security-web -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.0.4.RELEASE</version>
</dependency>
<!--
http://mvnrepository.com/artifact/org.springframework.security/spring-
security-config -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.0.4.RELEASE</version>
</dependency>
<!--
http://mvnrepository.com/artifact/org.springframework.security/spring-
security-taglibs -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.0.4.RELEASE</version>
</dependency>
<!-- Spring Security Artifacts - END -->
<!-- Hibernate -->
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-
entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.11.Final</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.11.Final</version>
</dependency>
<!-- MySQL JDBC driver -->
<!-- http://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!-- Oracle JDBC driver -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<!-- SQLServer JDBC driver (JTDS) -->
<!-- http://mvnrepository.com/artifact/net.sourceforge.jtds/jtds -->
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
<!-- PostgreSQL driver -->
<!-- https://mvnrepository.com/artifact/postgresql/postgresql -->
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
<!-- Email validator,... -->
<!-- http://mvnrepository.com/artifact/commons-validator/commons-
validator -->
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.5.0</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMVCANnotationShoppingCart</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source> <!-- yours Java version -->
<target>1.8</target> <!-- yours Java version -->
</configuration>
</plugin>
</plugins>
</build>
</project>
MyDBAuthenticationService.java
package org.o7planning.springmvcshoppingcart.authentication;
import java.util.ArrayList;
import java.util.List;
import org.o7planning.springmvcshoppingcart.dao.AccountDAO;
import org.o7planning.springmvcshoppingcart.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import
org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import
org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
#Service
public class MyDBAuthenticationService implements UserDetailsService {
#Autowired
private AccountDAO accountDAO;
#Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
Account account = accountDAO.findAccount(username);
System.out.println("Account= " + account);
if (account == null) {
throw new UsernameNotFoundException("User " //
+ username + " was not found in the database");
}
// EMPLOYEE,MANAGER,..
String role = account.getUserRole();
List<GrantedAuthority> grantList = new ArrayList<GrantedAuthority>();
// ROLE_EMPLOYEE, ROLE_MANAGER
GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + role);
grantList.add(authority);
boolean enabled = account.isActive();
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
UserDetails userDetails = (UserDetails) new User(account.getUserName(),
//
account.getPassword(), enabled, accountNonExpired, //
credentialsNonExpired, accountNonLocked, grantList);
return userDetails;
}
}
AplicationContextConfig.java
package org.o7planning.springmvcshoppingcart.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.o7planning.springmvcshoppingcart.dao.AccountDAO;
import org.o7planning.springmvcshoppingcart.dao.impl.AccountDAOImpl;
import org.o7planning.springmvcshoppingcart.dao.OrderDAO;
import org.o7planning.springmvcshoppingcart.dao.impl.OrderDAOImpl;
import org.o7planning.springmvcshoppingcart.dao.ProductDAO;
import org.o7planning.springmvcshoppingcart.dao.impl.ProductDAOImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import
org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#ComponentScan("org.o7planning.springmvcshoppingcart.*")
#EnableTransactionManagement
// Load to Environment.
#PropertySource("classpath:ds-hibernate-cfg.properties")
public class ApplicationContextConfig {
// The Environment class serves as the property holder
// and stores all the properties loaded by the #PropertySource
#Autowired
private Environment env;
#Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource rb = new ResourceBundleMessageSource();
// Load property in message/validator.properties
rb.setBasenames(new String[] { "messages/validator" });
return rb;
}
#Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
System.out.println("Executing intervnal view Resolver");
InternalResourceViewResolver viewResolver = new
InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
// Config for Upload.
#Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver commonsMultipartResolver = new
CommonsMultipartResolver();
// Set Max Size...
// commonsMultipartResolver.setMaxUploadSize(...);
return commonsMultipartResolver;
}
#Autowired
#Bean(name = "dataSource")
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
// See: ds-hibernate-cfg.properties
dataSource.setDriverClassName(env.getProperty("ds.database-driver"));
dataSource.setUrl(env.getProperty("ds.url"));
dataSource.setUsername(env.getProperty("ds.username"));
dataSource.setPassword(env.getProperty("ds.password"));
System.out.println("## getDataSource: " + dataSource);
return dataSource;
}
#Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) throws
Exception {
Properties properties = new Properties();
System.out.println("Datasource");
// See: ds-hibernate-cfg.properties
properties.put("hibernate.dialect",
env.getProperty("hibernate.dialect"));
properties.put("hibernate.show_sql",
env.getProperty("hibernate.show_sql"));
properties.put("current_session_context_class",
env.getProperty("current_session_context_class"));
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
// Package contain entity classes
factoryBean.setPackagesToScan(new String[] {
"org.o7planning.springmvcshoppingcart.entity" });
factoryBean.setDataSource(dataSource);
factoryBean.setHibernateProperties(properties);
factoryBean.afterPropertiesSet();
//
SessionFactory sf = factoryBean.getObject();
System.out.println("## getSessionFactory: " + sf);
return sf;
}
#Autowired
#Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory
sessionFactory) {
HibernateTransactionManager transactionManager = new
HibernateTransactionManager(sessionFactory);
return transactionManager;
}
#Bean(name = "accountDAO")
public AccountDAO getApplicantDAO() {
return new AccountDAOImpl();
}
#Bean(name = "productDAO")
public ProductDAO getProductDAO() {
return new ProductDAOImpl();
}
#Bean(name = "orderDAO")
public OrderDAO getOrderDAO() {
return new OrderDAOImpl();
}
#Bean(name = "accountDAO")
public AccountDAO getAccountDAO() {
return new AccountDAOImpl();
}
}
Please using Hibernate 5 in pom.xml:
<!-- Hibernate -->
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.2.10.Final</version>
</dependency>
I have a restful server i want to deploy on an AWS virtual machine. The application works fine on my local tomcat. I am able to access to the tomcat's default pages & manager apps from my browser and it works fine as well. But when i deploy the war file on tomcat it deploys but says
FAIL - Application at context path /zift-0.0.1-SNAPSHOT could not be started
I checked on catalina.out and realized i get mostly "UnsatisfiedDependencyExceptions", weird that i get none of them in my own computer. Here is the catalina.out:
0:10:45.466 [http-nio-8080-exec-16] ERROR org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'projectController': Unsatisfied dependency expressed through field 'projectService'; nes$
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4851)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.manager.ManagerServlet.start(ManagerServlet.java:1284)
at org.apache.catalina.manager.HTMLManagerServlet.start(HTMLManagerServlet.java:666)
at org.apache.catalina.manager.HTMLManagerServlet.doPost(HTMLManagerServlet.java:217)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.filters.CsrfPreventionFilter.doFilter(CsrfPreventionFilter.java:136)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:616)
And this goes on with other components with same exceptions.
Here is the pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zift.org</groupId>
<artifactId>zift</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>ziftorganizasyon</name>
<description>Zift Organizasyon</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
<start-class>com.ziftorg.configurations.ZiftInitializer</start-class>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.0.12.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
JavaConfig Files:
package com.ziftorg.configurations;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class ZiftInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { ZiftConfiguration.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
And this:
package com.ziftorg.configurations;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.ziftorg")
public class ZiftConfiguration {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/jsps/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean
public DataSource dataSource() {
final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
dsLookup.setResourceRef(true);
DataSource dataSource = dsLookup.getDataSource("jdbc/zift");
return dataSource;
}
}
One of the Controller's:
package com.ziftorg.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
//import com.mysql.jdbc.Constants;
import com.ziftorg.models.Chapter;
import com.ziftorg.models.Project;
import com.ziftorg.models.User;
import com.ziftorg.services.ProjectService;
import sun.awt.RepaintArea;
#JsonIgnoreProperties(ignoreUnknown = true)
#RestController
public class ProjectController {
#Autowired
private ProjectService projectService;
// GET METHOD TO RETRIEVE ALL PROJECTS
#CrossOrigin(origins = com.ziftorg.Constants.CORS_ORIGIN)
#RequestMapping(value = "/projects", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Project>> getAllProject() {
List<Project> projects = projectService.findAll();
return new ResponseEntity<List<Project>>(projects, HttpStatus.OK);
}
// GET Request to retrieve a single project by ID Numberto
#CrossOrigin(origins = com.ziftorg.Constants.CORS_ORIGIN)
#RequestMapping(value = "/projects/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Project> getSingleProject(#PathVariable("id") long id) {
Project project = projectService.findById(id);
if (project == null)
return new ResponseEntity<Project>(HttpStatus.NOT_FOUND);
return new ResponseEntity<Project>(project, HttpStatus.OK);
}
// POST request to create a BLANK PROJECT and return it back
#CrossOrigin(origins = com.ziftorg.Constants.CORS_ORIGIN)
#RequestMapping(value = "/projects", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Project> create(#RequestBody Project project, UriComponentsBuilder ucBuilder) {
System.out.println("passed project to POST project is : " + project);
System.out.println("UserID wanted to create a project is: " + project.getAuthorId());
Project p = projectService.create(project.getAuthorId());
return new ResponseEntity<Project>(p, HttpStatus.OK);
}
#RequestMapping(value = "projects/{id}", method = RequestMethod.DELETE)
#CrossOrigin(origins = com.ziftorg.Constants.CORS_ORIGIN)
public ResponseEntity<Project> delete(#PathVariable("id") int id) {
Project project = projectService.findById(id);
if (project == null)
return new ResponseEntity<Project>(HttpStatus.NOT_FOUND);
projectService.delete(project);
return new ResponseEntity<Project>(HttpStatus.NO_CONTENT);
}
#RequestMapping(value = "projects/{id}", method = RequestMethod.PUT)
#CrossOrigin(origins = com.ziftorg.Constants.CORS_ORIGIN)
public ResponseEntity<Project> update(#PathVariable("id") int id, #RequestBody Project project) {
System.out.println("received project city for update is : " + project.getCity());
System.out.println("came here too");
Project currentProject = projectService.findById(id);
if (currentProject == null)
return new ResponseEntity<Project>(HttpStatus.NOT_FOUND);
currentProject.setName(project.getName());
currentProject.setAuthor(project.getAuthor());
currentProject.setPartnerCountries(project.getPartnerCountries());
currentProject.setCity(project.getCity());
currentProject.setStartDate(project.getStartDate());
currentProject.setEndDate(project.getEndDate());
currentProject.setChapters(project.getChapters());
projectService.update(currentProject);
return new ResponseEntity<Project>(currentProject, HttpStatus.OK);
}
#RequestMapping(value = "projects/{id}/chapters/{chapterID}", method = RequestMethod.PUT)
#CrossOrigin(origins = com.ziftorg.Constants.CORS_ORIGIN)
public ResponseEntity<String> update(#PathVariable("id") long id, #PathVariable("chapterID") long chapterID,
#RequestBody Chapter chapter) {
Project p = projectService.findById(id);
List<Chapter> chapters = p.getChapters();
for (Chapter c : chapters) {
if (c.getId() == chapterID) {
System.out.println("will print the subtitles now");
System.out.println(chapter.getSubtitles().toString());
projectService.updateChapter(chapter);
}
}
return new ResponseEntity<String>(HttpStatus.OK);
}
}
And here is the Service class regarding to the previous Controller:
package com.ziftorg.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.ziftorg.models.Chapter;
import com.ziftorg.models.Project;
import com.ziftorg.models.Subtitle;
import com.ziftorg.repositories.ProjectRepository;
#Service("projectService")
#Qualifier("localProjectRepository")
public class ProjectService {
#Autowired
private ProjectRepository projectRepository;
public void setProjectRepository(ProjectRepository projectRepository) {
this.projectRepository = projectRepository;
}
public List<Project> findAll() {
return projectRepository.findAll();
}
public Project findByName(String name) {
return projectRepository.findByName(name);
}
public Project findById(long id) {
return projectRepository.findById(id);
}
public void update(Project project) {
projectRepository.update(project);
}
public void delete(Project project) {
projectRepository.delete(project);
}
public void create(Project project) {
projectRepository.create(project);
}
public Project create(long userID) {
return projectRepository.create(userID);
}
public boolean projectExists(Project project) {
return projectRepository.findById((int) project.getId()) != null;
}
public void updateChapter(Chapter chapter) {
projectRepository.updateChapter(chapter);
}
}
When you said that you're not having problems on your computer is because you're running your project on the embedded tomcat in the STS? Because if that's the case you are have to add WebApplicationInitializer.