Access RestWebservice by passing parameter through URL - spring

I am trying to pass parameter required in rest method via URL in Jersey+Spring.
this is my service class.
#Path("/find")
public class DownLoadService {
#Autowired
TransactionWork transactionDownload;
#POST
#Path("/bring")
public Response GetFile(String uid) {
String result = transactionDownload.BringFile(uid);
return Response.status(200).entity(result).build();
}
}
I am trying to access via URL
http://localhost:8080/ProjectName/rest/find/bring'parameter for method getFile??'
I don't know is it possible or not.
(I am using this first time may be silly question)
NOTE:I am accessing this service easily in servlet and working fine.

After waiting for long I found this way
#GET
#Path("/bring/{withUID}")
public Response GetFile(#PathParam("withUID") String uid) {
String result = transactionDownload.BringFile(uid);
return Response.status(200).entity(result).build();
}
Now I am able to access the service in this way.
http://localhost:8080/RESTfulExample/rest/my/bring/AB
^
parameter I passed to method
Ready to learn other way to do the same thing.

Related

Spring's RestTemplate: complex object to query params

I have a complex object like this:
public class ComplexObject {
private String a;
private String b;
...
private String z;
//getters and setters
}
I want to call a web service that receives all the complex object fields: http://localhost:8080/api/some_service?a=something&b=something&...&z=something
Is there any way to pass a ComplexObject to RestTemplate and have the work done automatically or I have to do the manual mapping by myself?
Thanks!
YES! there is a way to pass complete complex object to make the service call and then for sure it can be achieved automatically.
And for this you have to alter the way you send this complexObject and have to use HTTP POST (highly recommended ), as:
public HttpStatus send()
{
ComplexObject complexObj = getYourFilledObject();
ResponseEntity<HttpStatus> response = restTemplate.postForEntity(ROOT_URI, complexObj, HttpStatus.class);
return response;
}
And if not and GET is the only option then unfortunately you have to send as you’re. Because at the end of the day either you use rest templates ‘s function which intake params map or you create your own URI with params, it is the same HTTP GET and you have to achieve programmatically.
For examples & illustration you can visit here and best reference will be spring resttemplate doc

How to Forwarding Requests from a Controller to Another Controller Programmatically in Spring MVC

