WARNING: A HTTP GET method, public java.lang.String, should not consume any form parameter(UPDATED) - jersey

I have that error when i execute my getCustomers() method in Postman. The problem is that for some reason executes the method getOrder() isntead of just getCustomers(), if i let it uncommented. I have searched about this issue but i was not able to find anything that worked in my case. Any help will be very apreciate.
Error:
org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
[[FATAL] A HTTP GET method, public java.lang.String com.something.JerseyProjectConnectionToDB.App.getOrder(java.lang.String), should not consume any form parameter.; source='ResourceMethod{httpMethod=GET, consumedTypes=[], producedTypes=[application/json], suspended=false, suspendTimeout=0, suspendTimeoutUnit=MILLISECONDS, invocable=Invocable{handler=ClassBasedMethodHandler{handlerClass=class com.something.JerseyProjectConnectionToDB.App, handlerConstructors=[org.glassfish.jersey.server.model.HandlerConstructor#3ea75b05]}, definitionMethod=public java.lang.String com.something.JerseyProjectConnectionToDB.App.getOrder(java.lang.String), parameters=[Parameter [type=class java.lang.String, source=date, defaultValue=null]], responseType=class java.lang.String}, nameBindings=[]}']
at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:371)
at org.glassfish.jersey.server.ApplicationHandler.lambda$initialize$1(ApplicationHandler.java:293)
at org.glassfish.jersey.internal.Errors.process(Errors.java:292)
at org.glassfish.jersey.internal.Errors.process(Errors.java:274)
at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:232)
at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:292)
at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:259)
at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:311)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:154)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:346)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1134)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1089)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:983)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4902)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5206)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
at java.util.concurrent.FutureTask.run(Unknown Source)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:843)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
at java.util.concurrent.FutureTask.run(Unknown Source)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:433)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.startup.Catalina.start(Catalina.java:772)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:342)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:473)
App.java
#Path("/app")
public class App {
#GET
#Path("/getCustomers")
#Produces(MediaType.APPLICATION_JSON)
public List<CustomerPOJO> getCustomers() {
return CustomerDAO.getAllCustomers();
}
/*
#GET
#Path("/getOrder")
#Produces(MediaType.APPLICATION_JSON)
public String getOrder(#FormParam("date") String date){
return CustomerDAO.getOrder(date);
}
*/
}
CustomerDAO.java
public class CustomerDAO {
public static List<CustomerPOJO> getAllCustomers(){
List<CustomerPOJO> customerList = new ArrayList<CustomerPOJO>();
CustomerPOJO customer = null;
try(Connection conn = DBConnection.createNewDBconnection()){
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("Select * from customer");
while(rs.next()) {
customer = new CustomerPOJO();
customer.setCustomer_code(rs.getInt(1));
customer.setCustomer_name(rs.getString(2));
customer.setCustomer_adress(rs.getString(3));
customer.setCustomer_age(rs.getInt(4));
customerList.add(customer);
}
rs.close();
stmt.close();
} catch (SQLException e) {
logger.error(e);
}
return customerList;
}
public static String getOrder(String pattern){
List<OrderShipmentPOJO> orderList = new ArrayList<OrderShipmentPOJO>();
OrderShipmentPOJO order = null;
ObjectMapper objectMapper = new ObjectMapper();
String orderListToString = null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd");
Date date = null;
try(Connection conn = DBConnection.createNewDBconnection()){
date = simpleDateFormat.parse(pattern);
logger.info(date);
if(CheckDate.execute(date)) {
String query = "select customer.customer_name, product.product_title, order_shipment.order_date\r\n"
+ "from customer, product, order_shipment, order_shipment_has_product\r\n"
+ "where order_shipment.order_code = order_shipment_has_product.order_code \r\n"
+ "and (order_shipment_has_product.product_code = product.product_code\r\n"
+ "and (order_shipment.customer_code = customer.customer_code\r\n"
+ "and (date(order_shipment.order_date) = '?')))";
PreparedStatement ps = conn.prepareStatement(query);
ps.setDate(1, (java.sql.Date) date);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
order = new OrderShipmentPOJO();
order.setCustomer_name(rs.getString(1));
order.setProduct_title(rs.getString(2));
order.setOrder_date(rs.getDate(3));
orderList.add(order);
}
rs.close();
} else {
return "You have inserted a date that dont exist, try again";
}
orderListToString = objectMapper.writeValueAsString(orderList);
} catch (SQLException e) {
logger.error(e);
} catch (ParseException e) {
logger.error(e);
return "Unparseable using " + date + ". Use a format like this one: 2020-11-30";
} catch (JsonProcessingException e) {
logger.error(e);
}
return orderListToString;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://JAVA.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.something.JerseyProjectConnectionToDB</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
pom.xml
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.something</groupId>
<artifactId>JerseyProjectConnectionToDB</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>JerseyProjectConnectionToDB</name>
<build>
<finalName>JerseyProjectConnectionToDB</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.29.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.29.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.29.1</version>
</dependency>
</dependencies>
</project>
I have found that the problem was the method getOrder(), so i commented it and now works. My problem now is that when i let that method uncommented and i call to other methods, the code executes the method getOrder() instead of the method i called, what could be the problem?
Thank you for your help and time ^^

I have found the solution to this problem. The method #GET dont accept #FormParam, you just need to use #QueryParam or #PathParam. More info: https://stackoverflow.com/a/29789846/15633133

Related

Problems setting up Spring form validation

I have some problems setting up the validation in Spring MVC (4.3.9) application.
Basically, there is a simple application, with the issue isolated to one "contact" form.
Here is part of the code of the bean underlying the form:
#Component
#Scope("request")
public class SendMail {
#Min(20)
private String userName;
#Size(min=10, max=11)
private String message;
private String userEmail;
public static class CustomValidator implements Validator {
#Override
public boolean supports(Class clazz) {
return SendMail.class.equals(clazz);
}
#Override
public void validate(Object targets, Errors errors) {
SendMail o = (SendMail) targets;
if (o.getUserName() == null || o.getUserName().length() < 1) {
errors.rejectValue("userName", "Empty.userName");
}
}
}
....
}
and here is the part of the relevant controller:
#RequestMapping(value = {"/contact"}, method = RequestMethod.POST)
public ModelAndView sendEmail(#Valid SendMail sendmail, BindingResult result) {
System.out.println("Result1: " + result.hasErrors());
DataBinder binder = new DataBinder(sendmail);
binder.setValidator(new SendMail.CustomValidator());
binder.validate();
result = binder.getBindingResult();
System.out.println("Result2: " + result.hasErrors());
I get the following result:
Result1: false
Result2: true
So, the 'general' (denoted by the #Valid annotation) validation doesnt seem to work, but a manually-invoked validation does.
I googled for some time and have come across suggestions that a validation bean needs to be defined in the spring config. Unfortunately, when I add the following to my Config.java:
....
#Bean(name = "validator")
public Validator getValidator() {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
return validator;
}
The application crashes with the following exception:
....
root cause
java.lang.ClassNotFoundException: javax.el.ExpressionFactory
java.net.URLClassLoader.findClass(URLClassLoader.java:381)
java.lang.ClassLoader.loadClass(ClassLoader.java:424)
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
java.lang.ClassLoader.loadClass(ClassLoader.java:357)
java.lang.ClassLoader.defineClass1(Native Method)
java.lang.ClassLoader.defineClass(ClassLoader.java:763)
java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
java.net.URLClassLoader.access$100(URLClassLoader.java:73)
java.net.URLClassLoader$1.run(URLClassLoader.java:368)
java.net.URLClassLoader$1.run(URLClassLoader.java:362)
java.security.AccessController.doPrivileged(Native Method)
java.net.URLClassLoader.findClass(URLClassLoader.java:361)
java.lang.ClassLoader.loadClass(ClassLoader.java:424)
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
java.lang.ClassLoader.loadClass(ClassLoader.java:411)
java.lang.ClassLoader.loadClass(ClassLoader.java:357)
java.lang.Class.forName0(Native Method)
java.lang.Class.forName(Class.java:348)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(Unknown Source)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(Unknown Source)
javax.el.ExpressionFactory.newInstance(Unknown Source)
javax.el.ExpressionFactory.newInstance(Unknown Source)
....
This supposedly indicates, there is no lib with EL implementation. And here is where I'm stuck. I have tried a number of dependency (using maven) with no avail. Currently the relevant part of my pom looks like this:
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>5.4.1.Final</version>
</dependency>
I have tried various set-ups, with el-impl 2.2, etc. addin el.jar to Tomcat clasppath. But no luck at all =(
What is even more starange, if you look at the exception above, the call actually goes through "javax.el.ExpressionFactory.newInstance(Unknown Source)" before resulting in "java.lang.ClassNotFoundException: javax.el.ExpressionFactory".
I'd be grateful for any hints on how to fix/debug the issue...
Add this dependency .
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>el-impl</artifactId>
<version>2.2</version>
</dependency>
Follow solution here .
I have found the solution to my issue. Strange as it seems, when I added el.jar supplied with Tomcat to the classpath in catalina.sh, the validation works. It might be a distro-related issue (i'm running it on Gentoo).

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.spring_session' doesn't exist - Spring Boot

I am developing springboot-springsession-jdbc-demo. When I simply run the code I get the following error. It looks to me some property must need to set in application.properties in order create the schema/tables before hand. Required configuration is already in placed and still it gives error. The code is present in https://github.com/sivaprasadreddy/spring-session-samples
The error for reference:
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [DELETE FROM SPRING_SESSION WHERE LAST_ACCESS_TIME < ?]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.spring_session' doesn't exist
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231) ~[spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73) ~[spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649) ~[spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:870) ~[spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:931) ~[spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:941) ~[spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.session.jdbc.JdbcOperationsSessionRepository$6.doInTransaction(JdbcOperationsSessionRepository.java:481) ~[spring-session-1.2.1.RELEASE.jar:na]
at org.springframework.session.jdbc.JdbcOperationsSessionRepository$6.doInTransaction(JdbcOperationsSessionRepository.java:478) ~[spring-session-1.2.1.RELEASE.jar:na]
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133) ~[spring-tx-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.session.jdbc.JdbcOperationsSessionRepository.cleanUpExpiredSessions(JdbcOperationsSessionRepository.java:478) ~[spring-session-1.2.1.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_45]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_45]
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81) [spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_45]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_45]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [na:1.8.0_45]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [na:1.8.0_45]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_45]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_45]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_45]
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.spring_session' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_45]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_45]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_45]
at java.lang.reflect.Constructor.newInstance(Constructor.java:422) ~[na:1.8.0_45]
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.Util.getInstance(Util.java:387) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:942) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2526) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2673) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2549) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2073) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2009) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5098) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1994) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:877) ~[spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:870) ~[spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633) ~[spring-jdbc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
... 21 common frames omitted
pom.xml
<!-- Parent pom providing dependency and plugin management for applications
built with Maven -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Boot Starter JDBC -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter Thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Spring Session -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
</dependency>
<!-- Spring Boot devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- MYSQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- H2 DB -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
</project>
Application.java
#SpringBootApplication
#EnableJdbcHttpSession
#EnableAutoConfiguration
public class Application{
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
}
HomeController.java
#Controller
public class HomeController {
private static final AtomicInteger UserId = new AtomicInteger(0);
#RequestMapping("/")
public String home(Model model){
return "index";
}
#RequestMapping("/add-simple-attrs")
public String handleSimpleSessionAttributes(HttpServletRequest req, HttpServletResponse resp){
String attributeName = req.getParameter("attributeName");
String attributeValue = req.getParameter("attributeValue");
req.getSession().setAttribute(attributeName, attributeValue);
User user = new User();
user.setName(attributeValue);
req.getSession().setAttribute(attributeName, user);
return "redirect:/";
}
#RequestMapping("/add-object-attrs")
public String handleObjectSessionAttributes(HttpServletRequest req, HttpServletResponse resp){
String name = req.getParameter("name");
User user = new User();
user.setId(UserId.incrementAndGet());
user.setName(name);
req.getSession().setAttribute("USER_ID_"+user.getId(), user);
return "redirect:/";
}
}
User.java
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
public User(){
}
public User(Integer id, String name){
this.id = id;
this.name = name;
}
#Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
public Integer getId(){
return id;
}
public void setId(Integer id){
this.id = id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
application.properties
logging.level.org.springframework=INFO
################### DataSource Configuration ##########################
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.initialize=true
#spring.datasource.data=classpath:org/springframework/session/jdbc/schema-h2.sql
spring.datasource.data=classpath:org/springframework/session/jdbc/schema-mysql.sql
spring.datasource.continue-on-error=true
spring.jpa.hibernate.ddl-auto=create
#spring.jpa.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<title>Home</title>
</head>
<body>
<h2 th:text="#{app.title}">App Title</h2>
<h4>Add Simple Attributes To Session</h4>
<form class="form-inline" role="form" action="add-simple-attrs" method="post">
<label for="attributeName">Attribute Name</label>
<input id="attributeName" type="text" name="attributeName"/>
<label for="attributeValue">Attribute Value</label>
<input id="attributeValue" type="text" name="attributeValue"/>
<input type="submit" value="Set Attribute"/>
</form>
<h4>Add Object Attributes To Session</h4>
<form class="form-inline" role="form" action="add-object-attrs" method="post">
<label for="name">User Name</label>
<input id="name" type="text" name="name"/>
<input type="submit" value="Save"/>
</form>
<h3>Session Attributes</h3>
<table>
<thead>
<tr>
<th>Attribute Name</th>
<th>Attribute Value</th>
</tr>
</thead>
<tbody>
<tr th:each="attr : ${session}">
<td th:text="${attr.key}">Name</td>
<td th:text="${attr.value}">Value</td>
</tr>
</tbody>
</table>
</body>
</html>
I've just had a quite similar error while using spring-boot 2.0.5 (as opposed to 1.4.0 used by OP) with Postgres driver:
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [DELETE FROM spring_sessions WHERE EXPIRY_TIME < ?]; nested exception is org.postgresql.u
til.PSQLException: ERROR: relation "spring_sessions" does not exist
Position: 13
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:234) ~[spring-jdbc-5.0.8.RELEASE.jar!/:5.0.8.RELEA
SE]
// redacted...
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_181]
Caused by: org.postgresql.util.PSQLException: ERROR: relation "spring_sessions" does not exist
Position: 13
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2433) ~[postgresql-42.2.2.jar!/:42.2.2]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2178) ~[postgresql-42.2.2.jar!/:42.2.2]
// redacted...
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:605) ~[spring-jdbc-5.0.8.RELEASE.jar!/:5.0.8.RELEASE]
... 16 common frames omitted
According to documentation, setting up Spring Session backed by a relational database is as simple as adding a single configuration property to your application.properties:
spring.session.store-type=jdbc
Note that in order to get the session tables auto-created, I had to also specify:
spring.session.jdbc.initialize-schema=always
Once this setting specified, Spring used the correct SQL initialization script from spring-session-jdbc jar. My mistake was not specifying that option - in which case embedded was being used as default value.
I'm not sure this is the best solution (or even the solution as i'm new to spring and am not aware of the repercussions of doing this) but I was having the same issue, managed to solve it by deleting the annotation #EnableJdbcHttpSession
According to Vedran Pavic:
The reason spring.session.* do not work for you is because your are
using #EnableJdbcHttpSession. That means that you are configuring
Spring Session explicitly, so Spring Boot backs off with its
auto-configuration.
You should remove #EnableJdbcHttpSession and ensure Spring Boot is
auto-configuring Spring Session. Additionally, you could also leave
spring.session.store-type out, since Spring Boot should be able to
deduce which session repository implementation are you using as long
as you have only only SessionRepository implementation on the
classpath (i.e. you depend only on spring-session-jdbc and no other
Spring Session modules).
Original Post
This will solve your immediate problem, but i'm unsure if it will break something else...
I think you have multiple issues By default jdbc has H2 database. It is automatically created by spring.
Check if it is there. So first run it on H2. Then copy the same database and table to MySQL. create same schema and table to MySQL then change connection to MySQL.
Spring Boot automatically creates a DataSource that connects Spring Session to an embedded instance of H2 database
src/main/resources/application.properties
spring.datasource.url= # JDBC URL of the database.
spring.datasource.username= # Login username of the database.
spring.datasource.password= # Login password of the database.
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root

