Error 404 during GWT RPC jetty server - gwt

I just written simple RPC call, when i tried i get the below error, could you please help me out to fix this..
[WARN] 404 - POST /com.sribalajiele.gwt.client.SriBalajiEle/emailRpcService (127.0.0.1)
Email Failure404
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 404 NOT_FOUND</title>
The code like below.
/*
* Copyright (c) Balaji electricals AG 2011, All Rights Reserved
*/
package com.sribalajiele.gwt.client.client;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
/**
* #author kdel.
* This interface provides Email Service.
*
*/
#RemoteServiceRelativePath("emailRpcService")
public interface EmailRpcService extends RemoteService {
public WriteToUsForm sendEmail(WriteToUsForm writeToUsForm) throws IllegalArgumentException;
}
/*
* Copyright (c) Balaji electricals 2011, All Rights Reserved
*/
package com.sribalajiele.gwt.client.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
/**
* #author kdel
* Async service for Email.
*/
public interface EmailRpcServiceAsync {
void sendEmail(WriteToUsForm writeToUsForm, AsyncCallback<WriteToUsForm> asyncCallback)
throws IllegalArgumentException;
}
public final class EmailRpcServiceImpl extends RemoteServiceServlet implements EmailRpcService {
/**
* Default serialVersionUID.
*/
private static final long serialVersionUID = 1L;
#Override
public WriteToUsForm sendEmail(WriteToUsForm writeToUsForm) throws IllegalArgumentException {
System.out.println("send Email called");
}
}
In web.xml:
<servlet>
<servlet-name>emailService</servlet-name>
<servlet-class>com.sribalajiele.gwt.client.server.EmailRpcServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>emailService</servlet-name>
<url-pattern>sriBalajiEle/emailRpcService</url-pattern>
</servlet-mapping>

Finally i could correct my self, may be this is use full for others.
1) #RemoteServiceRelativePath("emailRpcService")
public interface EmailRpcService extends RemoteService {
2) In *Module*.gwt.xml
<servlet class="com.sribalajiele.ui.server.EmailRpcServiceImpl" path="/emailRpcService"/>
3) Register your servlet in web.xml
<servlet>
<servlet-name>eamilService</servlet-name>
<servlet-class>com.sribalajiele.ui.server.EmailRpcServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>eamilService</servlet-name>
<url-pattern>/com.sribalajiele.ui.SriBalaji/emailRpcService</url-pattern>
</servlet-mapping>
4) Usage:
final EmailRpcServiceAsync emailRpcServiceAsync = (EmailRpcServiceAsync) GWT.create(EmailRpcService.class);
ServiceDefTarget serviceDef = (ServiceDefTarget) emailRpcServiceAsync;
serviceDef.setServiceEntryPoint(GWT.getModuleBaseURL() + "emailRpcService");
emailRpcServiceAsync.sendEmail(parameter, new AsyncCall()) {
onSuccess() { }
onFailure() { }
}
Hope this will help...

The problem is that you have the servlet mapped to /sriBalajiEle/emailRpcService, but the request is being sent to /com.sribalajiele.gwt.client.SriBalajiEle/emailRpcService. The URL that the request is being sent to is generated by GWT in the form /${moduleName}/relativePath. If you include the following at the top of your GWT module, it should fix the 404.
<module rename-to="sriBalajiEle">

1) Include annotatation in your interface too.
#RemoteServiceRelativePath("emailRpcService")
public interface EmailRpcServiceAsync {
void sendEmail(WriteToUsForm writeToUsForm,
AsyncCallback asyncCallback)
throws IllegalArgumentException;
}
2) And change your url mapping to the following.
<url-pattern>com.sribalajiele.gwt.EmailRpcService/emailRpcService</url-pattern>
For my case, url mapping gave me headache for hours. Hope this helps.

