The requested resource is not available- 404 - RESTful web service in Eclipse - java

I've been using the following guide to develop a hello world REST web service.
The guide can be found at: http://wiki.eclipse.org/Creating_a_JAX-RS_Web_Service
I'm trying to open the path: "http://localhost:8080/BeezerServer/jaxrs/addresses"
but it keeps on saying that "The requested resource (/BeezerServer/jaxrs/addresses) is not available."
my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>BeezerServer</display-name>
<servlet>
<description>JAX-RS Tools Generated - Do not modify</description>
<servlet-name>JAX-RS Servlet</servlet-name>
<servlet-class>org.apache.wink.server.internal.servlet.RestServlet</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.test.AddressBookApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS Servlet</servlet-name>
<url-pattern>/jaxrs/*</url-pattern>
</servlet-mapping>
</web-app>
The project looks as following(in case it might help someone):
The tomcat log:
Aug 31, 2012 7:48:58 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program...
Aug 31, 2012 7:48:59 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Aug 31, 2012 7:48:59 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Aug 31, 2012 7:48:59 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1536 ms
Aug 31, 2012 7:48:59 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Aug 31, 2012 7:48:59 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.29
Aug 31, 2012 7:48:59 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Aug 31, 2012 7:48:59 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Aug 31, 2012 7:48:59 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 737 ms
AddressBookApplication.java:
package com.test;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
public class AddressBookApplication extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(AddressBook.class);
return classes;
}
}
AddressBook.java:
package com.test;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
/**
* A sample resource that provides access to
* server configuration properties
*/
#Path(value="/addresses")
public class AddressBook {
public AddressBook() {
System.out.println();
}
private static String[] list = new String[] {
"Eric- 932 Deloraine Av.",
"Yen - 687 Markham Rd.",
"Keith - 4301 McCowan Rd.",
"Ron - 465 Melrose St.",
"Jane - 35 Cranbrooke Av.",
"Sam - 146 Brooke Av."
};
#GET
#Produces(value="text/plain")
public String getList() {
StringBuffer buffer = new StringBuffer();
buffer.append("{");
for (int i = 0; i < list.length; ++i) {
if (i != 0)
buffer.append(", ");
buffer.append(list[i]);
}
buffer.append("}");
return buffer.toString();
}
#GET
#Produces(value="text/plain")
#Path(value="{id}")
public String getPropety(#PathParam("id") int id) {
if (id > -1 && id < list.length -1) {
return list[id];
}
else {
return "Name Not Found";
}
}
#GET
#Produces(value="text/html")
#Path(value="html")
public String getHTMLList()
{
return "<html><body><p><b>Hello</b></body></html>";
}
#POST
#Produces(value="text/html")
#Path(value="form")
public String handlePost(#PathParam("name") String name,#PathParam("age") int age)
{
return "<html><body><p>name: " + name + "<p>age: " + age;
}
}

Related

Spring REST noHandlerFound

I am creating simple REST API with spring mvc, but when I go to http://localhost:8080/fundnesia/api/loans I got noHandlerFound eror. Seems like spring doesnt register these #RestController, #RequestMapping and #PostMapping, #DeleteMapping annotations. Any help please
Here is my entity class
package com.fundnesia.entity;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="loan")
public class Loan {
#Id
#GeneratedValue(strategy =GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="tenure")
private int tenure;
#Column(name="ticket_size")
private BigDecimal ticketSize;
#Column(name="fee")
private BigDecimal fee;
#Column(name="total_loan")
private BigDecimal totalLoan;
#Column(name="installment_per_month")
private BigDecimal installmentPerMonth;
#Column(name="status")
private String status;
public Loan() {
}
public Loan(int tenure, BigDecimal ticketSize, BigDecimal fee, BigDecimal totalLoan, BigDecimal installmentPerMonth,
String status) {
this.tenure = tenure;
this.ticketSize = ticketSize;
this.fee = fee;
this.totalLoan = totalLoan;
this.installmentPerMonth = installmentPerMonth;
this.status = status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTenure() {
return tenure;
}
public void setTenure(int tenure) {
this.tenure = tenure;
}
public BigDecimal getTicketSize() {
return ticketSize;
}
public void setTicketSize(BigDecimal ticketSize) {
this.ticketSize = ticketSize;
}
public BigDecimal getFee() {
return fee;
}
public void setFee(BigDecimal fee) {
this.fee = fee;
}
public BigDecimal getTotalLoan() {
return totalLoan;
}
public void setTotalLoan(BigDecimal totalLoan) {
this.totalLoan = totalLoan;
}
public BigDecimal getInstallmentPerMonth() {
return installmentPerMonth;
}
public void setInstallmentPerMonth(BigDecimal installmentPerMonth) {
this.installmentPerMonth = installmentPerMonth;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "Loan [id=" + id + ", ticketSize=" + ticketSize + ", fee=" + fee + ", totalLoan=" + totalLoan
+ ", installmentPerMonth=" + installmentPerMonth + ", status=" + status + "]";
}
}
Here is the the configuration file
package com.fundnesia.config;
import java.beans.PropertyVetoException;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import
org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
importorg.springframework.transaction.annotation.EnableTransactionManagement;
import
org.springframework.web.servlet.config.annotation.EnableWebMvc;
import
org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.mchange.v2.c3p0.ComboPooledDataSource;
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan(basePackages="com.fundnesia")
#PropertySource({"classpath:persistence-mysql.properties"})
public class RestConfig implements WebMvcConfigurer {
#Autowired
private Environment env;
#Bean
public DataSource dataSource() {
ComboPooledDataSource dataSource =new ComboPooledDataSource();
try {
dataSource.setDriverClass(env.getProperty("jdbc.driver"));
} catch (PropertyVetoException e) {
throw new RuntimeException(e);
}
dataSource.setJdbcUrl(env.getProperty("jdbc.url"));
dataSource.setUser(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.password"));
dataSource.setInitialPoolSize(Integer.parseInt(env.getProperty("connection.pool.initialPoolSize")));
dataSource.setMinPoolSize(Integer.parseInt(env.getProperty("connection.pool.minPoolSize")));
dataSource.setMaxPoolSize(Integer.parseInt(env.getProperty("connection.pool.maxPoolSize")));
dataSource.setMaxIdleTime(Integer.parseInt(env.getProperty("connection.pool.maxIdleTime")));
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory =new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(env.getProperty("hibernate.packagesToScan"));
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
private Properties hibernateProperties() {
Properties properties =new Properties();
properties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
properties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager txManager(SessionFactory sessionFactory) {
HibernateTransactionManager txManager =new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
}
Here the DispetcherServlet initializer
package com.fundnesia.config;
importorg.springframework.web.servlet.support.
AbstractAnnotationConfigDispatcherServletInitializer;
public class ConfigInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {RestConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
The controller class
package com.fundnesia.controller;
import java.math.BigDecimal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fundnesia.entity.Loan;
import com.fundnesia.service.LoanService;
#RestController
#RequestMapping("/fundnesia/api")
public class LoanResource {
#Autowired
private LoanService loanService;
#GetMapping("/loans")
public List<Loan> findAll() {
List<Loan> loans= loanService.findAll();
return loans;
}
#GetMapping("/loans/{loanId}")
public Loan findById(#PathVariable("loanId") int loanId) {
return loanService.findById(loanId);
}
#PostMapping("/loans")
public Loan save(#RequestBody Loan loan) {
BigDecimal ticketSize =loan.getTicketSize();
int tenure =loan.getTenure();
BigDecimal fee =ticketSize.multiply(BigDecimal.valueOf(tenure * 0.02));
BigDecimal totalLoan =ticketSize.add(fee);
BigDecimal installmentPerMonth =totalLoan.divide(BigDecimal.valueOf(tenure));
loan.setFee(fee);
loan.setTotalLoan(totalLoan);
loan.setInstallmentPerMonth(installmentPerMonth);
loan.setStatus("SUBMITTED");
loanService.save(loan);
return loan;
}
#DeleteMapping("/loans/{loanId}")
public String deleteById(#PathVariable("loanId") int loanId) {
loanService.deleteById(loanId);
return "Deleted loan with Id: " + loanId;
}
}
The Service Impl class
package com.fundnesia.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fundnesia.dao.LoanDao;
import com.fundnesia.entity.Loan;
#Service
public class LoanServiceImpl implements LoanService {
#Autowired
private LoanDao loanDao;
#Override
#Transactional
public List<Loan> findAll() {
return loanDao.findAll();
}
#Override
#Transactional
public void save(Loan loan) {
loanDao.save(loan);
}
#Override
#Transactional
public Loan findById(int loanId) {
return loanDao.findById(loanId);
}
#Override
#Transactional
public void deleteById(int loanId) {
loanDao.deleteById(loanId);
}
}
The Dao Impl class
package com.fundnesia.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.fundnesia.entity.Loan;
#Repository
public class LoanDaoImpl implements LoanDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public List<Loan> findAll() {
Session session =sessionFactory.getCurrentSession();
Query<Loan> query =session.createQuery("from Loan", Loan.class);
return query.getResultList();
}
#Override
public void save(Loan loan) {
Session session =sessionFactory.getCurrentSession();
session.saveOrUpdate(loan);
}
#Override
public Loan findById(int loanId) {
Session session =sessionFactory.getCurrentSession();
return session.get(Loan.class, loanId);
}
#Override
public void deleteById(int loanId) {
Session session =sessionFactory.getCurrentSession();
Query query =session.createQuery("delete from Loan where id=:loanId");
query.setParameter("loanId", loanId);
query.executeUpdate();
}
}
POM file
<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.sagala</groupId>
<artifactId>fundnesia</artifactId>
<packaging>war</packaging>
<version>0.01</version>
<name>fundnesia Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<springframework.version>5.2.5.RELEASE</springframework.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.10.3</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<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>
</dependencies>
<build>
<finalName>fundnesia</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
StackTrace
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version name: Apache Tomcat/9.0.30
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built: Dec 7 2019 16:42:04 UTC
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version number: 9.0.30.0
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name: Windows 7
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version: 6.1
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture: x86
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home: C:\Program Files\Java\jre1.8.0_162
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version: 1.8.0_162-b12
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor: Oracle Corporation
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE: C:\Users\Tunggul\eclipse-
workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME: C:\Program Files\Apache Software
Foundation\Tomcat 9.0
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -
Dcatalina.base=C:\Users\Tunggul\eclipse-
workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Program
Files\Apache Software Foundation\Tomcat 9.0
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\Tunggul\eclipse-
workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
\wtpwebapps
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Program
Files\Apache Software Foundation\Tomcat 9.0\endorsed
Mei 02, 2020 12:02:03 PM
org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Mei 02, 2020 12:02:03 PM
org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows
optimal performance in production environments was not found on the
java.library.path: [C:\Program
Files\Java\jre1.8.0_162\bin;C:\Windows\Sun\Java\bin;C:\Windows\
system32;C:\Windows;C:/Program
Files/Java/jre1.8.0_162/bin/client;C:/Program
Files/Java/jre1.8.0_162/bin;C:/Program
Files/Java/jre1.8.0_162/lib/i386;C:\ProgramData\Oracle\Java\
javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;
C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program
Files\Git\cmd;C:\Program Files\Git\mingw32\bin;C:\Program
Files\Git\usr\bin;;C:\Users\Tunggul\AppData\Local\Programs\
Microsoft VS Code\bin;C:\Program Files\eclipse;;.]
Mei 02, 2020 12:02:03 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Mei 02, 2020 12:02:03 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Mei 02, 2020 12:02:03 PM org.apache.catalina.startup.Catalina load
INFO: Server initialization in [980] milliseconds
Mei 02, 2020 12:02:04 PM org.apache.catalina.core.StandardService
startInternal
INFO: Starting service [Catalina]
Mei 02, 2020 12:02:04 PM org.apache.catalina.core.StandardEngine
startInternal
INFO: Starting Servlet engine: [Apache Tomcat/9.0.30]
Mei 02, 2020 12:02:08 PM org.apache.jasper.servlet.TldScanner
scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs.
Enable debug logging for this logger for a complete list of JARs
that were scanned but no TLDs were found in them. Skipping unneeded
JARs during scanning can improve startup time and JSP compilation
time.
Mei 02, 2020 12:02:15 PM
org.apache.catalina.core.ApplicationContext log
INFO: 1 Spring WebApplicationInitializers detected on classpath
Mei 02, 2020 12:02:15 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs.
Enable debug logging for this logger for a complete list of JARs
that were scanned but no TLDs were found in them. Skipping unneeded
JARs during scanning can improve startup time and JSP compilation
time.
Mei 02, 2020 12:02:15 PM
org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring DispatcherServlet 'dispatcher'
Mei 02, 2020 12:02:15 PM
org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: Initializing Servlet 'dispatcher'
Mei 02, 2020 12:02:16 PM com.mchange.v2.log.MLog
INFO: MLog clients using java 1.4+ standard logging.
Mei 02, 2020 12:02:16 PM com.mchange.v2.c3p0.C3P0Registry
INFO: Initializing c3p0-0.9.5.3 [built 27-January-2019 00:11:37
-0800; debug? true; trace: 10]
Mei 02, 2020 12:02:17 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.1.Final}
Mei 02, 2020 12:02:17 PM
org.hibernate.annotations.common.reflection.java.
JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
Mei 02, 2020 12:02:18 PM
com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource
INFO: Initializing c3p0 pool...
com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3,
acquireRetryAttempts -> 30, acquireRetryDelay -> 1000,
autoCommitOnClose -> false, automaticTestTable -> null,
breakAfterAcquireFailure -> false, checkoutTimeout -> 0,
connectionCustomizerClassName -> null, connectionTesterClassName ->
com.mchange.v2.c3p0.impl.DefaultConnectionTester,
contextClassLoaderSource -> caller, dataSourceName ->
1hge9kua91mr8xjwcsbkvv|8b45e, debugUnreturnedConnectionStackTraces
-> false, description -> null, driverClass ->
com.mysql.jdbc.Driver, extensions -> {}, factoryClassLocation ->
null, forceIgnoreUnresolvedTransactions -> false,
forceSynchronousCheckins -> false, forceUseNamedDriverClass ->
false, identityToken -> 1hge9kua91mr8xjwcsbkvv|8b45e,
idleConnectionTestPeriod -> 0, initialPoolSize -> 5, jdbcUrl ->
jdbc:mysql://localhost:3306/loan_calculator?useSSL=false,
maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime
-> 3000, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20,
maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize ->
5, numHelperThreads -> 3, preferredTestQuery -> null,
privilegeSpawnedThreads -> false, properties -> {user=******,
password=******}, propertyCycle -> 0,
statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin
-> false, testConnectionOnCheckout -> false,
unreturnedConnectionTimeout -> 0, userOverrides -> {},
usesTraditionalReflectiveProxies -> false ]
Mei 02, 2020 12:02:18 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Mei 02, 2020 12:02:20 PM
org.hibernate.engine.transaction.jta.platform.internal.
JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation:
[org.hibernate.engine.transaction.jta.platform.internal.
NoJtaPlatform]
Mei 02, 2020 12:02:21 PM
org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: Completed initialization in 6287 ms
Mei 02, 2020 12:02:21 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Mei 02, 2020 12:02:21 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Mei 02, 2020 12:02:21 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in [17,684] milliseconds
Mei 02, 2020 12:02:23 PM
org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping for GET /fundnesia/api/loans

JavaFX Observable list not updating GUI properly after being bound to listview [duplicate]

This question already has answers here:
JavaFX controller class not working
(1 answer)
Javafx - Can application class be the controller class
(2 answers)
Closed 5 years ago.
Issue:
After receiving a message from a the MessageListener class adds a message to a private final ObservableList<String> which in turn updates the GUI on change. the problem is that this happens inconsistently and for some unknown reason there seems to be 2 lists that interchange in adding the message to its list.
here is a log of this behavior:
INFO: Message received:
Text: SSN= 1223 Requested amount= 11€ time= 110
ID: ID:78-192.168.0.23(84:be:e3:92:5b:b3)-1-1519325025180
Reply to: null
Feb 22, 2018 7:43:45 PM Bank.ABNAmbro addMessages
INFO: Adding message to List:SSN= 1223 Requested amount= 11€ time= 110
Feb 22, 2018 7:43:45 PM Bank.ABNAmbro addMessages
INFO: New size: 2
Feb 22, 2018 7:43:54 PM Bank.BankMessageListener onMessage
INFO: Message received:
Text: SSN= 1223 Requested amount= 11€ time= 110
ID: ID:82-192.168.0.23(84:be:e3:92:5b:b3)-1-1519325034484
Reply to: null
Feb 22, 2018 7:43:54 PM Bank.ABNAmbro addMessages
INFO: Adding message to List:SSN= 1223 Requested amount= 11€ time= 110
Feb 22, 2018 7:43:54 PM Bank.ABNAmbro addMessages
INFO: New size: 9
Feb 22, 2018 7:43:55 PM Bank.BankMessageListener onMessage
INFO: Message received:
Text: SSN= 1223 Requested amount= 11€ time= 110
ID: ID:86-192.168.0.23(84:be:e3:92:5b:b3)-1-1519325035575
Reply to: null
Feb 22, 2018 7:43:55 PM Bank.ABNAmbro addMessages
INFO: Adding message to List:SSN= 1223 Requested amount= 11€ time= 110
Feb 22, 2018 7:43:55 PM Bank.ABNAmbro addMessages
INFO: New size: 10
Feb 22, 2018 7:43:57 PM Bank.BankMessageListener onMessage
INFO: Message received:
Text: SSN= 1223 Requested amount= 11€ time= 110
ID: ID:90-192.168.0.23(84:be:e3:92:5b:b3)-1-1519325037074
Reply to: null
Feb 22, 2018 7:43:57 PM Bank.ABNAmbro addMessages
INFO: Adding message to List:SSN= 1223 Requested amount= 11€ time= 110
Feb 22, 2018 7:43:57 PM Bank.ABNAmbro addMessages
INFO: New size: 11
Feb 22, 2018 7:43:58 PM Bank.BankMessageListener onMessage
INFO: Message received:
Text: SSN= 1223 Requested amount= 11€ time= 110
ID: ID:94-192.168.0.23(84:be:e3:92:5b:b3)-1-1519325038499
Reply to: null
Feb 22, 2018 7:43:58 PM Bank.ABNAmbro addMessages
INFO: Adding message to List:SSN= 1223 Requested amount= 11€ time= 110
Feb 22, 2018 7:43:58 PM Bank.ABNAmbro addMessages
INFO: New size: 3
If I mock the MessageListener class to just add a String every few seconds the log shows 2 lists that have the same size.
Feb 22, 2018 9:12:16 PM Bank.ABNAmbro addMessages
INFO: Adding message to List:Test 0
Feb 22, 2018 9:12:16 PM Bank.ABNAmbro addMessages
INFO: New sieze: 0
Feb 22, 2018 9:12:16 PM Bank.ABNAmbro addMessages
INFO: Adding message to List:Test 0
Feb 22, 2018 9:12:16 PM Bank.ABNAmbro addMessages
INFO: New sieze: 0
Feb 22, 2018 9:12:17 PM Bank.ABNAmbro addMessages
INFO: Adding message to List:Test 1
Feb 22, 2018 9:12:17 PM Bank.ABNAmbro addMessages
INFO: New sieze: 1
Feb 22, 2018 9:12:17 PM Bank.ABNAmbro addMessages
INFO: Adding message to List:Test 1
Feb 22, 2018 9:12:17 PM Bank.ABNAmbro addMessages
INFO: New sieze: 1
Feb 22, 2018 9:12:18 PM Bank.ABNAmbro addMessages
INFO: Adding message to List:Test 2
Feb 22, 2018 9:12:18 PM Bank.ABNAmbro addMessages
INFO: New sieze: 2
Feb 22, 2018 9:12:18 PM Bank.ABNAmbro addMessages
INFO: Adding message to List:Test 2
Feb 22, 2018 9:12:18 PM Bank.ABNAmbro addMessages
INFO: New sieze: 2
The Controller class:
package Bank;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.stage.Stage;
import javax.jms.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ABNAmbro extends Application implements Bank {
private String tile = "bank";
private List<String> messages = new ArrayList<String>();
private final ObservableList<String> olMessages = FXCollections.observableArrayList(messages);
Logger logger = Logger.getLogger("ABNAmbro");
#FXML
ListView lsRequestView;
#Override
public void start(Stage primaryStage) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("/Bank/Bank.fxml"));
Scene scene = new Scene(root);
primaryStage.setTitle(tile);
primaryStage.setScene(scene);
primaryStage.show();
}
#FXML
public void initialize() {
lsRequestView.setItems(olMessages);
}
public ABNAmbro() throws NamingException {
tile = "ABNAmbro Loan Department.";
String queuename = "ABNBankqueue";
MessageListener messageListener = new BankMessageListener(this);
InitialContext initialContext = new InitialContext();
//JMS 2.0 lookup
ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("java:comp/DefaultJMSConnectionFactory");
//Creating context to reseive messages
JMSContext context = connectionFactory.createContext();
Queue queue = (Queue) initialContext.lookup(queuename);
//create consumer and add a message listener to it so it can get its message async
JMSConsumer consumer = context.createConsumer(queue);
consumer.setMessageListener(messageListener);
}
#FXML
public void SendResponse(ActionEvent event) {
}
public void addMessages(final String messages) {
logger.log(Level.INFO,"Adding message to List:" + messages);
Platform.runLater(new Runnable() {
#Override
public void run() {
//adding message to list
olMessages.add(messages);
}
});
logger.log(Level.INFO, "New sieze: " + olMessages.size());
}
}
MessageListener:
package Bank;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.util.logging.Level;
import java.util.logging.Logger;
public class BankMessageListener implements MessageListener{
private Bank bank;
private Logger logger;
public BankMessageListener(Bank bank){
this.bank = bank;
logger = Logger.getLogger("BankMessageListener");
}
public void onMessage(final Message message) {
try {
logger.log(Level.INFO,"Message received: \n" +
"Text: "+((TextMessage)message).getText()
+ "\nID: " +message.getJMSMessageID()
+ "\nReply to: " +((message.getJMSReplyTo() != null) ? message.getJMSReplyTo().toString() : "null")
);
bank.addMessages(((TextMessage) message).getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}

NumberFormatException getting simplecart items,quantity,price and grandtotal in an array in java servlet

I have implemented simplecart to my project.
On clicking the checkout button it went to PayPal which I didn't wanted it to. So I changed the action URL in simplecart.js file to point to my servlet
action = opts.sandbox ? "cart_checkout" :"cart_checkout",
method = opts.method === "GET" ? "GET" : "POST";
It calls the servlet but I get a NumberFormatException in my servlet
Servlet
package com.kunal.servlet;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CartCheckout
*/
#WebServlet("/CartCheckout")
public class CartCheckout extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public CartCheckout() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String count=request.getParameter("ItemCount");
ArrayList<String> item_detail=new ArrayList<String>();
int cnt=Integer.parseInt(count);
for(int i=1;i<cnt+1;i++)
{
String name=request.getParameter("item_name_");
item_detail.add(name);
String price=request.getParameter("item_price_");
item_detail.add(price);
String qty=request.getParameter("item_quantity_");
item_detail.add(qty);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String count=request.getParameter("ItemCount");
ArrayList<String> item_detail=new ArrayList<String>();
int cnt=Integer.parseInt(count);
for(int i=1;i<cnt+1;i++)
{
String name=request.getParameter("item_name_");
item_detail.add(name);
String price=request.getParameter("item_price_");
item_detail.add(price);
String qty=request.getParameter("item_quantity_");
item_detail.add(qty);
}
}
}
Stacktrace
Sep 01, 2014 1:15:51 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
Sep 01, 2014 1:15:51 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Agro' did not find a matching property.
Sep 01, 2014 1:15:51 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Sep 01, 2014 1:15:51 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Sep 01, 2014 1:15:51 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Sep 01, 2014 1:15:51 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Sep 01, 2014 1:15:51 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 763 ms
Sep 01, 2014 1:15:51 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Sep 01, 2014 1:15:51 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.9
Sep 01, 2014 1:15:52 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Sep 01, 2014 1:15:52 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Sep 01, 2014 1:15:52 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1316 ms
Sep 01, 2014 1:15:59 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Cart_Checkout] in context with path [/Agro] threw exception
java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.parseInt(Integer.java:527)
at com.kunal.servlet.CartCheckout.doPost(CartCheckout.java:53)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
You should capture the request that is being sent to your webservice.
In the error you can see that you get a NumberFormatException: null. This suggests that your count String is null.
String count=request.getParameter("ItemCount");
This can happen when ItemCount is not a parameter of your request.
It would be good practice to test count (= "ItemCount" parameter) for null values in your code, so that you can return a nice looking error to your client.
It is because your count variable is null you can avoid it by
String count=request.getParameter("ItemCount");
if(count.length()>0){
int cnt=Integer.parseInt(count.trim());
// other logic
}
else{
//do nothing
}
The cause of the problem is quite straightforward:
int cnt=Integer.parseInt(count);
this is pointed out clearly from your stack trace:
at com.kunal.servlet.CartCheckout.doPost(CartCheckout.java:53)
A simple solution would be to check the count against null, hence change your doPost (..) implementation into:
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String count=request.getParameter("ItemCount");
ArrayList<String> item_detail=new ArrayList<String>();
int cnt= count == null 0 : Integer.parseInt(count);
for(int i=1;i<cnt+1;i++)
{
String name=request.getParameter("item_name_");
item_detail.add(name);
String price=request.getParameter("item_price_");
item_detail.add(price);
String qty=request.getParameter("item_quantity_");
item_detail.add(qty);
}
}
In order to ensure that you'll not encounter the same issue with empty strings, you can check also for empty strings. If using other libraries is an option I would suggest using StringUtils.isNotBlank(..)
then your parsing line becomes:
int cnt= StringUtils.isNotBlank(count) 0 : Integer.parseInt(count);

HIbernate Annotation Auto Generate table in MySQL

I am new in hibernate and i want to do hibernate annotation and auto generate table in mysql as i submit data.but i have some error like sql grammar.please help me to solve this error.my all code is below..
My Jsp File
<html>
<head>
</head>
<body>
<form action="controller" method="post">
Id : <input type="text" name="id"><br>
First-Name : <input type="text" name="fName"><br>
Last-Name : <input type="text" name="lName"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
This is My Pojo Class
package com.connection;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "csl_emp")
public class Employee {
#Id
private int id;
private String firstName, lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
This is my servler
package com.connection;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class controller
*/
public class controller extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public controller() {
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("in the controller");
String id = request.getParameter("id");
String fname = request.getParameter("fName");
String lname = request.getParameter("lName");
System.out.println(id + fname + lname);
Employee employee = new Employee();
employee.setFirstName(fname);
employee.setLastName(lname);
employee.setId(Integer.parseInt(id));
EmpDao dao = new EmpDao();
dao.addData(employee);
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/success.jsp");
requestDispatcher.forward(request, response);
}
}
This is mY dao class
package com.connection;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
public class EmpDao {
public void addData(Employee employee) {
Session session = new AnnotationConfiguration().configure().buildSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(employee);
transaction.commit();
session.close();
}
}
And This is my Configuration File
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/javadb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">true</property>
<mapping class="com.connection.Employee"/>
</session-factory>
</hibernate-configuration>
And I have getting error like this
Sep 12, 2013 11:49:25 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\java\jdk1.6.0_43\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/java/jdk1.6.0_43/bin/../jre/bin/server;C:/Program Files/java/jdk1.6.0_43/bin/../jre/bin;C:/Program Files/java/jdk1.6.0_43/bin/../jre/lib/amd64;C:\Windows\System32;C:\Program Files\java\jdk1.6.0_43\bin;C:\Program Files\apache-ant-1.8.4\bin;C:\Program Files (x86)\MySQL\MySQL Server 5.0\bin;D:\eclipse;;.
Sep 12, 2013 11:49:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:jspcrud' did not find a matching property.
Sep 12, 2013 11:49:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Hibernate-J2EE-Annotation' did not find a matching property.
Sep 12, 2013 11:49:27 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Sep 12, 2013 11:49:27 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Sep 12, 2013 11:49:27 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2769 ms
Sep 12, 2013 11:49:27 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Sep 12, 2013 11:49:27 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.40
Sep 12, 2013 11:49:28 AM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [203] milliseconds.
Sep 12, 2013 11:49:30 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(E:\projects\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Hibernate-J2EE-Annotation\WEB-INF\lib\servlet-api-2.4.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
Sep 12, 2013 11:49:31 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Sep 12, 2013 11:49:31 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Sep 12, 2013 11:49:31 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3324 ms
in the controller
1chiragsoni
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Sep 12, 2013 11:49:48 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [controller] in context with path [/Hibernate-J2EE-Annotation] threw exception
org.hibernate.exception.SQLGrammarException: could not retrieve snapshot: [com.connection.Employee#1]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.persister.entity.AbstractEntityPersister.getDatabaseSnapshot(AbstractEntityPersister.java:1039)
at org.hibernate.engine.StatefulPersistenceContext.getDatabaseSnapshot(StatefulPersistenceContext.java:232)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:189)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:487)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:84)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:495)
at com.connection.EmpDao.addData(EmpDao.java:12)
at com.connection.controller.doPost(controller.java:52)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:662)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.csl_emp' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2293)
at org.hibernate.persister.entity.AbstractEntityPersister.getDatabaseSnapshot(AbstractEntityPersister.java:1012)
... 28 more
In your configuration file add this property:
<property name="hibernate.hbm2ddl.auto" value="update" />
and also, very useful are these:
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
From Hibernate docs
Change your configuration file property as below
<property name="hibernate.hbm2ddl.auto" value="create"/>
instead of
<property name="hbm2ddl.auto">true</property>

