Jersey/Glassfish: what is consuming POST parameters? - glassfish

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).

Related

Secured REST call on Websphere

I am trying to create a secured REST service on WebSphere 8.5.0.2. I want to secure using basic authentication. I modified my web.xml and tryed to read auto injected SecurityContext. I get an auto injected object but various operations are failing for e.g. securityContext.getAuthenticationScheme();
I have also mapped my role to all authentiacted realm's users.
I could not find anything in Wink's documentation too. Am i doing anything wrong ?
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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>RESTModulation</display-name>
<!-- Wink SDK servlet configuration.
This servlet handles HTTP requests
of SDK web service on application server.-->
<servlet>
<description>
JAX-RS Tools Generated - Do not modify</description>
<servlet-name>EntryRestServlet</servlet-name>
<servlet-class>com.ibm.websphere.jaxrs.server.IBMRestServlet</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.demo.DemoResourceApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>EntryRestServlet</servlet-name>
<url-pattern>
/resources/*</url-pattern>
</servlet-mapping>
<security-constraint id="SecurityConstraint_1">
<web-resource-collection id="WebResourceCollection_1">
<web-resource-name>EntryRestServlet</web-resource-name>
<description>Protection area for Rest Servlet</description>
<url-pattern>/resources/</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint id="AuthConstraint_1">
<description>Role1 for this rest servlet</description>
<role-name>Role1</role-name>
</auth-constraint>
</security-constraint>
<security-role id="SecurityRole_1">
<description>This is Role1</description>
<role-name>Role1</role-name>
</security-role>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>defaultWIMFileBasedRealm</realm-name>
</login-config>
<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>
==========================================================================
Service implementation
#Path("/MyTestService")
public class MyTestService{
#Context
SecurityContext securityContext;
#GET
#Path("/getUser1")
#Produces(MediaType.TEXT_PLAIN)
public Response doInquiry()throws Exception {
String jsonData= "{'user':'I am here '}";
String authnScheme = securityContext.getAuthenticationScheme();
System.out.println("authnScheme : " + authnScheme);
// retrieve the name of the Principal that invoked the resource
String username = securityContext.getUserPrincipal().getName();
System.out.println("username : " + username);
// check if the current user is in Role1
Boolean isUserInRole = securityContext.isUserInRole("Role1");
System.out.println("isUserInRole : " + isUserInRole);
return Response.status(Response.Status.OK).entity(jsonData).build();
}
}
I did not pass correct password from REST client. After providing correct credentials, it has started working.

How to get id of authenticated user in Olingo ODataServiceFactory

I am trying to read the user id of the user that is calling my OData service.
In my web.xml the OData servlet is a protected area
<servlet>
<servlet-name>EJODataServlet</servlet-name>
<servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>org.apache.olingo.odata2.core.rest.app.ODataApplication</param-value>
</init-param>
<init-param>
<param-name>org.apache.olingo.odata2.service.factory</param-name>
<param-value>com.wombling.odata.service.EJServiceFactory</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>EJODataServlet</servlet-name>
<url-pattern>/EJOData.svc/*</url-pattern>
</servlet-mapping>
<login-config>
<auth-method>FORM</auth-method>
</login-config>
<security-constraint>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<url-pattern>/a/*</url-pattern>
<url-pattern>/index.html</url-pattern>
<url-pattern>*.html</url-pattern>
<url-pattern>/EJOData.svc/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>extension_user</role-name>
</auth-constraint>
</security-constraint>
When I create the factory to serve the response to a query:
public class EJServiceFactory extends ODataServiceFactory {
#Override
public ODataService createService(ODataContext ctx) throws ODataException {
return RuntimeDelegate
.createODataSingleProcessorService(
new AnnotationEdmProvider(
"com.wombling.odata.models"),
new EJODataProcessor("admin")); //TODO this should not be hardcoded
}
}
I cannot see any way that I can get from the ODataContext the user that has passed authentication. If I were to be using basic auth - then I could just get the header, but I'm not using basic auth, but OAuth2 bearer tokens (created by a SAML assertion).
I'd expect the ODataContext provide me access to the request user id, but no luck. Is there some other means that I can use? Or do I need to force the calling application to insert the user id in the request headers (doesn't seem ideal to me!)
To retrieve the request object via the ODataContext object is a little bit tricky. Try this:
HttpServletRequest r = (HttpServletRequest) ctx.getParameter(ODataContext.HTTP_SERVLET_REQUEST_OBJECT);
ctx is your instance of the ODataContext class. From the request object you get all what you need.

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)

PrimeFaces 4.0 FileUpload works with Mojarra 2.2 but not MyFaces 2.2

I am having an interesting problem with the PrimeFaces 4.0 final FileUpload element.
I am trying to run:
PrimeFaces 4.0 final
Apache MyFaces 2.2.0-beta
Tomcat 7.0.27
I have a very simple setup right now,
XHTML page:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<h:form>
<p:fileUpload
fileUploadListener="#{fileUploadController.handleFileUpload}"
mode="advanced" update="messages" sizeLimit="100000"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/" />
<p:growl id="messages" showDetail="true" />
</h:form>
</h:body>
</html>
With this backing bean:
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
#ManagedBean
#RequestScoped
public class FileUploadController
{
public void handleFileUpload(FileUploadEvent event)
{
FacesMessage msg = new FacesMessage("Succesful", event.getFile()
.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
When selecting a file and uploading it, nothing happens.
The upload submit succeeds with the following response:
<?xml version="1.0" encoding="UTF-8"?><partial-response><changes><update id="j_id__v_0:javax.faces.ViewState:1"><![CDATA[2C7ZmtwSmrlbgI/wJLI2CLBaMOQP9R/pYkIXpHlXkhSKIhtfFM0sx0HmL8o9MQY2MdHXg4t1vUjJbUYkAdFBmOQUaFy7hFhPr34Za4hOuLW4CPNx]]></update></changes></partial-response>
but no message is displayed, and if I set a breakpoint, it does not get hit.
If, however, I pull out MyFaces 2.2.0-beta and put in Mojarra 2.2.0, everything works as expected.
I would prefer to continue to use MyFaces as it is what I've used in the past, so if anyone has any ideas as to a patch to get this to work, it would be much appreciated.
Thank you
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>UploadTest</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>
<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>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>resources.application</param-value>
</context-param>
<context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<description>
This parameter tells MyFaces if javascript code should be allowed in
the rendered HTML output.
If javascript is allowed, command_link anchors will have javascript code
that submits the corresponding form.
If javascript is not allowed, the state saving info and nested parameters
will be added as url parameters.
Default is 'true'</description>
<param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<description>
If true, rendered HTML code will be formatted, so that it is 'human-readable'
i.e. additional line separators and whitespace will be written, that do not
influence the HTML code.
Default is 'true'</description>
<param-name>org.apache.myfaces.PRETTY_HTML</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<description>
If true, a javascript function will be rendered that is able to restore the
former vertical scroll on every request. Convenient feature if you have pages
with long lists and you do not want the browser page to always jump to the top
if you trigger a link or button action that stays on the same page.
Default is 'false'
</description>
<param-name>org.apache.myfaces.AUTO_SCROLL</param-name>
<param-value>true</param-value>
</context-param>
<listener>
<listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
<!-- <listener-class>com.sun.faces.config.ConfigureListener</listener-class> -->
</listener>
Update
It seems that Myfaces 2.2.0-beta has problems using the Part API present in servlet 3.x.
udaykiran pulipati has part of a solution with using web the web.xml filters that PrimeFaces 3.x required and the commons file upload & commons io jars, however, we also need to add the following context-param to the web.xml or the filters get ignored :
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>commons</param-value>
</context-param>
This will force PrimeFaces to use the commons library which fixes the problem
That being said, I would still like to know why MyFaces can't seem to use the servlet Part API if anyone has any ideas. I suspect it may have to do with my Tomcat version as I am only on 7.0.27, but I doubt that.
Mention below filters in web.xml file for uploading a file using PrimeFaces
<!-- PrimeFaces FileUpload Filter -->
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
and add jars to lib folder. PrimeFaces needs below jars for fileuploading.
commons-fileupload-1.3.jar,
commons-io-2.4.jar
Recently it was found a similar issue with a better description in MYFACES-3835. It was a problem related to webkit browsers that only appears when the ajax response is large enough. It has been already fixed.
udaykiran pulipati's answer motivated me to replace commons-fileupload-1.2.2.jar with commons-fileupload-1.3.jar in my project, but that didn't solve the issue for me, as I'm using MyFaces 2.2, PrimeFaces Elite 4.0.8, and TomEE 1.6.1-snapshot.
Also, per udaykiran pulipati's answer, I already added PrimeFaces FileUpload filter config to my web.xml, many months ago.
So, I looked at PrimeFaces 4.0 user guide, and recognized something 'new' that could be specified in web.xml. So, I added the following to my web.xml,
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>commons</param-value>
</context-param>
and finally, PrimeFaces (Elite) 4.0.x FileUpload works with MyFaces 2.2.

File upload doesn't work with PrimeFaces 4.0, JSF Mojarra 2.2.3 and Wildfly Beta 1

I have a web application running on:
Wildfly Beta 1
JSF Mojarra 2.2.3 (from Wildfly)
Primefaces 4.0
rewrite-servlet-2.0.7.Final / rewrite-config-prettyfaces-2.0.7.Final
commons-io-2.4 / commons-fileupload-1.3
And I have problem with file upload component (advanced and simple mode doesn't work, never print inside upload()).
Same is even run without rewrite-servlet-2.0.7.Final/rewrite-config-prettyfaces-2.0.7.Final libs.
My upload.xhtml file:
<h:form prependId="false" id="formLateralUpload" enctype="multipart/form-data">
<h:panelGrid columns="1" cellpadding="5">
<p:fileUpload mode="advanced" multiple="true" update="#widgetVar(msg)"
fileUploadListener="#{test.upload}" auto="true" sizeLimit="10500000"/>
</h:panelGrid>
</h:form>
My bean:
#ManagedBean(name = "test")
#ViewScoped
public class Test {
private UploadedFile file;
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public void upload(FileUploadEvent event) {
System.out.println("inside upload()");
}
}
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="test"
version="3.1">
<display-name>test</display-name>
<welcome-file-list>
<welcome-file>/</welcome-file>
</welcome-file-list>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-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>/faces/*</url-pattern>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.PARTIAL_STATE_SAVING</param-name>
<param-value>true</param-value>
</context-param>
<error-page>
<exception-type>javax.faces.application.ViewExpiredException</exception-type>
<location>/redirect</location>
</error-page>
</web-app>
I have the same issue with Wildfly 8.1, PrimeFaces 5.1, Pretty faces and file upload. There is a HACK to make this work in Tomcat, but I can't find one in undertow. PrettyFaces appears to be doing something bad to multipart post requests that prevents them from working correctly... They seem to be pushing it back to Undertow/Wildfly because the hack exists in Tomcat instead of fixing the actual issue.
Wildfly Discussion: http://ocpsoft.org/support/topic/pretty-primefaces-fileupload/
Tomcat Hack: http://ocpsoft.org/support/topic/split-prettyfaces-anchor-with-primefaces-file-upload-not-working/
I'm road blocked on this and I can't really extract either PrettyFaces, PrimeFaces-Fileupload (I need background ajax/html5 uploading) or Wildfly... Anyone with a suggestion other than "use an iframe/simple mode" would be much appreciated.