JUnit Mockito SpringMVC 404 - java

while testing spring mvc controller with JUnit and Mockito
got this line
WARNING: No mapping found for HTTP request with URI [application] in DispatcherServlet with name ''
Does that mean that DispatcherServlet was not loaded? How to configure it properly? Thanks
test trace
Jan 09, 2017 10:03:12 PM org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping register
INFO: Mapped "{[/application],methods=[GET]}" onto public java.lang.String com.resman.web.controller.ApplicationController.index(org.springframework.ui.Model,com.resman.service.user.DBAuthenticationService$CustomUser)
Jan 09, 2017 10:03:12 PM org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping register
INFO: Mapped "{[/application/remove-app/{id}],methods=[GET]}" onto public java.lang.String com.resman.web.controller.ApplicationController.remove(java.lang.Long,com.resman.service.user.DBAuthenticationService$CustomUser)
Jan 09, 2017 10:03:12 PM org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping register
INFO: Mapped "{[/application/profile-app/{id}],methods=[GET]}" onto public java.lang.String com.resman.web.controller.ApplicationController.findProfile(org.springframework.ui.Model,java.lang.Long,com.resman.service.user.DBAuthenticationService$CustomUser)
Jan 09, 2017 10:03:12 PM org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping register
INFO: Mapped "{[/application/create-app-form],methods=[GET]}" onto public java.lang.String com.resman.web.controller.ApplicationController.createApplicationForm(org.springframework.ui.Model)
Jan 09, 2017 10:03:12 PM org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping register
INFO: Mapped "{[/application/create-app],methods=[POST]}" onto public java.lang.String com.resman.web.controller.ApplicationController.createApplication(org.springframework.ui.Model,java.util.Date,java.util.Date,java.lang.Long,java.lang.String,com.resman.service.user.DBAuthenticationService$CustomUser) throws java.text.ParseException
Jan 09, 2017 10:03:12 PM org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping register
INFO: Mapped "{[/application/edit-app],methods=[POST]}" onto public java.lang.String com.resman.web.controller.ApplicationController.editApplication(org.springframework.ui.Model,java.lang.Long,int,java.util.Date,java.lang.String,java.lang.Long,com.resman.service.user.DBAuthenticationService$CustomUser)
Jan 09, 2017 10:03:12 PM org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping register
INFO: Mapped "{[/application/all-apps],methods=[GET]}" onto public java.lang.String com.resman.web.controller.ApplicationController.findAll(org.springframework.ui.Model,com.resman.service.user.DBAuthenticationService$CustomUser)
Jan 09, 2017 10:03:12 PM org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping register
INFO: Mapped "{[/application/find-for-approver],methods=[GET]}" onto public java.lang.String com.resman.web.controller.ApplicationController.findForApprover(org.springframework.ui.Model)
Jan 09, 2017 10:03:12 PM org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping register
INFO: Mapped "{[/application/find-for-admin],methods=[GET]}" onto public java.lang.String com.resman.web.controller.ApplicationController.findForAdmin(org.springframework.ui.Model)
Jan 09, 2017 10:03:12 PM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext#34e9fd99
Jan 09, 2017 10:03:12 PM org.springframework.mock.web.MockServletContext log
INFO: Initializing Spring FrameworkServlet ''
Jan 09, 2017 10:03:12 PM org.springframework.test.web.servlet.TestDispatcherServlet initServletBean
INFO: FrameworkServlet '': initialization started
Jan 09, 2017 10:03:12 PM org.springframework.test.web.servlet.TestDispatcherServlet initServletBean
INFO: FrameworkServlet '': initialization completed in 2 ms
Jan 09, 2017 10:03:13 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [application] in DispatcherServlet with name ''
java.lang.AssertionError: Status
Expected :200
Actual :404
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:653)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:152)
at com.resman.web.controller.ApplicationControllerTest.indexText(ApplicationControllerTest.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Process finished with exit code 255
class itself
#Controller
public class ApplicationController {
private static final Logger LOGGER =
LogManager.getLogger(ApplicationController.class);
#Autowired
private ApplicationDAO applicationDAO;
#Autowired
private UserDao userDAO;
#Autowired
private ResourceDao resourceDao;
#Autowired
private ResourceTypeService resourceTypeService;
#Autowired
private ApplicationValidator applicationValidator;
#RequestMapping(value = "application", method = RequestMethod.GET)
public String index(Model model, #AuthenticationPrincipal DBAuthenticationService.CustomUser currentUser) {
LOGGER.debug("application index page");
model.addAttribute("userRole", currentUser.getUserRole());
return "application/index";
}
test class
#RunWith(MockitoJUnitRunner.class)
#ContextConfiguration(classes = AppConfig.class)
#WebAppConfiguration
public class ApplicationControllerTest {
#Mock
private ApplicationDAO applicationDAO;
#Mock
private UserDao userDAO;
#Mock
private ResourceDao resourceDao;
#Mock
private ResourceTypeService resourceTypeService;
#Mock
private ApplicationValidator applicationValidator;
#InjectMocks
private ApplicationController controller;
private MockMvc mockMvc;
#Before
public void setUp(){
this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
#Test
public void indexText() throws Exception {
mockMvc.perform(get("application")).andExpect(status().isOk());
}
}
configuration class
#Configuration
#EnableWebMvc
#ComponentScan("com.resman.*")
#Import({ SecurityConfig.class })
#EnableTransactionManagement
public class AppConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/view/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dataSource.setUrl("jdbc:oracle:thin:#//localhost:1521/XE");
dataSource.setUsername("project");
dataSource.setPassword("projectsql");
return dataSource;
}
#Bean
public DataSourceTransactionManager dataSourceTransactionsManager() {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource());
return dataSourceTransactionManager;
}
web.xml
<web-app id="resourceManager" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
</web-app>

probably you may need
default-servlet-handler
in your AppConfig,
eg:
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}

