Spring REST noHandlerFound - java

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

Related

Why is Retrofit GraphQL query failing with Unexpected character 'M' expected '}'?

I am attempting to execute GraphQL queries agains the SWAPI end point
https://api.graphcms.com/simple/v1/swapi
using Retrofit
My Retrofit API resembles
#Headers("Content-Type: application/json")
#POST("swapi")
Single<Response<String>> query(#Body final String query);
My Retrofit Services
public class StarWarsService extends BaseService implements StarWarsApi {
private static final String BASE_URL = "https://api.graphcms.com/simple/v1/";
private static final StarWarsApi INSTANCE = new StarWarsService();
/**
*
* #return
*/
public static StarWarsApi instance() {
return INSTANCE;
}
private final StarWarsApi service;
/**
*
*/
private StarWarsService() {
final Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(okHttpClient)
.addCallAdapterFactory(Java8CallAdapterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create()).build();
service = retrofit.create(StarWarsApi.class);
}
#Override
public Single<Response<String>> query(String query) {
return service.query(query);
}
}
My main method
private static final String QUERY_STAR_WARS_0001 = "{ \"query\": \"{Starship(name:\"Millennium Falcon\") { name, hyperdriveRating, pilots(orderBy: height_DESC) { name, height, homeworld {name} } }}\" }";
public static void main(String[] args) {
StarWarsService.instance().query(QUERY_STAR_WARS_0001).subscribe();
}
I get the following logs
Sep 19, 2018 3:54:01 PM okhttp3.internal.platform.Platform log
INFO: --> POST https://api.graphcms.com/simple/v1/swapi
Sep 19, 2018 3:54:01 PM okhttp3.internal.platform.Platform log
INFO: Content-Type: application/json
Sep 19, 2018 3:54:01 PM okhttp3.internal.platform.Platform log
INFO: Content-Length: 145
aSep 19, 2018 3:54:01 PM okhttp3.internal.platform.Platform log
INFO:
Sep 19, 2018 3:54:01 PM okhttp3.internal.platform.Platform log
INFO: { "query": "{Starship(name:"Millennium Falcon") { name, hyperdriveRating, pilots(orderBy: height_DESC) { name, height, homeworld {name} } }}" }
Sep 19, 2018 3:54:01 PM okhttp3.internal.platform.Platform log
INFO: --> END POST (145-byte body)
Sep 19, 2018 3:54:02 PM okhttp3.internal.platform.Platform log
INFO: <-- 400 https://api.graphcms.com/simple/v1/swapi (325ms)
Sep 19, 2018 3:54:02 PM okhttp3.internal.platform.Platform log
INFO: content-type: text/plain; charset=UTF-8
Sep 19, 2018 3:54:02 PM okhttp3.internal.platform.Platform log
INFO: content-length: 291
Sep 19, 2018 3:54:02 PM okhttp3.internal.platform.Platform log
INFO: date: Wed, 19 Sep 2018 14:54:39 GMT
Sep 19, 2018 3:54:02 PM okhttp3.internal.platform.Platform log
INFO: server: akka-http/10.0.8
Sep 19, 2018 3:54:02 PM okhttp3.internal.platform.Platform log
INFO: via: 1.1 cd9298825de9a9f64f66b3bc944bdd09.cloudfront.net (CloudFront), 1.1 3965285cac2a9323992ecbe26f94d453.cloudfront.net (CloudFront)
Sep 19, 2018 3:54:02 PM okhttp3.internal.platform.Platform log
INFO: x-cache: Error from cloudfront
Sep 19, 2018 3:54:02 PM okhttp3.internal.platform.Platform log
INFO: x-amz-cf-id: u17uzCW9lF5XI0o4_7hd5OatIqZshrKTlnX0G9iZWHb3CsJ8_Hobww==
Sep 19, 2018 3:54:02 PM okhttp3.internal.platform.Platform log
INFO:
Sep 19, 2018 3:54:02 PM okhttp3.internal.platform.Platform log
INFO: The request content was malformed:
Unexpected character 'M' at input index 28 (line 1, position 29), expected '}':
{ "query": "{Starship(name:"Millennium Falcon") { name, hyperdriveRating, pilots(orderBy: height_DESC) { name, height, homeworld {name} } }}" }
^
Sep 19, 2018 3:54:02 PM okhttp3.internal.platform.Platform log
INFO: <-- END HTTP (291-byte body)
When I can execute the same query with an online GraphQL "browser" OK?
What error have I made in my code/approach?
Whatever code is producing the JSON object is not properly escaping " characters inside the json values.
{ "query": "{Starship(name:"Millennium Falcon") { name, hyperdriveRating, pilots(orderBy: height_DESC) { name, height, homeworld {name} } }}" }
should be
{ "query": "{Starship(name:\"Millennium Falcon\") { name, hyperdriveRating, pilots(orderBy: height_DESC) { name, height, homeworld {name} } }}" }

Batch update returned unexpected row count from update [0]; actual row count: -1; expected: 1

I am new to Hibernate.
I am using NetBeans 7.4 , Hibernate 4.3.6 and Database as Ms Sql Server.
It works fine for fetching data from database but it gives error for Insert , Update , Delete.
My Hibernate Configuration file as :
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://SqlSer:1433;databaseName=HibSample</property>
<property name="hibernate.connection.username">SA</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="Entity/Sample.hbm.xml"/>
</session-factory>
</hibernate-configuration>
my HibernateUtil File is as:
public class NewHibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
My Reverse Engineering File as:
<hibernate-reverse-engineering>
<schema-selection match-catalog="HibSample" match-schema="dbo"/>
<table-filter match-name="Sample"/>
</hibernate-reverse-engineering>
My Pojo and Mapping Files are :
public class Sample implements java.io.Serializable {
private int id;
private String fullName;
private String address;
public Sample() {
}
public Sample(int id, String fullName) {
this.id = id;
this.fullName = fullName;
}
public Sample(int id, String fullName, String address) {
this.id = id;
this.fullName = fullName;
this.address = address;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getFullName() {
return this.fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
}
and
<hibernate-mapping>
<class name="Entity.Sample" table="Sample" schema="dbo" catalog="HibSample">
<id name="id" type="int">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="fullName" type="string">
<column name="FullName" length="50" not-null="true" />
</property>
<property name="address" type="string">
<column name="Address" length="50" />
</property>
</class>
</hibernate-mapping>
Main File is :
public class Main
{
public Main(){};
public static void main(String args[])
{
Session session = NewHibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Sample s = new Sample();
s.setId(3);
s.setFullName("Demo");
s.setAddress("Demo");
Sample s1 = (Sample)session.load(Sample.class, 2);
System.out.println("ID :"+s1.getId());
System.out.println("Full Name : "+s1.getFullName());
System.out.println("Address : "+s1.getAddress());
session.save(s);
if(!tx.wasCommitted())
{
tx.commit();
}
}catch(Exception ex)
{
if(tx != null)
{
tx.rollback();
ex.printStackTrace();
}
}finally{
session.close();
}
System.exit(0);
}
}
Table Data are as follow :
ID Full Name Address
1 XYZ India
2 ABC India
Error IS :
Dec 17, 2014 4:42:42 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Dec 17, 2014 4:42:42 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.6.Final}
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Dec 17, 2014 4:42:42 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: Entity/Demo.hbm.xml
Dec 17, 2014 4:42:42 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: Entity/Sample.hbm.xml
Dec 17, 2014 4:42:42 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Dec 17, 2014 4:42:42 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Dec 17, 2014 4:42:42 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Dec 17, 2014 4:42:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] at URL [jdbc:sqlserver://150.10.10.233;databaseName=HibSample]
Dec 17, 2014 4:42:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=SA, password=****}
Dec 17, 2014 4:42:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Dec 17, 2014 4:42:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Dec 17, 2014 4:42:43 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.SQLServerDialect
Dec 17, 2014 4:42:43 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Dec 17, 2014 4:42:43 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Result
ID :2
Full Name : ABC
Address : India
Hibernate: insert into HibSample.dbo.Sample (FullName, Address, ID) values (?, ?, ?)
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: -1; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:81)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:73)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:63)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3124)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3581)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:104)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at UI.Main.main(Main.java:45)
Dec 17, 2014 4:42:43 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
BUILD SUCCESSFUL (total time: 1 second)
I have search all possibilities but can't find the solution.