Jetty scavenging sessions error with view-scoped beans

I am trying to port a Tomcat app to JettyRunner 9.2 I want to move my app to Heroku, so I need to start it with either an embedded server, or JettyRunner. I thought JettyRunner would be easiest, as I could keep a WAR format, and make it easy to port away if necessary.
Any help would be much appreciated. If I can't get it to work soon, I may try embedded Tomcat, or look at hosting which doesn't require me to change my container.
If a different method of using Jetty - maybe embedded Jetty would be easier, please let me know and point me to some details.
So, to the app behaviour. The app seems to be ported fine and starts ok, but I'm getting an error on login. Here is the exception
2014-12-26 05:18:21.189:WARN:oejs.session:org.eclipse.jetty.server.session.HashSessionManager#69f63d95Timer: Problem scavenging sessions
java.lang.NullPointerException
at com.sun.faces.application.view.ViewScopeContextManager.destroyBeans(Unknown Source)
at com.sun.faces.application.view.ViewScopeContextManager.sessionDestroyed(Unknown Source)
at com.sun.faces.application.view.ViewScopeManager.sessionDestroyed(Unknown Source)
at com.sun.faces.application.WebappLifecycleListener.sessionDestroyed(Unknown Source)
at com.sun.faces.config.ConfigureListener.sessionDestroyed(Unknown Source)
at org.eclipse.jetty.server.session.AbstractSessionManager.removeSession(AbstractSessionManager.java:772)
at org.eclipse.jetty.server.session.AbstractSession.timeout(AbstractSession.java:302)
at org.eclipse.jetty.server.session.HashSessionManager.scavenge(HashSessionManager.java:358)
at org.eclipse.jetty.server.session.HashSessionManager$Scavenger.run(HashSessionManager.java:84)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Here are my jetty and jsf dependencies:
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.2.6.v20141205</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.2.6.v20141205</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
<version>2.2.9</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
Here is my maven jetty plugin section of my pom:
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${org.eclipse.jetty.version}</version>
<configuration>
<webApp>
<overrideDescriptor>src/main/webapp/WEB-INF/jetty-web-override.xml</overrideDescriptor>
</webApp>
<contextXml>src/main/webapp/WEB-INF/jetty-context.xml</contextXml>
</configuration>
</plugin>
Listeners in my web.xml
<listener>
<listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>
</listener>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
jetty-web-override.xml
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<listener>
<listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>
</listener>
<resource-env-ref>
<resource-env-ref-name>BeanManager</resource-env-ref-name>
<resource-env-ref-type>
javax.enterprise.inject.spi.BeanManager
</resource-env-ref-type>
</resource-env-ref>
jetty-env.xml
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
<Configure id="webAppCtx" class="org.eclipse.jetty.webapp.WebAppContext">
<New id="BeanManager" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg>
<Ref id="webAppCtx"/>
</Arg>
<Arg>BeanManager</Arg>
<Arg>
<New class="javax.naming.Reference">
<Arg>javax.enterprise.inject.spi.BeanManager</Arg>
<Arg>org.jboss.weld.resources.ManagerObjectFactory</Arg>
<Arg/>
</New>
</Arg>
</New>
</Configure>
and finally, jetty.context:
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN"
"http://www.eclipse.org/jetty/configure.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="serverClasses">
<Array type="java.lang.String">
<Item>-org.eclipse.jetty.servlet.ServletContextHandler.Decorator</Item>
</Array>
</Set>
</Configure>
This issue is caused by a bug in the JSF implementation to do with ViewScoped beans, which is described here The described bug is in JSF 2.29 and 2.28. The fix is in 2.30, which is not yet released.
I tried going back versions in the 2.2 heirarchy. 2.27 and before this bug disappeared, but other bugs occur in ViewScoped beans.
It looks like View Scoped beans are basically broken in jsf 2.2 (as far as I looked), so as a temporary measure, I have changed all my View Scoped beans to Request Scoped. This avoids the error.
I just made the following workaround.
I'm using Jetty 9.2, CDI 1.2 (Weld) and Mojarra 2.28.
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import javax.enterprise.inject.spi.CDI;
import javax.faces.FacesException;
import javax.faces.context.ExternalContext;
import javax.faces.context.ExternalContextFactory;
import javax.faces.context.ExternalContextWrapper;
import com.sun.faces.util.Util;
public class CDIViewScopeFixExternalContextFactory extends ExternalContextFactory{
private final ExternalContextFactory wrapped;
public CDIViewScopeFixExternalContextFactory(ExternalContextFactory wrapped){
this.wrapped = wrapped;
}
#Override
public ExternalContext getExternalContext(Object context, Object request,
Object response) throws FacesException {
ExternalContext externalContext = getWrapped().getExternalContext(context, request, response);
CDIViewScopeWorkaround wrapper = new CDIViewScopeWorkaround(externalContext);
return wrapper;
}
#Override
public ExternalContextFactory getWrapped() {
return this.wrapped;
}
private static class CDIViewScopeWorkaround extends ExternalContextWrapper{
private static String CDI_KEY;
static {
try {
Field f = Util.class.getDeclaredField("CDI_AVAILABLE_PER_APP_KEY");
f.setAccessible(true);
CDI_KEY = (String) f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private final ExternalContext wrapped;
public CDIViewScopeWorkaround(ExternalContext wrapped){
this.wrapped = wrapped;
}
#Override
public ExternalContext getWrapped() {
return wrapped;
}
#Override
public Map<String, Object> getApplicationMap() {
MapFix mapFix = new MapFix(super.getApplicationMap());
return mapFix;
}
}
private static class MapFix extends MapWrapper<String,Object>{
public MapFix(Map<String, Object> delegate) {
super(delegate);
}
#Override
public Object get(Object key) {
if(CDIViewScopeWorkaround.CDI_KEY.equals(key)){
return CDI.current().getBeanManager();
}
return super.get(key);
}
}
private static class MapWrapper<K,V> implements Map<K,V>{
private Map<K,V> delegate;
public int size() {
return delegate.size();
}
public boolean isEmpty() {
return delegate.isEmpty();
}
public boolean containsKey(Object key) {
return delegate.containsKey(key);
}
public boolean containsValue(Object value) {
return delegate.containsValue(value);
}
public V get(Object key) {
return delegate.get(key);
}
public V put(K key, V value) {
return delegate.put(key, value);
}
public V remove(Object key) {
return delegate.remove(key);
}
public void putAll(Map<? extends K, ? extends V> m) {
delegate.putAll(m);
}
public void clear() {
delegate.clear();
}
public Set<K> keySet() {
return delegate.keySet();
}
public Collection<V> values() {
return delegate.values();
}
public Set<java.util.Map.Entry<K, V>> entrySet() {
return delegate.entrySet();
}
public boolean equals(Object o) {
return delegate.equals(o);
}
public int hashCode() {
return delegate.hashCode();
}
public MapWrapper(Map<K,V> delegate){
this.delegate = delegate;
}
}
}
faces-config.xml
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.ord/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
<application>
…
</application>
<factory>
<external-context-factory>your.package.CDIViewScopeFixExternalContextFactory</external-context-factory>
</factory>
</faces-config>
I have the same issue with a 7.0.55 tomcat on a linux system.
For me, JAVASERVERFACES-3450 is not the problem, because this ticket refers to null instances of view scoped beans which are already destroyed.
Our exception in ViewScopeContextManager.destroyBeans(Unknown Source) occurs because of a null instance of beanManager.
With a Tomcat 7.0.55 on a windows system, everything works... :(

Ehcache, CacheException with JMS replication and activemq

I'm trying to implement a hibernate clustered 2nd level cache with ehcache, using JMS replication.
Hibernate version is 3.6.10.final, spring version is 3.2.2.
When the servlet is starting, I get the following error:
Caused by: org.hibernate.cache.CacheException: net.sf.ehcache.CacheException: Failure cloning default cache. Initial cause was not supported
at net.sf.ehcache.hibernate.AbstractEhcacheProvider.buildCache(AbstractEhcacheProvider.java:73)
at org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge.buildEntityRegion(RegionFactoryCacheProviderBridge.java:104)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:280)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1872)
at com.targa.fleetGateway.HibernateUtil.<init>(HibernateUtil.java:26)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
... 73 more
Caused by: net.sf.ehcache.CacheException: Failure cloning default cache. Initial cause was not supported
at net.sf.ehcache.CacheManager.cloneDefaultCache(CacheManager.java:1877)
at net.sf.ehcache.CacheManager.addCache(CacheManager.java:1173)
at net.sf.ehcache.hibernate.AbstractEhcacheProvider.buildCache(AbstractEhcacheProvider.java:66)
... 82 more
Caused by: java.lang.CloneNotSupportedException: not supported
at net.sf.ehcache.distribution.jms.JMSCacheLoader.clone(JMSCacheLoader.java:269)
at net.sf.ehcache.Cache.clone(Cache.java:2846)
at net.sf.ehcache.Cache.clone(Cache.java:163)
at net.sf.ehcache.CacheManager.cloneDefaultCache(CacheManager.java:1875)
... 84 more
My ehcache.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true">
<cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.jms.JMSCacheManagerPeerProviderFactory"
properties="initialContextFactoryName=com.targa.fleetGateway.ExampleActiveMQInitialContextFactory,
providerURL=tcp://127.0.0.1:61616, replicationTopicConnectionFactoryBindingName=topicConnectionFactory,
replicationTopicBindingName=ehcache, getQueueConnectionFactoryBindingName=queueConnectionFactory, getQueueBindingName=ehcacheGetQueue, topicConnectionFactoryBindingName=topicConnectionFactory, topicBindingName=ehcache"
propertySeparator="," />
<defaultCache
maxElementsInMemory="100"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="false">
<cacheEventListenerFactory class="net.sf.ehcache.distribution.jms.JMSCacheReplicatorFactory"
properties="replicateAsynchronously=true, replicatePuts=true, replicateUpdates=true,
replicateUpdatesViaCopy=true, replicateRemovals=true, asynchronousReplicationIntervalMillis=1000"
propertySeparator="," />
<cacheLoaderFactory class="net.sf.ehcache.distribution.jms.JMSCacheLoaderFactory"
properties="initialContextFactoryName=com.targa.fleetGateway.ExampleActiveMQInitialContextFactory,
providerURL=tcp://127.0.0.1:61616, replicationTopicConnectionFactoryBindingName=topicConnectionFactory,
getQueueConnectionFactoryBindingName=queueConnectionFactory, replicationTopicBindingName=ehcache,
getQueueBindingName=ehcacheGetQueue, timeoutMillis=10000" />
</defaultCache>
</ehcache>
If I comment out the cacheLoaderFactory section, things start working again.
The same configuration works in another application where I'm using hibernate 4.2, but I can't upgrade to 4.2 on this one.
Has anybody got any clue about this?
Below are the other relevant pieces of my configuration. Please tell me if anything is missing.
POM.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>3.6.10.Final</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.8</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-jmsreplication</artifactId>
<version>0.5</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-core</artifactId>
<version>5.7.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>16.0.1</version>
</dependency>
Hibernate properties:
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.provider_class">
net.sf.ehcache.hibernate.SingletonEhCacheProvider</property>
ExampleActiveMQInitialContextFactory.java
public class ExampleActiveMQInitialContextFactory extends
ActiveMQInitialContextFactory {
/**
* {#inheritDoc}
*/
#Override
public Context getInitialContext(Hashtable environment) throws NamingException {
Map<String, Object> data = new ConcurrentHashMap<String, Object>();
String replicationTopicConnectionFactoryBindingName = (String) environment
.get(JMSUtil.TOPIC_CONNECTION_FACTORY_BINDING_NAME);
if (replicationTopicConnectionFactoryBindingName != null) {
try {
data.put(replicationTopicConnectionFactoryBindingName,
createConnectionFactory(environment));
} catch (URISyntaxException e) {
throw new NamingException(
"Error initialisating TopicConnectionFactory with message "
+ e.getMessage());
}
}
String getQueueConnectionfactoryBindingName = (String) environment
.get(JMSUtil.GET_QUEUE_CONNECTION_FACTORY_BINDING_NAME);
try {
data.put(getQueueConnectionfactoryBindingName,
createConnectionFactory(environment));
} catch (URISyntaxException e) {
throw new NamingException(
"Error initialisating TopicConnectionFactory with message "
+ e.getMessage());
}
String replicationTopicBindingName = (String) environment
.get(JMSUtil.REPLICATION_TOPIC_BINDING_NAME);
String getQueueBindingName = (String) environment
.get(JMSUtil.GET_QUEUE_BINDING_NAME);
if (replicationTopicBindingName != null) {
data.put(replicationTopicBindingName,
createTopic(replicationTopicBindingName));
}
data.put(getQueueBindingName, createQueue(getQueueBindingName));
return createContext(environment, data);
}
}
I faced this problem today: the reason is that defaultCache should not have: cacheLoaderFactory.
Strange that it does not mentioned in the documentation(
So I removed cacheLoaderFactory from defaultCache - and everything works fine;

java.lang.IllegalArgumentException: Prefix '' is already bound to ''

sun-jaxws.xml
<?xml version="1.0" encoding="UTF-8"?>
<endpoints version="2.0" xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime">
<endpoint implementation="ways.org.commerce.inventory.service.InventoryServiceImpl" name="InventoryServiceImpl" url-pattern="/services/InventoryServiceImpl"/>
</endpoints>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-Main.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>InventoryServiceImpl</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>InventoryServiceImpl</servlet-name>
<url-pattern>/services/InventoryServiceImpl</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
InventoryServiceImpl.java
#WebService(serviceName = "InventoryServiceImpl")
public class InventoryServiceImpl implements IFInventoryService {
private IFInventoryDAO inventoryDAO;
#WebMethod(exclude = true)
public IFInventoryDAO getInventoryDAO() {
return inventoryDAO;
}
#WebMethod(exclude = true)
public void setInventoryDAO(IFInventoryDAO inventoryDAO) {
this.inventoryDAO = inventoryDAO;
}
#WebMethod(operationName = "addProduct")
public void addProduct(
#WebParam(name = "product") ProductBean product) throws CommerceBaseException {
if (inventoryDAO.productExists(product.getProductUniqueCode())) {
throw new CommerceBaseException("Product Not Found", InventoryErrorCode.PRODUCT_NOT_FOUND_ERROR);
}
inventoryDAO.addProduct(product);
}
#WebMethod(operationName = "getProduct")
public ProductBean getProduct(
#WebParam(name = "productUniqueCode") String productUniqueCode) throws CommerceBaseException {
if (inventoryDAO.productExists(productUniqueCode)) {
throw new CommerceBaseException("Product Not Found", InventoryErrorCode.PRODUCT_NOT_FOUND_ERROR);
}
return inventoryDAO.getProduct(productUniqueCode);
}
#WebMethod(operationName = "productExists")
public boolean productExists(
#WebParam(name = "productUniqueCode") String productUniqueCode) {
return inventoryDAO.productExists(productUniqueCode);
}
}
I am getting following exception
SEVERE: Exception sending context initialized event to listener instance of class com.sun.xml.ws.transport.http.servlet.WSServletContextListener
com.sun.xml.ws.transport.http.servlet.WSServletException: WSSERVLET11: failed to parse runtime descriptor: java.lang.IllegalArgumentException: Prefix '' is already bound to ''
at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.contextInitialized(WSServletContextListener.java:139)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4681)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5184)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5179)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.IllegalArgumentException: Prefix '' is already bound to ''
at com.sun.xml.txw2.StartTag.addNamespaceDecl(StartTag.java:171)
at com.sun.xml.txw2.ContainerElement._namespace(ContainerElement.java:313)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.xml.txw2.ContainerElement.invoke(ContainerElement.java:114)
at $Proxy179._namespace(Unknown Source)
at com.sun.xml.ws.wsdl.writer.WSDLGenerator.generateDocument(WSDLGenerator.java:339)
at com.sun.xml.ws.wsdl.writer.WSDLGenerator.doGeneration(WSDLGenerator.java:272)
at com.sun.xml.ws.server.EndpointFactory.generateWSDL(EndpointFactory.java:443)
at com.sun.xml.ws.server.EndpointFactory.createEndpoint(EndpointFactory.java:209)
at com.sun.xml.ws.api.server.WSEndpoint.create(WSEndpoint.java:505)
at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parseAdapters(DeploymentDescriptorParser.java:253)
at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parse(DeploymentDescriptorParser.java:147)
at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.contextInitialized(WSServletContextListener.java:124)
... 8 more
20 Oct, 2012 11:17:18 PM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Please help me to figure out where i am doing mistake...
There is a conflict between your web service libs and tomcat's libs.
use the folowing dependecy :
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>2.2.8</version>
<scope>provided</scope>
</dependency>
I had the same problem.
I was using the webservice-rt-1.4 with Maven's dependency and repaired who the webservice-api jar also was coming along with COMPILE scope. Then change to PROVIDE scope in the Maven and put webservice-rt-1.4 in the tomcat.
Also check was conflicts between the XML's lib of app with the tomcat.
Hopefully this is also be the case.
Hugs!
In my case, it was the jaxws-rt.jar included in the war file generated for the web service which was causing the problem but once I cleaned and built the war again keeping dependency as provided, it worked fine

Resources