the 404 error will site a url, I had to make sure the url sited in the 404 message was the url in my web.xml
<servlet-mapping>
<servlet-name>messageServiceImpl</servlet-name>
<url-pattern>/com.mbe.site.main/message</url-pattern>
</servlet-mapping>

Related

Jersey returns 500 when trying to return an XML response

I'm trying to create my own RESTful WS application using Jersey 2.12 based from this article. I want to return an XML representation of a class depending on the id been passed from the url, however, I'm getting a 500 response code when trying from either Advanced Rest Client Application (google chrome app) or browser. Below are the details:
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>WS_RESTful_Practice</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>test.services</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>
TestRestModel.java
package test.model;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class TestRestModel{
/**
*
*/
private static final long serialVersionUID = -8391589100962515747L;
private String name;
private String content;
public TestRestModel(String name, String content){
this.name = name;
this.content = content;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
TestResource.java
package test.services;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import test.dao.TestModelDao;
import test.model.TestRestModel;
#Path("/test")
public class TestResource {
#GET
#Path("{id}")
public Response getModel(#PathParam("id") String id){
return Response.ok().entity(TestModelDao.instance.getModel().get(id)).build();
}
}
TestModelDao.java
package test.dao;
import java.util.HashMap;
import java.util.Map;
import test.model.TestRestModel;
public enum TestModelDao {
instance;
private Map<String, TestRestModel> container = new HashMap<String, TestRestModel>();
private TestModelDao(){
TestRestModel model = new TestRestModel("a", "this is first");
container.put("1", model);
model = new TestRestModel("b", "this is second");
container.put("2", model);
model = new TestRestModel("c", "this is third");
container.put("3", model);
}
public Map<String, TestRestModel> getModel(){
return container;
}
}
I'm totally new to Jersey and REST. And I don't know how to log error from Jersey yet.
This happens when you don't provide a default no arg constructor to your JAXB bean. So in your case you should amend the class by adding one:
public TestRestModel(){
}
This is due to a requirement in the JSR-222:
existing types, authored by users, are required to provide a no arg
constructor. The no arg constructor is used by an unmarshaller during
unmarshalling to create an instance of the type.
Stuff below is not the answer, but will probably help Johne to find out, whats up.
Out of the comments I've extract, that the main problem is, that you don't have any noticeable debug output in your console. So you are not able to find the issue by yourself, rather than give us some logs which would help to find out, what the exact problem could be.
Therefore pls implement an ExceptionMapper first, which will force console output of the stacktrace:
Example:
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
#Provider
public class HelpMeExceptionMapper implements ExceptionMapper<Exception> {
#Override
public Response toResponse(Exception e) {
e.printStackTrace();
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.type(MediaType.APPLICATION_JSON)
.entity(e.getCause())
.build();
}
}
The ExceptionMapper has to be in a subpackage of your resource-config/providers path test.services:
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>test.services</param-value>
</init-param>
As i didn't implement your/vogellas code i would like to recommend you, to debug this step by step to find out whats up.
I reckon, that you miss to import something. But who knows ...
Have a nice day ...
To the ones with the same problem, I had something like it but in my case it was a List that i wanted in my response. The source of the problem was that the object had a lazy load relationship and when I used GenericEntity> to return my list the same problem as occurred to me.
Just change to null the relationship or bring the lazy load relation to the object before create GenericEntity> and it will be fine.
We need to understand this problem first
Jersey returns 500 when trying to return an XML response. This issue is coming because of missing dependency in pom.xml and that is:
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.2.11</version>
</dependency>
But this is not enough. This will resolve the 500 Error but one more error will come, while using endpoint.
javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: com/sun/xml/bind/v2/model/annotation/AnnotationReader
To resolve this you need to add following dependencies too into pom.xml
<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-core -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.1</version>
</dependency>
So this is the complete solution, to make your Jersey webApp work

Tomcat Class Not Found - Servlet

I am having a strange problem in deploying a basic web app through Eclipse and Tomcat
The error -
SEVERE: Allocate exception for servlet DeCommServlet
java.lang.ClassNotFoundException: com.authentication.DeCommServlet
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
However, the application still gets to the DeCommServlet doPost() method and tomcat stays deployed but with that error.
Servlet:
<servlet>
<servlet-name>DeCommServlet</servlet-name>
<servlet-class>com.authentication.DeCommServlet</servlet-class>
</servlet>
<!-- Servlet Mappings -->
<servlet-mapping>
<servlet-name>DeCommServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
The servlet class is the correct link but still getting this error. I have nothing in any of the lib folders, but in the application properties I have the Apache Tomcat Lib added in Build Path >> Libraries
Has anyone seen this before?
Code for DeCommServlet:
#WebServlet("/DeCommServlet")
public class DeCommServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public DeCommServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("sdf");
System.out.println("ddd");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.getUserPrincipal().getName();
response.sendRedirect("http://www.google.com");
}
New Class Path1
This is how your webapp should look like :
> DeCommGlobal
> |-->src
> |-->com
> |-->authentication
> |-->DeCommServlet.java
> |-->META-INF
> |-->WEB-INF
> |-->classes
> |-->lib
It was the deployment assembly that was causing the issue. Added the lib folder and we are good to go! Thanks

what values can a JSP form "action" take?

What can a JSP form action be?
I have a Login.jsp page for the user to end the details.
Can i give the servlet class in the form action?
here is the the servlet code.
package mybean;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
System.out.println("In the Login Servlet");
LoginBean user = new LoginBean();
user.setUemail(request.getParameter("uemail"));
user.setUpass(request.getParameter("upass"));
user = LoginDAO.login(user);
if(user.isValid())
{
HttpSession session = request.getSession(true);
session.setAttribute("currentSessionUser",user);
response.sendRedirect("LoginSuccess.jsp");
}else
response.sendRedirect("LoginFailed.jsp");
} catch (Throwable exc)
{
System.out.println(exc);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
As per the specs , it can take any valid URI
This attribute specifies a form processing agent. User agent behavior for a value other than an HTTP URI is undefined.
Can i give the servlet class in the form action ?
Yes if the servlet class name resolves to a valid URL mapped in the web.xml or else you will encounter a 404 .
Let us consider your JSP is at the root of the application, then
<FORM action="someServletName" method="post">
Now this will be resolved as protocol://servername:port/context/someServletName .Now somewhere you should have a mapping for /someServletName , either in web.xml or through annotation to a Servlet or JSP.
<servlet>
<servlet-name>someServletName</servlet-name>
<servlet-path>packageName.servletName</servlet-path>
</servlet>
<servlet-mapping>
<servlet-name>someServletName</servlet-name>
<url-pattern>/someServletName</url-pattern>
</servlet-mapping>

GWT RPC Service not found

I have searched the Web almost for hours, but I didn't find an answer.
The Problem is that i want to the test the gwt RPC.
So I generate with the Eclipse Plugin a GWT remote Service.
But everytime I get the following Failure: "[WARN] No file found for: /kuss_projekt/SpeicherService"
I have tryed a lot, but I dont knwo what is the Problem.
Thats my Code:
web.xml:
<web-app>
<servlet>
<servlet-name>SpeicherService</servlet-name>
<servlet-class>de.fhdo.kuss.server.SpeicherServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SpeicherService</servlet-name>
<url-pattern>/kuss_projekt/SpeicherService</url-pattern>
</servlet-mapping>
<!-- Default page to serve -->
<welcome-file-list>
<welcome-file>Kuss_Projekt.html</welcome-file>
</welcome-file-list>
</web-app>
-
Speicherservice:
#RemoteServiceRelativePath("SpeicherService")
public interface SpeicherService extends RemoteService {
String getName(String name);
public static class Util {
private static SpeicherServiceAsync instance;
public static SpeicherServiceAsync getInstance(){
if (instance == null) {
instance = GWT.create(SpeicherService.class);
}
return instance;
}
}
}
-
SpeicherServiceAsync:
public interface SpeicherServiceAsync {
void getName(String name, AsyncCallback<String> callback);
}
-
SpeicherServiceImpl
public class SpeicherServiceImpl extends RemoteServiceServlet implements SpeicherService {
#Override
public String getName(String name) {
return("Server meldet sich " + name);
}
}
-
Test():
public void test() {
AsyncCallback<String> callback = new AsyncCallback<String>() {
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
}
#Override
public void onSuccess(String result) {
Window.alert(result);
}
};
SpeicherService.Util.getInstance().getName("test",callback);
}
Have you tried removing /kuss_projekt from servlet mapping to make it:
<servlet-mapping>
<servlet-name>SpeicherService</servlet-name>
<url-pattern>/SpeicherService</url-pattern>
</servlet-mapping>
GWT client is expecting the service to be available at the URL defined via #RemoteServiceRelativePath. When you are running in browser, the path is resolved relative to your module base url. As you have given:
#RemoteServiceRelativePath("SpeicherService")
the client will make request to the URL made by concatenating
GWT.getModuleBaseURL() + "SpeicherService"
If your servlet is not mapped at this url, the request will fail. Try printing GWT.getModuleBaseURL()+ "SpeicherService" on console to see what is the base url in your test case. Once you have got this, open the browser and go to that url. If the response says something like "Get method is not supported" everything is mapped correctly. On the other hand if you get a 404 you got to fix your servlet mapping
Does your application xml file contain
<module rename-to='kuss_projekt'>

