I am trying to use Jersey to provide a simple web service for my struts application.
When I call the client action I get the following error
com.sun.jersey.api.client.UniformInterfaceException
Message: GET http://localhost:8080/shumer/rest/employee/get returned a response status of 404
servlet declaration in web.xml
<servlet>
<servlet-name>JAX-RS Servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>spring.autowire</param-name>
<param-value>byName</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS Servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Server resource
#Path("employee")
public class EmployeeResource {
#Autowired
EmpDao empDao;
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Employee> get(#QueryParam("empCode") String empCode) throws Exception {
EmpCriteria criteria = new EmpCriteria();
criteria.setEmpCode(empCode);
return empDao.searchByCondition(criteria);
}
}
Client action
public class EmployeeClientTestAction extends Action {
#Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
Client client = Client.create();
WebResource resource = client.resource("http://localhost:8080/shumer/rest/employee/get");
String employees= resource.accept(MediaType.APPLICATION_JSON)
.get(String.class);
System.out.println(employees);
request.setAttribute("employees", employees);
return mapping.findForward("successful");
}
}
I have tried this with and without the /get and the end of the resource url, and with and without a leading / in the EmployeeResource #Path annotation. My guess is that there is somewhere I have to declare where my resources are lcoated at in order for the Jersey servlet to handle them, but I can't figure it out. A point in the right direction would be much appreciated.
EDIT
I have added the following init-param to the servlet element and it is still not working (this package is where my resource class is)
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>shumer.rest.resource</param-value>
</init-param>
in get method write #Path("/get")
Related
I have an api that needs to implement security.
But the filter is not invoked. my call pass directly to the endpoint...
My Secure interface
#NameBinding
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.TYPE,ElementType.METHOD})
public #interface Seguro {}
My Filter
#Seguro
#Provider
#Priority(Priorities.AUTHENTICATION)
public class FiltroAutenticacao implements ContainerRequestFilter {
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
throw new NotAuthorizedException("Authorization header precisa ser provido");
}
String token = authorizationHeader.substring("Bearer".length()).trim();
try {
...
} catch (Exception e) {
...
}
}
}
My method that needs to be authenticated.
#Seguro
#GET
#Path("/metodo-teste")
#Produces("application/json")
public Response medotoTeste(#QueryParam("codigo") String codigo){
ModeloTesteTO to = new ModeloTesteTO("codigo enviado foi " + codigo);
return Response.ok(to, MediaType.APPLICATION_JSON).build();
}
Do I need to implement anything else?
My web.xml
<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.resourceConfigClass</param-name>
<param-value>com.sun.jersey.api.core.PackagesResourceConfig</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>br.gov.es.dataci.aprender</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
<param-value>br.gov.es.dataci.aprender.seguranca.FiltroAutenticacao</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>
I am using Jersey 1.17 and glassfish 4
I discovered the problem, following Paul's suggestion of trying to publish the application with Jersey 2 on the glassfish, I discovered incompatibility in glassfish version. Glassfish 4.0 does not support jersey 2, the 4.1.2 version yes. I migrated the server and solved the problem.
I am having problem in some request access, in my web application. I am not able to figure out the issue.
In my we application servlet mapping configuration is like this..
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.eclipse.jetty.servlet.DefaultServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and the spring configuration for dispatcher servlet is like this.
In WebApplicationInitializerConfig
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(DispatcherConfig.class);
DispatcherServlet dispatcherServlet = new DispatcherServlet(dispatcherContext);
ServletRegistration.Dynamic dispatcher;
dispatcher = servletContext.addServlet("api/", dispatcherServlet);
dispatcher.setLoadOnStartup(1);
String apiMappingPath = /api/*;
dispatcher.addMapping(apiMappingPath);
When I make some API request, the call goes to the method and method sout also print in server log.But no response comes out.
For information I am deploying the application on glassfish server.
I am not able to get the issue reason also. If any one knows then help me out.
Method code:
#RequestMapping(value = "/email", method = RequestMethod.POST)
public Map passwordResetMail(#RequestBody(required = false) String email, HttpServletRequest request, HttpServletResponse response) {
system.out.println("email"+email);
Map map = new HashMap();
map.put("email",email);
return map;
}
I'm trying to connect to a Jersey service using JQuery. But, it's not getting connected to the service, because I'm checking the logs whether it has hit the service or not. Is there anything missing?
$('#update').click(function() {
alert("updating the labelll");
$.ajax({
url:"/updatecontent",
type: 'POST',
dataType:"json",
data:$( "#labels option:selected" ).text(),
async:false,
success:function(contentdata) { // Success Call Back Function.
if(contentdata == "1") {
alert("successfully updated");
} else {
alert("sorry.. failed in updating");
}
},
error:function(){ // Error Call back function.
alert("sorry.. failed in updating in Error call back");
}
});
});
Service
---------
#Path("/updatecontent")
public class updatecontent {
private static final org.slf4j.Logger LOGGER=org.slf4j.LoggerFactory.getLogger(updatecontent.class);
#Context
HttpServletRequest request;
#Context
HttpServletResponse response;
#POST
#Consumes(MediaType.APPLICATION_JSON)
public String updateStatus(String packet) throws JSONException {
// Get the object from the UI.
LOGGER.info("In the API class of updating content for review.");
return "1";
}
}
Web.xml
---------
<servlet>
<servlet-name>jersey-serlvet</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>net.my.services</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>6</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Am I missing anything here? There should be a minor issue. Any ideas would be greatly appreciated.
Your web.xml has an url-pattern of
<url-pattern>/rest/*</url-pattern>
So jQuery must connect to
/rest/updatecontent
I've recently joined a project where I'm supposed to change the web services from Axis1.2 to REST. The project is in development for 10 years and many people have worked on it, so unfortunately I can't tell why something is done, only that it is done.
I am using Jersey and though I have worked through many tutorials, it still doesn't work.
This is my server code:
#Path("/positionfacade")
#Consumes(MediaType.APPLICATION_XML)
public class PositionFacadeRest implements PositionFacadeInterface {
#POST
#Path("/{sessionId}/{type}/{mapIdentifier}/{positionX}/{positionY}/{positionZ}/{character}/{identifier}/{displayName}/{fixed}/{attributes}/{lastObservedTime}/{sensorData}/{coordinates}")
#Consumes(MediaType.APPLICATION_XML)
public void createOrUpdatePositionRest(
#PathParam("sessionId") long sessionId,
#PathParam("type") String type,
#PathParam("mapIdentifier") String mapIdentifier,
#PathParam("positionX") Integer positionX,
#PathParam("positionY") Integer positionY,
#PathParam("positionZ") Integer positionZ,
#PathParam("character") SignalCharacterDTO character,
#PathParam("identifier") String identifier,
#PathParam("displayName") String displayName,
#PathParam("fixed") Boolean fixed,
#PathParam("attributes") AttributesDTO attributes,
#PathParam("lastObservedTime") long lastObservedTime,
#PathParam("sensorData") SensorDTO[] sensorData,
#PathParam("coordinates") CoordinateDTO[] coordinates)
throws SessionException, MapException {
...
}
}
My client code:
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
...
Client restclient = Client.create();
WebResource resource = restclient.resource("http://"+sci.getHostName()+":"+new Integer(sci.getPort()).toString()+"/application/rest/positionfacade/"+
sessionIds.get(sci)+"/"+
node.getType()+"/"+
controller.getCurrentMap().getIdentifier()+"/"+
node.getX()+"/"+
node.getY()+"/"+
node.getZ()+"/"+
signalCharacter_+"/"+
node.getIdentifier()+"/"+
node.getDisplayName()+"/"+
null+"/"+
null+"/"+
lastObservedTime_+"/"+
null+"/"+
null
);
resource.post();
The web.xml:
<servlet>
<servlet-name>rest</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>net.sf.application.server.facade</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
And the error Message:
Exception in thread "Thread-64" com.sun.jersey.api.client.UniformInterfaceException: POST http://localhost:8080/application/rest/positionfacade/121/CLIENT/eca723a4-bd53-405e-893b-6ff8365d58b9/0/0/0/net.sf.application.server.dto.SignalCharacterDTO#229509bb/1/1/null/null/-1/null/null returned a response status of 404 Not Found
The application is running on Tomcat7 and is in webapps/application
Many many thanks for your help in advance. :-)
I have code along the following lines in my Spring MVC webapp:
#RequestMapping("/{someVariable}/aPath/aPage.do")
public void serveAPage() {
doStuff();
}
We want "someVariable" to be in the URL, but we aren't interested in capturing and using the value of it. Is there any way of replacing it with a wildcard, e.g. /*/aPath/aPage.do?
Yes, #RequestMapping accepts Ant-style patterns as from http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html#params()
So this works:
#RequestMapping(value="/*/test2.do")
public void getMeta5(HttpServletRequest request, HttpServletResponse response) throws IOException {
final PrintWriter writer = response.getWriter();
writer.print("requestURI:" + request.getRequestURI());
writer.flush();
}
This assumes that servlet-mapping in web.xml maps that URL path to the DispatcherServlet, e.g.
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>