the problem was in the line
mockMvc.perform(get("application")).andExpect(status().isOk());
"application" should be changed to "/application" and everything will work

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

How to configure Spring Mvc Configuration Error

I´m updating my project from spring 2.5 to 5 with MVC configuration
I try to make java based config with some problems this is my code:
Web.xml
<web-app
xmlns:javaee="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Publisher Portal</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
com.netsol.publisher.config.AppConfig
</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>1000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>publisher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.netsol.publisher.config.SpringWebMvcConfig</param-value>
</init-param>
<description>Spring MVC Dispatcher Servlet</description>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>publisher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
my AppConfig.java
#Configuration
#ComponentScan(excludeFilters=#Filter(org.springframework.stereotype.Controller.class)})
public class AppConfig {
private static final Logger LOG = LoggerFactory.getLogger(AppConfig.class);
#Autowired
private Environment env;
}
And my SpringWebMvcConfig.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "com.netsol.publisher.controller" })
public class SpringWebMvcConfig implements WebMvcConfigurer {
private static final int CACHE_PERIOD = 31556926; // one year
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/jsp/", ".jsp");
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
//this will map uri to jsp view directly without a controller
registry.addViewController("/hi").setViewName("hello");
registry.addViewController("/").setViewName("home.do");
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
// Serving static files using the Servlet container's default Servlet.
configurer.enable();
}
#Override
public void addFormatters(FormatterRegistry formatterRegistry) {
// add your custom formatters
}
#Bean
PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setLocation(new ClassPathResource("publisher-portal.properties"));
ppc.setIgnoreUnresolvablePlaceholders(true);
return ppc;
}
#Bean
public SimpleUrlHandlerMapping simpleUrlHandlerMapping () {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(Integer.MAX_VALUE - 2);
Properties urlProperties = new Properties();
urlProperties.put("/home", "LoginController");
mapping.setMappings(urlProperties);
return mapping;
}
}
My controllers:
#Controller
#RequestMapping(value = "/home")
public class LoginController extends BaseController {
static final String sccsId = "%TC-INFO%";
#Autowired
private PublisherFacade publisherFacade;
private static Log log = LogFactory.getLog(LoginController.class);
#RequestMapping(value = "/index.do", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView showLoginPage(HttpServletRequest request, HttpServletResponse response)
throws Exception {
return getLoginView(request, Constants.USER_LOGIN_PAGE);
}
The problem is that
INFO: Initializing Spring FrameworkServlet 'publisher'
- FrameworkServlet 'publisher': initialization started
- Refreshing WebApplicationContext for namespace 'publisher-servlet': startup date [Wed Sep 19 16:12:08 ART 2018]; parent: Root WebApplicationContext
- No annotated classes found for specified class/package [com.netsol.publisher.config.SpringWebMvcConfig]
- JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
- Looking for #ControllerAdvice: WebApplicationContext for namespace 'publisher-servlet': startup date [Wed Sep 19 16:12:08 ART 2018]; parent: Root WebApplicationContext
- FrameworkServlet 'publisher': initialization completed in 1146 ms
sep 19, 2018 4:12:10 PM org.apache.catalina.core.ApplicationContext log
INFO: Marking servlet [PendingOrderCheckerServlet] as unavailable
sep 19, 2018 4:12:10 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [PendingOrderCheckerServlet] in web application [/publisher-portal] threw load() exception
java.lang.ClassNotFoundException: com.netsol.publisher.batch.PendingOrderCheckerServlet
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1309)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1137)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:546)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:527)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:150)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1044)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:983)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4978)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5290)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1420)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1410)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
sep 19, 2018 4:12:10 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
sep 19, 2018 4:12:10 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
sep 19, 2018 4:12:10 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 31382 ms
- No mapping found for HTTP request with URI [/publisher-portal/home/index.do] in DispatcherServlet with name 'publisher'
- No mapping found for HTTP request with URI [/publisher-portal/home/index.do] in DispatcherServlet with name 'publisher'
I want to know if my configuration its ok and why I cannot found the mappings of my controllers

