The requested URL /REST/WebService/MyMethod was not found on this server - java

i'm new to REST Service. i've done a small REST Webservice application and deployed in my online tomcat webserver,
My link -->
http://sample.com.au/REST/WebService/MyMethod?name=sss
but i'm getting the following message
The requested URL /REST/WebService/MyMethod was not found on this server.
when i run the similar in eclipse locally its working....
can anyone please tell me some solution for this...
my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'>
<web-app>
:
:
<servlet>
<servlet-name>ServletAdaptor</servlet-name>
<servlet-class>com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ServletAdaptor</servlet-name>
<url-pattern>/REST/*</url-pattern>
</servlet-mapping>
</web-app>
My FeedService.java
package webService;
import java.util.ArrayList;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import model.ProjectManager;
import com.google.gson.Gson;
import dto.FeedObjects;
#Path("/WebService")
public class FeedService {
#GET
#Path("/MyMethod")
#Produces("application/json")
public String names(#QueryParam("name") String name)
{
System.out.println("name----------->"+name);
String feeds = null;
try
{
ArrayList<FeedObjects> feedData = null;
ProjectManager projectManager= new ProjectManager();
feedData = projectManager.GetFeeds(name);
Gson gson = new Gson();
System.out.println(gson.toJson(feedData));
feeds = gson.toJson(feedData);
}
catch (Exception e)
{
System.out.println("Exception Error"); //Console
}
return feeds;
}
}
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/iloadlogistics.com.au"/>

Refer here. Specifically check Example 4.1 and Example 4.5. Should you not deploy that way?

Related

I am trying to do a simple jersey restful webservice hello world but its not working. Can anyone check where I am doing wrong?

my web.xml file :
Web.xml
I am trying to do a simple jersey restful webservice hello world but its not working. Can anyone check where I am doing wrong?
I am using the below URL :
http://localhost:8080/learning1/rest/firstRest/User1
<?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">
<servlet>
<servlet-name>Learn</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>org.java.learning1</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Learn</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
My restfulwebservice java file : java file
Server is responding with HTTP Status code 404 : not found
package org.java.learning1;
import javax.websocket.server.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
#Path("/firstRest")
public class firstRest {
#GET
#Produces("MediaType.TEXT_HTML")
#Path("{name}")
public String sendResponse(#Context HttpHeaders httpHeaders, #PathParam("name") String name){
String greeting = "hello";
return greeting;
}
}
Hello user7481861 and welcome to stackoverflow!
You have two errors in your code, I've corrected them bellow and added a comment in each, saying what was wrong.
package org.java.learning1;
//import javax.websocket.server.PathParam; <-- incorrect import
import javax.ws.rs.PathParam; // <<-- correct import
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
#Path("/firstRest")
public class firstRest {
#GET
#Produces(MediaType.TEXT_HTML) // No quotes like stdunbar said in the comments
#Path("/{name}") // missing slash before name
public String sendResponse(#Context HttpHeaders httpHeaders, #PathParam("name") String name){
String greeting = "hello " + name; // concatenate the string with the variable name
return greeting;
}
}

ExceptionMapper causes "No 'Access-Control-Allow-Origin' header is present on the requested resource" when handling an exception

I have an AngularJS client trying to consume a REST Web Service on Wildfly.
It works when the server returns an object, but when an exception is thrown, I'm getting the following message:
XMLHttpRequest cannot load
http://localhost:8080/ProdutosBackend-0.0.1-SNAPSHOT/rest/user/create.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://127.0.0.1:51647' is therefore not allowed
access. The response had HTTP status code 500.
I tried lots of combinations of headers and filters, but nothing can make this works.
Client code:
var user = {
email : $scope.signUpData.email,
password : $scope.signUpData.password,
name : $scope.signUpData.name
};
$http.post(
'http://localhost:8080/ProdutosBackend-0.0.1-SNAPSHOT/rest/user/create',
user).
then(function(data) {
console.log("It works!");
},
function(response) {
console.log(response);
});
Web Service
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import br.com.produtos.business.UserBO;
import br.com.produtos.business.exceptions.BusinessException;
import br.com.produtos.entity.User;
import br.com.produtos.transaction.Transaction;
#Path("/user")
public class UserREST {
#POST
#Path("/create")
#Consumes(MediaType.APPLICATION_JSON)
#Produces({ MediaType.APPLICATION_JSON })
public User createAcount(#Context HttpServletRequest httpServletRequest, User user) throws BusinessException {
if (user.getEmail().equals("fff")) {
throw new BusinessException("Bussiness error.");
}
{...}
return user;
}
}
ExceptionMapper
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
public class ThrowableMapper implements ExceptionMapper<Throwable> {
#Override
public Response toResponse(Throwable throwable) {
return Response.status(500).entity(throwable.getMessage()).build();
}
}
Application
#ApplicationPath("/rest")
public class ThisApplication extends Application {
public static CorsFilter cors;
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> empty = new HashSet<Class<?>>();
public ThisApplication() {
CorsFilter filter = new CorsFilter();
filter.getAllowedOrigins().add("*");
cors = filter;
singletons.add(filter);
singletons.add(new ThrowableMapper());
singletons.add(new UserREST());
}
public Set<Class<?>> getClasses() {
return empty;
}
public Set<Object> getSingletons() {
return singletons;
}
}
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="WebApp_ID" version="3.1">
<display-name>ProdutosBackend</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>br.com.produtos.rest.ThisApplication</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
I solved the problem returning the message encapsulated into a json string.
public class ThrowableMapper implements ExceptionMapper<Throwable> {
#Override
public Response toResponse(Throwable throwable) {
return Response.status(500).entity("{ \"message\": \"" + throwable.getMessage() + "\" }").build();
}
}

Error on a JERSEY REST project (and tomcat)

I met a surious problem when I want to develop an API to call an "exterior" method (this method is called "createClientNode" which is a simple request for neo4j).
Anyways, this 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>API</display-name>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>API</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>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/API/*</url-pattern>
</servlet-mapping>
</web-app>
And this my class :
package API;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.neo4j.graphdb.Node;
import function.query.weceipt.GraphManagement;
#Path("/API")
public class MyService {
#POST
#Path("/node")
#Produces({ MediaType.APPLICATION_JSON })
public Node createNode(#DefaultValue("default_id") #QueryParam("ID") String id) {
GraphManagement gm = new GraphManagement();
Node node = gm.createClientNode(id);
return node;
}
#GET
#Path("/node/{ID}")
#Produces({ MediaType.APPLICATION_JSON })
public Node getNode(#PathParam("ID") String id) {
GraphManagement gm = new GraphManagement();
Node node = gm.getClientNode(id);
return node;
}
#Path("/test")
#GET
#Produces(MediaType.TEXT_PLAIN)
public void afficher() {
System.out.println("test");
}
}
the error that I get is "the Servlet jersey-serlvet is not available".
I have the impression that I have-perhaps- a problem with a specific JAR or Tomcat, but I coudn't find the cause of this problem. So, can anyone help me please because I tried a loooong time with this!

Cant deploy WebService that uses MYSQL in Tomcat

This my code for webservice.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package customer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.jws.WebService;
/**
*
* #author Mihir
*/
public class Customer {
String date1;
Format formatter;
Date date = new Date();
public String feedback(String contactno,String comments,String ambience,String service,String
food,String email,String custno,String custname,String storeno,String sno)
{
formatter = new SimpleDateFormat("dd/MM/yy");
date1 = formatter.format(date);
Connection con = null;
PreparedStatement prest;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/feedback","root","root");
Statement stmt = con.createStatement();
String sql = "INSERT INTO fb(contact_no,
date,comments,ambience,service,food,email,cust_no,cust_name,store_no,s_no) " +
"VALUES ('"+contactno+"',
'"+date1+"','"+comments+"','"+ambience+"','"+service+"','"+food+"','"+email+"','"+custno+"',
'"+custname+"','"+storeno+"','"+sno+"')";
stmt.execute(sql);
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
}
Now this is what I am trying to do.
Creating folder in webapps in Tomcat with name customer_customer.
Inside that two more folder - WEB-INF META-INF
Inside META_INF context.xml with content-
Inside WEB-INF
4.a. classes/customer/Customer.class
4b. lib folder with jar -
I. webservices-api.jar
II. webservices-extra.jar
III.webservices--extra-api.jar
IV. webservices-rt.jar
V. webservices-tools.jar
VI. mysql-connector-java-5.1.18-bin.jar
4c. web.xml -
<?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">
<listener>
<listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>Customer</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Customer</servlet-name>
<url-pattern>/feedback</url-pattern>
</servlet-mapping>
</web-app>
4d. sun-jaxws.xml
<?xml version="1.0" encoding="UTF-8"?>
<endpoints version="2.0" xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime">
<endpoint implementation="ws.Customer" name="Adder" url-pattern="/feedback"/>
</endpoints>
I got it now and its working I make changes so that my package an name are different from each other and specified
#Webservice
before my class name.I already tested the Webservice and implemented on my android phone.
Thank you all for your comments.

