GET POST Rest Service not getting initialized - jersey

Web.xml
<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_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>de.vogella.jersey.jaxb</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.example.endpoint</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/atom/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>com.example.endpoint.DataWriteOptimizerOnLoad</listener-class>
</listener>
</web-app>
DataWriteOptimizerOnLoad
package com.example.endpoint;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.example.hibernate.DataWriteOptimizer;
public class DataWriteOptimizerOnLoad extends DataWriteOptimizer implements
ServletContextListener {
private static final long serialVersionUID = 1L;
#Override
public void contextDestroyed(ServletContextEvent arg0) {
}
#Override
public void contextInitialized(ServletContextEvent arg0) {
getInstance();
}
}
This initialization happens, I checked in catalina.out.
But this class does not get picked up by catalina.out.
package com.example.endpoint;
import javax.ws.rs.Consumes;
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;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBElement;
import com.mcruiseon.atom.api.tunnel.Consolidation;
import com.mcruiseon.atom.commons.AtomCommons;
#Path("/Consolidation")
public class EndPointConsolidation {
#GET
#Path("searchUsers/{passNumber}/{userMobileNumber}")
#Consumes({ MediaType.APPLICATION_JSON })
#Produces({ MediaType.APPLICATION_XML })
public ConsolidationSearchForUsersResponse searchUsers(
#PathParam("passNumber") String passNumber,
#PathParam("userMobileNumber") String userMobileNumber) {
return Consolidation.searchForUsers(passNumber, userMobileNumber);
}
}
Nothing comes up on catalina.out when I run
http://ipaddress:port//atom/Consolidation/searchUsers/9876543210
from the browser.

If you are using Jersey 2.0 and later then it does not recognize init-param with name com.sun.jersey.config.property.packages (web.xml). Try to change it to jersey.config.server.provider.packages as described in JerseyProperties

Related

REST Web Service not working