Java EE CDI interceptor not working inside JAX-RS resource class

I wanted to use a profiling interceptor inside a jax-rs resource class. The interceptor works otherwise, but it causes problems inside a jax-rs resource class. I have put the demo code on github.
Here is a description of the problem.
First, here is a list of the main code.
Profiled
#InterceptorBinding
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.METHOD, ElementType.TYPE})
public #interface Profiled {
}
Profiler
#Interceptor
#Profiled
public class Profiler {
#Inject
Logger logger;
#AroundInvoke
private Object profile( InvocationContext context ) throws Exception {
long startTime = System.currentTimeMillis();
try {
return context.proceed();
} finally {
long time = System.currentTimeMillis() - startTime;
logger.info( context.getMethod() + " took " + time + " milliseconds" );
}
}
}
UtilsProducer
public class UtilsProducer {
#Produces
private Logger createLogger( InjectionPoint point ) {
return Logger.getLogger( point.getMember().getDeclaringClass().getName() );
}
#Produces
private Client createClient() {
return ClientBuilder.newClient();
}
}
Foobar
public class Foobar {
public static final int SLEEP_TIME = 1000; // in milliseconds
#Inject
Logger logger;
public String hello() {
return "hello";
}
#Profiled
public long profiledCall() throws Exception {
long startTime = System.currentTimeMillis();
Thread.sleep( SLEEP_TIME );
return System.currentTimeMillis() - startTime;
}
}
RestFoobar
#Path("/")
public class RestFoobar {
public static final int SLEEP_TIME = 1000;
#Inject
private Logger logger;
#Inject
private Foobar foobar;
#Context
private UriInfo context;
#Path("hello")
#GET
public String hello() {
logger.info("Request from " + context.getRequestUri() );
return "hello";
}
#Path("profile")
#GET
#Profiled
public long profile() throws Exception {
logger.info("Request from " + context.getRequestUri() );
long startTime = System.currentTimeMillis();
Thread.sleep( SLEEP_TIME );
return System.currentTimeMillis() - startTime ;
}
}
FoobarTest
public class FoobarTest extends ArquillianWarBase {
#Inject
Foobar foobar;
#Test
public void shouldGetHello() {
assertEquals( "hello", foobar.hello() );
}
#Test
public void shouldHaveSlept() throws Exception {
assertTrue( foobar.profiledCall() >= Foobar.SLEEP_TIME );
}
}
RestFoobarTest
public class RestFoobarTest extends ArquillianWarBase {
#Inject
Client client;
static final String BASE_URL = "http://localhost:1119/demo/";
#Test
public void getHello() {
String url = BASE_URL + "hello";
Response response = client.target( url ).request(MediaType.TEXT_PLAIN_TYPE ).get();
String text = response.readEntity( String.class );
assertEquals( "hello", text );
}
#Test
public void getProfile() {
String url = BASE_URL + "profile";
Response response = client.target( url ).request(MediaType.TEXT_PLAIN_TYPE ).get();
long time = response.readEntity( Long.class );
assertTrue( time >= RestFoobar.SLEEP_TIME );
}
}
I use gradle wrapper to build the code. When I run ./gradlew test, which runs both FoobarTest and RestFoobarTest, I got this output:
demo.FoobarTest STANDARD_OUT
Found populator: org.glassfish.kernel.embedded.EmbeddedDomainXml
demo.FoobarTest STANDARD_ERROR
Apr 17, 2014 5:54:44 PM org.glassfish.security.services.impl.authorization.AuthorizationServiceImpl initialize
INFO: Authorization Service has successfully initialized.
Apr 17, 2014 5:54:44 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 5.0.0.Final
Apr 17, 2014 5:54:45 PM com.sun.enterprise.v3.services.impl.GrizzlyProxy start
INFO: Grizzly Framework 2.3.1 started in: 13ms - bound to [/0.0.0.0:1,119]
Apr 17, 2014 5:54:45 PM com.sun.enterprise.v3.services.impl.GrizzlyService createNetworkProxy
INFO: Network listener https-listener on port 0 disabled per domain.xml
Apr 17, 2014 5:54:45 PM com.sun.enterprise.v3.admin.adapter.AdminEndpointDecider setGuiContextRoot
INFO: Admin Console Adapter: context root: /admin
Apr 17, 2014 5:54:45 PM com.sun.enterprise.v3.admin.adapter.AdminEndpointDecider setGuiContextRoot
INFO: Admin Console Adapter: context root: /admin
Apr 17, 2014 5:54:45 PM com.sun.enterprise.v3.admin.adapter.AdminEndpointDecider setGuiContextRoot
INFO: Admin Console Adapter: context root: /admin
Apr 17, 2014 5:54:45 PM com.sun.enterprise.v3.server.AppServerStartup postStartupJob
INFO: Undefined Product Name - define product and version info in config/branding 0.0.0 (0) startup time : Embedded (885ms), startup services(662ms), total(1,547ms)
Apr 17, 2014 5:54:45 PM org.glassfish.jersey.server.ApplicationHandler initialize
INFO: Initiating Jersey application, version Jersey: 2.0 2013-05-03 14:50:15...
Apr 17, 2014 5:54:45 PM org.glassfish.admin.mbeanserver.JMXStartupService$JMXConnectorsStarterThread run
INFO: JMXStartupService has disabled JMXConnector system
Apr 17, 2014 5:54:45 PM com.sun.enterprise.connectors.jms.util.JmsRaUtil getInstalledMqVersion
WARNING: RAR7000 : Check for a new version of MQ installation failed : /var/folders/cj/b2rlrrg56ts96zdyc69l59fh002jb1/T/gfembed906146914977552454tmp/lib/install/applications/jmsra/../imqjmsra.rar (No such file or directory):/var/folders/cj/b2rlrrg56ts96zdyc69l59fh002jb1/T/gfembed906146914977552454tmp/lib/install/applications/jmsra/imqjmsra.rar
demo.FoobarTest STANDARD_OUT
demo.war:
/WEB-INF/
/WEB-INF/beans.xml
/WEB-INF/glassfish-web.xml
/WEB-INF/web.xml
/WEB-INF/classes/
/WEB-INF/classes/demo/
/WEB-INF/classes/demo/UtilsProducer.class
/WEB-INF/classes/demo/RestFoobar.class
/WEB-INF/classes/demo/Profiled.class
/WEB-INF/classes/demo/Profiler.class
/WEB-INF/classes/demo/Foobar.class
demo.FoobarTest STANDARD_ERROR
Apr 17, 2014 5:54:46 PM com.sun.enterprise.security.SecurityLifecycle <init>
INFO: security.secmgroff
Apr 17, 2014 5:54:46 PM com.sun.enterprise.security.SecurityLifecycle onInitialization
INFO: sec.service.startup.enter
Apr 17, 2014 5:54:46 PM com.sun.enterprise.security.PolicyLoader loadPolicy
INFO: policy.loading
Apr 17, 2014 5:54:46 PM com.sun.enterprise.security.auth.realm.Realm doInstantiate
INFO: realm.loaded.successfully
Apr 17, 2014 5:54:46 PM com.sun.enterprise.security.auth.realm.Realm doInstantiate
INFO: realm.loaded.successfully
Apr 17, 2014 5:54:46 PM com.sun.enterprise.security.auth.realm.Realm doInstantiate
INFO: realm.loaded.successfully
Apr 17, 2014 5:54:46 PM com.sun.enterprise.security.SecurityLifecycle onInitialization
INFO: sec.service.startup.exit
Apr 17, 2014 5:54:46 PM com.sun.enterprise.web.WebContainer createHttpListener
INFO: Created HTTP listener http-listener on host/port 0.0.0.0:1119
Apr 17, 2014 5:54:46 PM com.sun.enterprise.web.VirtualServer addProbes
SEVERE: Error adding HttpProbes. NetworkListener https-listeners GrizzlyProxy is NULL
Apr 17, 2014 5:54:46 PM com.sun.enterprise.web.WebContainer createHosts
INFO: Created virtual server server
Apr 17, 2014 5:54:47 PM org.apache.catalina.realm.JAASRealm setContainer
INFO: Setting JAAS app name glassfish-web
Apr 17, 2014 5:54:47 PM com.sun.enterprise.web.WebContainer loadSystemDefaultWebModules
INFO: Virtual server server loaded default web module
Apr 17, 2014 5:54:47 PM org.jboss.weld.bootstrap.WeldBootstrap <clinit>
INFO: WELD-000900 SNAPSHOT
Apr 17, 2014 5:54:48 PM org.glassfish.jersey.servlet.init.JerseyServletContainerInitializer addServletWithDefaultConfiguration
INFO: Registering the Jersey servlet application, named javax.ws.rs.core.Application, with the following root resource and provider classes: [class demo.RestFoobar]
Apr 17, 2014 5:54:48 PM org.glassfish.jersey.server.ApplicationHandler initialize
INFO: Initiating Jersey application, version Jersey: 2.0 2013-05-03 14:50:15...
Apr 17, 2014 5:54:48 PM com.sun.enterprise.web.WebApplication start
INFO: Loading application [demo] at [/demo]
Apr 17, 2014 5:54:48 PM org.glassfish.deployment.admin.DeployCommand execute
INFO: demo was successfully deployed in 2,328 milliseconds.
demo.FoobarTest > shouldGetHello PASSED
demo.FoobarTest > shouldHaveSlept STANDARD_ERROR
Apr 17, 2014 5:54:49 PM demo.Profiler profile
INFO: public long demo.Foobar.profiledCall() throws java.lang.Exception took 1000 milliseconds
demo.FoobarTest > shouldHaveSlept PASSED
demo.FoobarTest STANDARD_OUT
PlainTextActionReporterSUCCESSNo monitoring data to report.
demo.RestFoobarTest STANDARD_ERROR
Apr 17, 2014 5:54:50 PM org.glassfish.jersey.servlet.init.JerseyServletContainerInitializer addServletWithDefaultConfiguration
INFO: Registering the Jersey servlet application, named javax.ws.rs.core.Application, with the following root resource and provider classes: [class demo.RestFoobar]
Apr 17, 2014 5:54:50 PM org.glassfish.jersey.server.ApplicationHandler initialize
INFO: Initiating Jersey application, version Jersey: 2.0 2013-05-03 14:50:15...
Apr 17, 2014 5:54:50 PM com.sun.enterprise.web.WebApplication start
INFO: Loading application [demo] at [/demo]
Apr 17, 2014 5:54:50 PM org.glassfish.deployment.admin.DeployCommand execute
INFO: demo was successfully deployed in 666 milliseconds.
demo.RestFoobarTest > getProfile STANDARD_ERROR
Apr 17, 2014 5:54:51 PM org.apache.catalina.core.StandardWrapperValve log
WARNING: StandardWrapperValve[javax.ws.rs.core.Application]: Servlet.service() for servlet javax.ws.rs.core.Application threw exception
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=Logger,parent=RestFoobar,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,998142827)
at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)
at org.jvnet.hk2.internal.Utilities.justInject(Utilities.java:771)
at org.jvnet.hk2.internal.ServiceLocatorImpl.inject(ServiceLocatorImpl.java:790)
at org.glassfish.jersey.gf.cdi.CdiComponentProvider$1.inject(CdiComponentProvider.java:316)
at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:158)
at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:69)
at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:716)
at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:738)
at org.glassfish.jersey.gf.cdi.CdiComponentProvider$CdiFactory$1.getInstance(CdiComponentProvider.java:174)
at org.glassfish.jersey.gf.cdi.CdiComponentProvider$CdiFactory.provide(CdiComponentProvider.java:143)
at org.jvnet.hk2.internal.FactoryCreator.create(FactoryCreator.java:96)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:448)
at org.jvnet.hk2.internal.PerLookupContext.findOrCreate(PerLookupContext.java:69)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2204)
at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:579)
at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:566)
at org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:172)
at org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:185)
at org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:105)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:118)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:102)
at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:62)
at org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:215)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:198)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:946)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:323)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:745)
demo.RestFoobarTest > getProfile FAILED
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException at RestFoobarTest.java:32
demo.RestFoobarTest > getHello STANDARD_ERROR
Apr 17, 2014 5:54:51 PM org.apache.catalina.core.StandardWrapperValve log
WARNING: StandardWrapperValve[javax.ws.rs.core.Application]: Servlet.service() for servlet javax.ws.rs.core.Application threw exception
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=Logger,parent=RestFoobar,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,436148362)
at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)
at org.jvnet.hk2.internal.Utilities.justInject(Utilities.java:771)
at org.jvnet.hk2.internal.ServiceLocatorImpl.inject(ServiceLocatorImpl.java:790)
at org.glassfish.jersey.gf.cdi.CdiComponentProvider$1.inject(CdiComponentProvider.java:316)
at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:158)
at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:69)
at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:716)
at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:738)
at org.glassfish.jersey.gf.cdi.CdiComponentProvider$CdiFactory$1.getInstance(CdiComponentProvider.java:174)
at org.glassfish.jersey.gf.cdi.CdiComponentProvider$CdiFactory.provide(CdiComponentProvider.java:143)
at org.jvnet.hk2.internal.FactoryCreator.create(FactoryCreator.java:96)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:448)
at org.jvnet.hk2.internal.PerLookupContext.findOrCreate(PerLookupContext.java:69)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2204)
at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:579)
at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:566)
at org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:172)
at org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:185)
at org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:105)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:118)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:102)
at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:62)
at org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:215)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:198)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:946)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:323)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:745)
demo.RestFoobarTest > getHello FAILED
org.junit.ComparisonFailure at RestFoobarTest.java:25
demo.RestFoobarTest STANDARD_OUT
PlainTextActionReporterSUCCESSNo monitoring data to report.
4 tests completed, 2 failed
As shown above, the #Profiled annotation works in Foobar, but causes problems in RestFoobar. If remove the #Profiled above RestFoobar.profile(), the test will pass, except there is no longer the profiling output.
BTW, I use Arquillian and embedded Glassfish to run the tests. Here is a full list of the dependencies:
dependencies {
providedCompile 'javax:javaee-api:7.0'
testCompile 'junit:junit:4.11'
testCompile 'org.jboss.arquillian:arquillian-bom:1.1.4.Final'
testCompile 'org.jboss.arquillian.junit:arquillian-junit-container:1.1.4.Final'
testRuntime 'org.glassfish.main.extras:glassfish-embedded-all:4.0'
testRuntime 'org.jboss.arquillian.container:arquillian-glassfish-embedded-3.1:1.0.0.CR4'
}
The Arquillian war wrapper is as follows
ArquillianWarBase
public abstract class ArquillianWarBase {
private static WebArchive war;
#Deployment
public static WebArchive createDeployment() {
if( war == null ) {
war = ShrinkWrap.create( WebArchive.class, "demo.war" )
.addPackages( true, Filters.exclude( ".*Test.*" ),
"demo" )
.addAsWebInfResource( "beans-test.xml", "beans.xml" )
.addAsWebInfResource( "glassfish-web-test.xml", "glassfish-web.xml" )
.addAsWebInfResource( "web-test.xml", "web.xml" );
System.out.println( war.toString( true ) );
}
return war;
}
}
So, it looks like the interceptor annotation #Profiled doesn't work inside a jax-rs resource class (i.e., RestFoobar). But why? Is there a simple way to make it work?
Thank you very much.
So, it looks like the interceptor annotation #Profiled doesn't work
inside a jax-rs resource class (i.e., RestFoobar). But why?
Because your class (i.e RestFooBar) is not a CDI-managed-bean. Interceptors only work with this sort of beans.
Is there a simple way to make it work?
Yes, annotate your class (i.e RestFooBar) with #Stateless from the javax.ejb package, this will also give you the opportunity to inject other services with #EJB.
There are some other options:
Separate your service and REST classes in such a way that only the service classes need to be intercepted.
There seems to be a module named jersey-gf-cdi which implemtens a bridge between Glassfish CDI and Jersey, but I didn't get that to work and I'm not sure if this is a solution for the problem.
See also:
CDI interceptor injected into a jersey RS service(resource) not working?
Package org.glassfish.jersey.gf.cdi.spi
Package org.glassfish.jersey.gf.cdi.hk2ban

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?

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

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;
}
}

Categories