Unable to invoke rest web service - rest

I am just trying out a sample rest service example. My rest service class is :
#Path("oauth")
public class OauthClass {
private static Map<String, OauthBean> oAuthBeanMap = new HashMap<String, OauthBean>();
static {
OauthBean oAuthBean = new OauthBean();
oAuthBean.setAccess_token(String.valueOf(Math.random()));
oAuthBean.setToken_type("bearer");
oAuthBean.setRefresh_token(String.valueOf(Math.random()));
oAuthBean.setExpires_in("44517");
oAuthBeanMap.put(oAuthBean.getToken_type(), oAuthBean);
}
#GET
#Path("/token?client_id={clntID}")
#Produces("application/json")
public OauthBean getOAuthJSON(#PathParam("clntID") String clientID) {
System.out.println(clientID + " Secret ");
System.out.println("oAuthBeanMap.get(\"bearer\") :P " + oAuthBeanMap.get("bearer"));
return oAuthBeanMap.get("bearer");
}
}
Now when i trry to invoke this url :
http://localhost:7070/RESTfulWS/rest/oauth/token?client_id=clnt001
I get a 405 error.Method not allowed
Below 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>RESTfulWS</display-name>
<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.packages</param-name>
<param-value>com.eviac.blog.restws</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>
I am using jersey 1.18.
What am i doing wrong? Looking forward tyo your solutions.

Reading through your code, I think you should write #Path("/token") instead of #Path("/token?client_id={clntID}").
Besides, as you yourself noted, you should use QueryParam instead of PathParam

Related

how do I get a root path redirect to not respond to all requests in eclipse jetty?

I have a jetty servlet set of pages all set up and working.
to get to the landing page, you have to enter the full url http://127.0.0.1/console/console.jsp
everything is fine for my context "console".
I wanted to add a handler for the root url, so I could just put in a host and it would redirect to the above url.
I got that working, except it seems that every request comes through my root path handler as well and it messes up all the other requests to the real jsp pages.
How do I keep it from doing that, or what do I do differently?
my 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">
<servlet>
<description></description>
<servlet-name>console</servlet-name>
<servlet-class>net.console.Consoleservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>console</servlet-name>
<url-pattern>/console</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<servlet-name>redirect</servlet-name>
<servlet-class>net.console.Redirectservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>redirect</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
slimmed down version of my redirect servlet...
public class Redirectservlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet
{
static final long serialVersionUID = 1L;
public Redirectservlet()
{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
String redirect_path = "http://127.0.0.1/console/console.jsp";
response.sendRedirect(redirect_path);
}
catch (Exception e)
{
}
}
Try using welcome-files instead of your RedirectServlet, in your WEB-INF/web.xml...
<web-app ...>
<welcome-file-list>
<welcome-file>console/console.jsp</welcome-file>
</welcome-file-list>
... other entries
</web-app>
If that doesn't work, consider making that a RedirectFilter instead, and only sending a redirect if the request.getRequestURI() is only in a list of exact request URI string matches that should redirect.

JBoss AS 5.1.0 GA resteasy application - force login on every request

I'm using Resteasy 3.0.11.Final with JBoss AS 5.1.0 GA. I have a defined REST web service. The whole service is secured with BASIC authentication with a custom security domain. When I use Postman to send a request (#1) with BASIC authentication for user A, JBoss AS invokes a login module for the user, and then calls a local ejb (looked up with initial context) method with caller principal A. Immidiately after I send another request (#2) with BASIC authentication for user B, in this case JBoss AS does not invoke a login module and calls a local ejb method with caller principal A again. After some time sending a request with user B yields the desired result (local ejb method call with caller principal B). I'm not sure what causes the problem, the Resteasy service configuration / session handling or the JBoss AS security domain configuration which is responsible for login modules (subject timeout? lack of logout after method being called?)? Basically I want to configure Resteasy to force a new session with a new login module invocation for the local ejb method call for every rest request.
web.xml:
<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>my-app</display-name>
<context-param>
<param-name>resteasy.providers</param-name>
<param-value>org.jboss.resteasy.plugins.providers.jackson.ResteasyJackson2Provider,com.mycompany.infrastructure.ExceptionMapper</param-value>
</context-param>
<context-param>
<param-name>resteasy.resources</param-name>
<param-value>com.mycompany.resource.Resource</param-value>
</context-param>
<listener>
<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<servlet>
<servlet-name>my-app-resteasy-servlet</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
<init-param>
<param-name>javax.ws.rs.core.Application</param-name>
<param-value>com.mycompany.application.Application</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>my-app-resteasy-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>my-app-resteasy-servlet</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>User</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>MyRealm</realm-name>
</login-config>
<security-role>
<role-name>User</role-name>
</security-role>
</web-app>
jboss-web.xml
<jboss-web>
<context-root>/path</context-root>
<security-domain>java:/jaas/MyRealm</security-domain>
</jboss-web>
beans.xml
<beans
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/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
login-config.xml for MyRealm
<application-policy name="MyRealm">
<authentication>
<login-module code="com.mycompany.security.UsernamePasswordLoginModuleImpl"
flag="required">
<module-option name="password-stacking">useFirstPass</module-option>
</login-module>
</authentication>
</application-policy>
Resource.java
#Path("/resource")
#Stateless
public class Resource {
#POST
#Path("/execute")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public ResponseDTO execute(RequestDTO dto) {
try {
// code
} catch (Exception exception) {
// handle
}
}
}
I found a very rough solution:
Resource.java:
#Path("/resource")
#Stateless
public class Resource {
#POST
#Path("/execute")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public ResponseDTO execute(RequestDTO dto, #Context HttpServletRequest request) {
try {
// code
} catch (Exception exception) {
// handle
} finally {
if (request != null) {
request.getSession().invalidate();
}
}
}
}
or the same result, different implementation (without repeating the same code in every method in a resource, obviously):
SessionInvalidatorFilter.java
public class SessionInvalidatorFilter implements ContainerResponseFilter {
#Context
private HttpServletRequest request;
public void filter(ContainerRequestContext requestCtx, ContainerResponseContext responseCtx) throws IOException {
if ((request != null) && (request.getSession() != null)) {
request.getSession().invalidate();
}
}
}
web.xml
<context-param>
<param-name>resteasy.providers</param-name>
<param-value>com.mycompany.infrastructure.filter.SessionInvalidatorFilter</param-value>
</context-param>

