Jersey, Tomcat: The requested resource is not available error - eclipse

I have been working towards getting a RESTful service set up using Jersey and Tomcat in RAD 8.5. I have looked at tons of stackoverflow questions related to my error with none of them working. There are no errors in my console.
When I just type: http://localhost:8080/, I get the Apache homepage, so the server is working, but http://localhost:8080/jersey/rest/hello or http://localhost:8080/jersey/WEB-INF/classes/jersey/Hello.java
does not work.
Here is the error: (with my library of jars on the side)
Here is my Hello.java
package jersey;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#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>";
}
#GET
#Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello Jersey" + "</title>"
+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
}
}
And my web.xml
<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.example</param-value>
</init-param>
</servlet>
Versions:
Tomcat: 7.0.663
RAD: 8.5
Jersey: 2.19
Thanks,
In Response to Maciej
This worked! I needed to add <servlet-mapping> with url pattern of /*. Then use http://localhost:8080/jersey/hello, I got a response from the server!
<?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_2_5.xsd"
id="jersey" version="2.5">
<servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>jersey</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>

You are deploying a compiled code to Tomcat, so you won't be able to access the *.java resources.
Annotation #Path("/hello") indicates the path at which resource is available.
It is set to: base URL + /your_path. The base URL is based on your application name, the servlet and the URL pattern from the 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_2_5.xsd"
id="jersey" version="2.5">
<servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>jersey</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
Also replace #Produces annotation to #Consumes:
package jersey;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
#Path("/hello")
public class Hello {
// This method is called if TEXT_PLAIN is request
#GET
#Consumes(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
return "Hello Jersey";
}
// This method is called if XML is request
#GET
#Consumes(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}
#GET
#Consumes(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello Jersey" + "</title>"
+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
}
}
Try: http://localhost:8080/jersey/hello

Make sure that you have kept all the required Jersey Jar files in "WEB-INF -> lib" folder

Even after following the steps as mentioned by Maciej, if it says 404 resource not found, Mention the subclass that implements Application class and write it within init-param tag in web.xml
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>packagename.java_class_name</param-value>
</init-param>
This worked for me.

This problem solved by these steps
1. Select all files in lib folder and right click on it
2. Then click add to build path

Related

how do I get a root path redirect to not respond to all requests in eclipse jetty?

I have a jetty servlet set of pages all set up and working.
to get to the landing page, you have to enter the full url http://127.0.0.1/console/console.jsp
everything is fine for my context "console".
I wanted to add a handler for the root url, so I could just put in a host and it would redirect to the above url.
I got that working, except it seems that every request comes through my root path handler as well and it messes up all the other requests to the real jsp pages.
How do I keep it from doing that, or what do I do differently?
my web.xml...
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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">
<servlet>
<description></description>
<servlet-name>console</servlet-name>
<servlet-class>net.console.Consoleservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>console</servlet-name>
<url-pattern>/console</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<servlet-name>redirect</servlet-name>
<servlet-class>net.console.Redirectservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>redirect</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
slimmed down version of my redirect servlet...
public class Redirectservlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet
{
static final long serialVersionUID = 1L;
public Redirectservlet()
{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
String redirect_path = "http://127.0.0.1/console/console.jsp";
response.sendRedirect(redirect_path);
}
catch (Exception e)
{
}
}
Try using welcome-files instead of your RedirectServlet, in your WEB-INF/web.xml...
<web-app ...>
<welcome-file-list>
<welcome-file>console/console.jsp</welcome-file>
</welcome-file-list>
... other entries
</web-app>
If that doesn't work, consider making that a RedirectFilter instead, and only sending a redirect if the request.getRequestURI() is only in a list of exact request URI string matches that should redirect.

Issue when using Jersey 2.x with IBM WAS 8.x to scan and register JAX-RS resources

I am trying to integrate Jersey 2.22.1 with IBM WAS 8.5.4.I have a couple of JAX-RS resources under a certain package (com.innovation.postdata.integration.rest.test.jersey.resources).One of the JAX-RS resource is shown below:
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
#Path("/service")
public class FileSubmissionTestRestService
{
#PUT
#Consumes({ "text/csv" })
#Path("/file")
public Response submitBordereaux (#QueryParam("forceResponse") String forceResponse)
{
if (forceResponse != null && !"".equals (forceResponse))
{
switch (forceResponse)
{
case "404":
return Response.status (Response.Status.NOT_FOUND).entity ("Resource Not Found!").build ();
case "401":
return Response.status (Response.Status.UNAUTHORIZED).entity ("Unauthorized user!").build ();
case "403":
return Response.status (Response.Status.FORBIDDEN).entity ("User not allowed!").build ();
case "405":
return Response.status (Response.Status.METHOD_NOT_ALLOWED).entity ("Unsupported HTTP method!").build ();
case "415":
return Response.status (Response.Status.UNSUPPORTED_MEDIA_TYPE)
.entity ("Media type not supported.It should be TEXT/CSV or APPLICATION/JSON!").build ();
case "500":
return Response.status (Response.Status.INTERNAL_SERVER_ERROR).entity ("Error occured on server!").build ();
default:
return Response.status (Response.Status.NO_CONTENT).build ();
}
}
return Response.status (Response.Status.INTERNAL_SERVER_ERROR).entity ("Error occured on server!").build ();
}
}
and I added a entry in web.xml as shown below
<servlet>
<servlet-name>JAX-RS REST Servlet</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.innovation.postdata.integration.rest.test.jersey.resources</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS REST Servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
I also added a custom run time property(com.ibm.websphere.jaxrs.server.DisableIBMJAXRSEngine) and set it to true in WAS to disable default WAS JAX-RS implementation.The JAX-RS resources (under com.innovation.postdata.integration.rest.test.jersey.resources) are packaged in a separate jar that is added to the main EAR WEB-INF/lib when packaging the EAR. When I start WAS I get to see only this in the start up logs:
[1/5/16 0:27:24:106 GMT-05:00] 00000070 ServletWrappe I
com.ibm.ws.webcontainer.servlet.ServletWrapper init SRVE0242I:
[InnovationInsurer] [/Jasper] [JAX-RS REST Servlet]: Initialization
successful.
No where it says that it tried to scan the resource packages or anything like this.Just this.The jars I am using are:
hk2-api-2.4.0-b31.jar
hk2-locator-2.4.0-b31.jar
hk2-utils-2.4.0-b31.jar
javax.annotation-api-1.2.jar
javax.inject-2.4.0-b31.jar
javax.ws.rs-api-2.0.1.jar
jersey-client-2.22.1.jar
jersey-common-2.22.1.jar
jersey-container-servlet-core-2.22.1.jar
jersey-guava-2.22.1.jar
jersey-media-jaxb-2.22.1.jar
jersey-server-2.22.1.jar
osgi-resource-locator-1.0.1.jar
javassist-3.12.0.GA.jar
aopalliance-1.0.jar
I am using Postman Rest Client to access the JAX-RS at http://10.2.64.3:9080/Jasper/rest/service/file?forceResponse=403 but I am always getting 200 OK which is wrong.Can anybody please help me out as to what could be the reason for this? Why is not even trying to scan the package and only saying servlet successfully initialized.
As far as I know, there is a bug in Websphere that prevent package scanning to work correctly (it works only if the classes are under WEB-INF/classes, not from WEB-INF/lib).
Some informations here: https://developer.ibm.com/answers/questions/169221/packagesresourceconfig.html
I've workarounded that issue using:
public class MyRestApplication extends ResourceConfig {
public MyRestApplication() {
register(DefaultExceptionMapper.class);
register(ConstraintViolationExceptionExceptionMapper.class);
register(JacksonJsonProvider.class);
// does not work in IBM WAS 8.5.5 full profile: see it here
// https://developer.ibm.com/answers/questions/169221/packagesresourceconfig.html
// and
// http://www-01.ibm.com/support/docview.wss?rs=180&uid=swg1PM99378
// packages(getClass().getPackage().getName(), LookupEndpoint.class.getPackage().getName());
// Works under WAS 8.5
registerClasses(LookupEndpoint.class, XEndpoint.class, YEndpoint.class);
}
}
and
<servlet>
<servlet-name>jersey_v2-servlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>x.y.z.MyRestApplication</param-value>
</init-param>
<init-param>
<param-name>jersey.config.beanValidation.enableOutputValidationErrorEntity.server</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
That is obviously not optimal (you must maintain yourself the list of endpoints to be used) but at least it works.

Spring rest call not working

I had written a very small rest service. When I am trying through the rest cilent, I am getting the error as "method not supported". Can anybody, please suggest me on this.
**controller class**
#Controller
#RequestMapping("/movie")
public class MovieController {
#RequestMapping(value="/{name}", method = RequestMethod.PUT, consumes="application/json")
public #ResponseBody Student getMovie(#PathVariable String name, ModelMap model, #RequestBody Student student, HttpSession session) {
Map<Integer, Student> empData = new HashMap<Integer, Student>();
empData.put(1, student);
return student;
}
}
**Request I am sending throught Rest DHC Client**
URL: http://localhost:8081/SpringMVC/movie/test
method selected: PUT
Headers: Content-Type:application/json
Body: {
"userId":"21",
"firstName":"srinu",
"lastName":"nivas"
}
I use only Jersey to do what you want.
My web.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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>appName</display-name>
<filter>
<filter-name>jersey</filter-name>
<filter-class>com.sun.jersey.spi.container.servlet.ServletContainer</filter-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.appName.rest</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.property.JSPTemplatesBasePath</param-name>
<param-value>/Pages/</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name>
<param-value>/(resources|(Pages))/.*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>jersey</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
And in the rest class i return a Viewable:
My rest class:
#GET
#Path("/PathToAccessPage")
#Produces(MediaType.TEXT_HTML)
public Viewable GetMyClassPage(#Context HttpServletRequest request, #Context UriInfo ui, #Context HttpHeaders hh) {
try {
MyClass myClass = getMyClass();
return new Viewable("/page", myClass);
}
catch (Exception ex) {
return new Viewable("/error", "Error processing request: " + ex.getMessage());
}
}
Hope you help!
Finally, I got the solution. I didn't import the below two jars.
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
As I am using spring MVC and as you can see in the above code, I am giving as consumes=application/json, I thought springMVC will take care of that. It's my mistake and also, I think the error which was renedered by spring, should be something specific to this. Anyway, got the solution. Thanks all for the help.

Unable to invoke rest web service

I am just trying out a sample rest service example. My rest service class is :
#Path("oauth")
public class OauthClass {
private static Map<String, OauthBean> oAuthBeanMap = new HashMap<String, OauthBean>();
static {
OauthBean oAuthBean = new OauthBean();
oAuthBean.setAccess_token(String.valueOf(Math.random()));
oAuthBean.setToken_type("bearer");
oAuthBean.setRefresh_token(String.valueOf(Math.random()));
oAuthBean.setExpires_in("44517");
oAuthBeanMap.put(oAuthBean.getToken_type(), oAuthBean);
}
#GET
#Path("/token?client_id={clntID}")
#Produces("application/json")
public OauthBean getOAuthJSON(#PathParam("clntID") String clientID) {
System.out.println(clientID + " Secret ");
System.out.println("oAuthBeanMap.get(\"bearer\") :P " + oAuthBeanMap.get("bearer"));
return oAuthBeanMap.get("bearer");
}
}
Now when i trry to invoke this url :
http://localhost:7070/RESTfulWS/rest/oauth/token?client_id=clnt001
I get a 405 error.Method not allowed
Below is 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"
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>RESTfulWS</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.eviac.blog.restws</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
I am using jersey 1.18.
What am i doing wrong? Looking forward tyo your solutions.
Reading through your code, I think you should write #Path("/token") instead of #Path("/token?client_id={clntID}").
Besides, as you yourself noted, you should use QueryParam instead of PathParam

invient chart add on-vaadin indication in web.xml

I have learnt from other posts that the mainServlet file has to be modified according to the Demo code. N then servlet file had to be indicated in web.xml
However, in my web.xml, I already had a servlet class indicated in order to use my Rest service.
Question: How can I solve this?
Following is what I am doing:
1:
<servlet>
<servlet-name>ServletAdapter</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ServletAdapter</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
Problem is that Invient Widgetset won't be loaded.
2: and if I had to indicate the servletfile here, then how I am supposed to let my Rest Service works? My Rest service is used to for secure login with auth-constrain.
<servlet>
<servlet-name>VaadinApplication</servlet-name>
<servlet-class>suricate.vaadin.MyApplicationServlet</servlet-class>
<init-param>
<param-name>application</param-name>
<param-value>suricate.vaadin.MyApplication</param-value>
</init-param>
<init-param>
<param-name>widgetset</param-name>
<param-value>com.example.myapp.widgetset.MyAppWidgetSet</param-value>
</init-param>
</servlet>
I hope someone could help me out of this. Thanks very much in advance.
You could override the writeAjaxPageHtmlVaadinScripts method in the ApplicationServlet class and inject the required invient chart js and css files.
Here is what I have done.
public class TogetherApplicationServlet extends ApplicationServlet {
#Override
protected void writeAjaxPageHtmlVaadinScripts(Window window,
String themeName, Application application, BufferedWriter page,
String appUrl, String themeUri, String appId,
HttpServletRequest request) throws ServletException, IOException {
page.write("<script type=\"text/javascript\" language=\"javascript\" src=\""
+ appUrl
+ "/modules/core/jquery/jquery-1.4.4.min.js\"></script>\n");
page.write("<script type=\"text/javascript\" language=\"javascript\" src=\""
+ appUrl + "/modules/core/js/highcharts.js\"></script>\n");
page.write("<script type=\"text/javascript\" language=\"javascript\" src=\""
+ appUrl
+ "/modules/core/js/modules/exporting.js\"></script>\n");
super.writeAjaxPageHtmlVaadinScripts(window, themeName, application,
page, appUrl, themeUri, appId, request);
}
}
You will have to modify your suricate.vaadin.MyApplicationServlet like I have done above. Make sure to include the correct path to the invient chart js and css files.