Guice and GWT problem - can't find GWT.rpc

I build a simple contact manager app with simple service and it did work.
Then I decided I want to use Guice for managing my services and implementations.
I also use mvp4g plugin for MVP design pattern.
I followed the exmaple of Eric Burke on his blog, and my code looks like that:
ContactService.java
#RemoteServiceRelativePath("GWT.rpc")
public interface ContactService extends RemoteService {
public void saveContact(Contact c);
public List<Contact> listContacts();
}
ContactServletModule.java:
#Singleton
public class ContactServletModule extends ServletModule{
private static String SQL_MAP_CONFIG = "org/yuri/SqlMapConfig.xml";
private SqlSessionFactory factory = null;
#Provides
public SqlSessionFactory getSqlSessionFactory(){
if(this.factory == null){
try {
/*
* Create new factory
*/
Reader r = Resources.getResourceAsReader(SQL_MAP_CONFIG);
this.factory = new SqlSessionFactoryBuilder().build(r);
} catch (IOException ex) {
/*
* do nothing, factory is null still
*/
} finally{
return this.factory;
}
}
else{
return this.factory;
}
}
#Override
protected void configureServlets() {
serve("/YuriContactManager/GWT.rpc").with(GuiceRemoteServiceServlet.class);
bind(ContactService.class).to(ContactServiceImpl.class);
}
}
MyGuiceContextListener.java
public class MyGuiceContextListener extends GuiceServletContextListener {
#Override
protected Injector getInjector() {
return Guice.createInjector(new ContactServletModule());
}
}
But when when I start my app and try to list contacts by calling listContacts(), tomcat tells me that GWT RPC can't be found (exactly: The requested resource (/YuriContactManager/org.yuri.ContactManager/GWT.rpc) is not available.) My web.xml looks like that:
<?xml version="1.0" encoding="UTF-8"?>
<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">
<filter>
<filter-name>guiceFilter</filter-name>
<filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>guiceFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.yuri.server.MyGuiceContextListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>welcomeGWT.html</welcome-file>
</welcome-file-list>
</web-app>
Any one had similar problem or has any idea what might be wrong?
found the error :) In ContactServletModule serve path needs to be modified to "/org.yuri.YuriContactManager/GWT.rpc" - I think the reason why is that I'm also using mvp4g framework, but I'm not sure.