Jersey REST Service - Resource response - java

I'm executing a REST tutorial using jersey 2.26. I'm running in apache tomcat v 8.0.
I'm trying to change the response on my resource. Initially it was returning, "Got it!". Then I wanted to change it and I even tried adding a different resource with a new #PATH. Even though I changed the path annotation on my resource, changed the value of the String I'm returning and bounced the server a handfull of times, every time I navigate to this resource, it's returning "Got it!"
Why doesn't it return "Got it! This worked" since I changed the return value?
package com.demo.jersey.message.resource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* Root resource (exposed at "myresource" path)
*/
#Path("myresource")
public class MyResource {
/**
* Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
* #return String that will be returned as a text/plain response.
*/
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it! this worked";
}
}

Related

Jersey Client Posting Form Data

I'm learning about JAX-RS and Jersey. I am trying to post data to a URL however I have an issue I do not know to fix:
Form formData = new Form();
formData.param("merchant_id", mPayment.getMerchantId());
formData.param("transaction_id", mPayment.getTransactionId());
formData.param("code", mPayment.getCode());
formData.param("amount", String.valueOf(mPayment.getAmount()));
formData.param("desc", mPayment.getDesc());
formData.param("phone", mPayment.getPhone());
Response response = target.path("process").request()
.accept(MediaType.APPLICATION_JSON)
.post(Entity.form(formData));
Now everything works well when it's just a string however the server is expecting a float data type for the field amount however when I try to use it without String.valueOf() I get an error. How do I add params with different data types so I can post?
You cannot maintain the type information across the call to the server. The form data will be transferred as text with the application/x-www-form-urlencoded content type header, this is why the Form class accepts String parameter values (similarly to how you could only enter text values in a browser form).
So your code should be sufficient. At the server side, you can declare the parameter as a float and annotate it with javax.ws.rs.FormParam. If the parameter cannot be cast to the desired (float) type by the Jersey runtime, it will return a 400 BAD REQUEST.
In a nutshell:
Keep client code as it is.
Use server code similar to:
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
#Path("/service")
public class myService {
#POST
public Response addOrder(
#FormParam("merchant_id") String merchant_id,
#FormParam("amount") float amount
// more parameters
) {
return Response.ok().build();
}
}

New web service methods not being mapped on a tomcat instance on Azure

I have a web service running on tomcat 8.5, however whenever I try to update the version, the new methods do not map properly, and 404 as a result.
For example, if a prior version had a method such as host/ContextPath/HelloWorld/, that'd run completely fine, no issues there.
However if I were to add a new method, host/ContextPath/AnotherMethod/, this method would 404.
It's not a case of the newer versions aren't being run on Azure, as you can look at the deployment history and see that it's pulling the latest versions from github, and apparently deploys them successfully.
I am unsure of how to progress from here, as what I have should be working, eg the new versions are on the server, server is running and healthy etc, yet it isn't.
Additionally, by viewing what files are on the server through site\wwwroot[project files], I can actually see that the most up to date versions of the files are on the server.
However, the methods are not being exposed, so I am at a loss as to what is happening.
For example, consider the AdministrationService, which you can see the code for below:
package services;
import controllers.DatabaseController;
import controllers.EmailController;
import controllers.ProgrammeController;
import entities.Programme;
import java.io.InputStream;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonException;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import static javax.ws.rs.HttpMethod.POST;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import utilities.SQLQuery;
#Path("/Admin")
public class AdministrationService {
ProgrammeController pc = new ProgrammeController();
/**
* A simple method for testing if our service is online.
* -> GET /API/Admin/Health
* If true is returned, we will have configured our service properly.
* #return
*/
#GET
#Path("/Health")
public Boolean getHealthy(){
return true;
}
#GET
#Path("/TestEmail")
public void testEmail(#QueryParam("target")String target){
EmailController ec = EmailController.getInstance();
String messageBody = "Hello world";
String recipient = target;
String messageSubject = "Test email";
ec.sendEmail(recipient, messageBody, messageSubject);
}
}
The /Health method is an old method. It runs just fine if I access it through
myazurehost.net/ContextPath/Admin/Health
However if I attempt to do the same with
myazurehost.net/ContextPath/Admin/TestEmail?target=testemail#gmail.com
I receive a 404 error. It's not a case of the method being incorrectly called, as the error is a 404, not a 400 bad request, 405 wrong type etc. As far as the server is concerned, the method does not exist and it's baffling.
I've tried server reboots, reinitialising the project, to no avail. Any help is greatly appreciated.

Cannot invoke webservice method in Jersey/java