Spring Hello Dependency Injection #Autowired throws NullPointerException

Project Structure:
TestController.java:
package com.mypack;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
/**
* Servlet implementation class Test
*/
#WebServlet("/test")
#Controller
public class TestController extends HttpServlet {
private static final long serialVersionUID = 1L;
#Autowired
private TestManager testManager;
public TestManager getTestManager() {
return testManager;
}
public void setTestManager(TestManager testManager) {
this.testManager = testManager;
}
public TestController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
String name=testManager.getName();
PrintWriter pw=response.getWriter();
pw.write(name);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
TestManager.java:
package com.mypack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Service;
#Service("testManager")
public class TestManager {
#Autowired
private TestDao testDao;
public String getName(){
return testDao.getName();
}
public TestDao getTestDao() {
return testDao;
}
public void setTestDao(TestDao testDao) {
this.testDao = testDao;
}
}
TestDao.java:
package com.mypack;
import org.springframework.stereotype.Repository;
#Repository("testDao")
public class TestDao {
public String getName(){
return "Randhir";
}
}
spring.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- Enable Spring Application Context -->
<context:spring-configured />
<!-- Scan class file in class path for annotated component -> #Component, #Repository, #Service, and #Controller -->
<context:component-scan base-package="com.mypack" />
</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>SpringIOCWeb</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring.xml
</param-value>
</context-param>
</web-app>
Server Console:
INFO: 1 Spring WebApplicationInitializers detected on classpath
Jan 21, 2017 7:50:39 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Jan 21, 2017 7:50:39 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Jan 21, 2017 7:50:39 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Sat Jan 21 19:50:39 IST 2017]; root of context hierarchy
Jan 21, 2017 7:50:39 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/spring.xml]
Jan 21, 2017 7:50:40 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 731 ms
Jan 21, 2017 7:50:40 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8090"]
Jan 21, 2017 7:50:40 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Jan 21, 2017 7:50:40 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 2836 ms
Jan 21, 2017 7:50:45 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.mypack.TestController] in context with path [] threw exception
java.lang.NullPointerException
at com.mypack.TestController.doGet(TestController.java:43)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
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:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
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:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
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:724)
IOC Container will instantiate the bean and assign the object reference using setter method. Is my concept is right ?
But here #Autowired doesn't assign the object reference. Till I have used using main method with ApplicationContext and getBean to learn Spring.
But how the bean configuration works with servlet?
Your testManager is null.
You are mixing Servlet and Spring controllers.
You should use Spring dispatcher servlet :
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/spring/*</url-pattern>
</servlet-mapping>
The DispatcherServlet is one unique servlet, like a front controller (in a MVC2 pattern), that dispatches the request to Spring controllers (a spring component).
Then in your controller TestController, remove the inheritance of HttpServlet and override methods (doGet, doPost..), and use #RequestMapping.
In that way you will use the dependency injection of Spring framework.
#Controller
#RequestMapping("/test")
public class TestController {
#Autowired
private TestManager testManager;
#RequestMapping
#ResponseBody
public String handleRequest(final HttpServletRequest request, final HttpServletResponse response) {
String name=testManager.getName();
return name;
}
}
Since you are using servlet and not controller you could autowire it with the code
#WebServlet("/test")
public class TestController extends HttpServlet {
private static final long serialVersionUID = 1L;
private AutowireCapableBeanFactory ctx;
#Autowired
private TestManager testManager;
#Override
public void init() throws ServletException {
super.init();
WebApplicationContext context = WebApplicationContextUtils
.getWebApplicationContext(getServletContext());
ctx = context.getAutowireCapableBeanFactory();
ctx.autowireBean(this);
}
...
}
You already have integrated Spring using its own context listener
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

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

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>

Categories