Getting 404 error on JAX-RS web service/ Maven/Eclipse/Tomcat 9 - jax-rs

I am trying to show the Alien Object in XML format with AlienResouces as Resource.However, it is giving me 404 error during runtime on the browser and the debugging stmnt GeAlien called is not showing on Tomcat console
Web Service
package com.dip.testproj;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Alien {
private String name;
private int points;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
}
The following is the Resource for the Alien object. The object Alien is getting the resource Name and Number and trying to display it on the browser during runtime.
We Service Resources
package com.dip.testproj
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("aliens")
public class AlienResources {
#GET
#Produces(MediaType.APPLICATION_XML)
public Alien getAlien(){
System.out.println("getAlien Called");
Alien a1 = new Alien();
a1.setName("Navin");
a1.setPoints(60);
return a1;
}
}
There is no compilation error or any error on the console for Tomcat. server. However, it is giving "404" or "Resource could not be found" while trying to run the THIS on the FF browser
The URL Pattern on WEB.xml looks like this.
WEB.XML
<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" 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_2_5.xsd">
<servlet>
<servlet-name>Jersey Web Application</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.dip.testproj</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
</web-app>

Related

Wrong target URL

I've configured my project to load at this URL:
http://localhost:7101/foo/rs/user/home
However, when I deploy the application through JDeveloper I can see this in the Debugging: IntegratedWebLogicServer tab within the IDE:
Target Application WADL -- http://localhost:7101/foo/application.wadl
Target URL -- http://localhost:7101/foo/user/home
Note the /rs part is missing. It's mostly cosmetic (the site loads correctly in the browser when you use the correct URL) but, apart from confusing, it might be a symptom of some configuration issue. Where does JDeveloper get this URL from?
These are some of the hopefully relevant settings:
\ViewController\ViewController.jpr
<hash n="oracle.jdeveloper.model.J2eeSettings">
<value n="j2eeWebAppName" v="Foo-ViewController-webapp"/>
<value n="j2eeWebContextRoot" v="foo"/>
</hash>
ViewController\public_html\WEB-INF\web.xml
<?xml version = '1.0' encoding = 'windows-1252'?>
<web-app 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_2_5.xsd"
version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">
<filter>
<filter-name>JpsFilter</filter-name>
<filter-class>oracle.security.jps.ee.http.JpsFilter</filter-class>
<init-param>
<param-name>enable.anonymous</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>JpsFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<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>com.example.foo.view.rest</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.mvc.templateBasePath.jsp</param-name>
<param-value>/WEB-INF/jsp</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.media.multipart.MultiPartFeature, org.glassfish.jersey.server.mvc.jsp.JspMvcFeature</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/rs/*</url-pattern>
</servlet-mapping>
<mime-mapping>
<extension>js</extension>
<mime-type>application/javascript</mime-type>
</mime-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>Jersey resources</web-resource-name>
<url-pattern>/rs/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>valid-users</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
<security-role>
<role-name>valid-users</role-name>
</security-role>
<ejb-local-ref>
<ejb-ref-name>ejb/FooEJB</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local>com.example.foo.model.FooEJB</local>
<ejb-link>FooEJB</ejb-link>
</ejb-local-ref>
<listener>
<listener-class>com.example.foo.view.listeners.SessionListener</listener-class>
</listener>
</web-app>
com.example.foo.view.rest.UserService
package com.example.foo.view.rest;
import org.glassfish.jersey.server.mvc.Viewable;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.security.RolesAllowed;
import javax.naming.NamingException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("user")
#RolesAllowed("valid-users")
public class UserService extends BaseService {
public UserService() throws NamingException {
super();
}
#GET
#Path("/home")
#Produces(MediaType.TEXT_HTML)
public Response showHome() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("title", "Home");
return Response.ok(new Viewable("/user/home", map)).build();
}
}
com.example.foo.view.rest.BaseService
package com.example.foo.view.rest;
import com.example.foo.commons.Constants;
import com.example.foo.model.FooEJB;
import javax.annotation.Resource;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;
public class BaseService {
#Resource
protected FooEJB fooEJB;
#Context
protected HttpServletRequest request;
#Context
protected HttpServletResponse response;
#Context
protected SecurityContext securityContext;
public BaseService() throws NamingException {
InitialContext context = new InitialContext();
fooEJB = (FooEJB)context.lookup(Constants.EJB_JDNI_NAME);
}
}

Filter not functioning when used with omnifaces extensionless URLs

I am using omnifaces extensionless URLS in my web application.
My web.xml is as below
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<param-name>org.omnifaces.FACES_VIEWS_SCAN_PATHS</param-name>
<param-value>/*.xhtml</param-value>
</context-param>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>Login.xhtml</welcome-file>
</welcome-file-list>
</web-app>
My filter clas is as below
#WebFilter(filterName = "AuthFilter", urlPatterns = { "*.xhtml" })
public class AuthenticationFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession ses = req.getSession(false);
String reqURI = req.getRequestURI();
System.out.println(reqURI);
if (reqURI.indexOf("/Login") >= 0
|| (ses != null && ses.getAttribute("user") != null)
|| (reqURI.indexOf("/ForgotPassword") >=0)
|| reqURI.contains("javax.faces.resource")) {
if ((reqURI.indexOf("/Login") >= 0 || (reqURI.indexOf("/ForgotPassword") >=0))
&& (ses != null && ses.getAttribute("user") != null)) {
System.out.println("Invalidating session");
ses.invalidate();
}
chain.doFilter(request, response);
} else {
res.sendRedirect(req.getContextPath() + "/Login");
}
} catch (Throwable t) {
System.out.println(t.getMessage());
}
} // doFilter
}
My requirement is that, if the user is logged in redirect him to all the pages except the Login and ForgotPassword pages. When the user is logged in and tries to access either of those pages, log him out and send him to the requested page. If the user is not logged in, all requests to Login and ForgotPassword pages should be allowed and access to any other page should redirect him to Login page.
The problem I am facing is that with the extensionless URLs, I can access a page with or without the .xhtml file extensions. The filter is invoked only when I access it using the extension. Without the extension, the filter is bypassed.
I am not sure what URL pattern to provide in the filter class to get it to process every request.
Kindly help.
Either, listen on all URLs:
#WebFilter(urlPatterns = "/*")
or, attach it to the FacesServlet:
#WebFilter(servletNames = "Faces Servlet")
(note that this way the filter thus doesn't run when the URL doesn't hit the FacesServlet)

How to write JAX-RS resource for consuming uploaded file

This is my class:
package pkg.rest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;
#Path("/file")
public class UploadFileService {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = "d://uploaded/"
+ fileDetail.getFileName();
// save it
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(
uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is my Html File for uploading :
<html>
<body>
<h1>File Upload with Jersey</h1>
<form action="rest/file/upload" method="post" enctype="multipart/form-data">
<p>
Select a file : <input type="file" name="file" size="45" />
</p>
<input type="submit" value="Upload It" />
</form>
</body>
</html>
Web.xml file:
<?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" id="WebApp_ID" version="3.0">
<display-name>REST_WS</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
when i try to upload file to server then no action perform i dint create client direct run it html file in tomcat server and try to access it please help me what we need to do change this i am writing first time so please help .
You didn't put enough stuff in web.xml, so the container does not know how to route request to your Jersey servlet.
Add the following to your web.xml:
<servlet>
<servlet-name>UploadServlet</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>pkg.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
You need to have the pattern /rest/* in all the url's which you want to be handled as a service.

Jersey/Glassfish: what is consuming POST parameters?

I have a Jersey 2.x servlet running under Glassfish 4.0. There is a method that processes a form submission:
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Path("/{serial}")
public Response saveUnit(....) { ... }
I get the message "A servlet request to the ... contains form parameters in the request body but the request body has been consumed by the servlet or a servlet filter accessing the request parameters."
However, I don't have any filters defined. Other than whatever Glassfish and Jersey do by default.
I do however have a listener defined (which I had forgotten about).
I suspect this is why my attempt to use MultivaluedMap isn't working.
Any ideas what is consuming the request?
Here is the Jersey method:
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Path("/{unitid}")
public Response saveUnit(#PathParam("unitid")int unitId, #Context UriInfo uri) {
MultivaluedMap<String, String> queryParams = uri.getQueryParameters();
for (String k:queryParams.keySet()) {
logger.info(k);
}
return Response.ok().build();
}
The map queryParams is empty.
Here is my web.xml.
<?xml version="1.0" encoding="UTF-8"?>
<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">
<servlet>
<servlet-name>mycompany.ApplicationConfig</servlet-name>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>mypackage</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mycompany.ApplicationConfig</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<listener>
<listener-class>mycompany.ServletContextClass</listener-class>
</listener>
</web-app>
To get to the received form parameters in your resource method change the signature of the method to:
public Response saveUnit(#PathParam("unitid") int unitId,
final javax.ws.rs.core.Form form) {
...
}
or
public Response saveUnit(#PathParam("unitid") int unitId,
final MultivaluedMap<String, String> formData) {
...
}
Jersey will fill the values.
With your approach you're asking Jersey to return a map of query params (which are part of URI and assuming from the question you want Form params).

Page 404 NoT Found Even the Tomcat is not showing any error

I am trying to run this simple example on eclipse .As i run the server it is not showing any error .But in the browser it is showing 404 error page not found. I don't understand what is the error.I have used all the Jars in my WEB-INF/Lib folder too.
THE CODE SNIPPET is below:
CLASS HELLOWORLDACTION
package com.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.form.HelloWorldForm;
public class HelloWorldAction extends Action{
public ActionForward execute(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response) throws Exception {
HelloWorldForm helloWorldForm = (HelloWorldForm) form;
helloWorldForm.setMessage("Hello World! Struts");
return mapping.findForward("success");}
}
CLASS HelloWorldForm
package com.form;
import org.apache.struts.action.ActionForm;
public class HelloWorldForm extends ActionForm{
String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="helloWorldForm"
type="com.form.HelloWorldForm"/>
</form-beans>
<action-mappings>
<action path="/helloWorld"
type="com.action.HelloWorldAction"
name="helloWorldForm">
<forward name="success" path="/HelloWorld.jsp"/>
</action>
</action-mappings>
</struts-config>
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">
<display-name>Maven Struts Examples</display-name>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>
/WEB-INF/struts-config.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
HelloWorld.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1><bean:write name="helloWorldForm" property="message" />
</h1>
</body>
</html>
It sounds like you are using the wrong url. Tomcat generally has a folder called webapps for applications that are deployed on that server. To figure out the configuration, in Eclipse, open up the Server tab, find your Tomcat server and double-click on it.
It should bring up a properties pane with two tabs at the bottom Overview and Modules. Click on Modules and you should see the path to your app. For me, it's in the form of: /webapps/<project name>
Your full url would be localhost:8080/webapps/<project name>/anystringhere.do since you map anything in your app (localhost:8080/webapps/<project name>/) that ends in .do to the action servlet.