Tomcat class load exception after bytecode injection

I inject a invoke statement(cajolingMe.cajoleMe();) to One of the webgoat's class(HammerHead.class). This method is a static method that called from a jar file which crated by fat-jar. I copy that jar to lib directory of [webgoat][3] web application.
When I decompile injected class there are no problem and syntax is true.
(injected codes bolded)
package org.owasp.webgoat;
**import cajoleMe.cajolingMe;**
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.WelcomeScreen;
import org.owasp.webgoat.lessons.admin.WelcomeAdminScreen;
import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.session.ErrorScreen;
import org.owasp.webgoat.session.LessonTracker;
import org.owasp.webgoat.session.ParameterParser;
import org.owasp.webgoat.session.Screen;
import org.owasp.webgoat.session.UserTracker;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.WebgoatContext;
...
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
Screen screen;
WebSession mySession;
screen = null;
mySession = null;
ServletContext context = getServletContext();
mySession = updateSession(request, response, context);
if(response.isCommitted())
{
try
{
writeScreen(mySession, screen, response);
}
catch(Throwable thr)
{
thr.printStackTrace();
log(request, (new StringBuilder()).append("Could not write error screen: ").append(thr.getMessage()).toString());
}
WebSession.returnConnection(mySession);
return;
}
screen = makeScreen(mySession);
if(response.isCommitted())
{
try
{
writeScreen(mySession, screen, response);
}
catch(Throwable thr)
{
thr.printStackTrace();
log(request, (new StringBuilder()).append("Could not write error screen: ").append(thr.getMessage()).toString());
}
WebSession.returnConnection(mySession);
return;
}
if(screen instanceof AbstractLesson)
{
AbstractLesson lesson = (AbstractLesson)screen;
if("GET".equals(request.getMethod()))
{
String uri = (new StringBuilder()).append(request.getRequestURI()).append("?").append(request.getQueryString()).toString();
if(!uri.endsWith(lesson.getLink()))
screen.getLessonTracker(mySession).incrementNumVisits();
} else
if("POST".equals(request.getMethod()) && mySession.getPreviousScreen() == mySession.getCurrentScreen())
screen.getLessonTracker(mySession).incrementNumVisits();
}
UserTracker userTracker = UserTracker.instance();
userTracker.update(mySession, screen);
log(request, (new StringBuilder()).append(**cajolingMe.cajoleMe(screen.getClass()).getName()).append(" | ")**.append(**cajolingMe.cajoleMe(cajolingMe.cajoleMe(mySession.getParser()))**.toString()).toString());
String userAgent = request.getHeader("user-agent");
String clientBrowser = "Not known!";
if(userAgent != null)
clientBrowser = userAgent;
request.setAttribute("client.browser", clientBrowser);
request.getSession().setAttribute("websession", mySession);
request.getSession().setAttribute("course", mySession.getCourse());
request.getRequestDispatcher(getViewPage(cajolingMe.cajoleMe(mySession))).forward(request, response);
try
{
writeScreen(mySession, screen, response);
}
catch(Throwable thr)
{
thr.printStackTrace();
log(request, (new StringBuilder()).append("Could not write error screen: ").append(thr.getMessage()).toString());
}
WebSession.returnConnection(mySession);
break MISSING_BLOCK_LABEL_631;
Throwable t;
t;
t.printStackTrace();
log((new StringBuilder()).append("ERROR: ").append(t).toString());
screen = new ErrorScreen(mySession, t);
try
{
writeScreen(mySession, screen, response);
}
catch(Throwable thr)
{
thr.printStackTrace();
log(request, (new StringBuilder()).append("Could not write error screen: ").append(thr.getMessage()).toString());
}
WebSession.returnConnection(mySession);
break MISSING_BLOCK_LABEL_631;
Exception exception;
exception;
try
{
writeScreen(mySession, screen, response);
}
catch(Throwable thr)
{
thr.printStackTrace();
log(request, (new StringBuilder()).append("Could not write error screen: ").append(thr.getMessage()).toString());
}
WebSession.returnConnection(mySession);
throw exception;
}
...
}
But When I run tomcat I saw this exception
31, 2013 12:31:59 PM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-127.0.0.1-8080
jan 31, 2013 12:31:59 PM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-127.0.0.1-8443
jan 31, 2013 12:31:59 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 549 ms
jan 31, 2013 12:32:00 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina <br/> jan 31, 2013 12:32:00 PM org.apache.catalina.core.StandardEngine start <br/>INFO: Starting Servlet Engine: Apache Tomcat/5.5.4
jan 31, 2013 12:32:00 PM org.apache.catalina.core.StandardHost start
INFO: XML validation disabled
jan 31, 2013 12:32:00 PM org.apache.catalina.core.ApplicationContext log
INFO: org.apache.webapp.balancer.BalancerFilter: init(): ruleChain: Iorg.apache.webapp.balancer.RuleChain: Corg.apache.w bapp.balancer.rules.URLStringMatchRule: Target string: News / Redirect URL: http://www.cnn.com], Corg.apache.webapp.bal .ncer.rules.RequestParameterRule: Target param name: paramName / Target param paramUalue / Redirect URL: http://www.yahoo.com], Iorg.apache.webapp.balancer.rules.AcceptEverythingRule: Redirect URL: http://jakarta.apache.org]]
**-Marking serv let WebGoat as unavailable Servlet /WebGoat threw load() exception 'avax.servlet.ServletException: Error instantiating servlet class org.owasp.webgoat.HammerHead**
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1020)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:886)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3817)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4079)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:755)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:739)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:886)
at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:849)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:474)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1079)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:310)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1011)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:718)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1003)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:437)
at org.apache.catalina.core.StandardService.start(StandardService.java:450)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:2010)
at org.apache.catalina.startup.Catalina.start(Catalina.java:537)
at sun.reflect.NativeMethodAccessorImpl.invokeO(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 org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:271)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:409)
jan 31, 2013 12:32:01 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-127.0.0.1-8080 <br/> jan 31, 2013 12:32:01 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-127.0.0.1-8443
jan 31, 2013 12:32:01 PM org.apache.jk.common.ChannelSocket init
INFO: JH2: ajp13 listening on /127.0.0.1:8009 <br/> jan 31, 2013 12:32:01 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/11 config=null
jan 31, 2013 12:32:01 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1134 ms
and webgoat site is "HTTP Status 404"
I used [BCEL][5] for injection.
Where is problem?

Categories