How to configure Spring Mvc Configuration Error - java

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

Related

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>

JUnit Mockito SpringMVC 404

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

Stop deployment when Exception occurs in ServletContextListener

I have following web.xml configuration where exception is thrown at com.mkyong.context.ContextSecond in contextInitialized() method. In that case deployment does not stop and app.war keep servicing. How I can stop deployment when exception occurs?
Using weblogic 12c
Archetype Created Web Application
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>com.mkyong.context.ContextFirst</listener-class>
</listener>
<listener>
<listener-class>com.mkyong.context.ContextSecond</listener-class>
</listener>
ContextFirst .java
package com.mkyong.context;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ContextFirst implements ServletContextListener {
#Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("ContextFirst:contextDestroyed");
}
#Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("ContextFirst:contextInitialized");
}
}
ContextSecond .java
package com.mkyong.context;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ContextSecond implements ServletContextListener {
#Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("ContextSecond:contextDestroyed");
}
#Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("ContextSecond:contextInitialized");
throw new RuntimeException();
}
}
Log:
<Nov 19, 2014 1:52:36 PM EET> <Warning> <Deployer> <BEA-149124> <Failures were detected while initiating remove task for application "webservices". Error is: "[Deployer:149001]No a
pplication named "webservices" exists for operation "undeploy".">
ContextFirst:contextInitialized
ContextSecond:contextInitialized
<Nov 19, 2014 1:53:05 PM EET> <Warning> <HTTP> <BEA-101162> <User defined listener com.mkyong.context.ContextSecond failed: java.lang.RuntimeException.
java.lang.RuntimeException
at com.mkyong.context.ContextSecond.contextInitialized(ContextSecond.java:18)
at weblogic.servlet.internal.EventsManager$FireContextListenerAction.run(EventsManager.java:678)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)

RESTEasy - javax.ws.rs.NotFoundException: Could not find resource for full path

I've tried to implement a REST service with RESTEasy in a GWT project, but when I get into the respective URI the application returns:
Grave: failed to execute
javax.ws.rs.NotFoundException: Could not find resource for full path: http://127.0.0.1:8888/api/matches
at org.jboss.resteasy.core.registry.ClassNode.match(ClassNode.java:73)
at org.jboss.resteasy.core.registry.RootClassNode.match(RootClassNode.java:48)
at org.jboss.resteasy.core.ResourceMethodRegistry.getResourceInvoker(ResourceMethodRegistry.java:444)
at org.jboss.resteasy.core.SynchronousDispatcher.getInvoker(SynchronousDispatcher.java:234)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:171)
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:220)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
My web.xml is:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- All REST resources will be prefixed by /api -->
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/api</param-value>
</context-param>
<!-- Servlets -->
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>eii.api.MatchApplication</param-value>
</init-param>
</servlet>
<!-- Servlet mappings -->
<!-- All calls to /api/xxx will be sent to the reasy servlet -->
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
</web-app>
The implementation of Application:
public class MatchApplication extends Application {
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> classes = new HashSet<Class<?>>();
public MatchApplication() {
singletons.add(new MatchServiceImpl());
}
#Override
public Set<Class<?>> getClasses() {
return classes;
}
#Override
public Set<Object> getSingletons() {
return singletons;
}
}
And here's the class that provide the REST service:
/* Imports */
...
#Path("/matches")
public class MatchResource {
private static MatchResource _instance = null;
private MatchRepository repository;
public MatchResource() {
repository = new MapMatchRepository();
}
public static MatchResource getInstance() {
if (_instance == null)
_instance = new MatchResource();
return _instance;
}
#GET
#Path("/{id}")
#Produces("application/json")
public Match getMatch(#PathParam("id") int id) {
return repository.getMatch(id);
}
#GET
#Produces("application/json")
public Matches getMatchesCurrentRound() {
return repository.getMatchesCurrentRound();
}
...
}
What I want is to return a JSON file when getting into, for example: http://127.0.0.1:8888/api/matches
Does anyone know what I'm doing wrong?
Edit:
If I access to http://127.0.0.1:8888/api/ or http://127.0.0.1:8888/api/* (where * is whatever you want to write), the browser shows nothing. However, if I access to http://127.0.0.1:8888/oqiwn (where oqiwn is a random string) the browser shows a Error 404.
Also, I tried the RESTClient addon and these are the answers that returns:
With http://127.0.0.1:8888/api/ or http://127.0.0.1:8888/api/*
Status Code: 404 Not Found
Cache-Control: no-cache
Content-Length: 0
Date: Sun, 10 Nov 2013 22:59:57 GMT
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Server: Development/1.0
And with http://127.0.0.1:8888/oqiwn
Status Code: 404 Not Found
Cache-Control: no-cache
Content-Length: 83
Content-Type: text/html; charset=iso-8859-1
Date: Sun, 10 Nov 2013 22:59:05 GMT
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Server: Development/1.0
Note that Content-Type: text/html; charset=iso-8859-1 is not in the first one.
You added your resource using a method named getMatches(), which Resteasy knows nothing about. You need to override the getSingletons() method of Application and return your root resources from there as shown below.
Documentation Here
Example:
public class MatchApplication extends Application {
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> classes = new HashSet<Class<?>>();
public MatchApplication() {
singletons.add(new MatchServiceImpl());
}
#Override
public Set<Class<?>> getClasses() {
return classes;
}
#Override
public Set<Object> getSingletons() {
return singletons;
}
}
First, I think your MatchApplication class should be annotated with #ApplicationPath("/api"). I'm sorry if that's already done.
Then, depending on your RESTEasy version, it will scan automatically for classes that are providers or resources, so you don't need to give to implement anything on your MatchApplication for now. Just extend Application and you are done.
If you can update your web-app to use servlet 3.0, you don't need to put any kind of configuration into your web.xml.
Read more on the RESTEasy documentation.
This works for all my services.
This is a runtime exception indicating a resource requested by a client was not found on the server.
Add below entry into your web.xml :
<context-param>
<param-name>resteasy.resources</param-name>
<param-value>com.org.abc.xyz.MainClassName</param-value>
</context-param>
You can specify fully qualified name of your JAX-RS resource class name you want to register.
If you have multiple classes entries, use comma delimiter.

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