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'm having this error for days, please look into my codes:
error codes:
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:136)
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:496)
com.test.dao.DoctorDAOImpl.getDoctor(DoctorDAOImpl.java:34)
com.test.service.MainServiceImpl.getDoctor(MainServiceImpl.java:39)
com.test.controller.MainController.showMain(MainController.java:23)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.base/java.lang.reflect.Method.invoke(Method.java:566)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
config.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.test")
#PropertySource({"classpath:persistence-mysql.properties"})
public class Config {
#Autowired
private Environment env;
private Logger logger = Logger.getLogger(getClass().getName());
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
System.out.println("\ntesting "+env.getProperty("jdbc.url")+"\n\n");
return viewResolver;
}
#Bean
public DataSource myDataSource() {
// create connection pool
ComboPooledDataSource myDataSource = new ComboPooledDataSource();
// set the jdbc driver
try {
myDataSource.setDriverClass("com.mysql.jdbc.Driver");
}
catch (PropertyVetoException exc) {
throw new RuntimeException(exc);
}
// for sanity's sake, let's log url and user ... just to make sure we are reading the data
logger.info("jdbc.url=" + env.getProperty("jdbc.url"));
logger.info("jdbc.user=" + env.getProperty("jdbc.user"));
// set database connection props
myDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
myDataSource.setUser(env.getProperty("jdbc.user"));
myDataSource.setPassword(env.getProperty("jdbc.password"));
// set connection pool props
myDataSource.setInitialPoolSize(getIntProperty("connection.pool.initialPoolSize"));
myDataSource.setMinPoolSize(getIntProperty("connection.pool.minPoolSize"));
myDataSource.setMaxPoolSize(getIntProperty("connection.pool.maxPoolSize"));
myDataSource.setMaxIdleTime(getIntProperty("connection.pool.maxIdleTime"));
return myDataSource;
}
private Properties getHibernateProperties() {
// set hibernate properties
Properties props = new Properties();
props.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
props.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
return props;
}
// need a helper method
// read environment property and convert to int
private int getIntProperty(String propName) {
String propVal = env.getProperty(propName);
// now convert to int
int intPropVal = Integer.parseInt(propVal);
return intPropVal;
}
#Bean
public LocalSessionFactoryBean sessionFactory(){
// create session factorys
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
// set the properties
sessionFactory.setDataSource(myDataSource());
sessionFactory.setPackagesToScan(env.getProperty("hibernate.packagesToScan"));
sessionFactory.setHibernateProperties(getHibernateProperties());
return sessionFactory;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
// setup transaction manager based on session factory
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
}
MainServiceImpl.java
package com.test.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.test.dao.DoctorDAO;
import com.test.dao.PatientDAO;
import com.test.entity.Doctor;
import com.test.entity.Patient;
#Service
public class MainServiceImpl implements MainService {
#Autowired
private PatientDAO patientDao;
#Autowired
private DoctorDAO doctorDao;
#Override
#Transactional
public List<Patient> getPatients() {
System.out.println("inside service: getPatients method");
return patientDao.getPatients();
}
#Override
#Transactional
public Patient getPatient(int theId) {
return patientDao.getPatient(theId);
}
#Override
#Transactional
public Doctor getDoctor(int theId) {
return doctorDao.getDoctor(theId);
}
#Override
#Transactional
public void addPatient(Patient thePatient) {
patientDao.savePatient(thePatient);
}
#Override
#Transactional
public void addDoctor(Doctor theDoctor) {
doctorDao.saveDoctor(theDoctor);
}
#Override
#Transactional
public void deletePatient(int theId) {
patientDao.deletePatient(theId);
}
}
MainController.java
package com.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.test.entity.Doctor;
import com.test.service.MainService;
#Controller
#RequestMapping("main")
public class MainController {
#Autowired
private MainService service;
#RequestMapping("/")
#Transactional
public String showMain(Model theModel) {
System.out.println("inside show Main method");
Doctor theDoctor = service.getDoctor(1);
// List<Patient> thePatients = service.getPatients();
// System.out.println(thePatients);
theModel.addAttribute("doctor", theDoctor);
return "main";
}
}
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.practice</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>test</name>
<properties>
<springframework.version>5.0.2.RELEASE</springframework.version>
<springsecurity.version>5.0.0.RELEASE</springsecurity.version>
<hibernate.version>5.4.1.Final</hibernate.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- Spring MVC support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Spring orm and tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Spring Security Support -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<!-- Spring Security JSP tag support -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Add MySQL and C3P0 support -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- Servlet, JSP and JSTL support -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- to compensate for java 9+ not including jaxb -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<build>
<finalName>test</finalName>
<pluginManagement>
<plugins>
<plugin>
<!-- Add maven coordinates: maven-war-plugin -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
DoctorDAOImpl.java
package com.test.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.test.entity.Doctor;
import com.test.entity.Patient;
#Repository
public class DoctorDAOImpl implements DoctorDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public List<Patient> getPatients(int theId) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Query<Patient> theQuery = session.createQuery("from Patient p where p.doctor.id=:doctorId");
theQuery.setParameter("doctorId", theId);
List<Patient> result = theQuery.getResultList();
session.getTransaction().commit();
return result;
}
#Override
public Doctor getDoctor(int theId) {
Session session = sessionFactory.getCurrentSession();
return session.get(Doctor.class, theId);
}
#Override
public void saveDoctor(Doctor theDoctor) {
Session session = sessionFactory.getCurrentSession();
session.save(theDoctor);
}
}
PatientDAOImpl.java
package com.test.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.test.entity.Patient;
#Repository
public class PatientDAOImpl implements PatientDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public List<Patient> getPatients() {
System.out.println("inside repository: getPatients method");
Session session = sessionFactory.getCurrentSession();
Query<Patient> theQuery = session.createQuery("from Patient",Patient.class);
return theQuery.getResultList();
}
#Override
public void savePatient(Patient thePatient) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(thePatient);
}
#Override
public Patient getPatient(int theId) {
Session session = sessionFactory.getCurrentSession();
return session.get(Patient.class,theId);
}
#Override
public void deletePatient(int theId) {
Session session = sessionFactory.getCurrentSession();
Query theQuery = session.createQuery("delete from Patient where id=:patientId");
theQuery.setParameter("patientId", theId);
theQuery.executeUpdate();
}
}
I'm sorry that I dumped all my code here, but this is the best I could do.
Please consider using the search before posting a question, as this has been asked multiple times on Stack Overflow. Besides #m-deinum's comment (props go to him!) you would have found the answer e.g. here or here or here: Please add #EnableTransactionManagement annotation.
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".
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.