Nowadays, I've been making an API system and I've got stuck in a problem regarding forwarding requests.
In my API system, all of requests from users come to proxy controllers first, and then the requests are forwarded to real API versionized.
// proxy controller
#Controller
#RequestMapping("/proxy")
public class ProxyController {
private static final String VERSION = "v1";
#RequestMapping(value = "/users", method = RequestMethod.GET)
public String getUsers() {
return String.format("forward:/%s/users", VERSION);
}
}
// Real API controller
#RestController("v1UsersController")
#RequestMapping("/v1/users")
public class UsersController {
#RequestMapping(value = "/users", method = RequestMethod.GET)
public ApiResultsResponse<Users> findUsers(#RequestParam userId, ...) {
// ...
// ...
// ...
// return users found
}
I've located the proxy controller because I could easily change the real api when some case happens like upgrading version of the api.
However, because I've used forwarding with String(in this case, return String.format("forward:/%s/users", VERSION)), I'm not sure whether the forwarded real api exist or not currently.
So I'd like to be sure this by calling the real api's controller method directly. If so, when the called method doesn't exists, I can notice this with compile errors. The problem is, I gotta synchronize parameters condition of real api handler with proxy's.(It's kinda dirty works.)
Is it possible to call forwarded controller method directly with using the same HttpServletRequest object?
You could use spring HandlerInterceptorAdapter to intercept before call your controllers
Maybe this solution will help you.
#RequestMapping(value = "/users", method = RequestMethod.GET)
public void getUsers(HttpServletRequest request,HttpServletResponse response) {
String path = String.format("forward:/%s/users", VERSION);
RequestDispatcher dispatcher=request.getRequestDispatcher(path);
dispatcher.forward(request, response);
}

web api controller action methods

I am trying to get a web api call to work: I want to submit an email address and then on the server, the method will validate and return null or a message.
This is what I tried:
[Post]
public string validate(string email) {
return this._contextProvider.ValidateEmail(email);
}
However, I get this message returned to the client: No HTTP resource was found that matches the request URI 'https://localhost:44300/breeze/data/validate
The payload looks like this: {email: "Greg#gmail.com"}
The problem, it turns out, was the parameter binding.
In the Web API, binding is handling differently than MVC. By default, simple types are extracted from the URI, not the body. Complex types are extracted from the body of the message.
I then added the [FromBody] Attribute to the Action Method, and it then found the action method. But alas, the email parameter was null.
public string validate([FromBody]string email) {
return this._contextProvider.ValidateEmail(email);
}
Turns out when using this trick, the body must NOT be json, but constructed like a querystring - email=greg#gmail.com. I didn't want do do that, so ended up creating a class to accept the parameter, and that worked as expected.
public class ParameterizedAction {
public string Parameter { get; set; }
}
public string validate(ParameterizedAction arg) {
return this._contextProvider.ValidateEmail(arg.Parameter);
}
This article has more info: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection
as well as this one: http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

Return custom object AND controlling response code in JAX-RS

I'm using JAX-RS in my web application to return my own object.
I want to keep doing it, but I want to set the HTTP response code (e.g. 401 for unauthorized, etc.).
From the information I've found it seems like I have to return the type Response and not my custom object.
Is that correct?
My current code (simplified) - when MyReponse is an object that Jaxb knows how to deal with:
#POST
#Produces({MediaType.APPLICATION_XML , MediaType.APPLICATION_JSON})
public MyResponse RegisterUser (
#FormParam("userName") String userName,
#FormParam("password") String password) {
// add user logic
return new MyResponse(....<params to ctor...);
}
Yes, you are right.
You'll need to use something like:
#POST
#Produces({MediaType.APPLICATION_XML , MediaType.APPLICATION_JSON})
public Response RegisterUser (
#FormParam("userName") String userName,
#FormParam("password") String password) {
// add user logic
return Response.status(401).entity(new MyResponse(...)).build();
}
see http://jersey.java.net/nonav/documentation/latest/jax-rs.html#d4e355 (and other chapters) for additional useful information.
You can extend Response class and return your custom status when you override getStatus() method.

How do I inject something into request header for testing?

I am currently implementing SiteMinder for the site, which looks for a key called SM_USER in the request header. I retrieve it using the function below:
public string ReadUser()
{
return HttpContext.Current.Request.Headers["SM_USER"];
}
I wish to test if functionality releated to this function work; I have already tried unit testing using a mock class so I am looking to create the key SM_USER in the request header. How can I do that?
I am implementing the application with MVC3.
As long as you are using HttpContext.Current you will not be able to test it as Unit Test will not have HttpContext.Current.
Try to use an Interface with method returning string, say ReadUser(). Implement this interface in a class in your application. Use the interface variable whichever class you are using this method in. In that class' default constructor set that interface variable value to 'new' implementer class. Add an overload of the constructor which will take a parameter of type interface and set that parameter to interface variable.
Now in your UnitTest project implement same interface in another class. In this implementation you can now pass whatever mock value you want test.
public interface IReadUserInfo
{ string ReadUser(); }
public class ReadUserInfo: IReadUserInfo
{
public string ReadUser()
{
return HttpContext.Current.Request.Headers["SM_USER"];
}
}
public class UserClass
{
IReadUserInfo userinfo;
public UserClass()
{
userinfo = new ReadUserInfo();
}
public USerClass(IReadUserInfo newuserinfo)
{
userinfo = newuserinfo;
}
}
public class TestReadUserInfo : IReadUSerInfo
{
public string ReadUser()
{ return "testvalue"; }
}
If ReadUser is the only value you are using from Request header, then this approach will solve the problem. However, if you using more values from Request object, you might want to mock entire request object in similar way.

Resources