Jersey, Tomcat: The requested resource is not available error

I have been working towards getting a RESTful service set up using Jersey and Tomcat in RAD 8.5. I have looked at tons of stackoverflow questions related to my error with none of them working. There are no errors in my console.
When I just type: http://localhost:8080/, I get the Apache homepage, so the server is working, but http://localhost:8080/jersey/rest/hello or http://localhost:8080/jersey/WEB-INF/classes/jersey/Hello.java
does not work.
Here is the error: (with my library of jars on the side)
Here is my Hello.java
package jersey;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/hello")
public class Hello {
// This method is called if TEXT_PLAIN is request
#GET
#Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
return "Hello Jersey";
}
// This method is called if XML is request
#GET
#Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}
#GET
#Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello Jersey" + "</title>"
+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
}
}
And my web.xml
<servlet>
<servlet-name>Jersey REST Service</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</param-value>
</init-param>
</servlet>
Versions:
Tomcat: 7.0.663
RAD: 8.5
Jersey: 2.19
Thanks,
In Response to Maciej
This worked! I needed to add <servlet-mapping> with url pattern of /*. Then use http://localhost:8080/jersey/hello, I got a response from the server!
<?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="jersey" version="2.5">
<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>jersey</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
You are deploying a compiled code to Tomcat, so you won't be able to access the *.java resources.
Annotation #Path("/hello") indicates the path at which resource is available.
It is set to: base URL + /your_path. The base URL is based on your application name, the servlet and the URL pattern from the 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="jersey" version="2.5">
<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>jersey</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
Also replace #Produces annotation to #Consumes:
package jersey;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
#Path("/hello")
public class Hello {
// This method is called if TEXT_PLAIN is request
#GET
#Consumes(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
return "Hello Jersey";
}
// This method is called if XML is request
#GET
#Consumes(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}
#GET
#Consumes(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello Jersey" + "</title>"
+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
}
}
Try: http://localhost:8080/jersey/hello
Make sure that you have kept all the required Jersey Jar files in "WEB-INF -> lib" folder
Even after following the steps as mentioned by Maciej, if it says 404 resource not found, Mention the subclass that implements Application class and write it within init-param tag in web.xml
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>packagename.java_class_name</param-value>
</init-param>
This worked for me.
This problem solved by these steps
1. Select all files in lib folder and right click on it
2. Then click add to build path

Spring rest call not working

I had written a very small rest service. When I am trying through the rest cilent, I am getting the error as "method not supported". Can anybody, please suggest me on this.
**controller class**
#Controller
#RequestMapping("/movie")
public class MovieController {
#RequestMapping(value="/{name}", method = RequestMethod.PUT, consumes="application/json")
public #ResponseBody Student getMovie(#PathVariable String name, ModelMap model, #RequestBody Student student, HttpSession session) {
Map<Integer, Student> empData = new HashMap<Integer, Student>();
empData.put(1, student);
return student;
}
}
**Request I am sending throught Rest DHC Client**
URL: http://localhost:8081/SpringMVC/movie/test
method selected: PUT
Headers: Content-Type:application/json
Body: {
"userId":"21",
"firstName":"srinu",
"lastName":"nivas"
}
I use only Jersey to do what you want.
My web.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" 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_3_0.xsd">
<display-name>appName</display-name>
<filter>
<filter-name>jersey</filter-name>
<filter-class>com.sun.jersey.spi.container.servlet.ServletContainer</filter-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.appName.rest</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.property.JSPTemplatesBasePath</param-name>
<param-value>/Pages/</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name>
<param-value>/(resources|(Pages))/.*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>jersey</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
And in the rest class i return a Viewable:
My rest class:
#GET
#Path("/PathToAccessPage")
#Produces(MediaType.TEXT_HTML)
public Viewable GetMyClassPage(#Context HttpServletRequest request, #Context UriInfo ui, #Context HttpHeaders hh) {
try {
MyClass myClass = getMyClass();
return new Viewable("/page", myClass);
}
catch (Exception ex) {
return new Viewable("/error", "Error processing request: " + ex.getMessage());
}
}
Hope you help!
Finally, I got the solution. I didn't import the below two jars.
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
As I am using spring MVC and as you can see in the above code, I am giving as consumes=application/json, I thought springMVC will take care of that. It's my mistake and also, I think the error which was renedered by spring, should be something specific to this. Anyway, got the solution. Thanks all for the help.

AngularJS RESTful JSON requests with ngResource and Restangular

i have some problems with angularJS and REST requests / responses. Since three weeks i playing with AngularJS and now i would like do some cool stuff.
First i created a simple jersey REST service, that returns a simple list.
#Path("/hello")
public class Hello {
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Medication> sayJsonHello() {
List<Object1> objs = new ArrayList<Object1>();
objs.add(new Object1("1", "HUHU"));
objs.add(new Object1("2", "HUHU 2"));
return objs;
}
}
as you can see, there is no big magic.
Here my web.xml file, to configure Jersey:
<?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_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Jersey REST Example</display-name>
<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.packages</param-name>
<param-value>examples</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.feature.DisableWADL</param-name>
<param-value>true</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>
After some tests, the service will return a simple JSON list:
[
{
"id": "1",
"name": "HUHU"
},
{
"id": "2",
"name": "HUHU 2"
}
]
I deploying the webservice into a Tomcat7 instance. Now i would like to get this data into my webapplication. After reading some tutorials and example i starting to create few implementations.
After starting create my first service, i and this code-snipped into my app.js:
app.config(['$httpProvider', function ($httpProvider) {
delete $httpProvider.defaults.headers.common["X-Requested-With"];
}]);
this will remove X-Request-With request-header from the header defauls.
1. Request via Service and ngResource
angular.module('helloService', ['ngResource']).
factory('hService', function ($resource) {
return $resource('http://localhost\\:8180/rest/hello',
{callback: 'JSON_CALLBACK'}, {
get: {method: 'GET', headers: [
{'Content-Type': 'application/json'},
{'Accept': 'application/json'}
]}
});
});
MyController:
function MyController($scope, hService) {
hService.get(function(result){
alert(" Result of helloService");
}, function error(response){
alert(" Error during helloService "+response.status);
});
}
if i try to load data, the get functin will always return an error and the status is always 0.
2. Trying with Restangular
After get how to use Restangular i starting to configured Restangular:
app.config(function (RestangularProvider) {
RestangularProvider.setBaseUrl('http://localhost\\:8180/rest');
});
and also add the RestangularProvider to my angular.module:
var app = angular.module("html5App", ['helloService', 'restangular', 'ngResource']);
MyController:
function MyRestangularCtr($scope, Restangular){
var all = Restangular.all('hello');
$scope.allObjects = all.getList();
all.getList().then(function (hellos) {
console.log("Result "+ hellos);
}, function errorCallback(response) {
alert("Oops error from server :( status" + response.status);
console.log("status: "+response);
});
}
Here the same: No Data, Status 0. I have no idea, why i dont get any data from my service. Additional i getting sometimes this error: "Error: $digest already in progress". Im not sure, where the problem is. If the jersey service i wrong or bad or my beginner JavaScript is wrong.
First Solution
Client Side
The Angular request should look like this:
$scope.myData = $resource('http://localhost\\:8180/rest/:action',
{action: 'hello', callback:'JSON_CALLBACK'},
{get: {method: 'JSONP'}});
$scope.datas = $scope.myData.get();
The method need to JSONP (GET will still not working ( no repsonse data because CORPS?)
Service Side
Important here is, that the server also response with a JSONP fomat and can handle callback requests.
#GET
#Produces("application/x-javascript")
public JSONWithPadding sayJsonHello(#QueryParam("callback") String callback) {
MyObjectList obList= new MyObjectList ();
obList.getObjs().add(new MyObject(1, "HUHU"));
obList.getObjs().add(new MyObject(2, "HUHU 2"));
return new JSONWithPadding(obList, callback);
}
Still unclear
Is there any way to return normal json object from server to client?
Shouldn't be the first parameter of you controller be $scope? Maybe this is the issue?
function MyController($scope, hService) {