Integrating Jetty with RESTEasy

Any links on how to integrate Jetty and RESTEasy? I am kinda stuck trying to configure RESTEasy with Jetty together....and there seems to be no credible help on the web.
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
WebAppContext context = new WebAppContext();
context.setDescriptor("../WEB-INF/web.xml");
context.setResourceBase("../src/webapp");
context.setContextPath("/");
context.setParentLoaderPriority(true);
server.setHandler(context);
server.start();
server.join();
}
My Web.xml is copied directly from:
http://docs.jboss.org/resteasy/docs/1.0.0.GA/userguide/html/Installation_Configuration.html
The error I get back is a HTTP 404 when I try to open up a link in my resource file. Everything looks reasonable on the surface, any suggestions?
My resource file looks like:
package webapp;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
#Path("/*")
public class Resource {
#GET
public String hello() {
return "hello";
}
#GET
#Path("/books")
public String getBooks() {
return "books";
}
#GET
#Path("/book/{isbn}")
public String getBook(#PathParam("isbn") String id) {
return "11123";
}
}
This is the prints that I see when Jetty starts up:
2012-04-10 09:54:27.163:INFO:oejs.Server:jetty-8.1.1.v20120215 2012-04-10 09:54:27.288:INFO:oejw.StandardDescriptorProcessor:NO JSP Support for /, did not find org.apache.jasper.servlet.JspServlet 2012-04-10 09:54:27.319:INFO:oejsh.ContextHandler:started o.e.j.w.WebAppContext{/,file:/C:/Users/xyz/Anotherproj1/src/webapp} 2012-04-10 09:54:27.319:INFO:oejsh.ContextHandler:started o.e.j.w.WebAppContext{/,file:/C:/Users/xyz/Anotherproj1/src/webapp} 2012-04-10 09:54:27.381:INFO:oejs.AbstractConnector:Started SelectChannelConnector#0.0.0.0:8080
The follwing works for me:
web.xml:
<web-app xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>resteasy.resources</param-name>
<param-value>webapp.Resource</param-value>
</context-param>
<context-param>
<param-name>javax.ws.rs.core.Application</param-name>
<param-value>webapp.MyApplicationConfig</param-value>
</context-param>
<!-- set this if you map the Resteasy servlet to something other than /*
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/resteasy</param-value>
</context-param>
-->
<!-- if you are using Spring, Seam or EJB as your component model, remove the ResourceMethodSecurityInterceptor -->
<context-param>
<param-name>resteasy.resource.method-interceptors</param-name>
<param-value>
org.jboss.resteasy.core.ResourceMethodSecurityInterceptor
</param-value>
</context-param>
<listener>
<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
With
public class MyApplicationConfig extends Application {
private static final Set<Class<?>> CLASSES;
static {
HashSet<Class<?>> tmp = new HashSet<Class<?>>();
tmp.add(Resource.class);
CLASSES = Collections.unmodifiableSet(tmp);
}
#Override
public Set<Class<?>> getClasses(){
return CLASSES;
}
}
Resource
package webapp;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
#Path("/")
#Produces("text/plain")
public class Resource {
#GET
public String hello() {
return "hello";
}
#GET
#Path("/books")
public String getBooks() {
return "books";
}
#GET
#Path("/book/{isbn}")
public String getBook(#PathParam("isbn") String id) {
return "11123";
}
}
and Main Class
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap;
public class Main {
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
WebAppContext context = new WebAppContext();
context.setDescriptor("./src/main/webapp/WEB-INF/web.xml");
context.setResourceBase("./src/main/webapp");
context.setContextPath("/");
context.setParentLoaderPriority(true);
server.setHandler(context);
server.start();
server.join();
}
}
Are you sure that #Path("/*") is correct path. Try #Path("/") maybe this * is a problem. As far as I know path expressions does not accept regexps.
EDIT
I was wrong, you can use regexps in #Path, at least RESTEasy supports that.
To get RESTEasy and Jetty to work together without a web.xml ensure you have a dependency on resteasy-servlet-initializer in your pom.xml.
This may help (JBoss RESTEasy documentation): https://docs.jboss.org/resteasy/docs/3.0.4.Final/userguide/html/Installation_Configuration.html#d4e111

Categories

Resources