I have made a barebones hello world webservice using netbeans and jersey.
My problem is when I deploy my webservice to the server (I'm using glass fish) It takes me to the index page, but I cannot invoke the method I created in the java class.
The domain my glass fish service is using is
http://localhost:8080/HelloWorldApp/
To invoke my method (from what ive read) this is the way to do it:
http://localhost:8080/HelloWorldApp/helloworld
However this gives me a 404. Ive followed many examples but cant seem to invoke the method in my web browser.
I can however invoke the method when I click test RESTful Webservices in netbeans.
Here is how I Defined the Method:
package HelloWorldResource;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/helloworld")
public class Hellworld {
#Context
private UriInfo context;
/**
* Creates a new instance of Hellworld
*/
public Hellworld() {
}
/**
* Retrieves representation of an instance of HelloWorldResource.Hellworld
* #return an instance of java.lang.String
*/
#GET
#Produces(MediaType.TEXT_HTML)
public String getHtml() {
//TODO return proper representation object
return "<HTML>Hello</HTML>";
}
/**
* PUT method for updating or creating an instance of Hellworld
* #param content representation for the resource
*/
#PUT
#Consumes(MediaType.TEXT_HTML)
public void putHtml(String content) {
}
I looked up another tutorial and found some information. Theres a java class that's created called "ApplicationConfig.java" that has this tag: #javax.ws.rs.ApplicationPath("webresources")
so I had to invoke the method using this uri http://localhost:8080/HelloWorldApp/webresources/helloworld
Please share you web.xml and resource config implementation. If you have any custom resource config implementation, then your resource file has to be registered in the resource config implementation. For details please refer http://cloudskol.com/index.php/2015/09/22/simple-get-method-implementation-in-restful-java/

Spring/Java web: how can I know a request is a form post?

I am doing a Spring website. The website has many pages visitors can get. It also allows visitors to fill and submit a few forms.
I would like to use a Spring interceptor (as a central place) to examine each web request from visitors. How can I decide whether a web request is a get request or a form post?
Thanks and regards!
You can use getMethod() as follows -
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#Component
public class MyInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("Request Intercepted for : "
+ request.getRequestURI());
System.out.println("Request type : "
+ request.getMethod());
return true;
}
}
Form documentation
java.lang.String getMethod()
Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. Same as the value of the CGI variable REQUEST_METHOD.
Returns:
a String specifying the name of the method with which this request was made

JAX-RS, GlassFish, Eclipse. A simple web service doesn't work

I am trying to run a simple "Hello World" RESTful web service on my machine. I use Eclipse Kepler and GlassFish 4.0. I am able to deploy the service and I see it on the admin pages of GlassFish but when I try to access to it I get the following error: "HTTP Status 404 - Not Found".
Herein the code of the simple service:
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
#Path("hello")
public class HelloRest {
#SuppressWarnings("unused")
#Context
private UriInfo context;
/**
* Default constructor.
*/
public HelloRest() {
// TODO Auto-generated constructor stub
}
/**
* Retrieves representation of an instance of HelloRest
* #return an instance of String
*/
#GET
#Produces("application/xml")
public String getXml() {
// TODO return proper representation object
return "<greeting>Hello REST</greeting>";
}
/**
* PUT method for updating or creating an instance of HelloRest
* #param content representation for the resource
* #return an HTTP response with content of the updated or created resource.
*/
#PUT
#Consumes("application/xml")
public void putXml(String content) {
}
}
In order to access to the service I try the following URL: http://127.0.0.1:8080/hello-rest/hello, where hello-rest is the name of the Eclipse project and the root path suggested by the admin page of GlassFish.
Your code seems to be ok, so the problem most likely is that you have not defined the base url for your service. You need to tell JAX-RS (Jersey is the implementation in GlassFish) which url pattern it must intercept as your endpoint (base url).
One way of achieving this is using an Application Class which can be added to any package in the project (you could alternatively define the necessary in a web.xml file which I won't cover). The following is the code:
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("your-base-url")
public class ApplicationConfig extends Application {
}
You use the #ApplicationPath annotation to define your base url.
You can then access your service at http://127.0.0.1:8080/hello-rest/your-base-url/hello
#GET
#Produces("application/xml")
#path("/getxml")
public String getXml() {
// TODO return proper representation object
return "<greeting>Hello REST</greeting>";
}
Your url should be http://localhost:8080/hello-rest/hello/getxml
You should mention the path at the method level , so the request is redirected to appropriate method.
You can use SOAPUI to test the service. Please make sure you have choose the correct method.
Method as 'GET'
End point as 'hostname:8080'
Resource as 'hello-rest/hello/getxml'
If you face the same issue. Please attach more logs / exception in tomcat console.

Categories

Resources