I am just trying to create a simple test web service. I want to access the User in XML format at the following url: http://localhost:8080/Online_Shopping/dispatcher/rest/hello, but when I go to the URL nothing is displayed.
Here is my code for the service:
package com.shopping.controller;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.shopping.model.User;
#Path("/rest")
public class RESTController {
#GET
#Path("/hello")
#Produces(MediaType.APPLICATION_XML)
public User getUser() {
return new User("paymon","123",true);
}
}
The following code is in my spring-config.xml
<context:component-scan base-package="com.shopping.controller" />
This is in my web.xml
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/dispatcher/*</url-pattern>
</servlet-mapping>
Your application is running on port 8080 , so to access this URL you need to add in your servlet dispatcher the "Online_Shopping"
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>Online_Shopping/dispatcher/*</url-pattern>
</servlet-mapping>
or Just access your api without Online_Shoppping
You have to use Spring MVC's annotations instead and use #Controller or #RestController to annotate you controller to be registered as a spring controller.
Try this :
#RestController
#RequestMapping(value = "/rest")
public class RESTController {
#RequestMapping(value = "/hello",
method = RequestMethod.GET,
produces = "application/xml")
public User getUser() {
return new User("paymon","123",true);
}
}

Webservlet suddenly stopped working

I have got a Webservlet (Dynamic Web Module 3.1), it looks like this:
package de.timetoact.cce;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ibm.sbt.services.client.ClientServicesException;
import de.timetoact.cce.handler.ContentHandler;
import de.timetoact.cce.util.Connect;
import de.timetoact.cce.util.Util;
import de.timetoact.cce.util.Variables;
#WebServlet(urlPatterns = { "/main" }, loadOnStartup = 1)
public class InitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String actionn = request.getParameter("action").toLowerCase();
if (actionn.equals("delete")) {
System.out.println("It does work");
}
}
}
Web.xml:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<description>The service servlet handles requests from the toolkit to access external resources.</description>
<display-name>Social Business Toolkit Service Servlet</display-name>
<servlet-name>ServiceServlet</servlet-name>
<servlet-class>com.ibm.sbt.service.core.servlet.ServiceServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServiceServlet</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>
<servlet>
<description>This servlet initializes the specified JavaScript library for use by the Social Business Toolkit.</description>
<display-name>Social Business Toolkit Library Servlet</display-name>
<servlet-name>LibraryServlet</servlet-name>
<servlet-class>com.ibm.sbt.jslibrary.servlet.LibraryServlet</servlet-class>
<init-param>
<param-name>toolkitExtUrl</param-name>
<param-value>%local_server%/sbtx</param-value>
</init-param>
<init-param>
<param-name>jsLibraryUrl</param-name>
<param-value>%local_server%/sbt/js/libs</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>LibraryServlet</servlet-name>
<url-pattern>/library/*</url-pattern>
</servlet-mapping>
<filter>
<description>This filter is responsible for creating the toolkit application and context objects for every servlet within this web application.</description>
<display-name>Social Business Toolkit Filter</display-name>
<filter-name>SBTFilter</filter-name>
<filter-class>com.ibm.sbt.util.SBTFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SBTFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Yesterday it worked perfectly, but today I get the message:
The requested resource is not available. /CCE/main
I cleaned the project and did update (Maven Update Project)
Nevertheless I got this context error, although I did not change anything.
What is wrong here?
This problem is caused by running two instances of your project in eclipse or tomcat. You can resolve this problem by restarting eclipse or tomcat.

ServletContext Attribute is null when accessing it via restful web service in jersey implementation

I have a Java MVC application with a single controller. The database is initialized in servlet context listener class. I am passing the database object as a servlet context attribute to the controller servlet and webservice class. In controller servlet the "db" attribute is working fine but in web service class I am getting null and illegal state exception.
Error stacktrace -
javax.servlet.ServletException: A MultiException has 2 exceptions. They
are:
1. java.lang.NullPointerException
2. java.lang.IllegalStateException: Unable to perform operation: create on
com.home.mystorywriter.UserWS
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:489)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java: 388)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java: 341)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java: 228)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
at com.home.mystorywriter.UserWS.<init>(UserWS.java:36)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
webservice class
package com.home.mystorywriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import com.google.gson.Gson;
#Path("/users")
public class UserWS {
#Context
private HttpServletRequest req;
private HttpServletResponse res;
private ServletContext context ;
DAOdb db = (DAOdb)req.getServletContext().getAttribute("db");
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("allUsers")
public String getAllUsers() {
List<Profile> userlist = db.getProfileListOfAllUsers();
Gson gson = new Gson();
String jsonUsers = gson.toJson(userlist);
return jsonUsers;
}
}
Web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
si:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<listener>
<description>MyServletContextListener</description>
<listener-
class>com.home.mystorywriter.MyServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>StoryServlet</servlet-name>
<servlet-class>com.home.mystorywriter.StoryServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.home.mystorywriter</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>StoryServlet</servlet-name>
<url-pattern>/StoryServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
#Context injection happens inside the web service class or class method. Below code is working fine.
#Path("/users")
public class UserWS {
private ServletContext context ;
DAOdb db;
public UserWS() {
System.out.println("Inside Constructor " + context);
}
#Context
public void setServletContext(ServletContext context) {
System.out.println("servlet context set here");
this.context = context;
db = (DAOdb)context.getAttribute("db");
}
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/allUsers")
public String getAllUsers() {
System.out.println("Inside get method:"+ context);
System.out.println("db value"+ db);
Profile userlist = db.getProfileWithoutPic();
Gson gson = new Gson();
String jsonUsers = gson.toJson(userlist);
return jsonUsers;
}
}

Jersey HelloWorld throwing 404 error

I'm trying to learn jersey and using this simple example of printing Hello Jersey but when accessing the servlet at http://localhost:8080/testjersey2/hello getting 404 error. Deployed on tomcat 7. What am i possibly doing wrong here ? I dont see any errors in the tomcat logs either.
Hello.java,
package com.nixgadget.jersey;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
//Sets the path to base URL + /hello
#Path("hello")
public class Hello {
// This method is called if TEXT_PLAIN is request
#GET
#Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
return "Hello Jersey";
}
// This method is called if XML is request
#GET
#Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}
// This method is called if HTML is request
#GET
#Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello Jersey" + "</title>"
+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
}
}
In 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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>testjersey2</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<!-- Register resources and providers under com.vogella.jersey.first package. -->
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.nixgadget.jersey</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
Directory structure,

Spring Mvc:No mapping found for HTTP request with URI

Maven3 + Spring 4 + Jetty
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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.vito16.activiti.demo1.config.AppConfig</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</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.vito16.activiti.demo1.config.WebConfig</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Open Entity Manager in View filter -->
<filter>
<filter-name>openEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Spring mvc config using annotation:
package com.vito16.activiti.demo1.config;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.activiti.spring.annotations.EnableActiviti;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
/**
* #author Vito
* #version 2014/6/4
*/
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("/WEB-INF/views/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
#Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
return new RequestMappingHandlerMapping();
}
#Bean
public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
return new RequestMappingHandlerAdapter();
}
}
My test controller:
package com.vito16.activiti.demo1.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* #author Vito
* #version 2014/6/4
*/
#Controller
public class IndexController {
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
return "index";
}
}
when im visit http://127.0.0.1:8080/index result 404:
and console print message:
INFO o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/index],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.vito16.activiti.demo1.controller.IndexController.index()
INFO o.s.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcher': initialization completed in 265 ms
WARN o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/WEB-INF/views/index.jsp] in DispatcherServlet with name 'dispatcher'
How to fix it? I do not have this problem before using the XML configuration over time
your configuration is missing
#ComponentScan(basePackages = "your package to beans")
so it cant scan your beans like controller or whatever you try to make as bean
so add this on top of your configuration class like below
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.vito16.activiti.demo1")
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("/WEB-INF/views/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
#Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
return new RequestMappingHandlerMapping();
}
#Bean
public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
return new RequestMappingHandlerAdapter();
}
}

Resources