Calling Spring Rest service from c++ or Ruby - java

I am learning Spring Rest services, I have question regarding Spring rest services
Is it possible to call Spring Rest service from other language like c++ or Ruby, where c++ or Ruby will act as Client and Spring Rest service as service or resource provider.
If it's possible can some one explain simple, detailed manner with example.
The reason of asking the question, if we develop a web service using Jax-ws, the interoperability will happen across the technologies like calling Java based web service calling from C++ or and vice versa, can same thing happen using Rest service which is developed in Spring Rest or using Jersey api framework.

A REST call is just an http call. The service doesn't care what language the client is coded in - could be a browser, a mobile phone, written in c++, java, c, objective-c, it doesn't matter.
Typically if you have object data to pass from the client to the service, you would encode it in JSON or XML.

Yes, it is possible. The key of course is Serializing/Deserializing Data. As long as your Rest service accepts serialized data as input, and returns serialized data as output.
For Example, lets say you have an endpoint http://www.example.com/public-api/foo, with acceptable method GET (it provides data).
In Spring, you have a resource named Foo.java, that takes the following form
class Foo implements Serializable {
private static long serialVersionUID = -1L;
private String someProperty;
public Foo() {
...
}
public String getSomeProperty() {
return this.someProperty;
}
public void setSomeProperty(String someProperty) {
this.someProperty = someProperty;
}
}
With the following Controller
#Controller
#RequestMapping(value={"/"})
class FooController {
#RequestMapping(value={"/foo"}, method={RequestMethod.GET})
public HttpEntity<Foo> foo() {
...
Foo foo = new Foo();
...
return new ResponseEntity<ResourceSupport>(foo, HttpStatus.OK);
}
}
When you access this in your browser, it will return the following text
{
"_self": "http://www.example.com/public-api/foo",
"someProperty": ...
}
This output (in JSON), can be parsed in Ruby and C++ (or any language really) quite simply.
Inputting is the same way. Instead of parsing JSON, you would just POST or PUT JSON data that conforms to whatever resource you're trying to input. To POST or PUT a new Foo object, you just POST or PUT JSON data with the appropriate Properties.

Related

How to create a java client for a Spring service?

I have a service definition using Spring annotations. Example (source):
#RequestMapping(value = "/ex/foos/{id}", method = GET)
#ResponseBody
public String getFoosBySimplePathWithPathVariable(
#PathVariable("id") long id) {
return "Get a specific Foo with id=" + id;
}
The question is whether spring (or another library) can auto-create a remote implementation (client) of the same API without the need to manually type paths, method type, param names, etc. (like needed when using RestTemplate)?
Example of an such a client usage:
FooClient fooClient = new FooClient("http://localhost:8080");
String foo = fooClient.getFoosBySimplePathWithPathVariable(3l);
How can I get to such a client "generated" implementation"?
You are probably looking for Feign Client. It does everything you need: calling one service via HTTP is similar to calling method of Java interface. But to make it work you need Spring Cloud, standard Spring framework doesn't have this feature yet.
You can generate it using Swagger Editor. You shoud just define the path of the resources and then it'll generate for you the client for almost any language of your choice

Android Json Post to ServiceStack web service

Good morning all,
I am following this json post to server tutorial, , which is so far working very well, until I hit an issue saving the post to a c# service stack web service.
When I debug the json = jsonObject.toString(); it returns the following valid json.
{"name":"Test Name","country":"Test Country","twitter":"Test Twitter"}
As a general test, my web service looks like the following.
public object Any(String jsonString)
{
return jsonString;
}
But the response that I get back strips the " out of the string.
{name:Test Name,country:Test Country,twitter:Test Twitter}
With my limited understand of JAVA currently, I am guessing that the tutorial is correct and works fine, but the c# method just will not accept the json string correctly?
Thank you
You should only use Request DTO's as the argument for ServiceStack Services (i.e. never Strings), e.g:
public class MyRequest
{
public string Name { get; set ;}
public string Country { get; set ;}
public string Twitter { get; set ;}
}
public object Any(MyRequest request)
{
return request;
}
Returning a POCO enables ServiceStack to provide automatic Content Negotiation for your Response DTO's.
But returning a raw string in a ServiceStack Service gets written as-is, i.e. ServiceStack doesn't apply any further processing to string responses.
Java Add ServiceStack Reference for Android
If you're looking to invoke ServiceStack Services from Android you should consider Java Add ServiceStack Reference which enables a typed end-to-end API for consuming ServiceStack Services from Java/Android.

A message body writer for Java type, class myPackage.Sample, and MIME media type, application/xml, was not found

I am using Jersey RESTful webservices. I wrote client as below but it throws above exception which i mentioned in the title.
public class MyRestClient {
public static void main(String[] args) {
Client client = Client.create();
WebResource resource = client.resource("http://localhost:8080/myapp/rest/a/update/123");
Sample b1 = new Sample("debris");
ClientResponse response = resource.type(MediaType.APPLICATION_XML).put(ClientResponse.class, b1);
}
}
Someone told to annotate Sample class with #XmlRootElement. But i cannot do it since Sample is generated by third party. Any help ?
This is a little difficult to answer without seeing your REST service class, but I'm guessing you're trying to consume your data as a Sample object in your service, as so:
#PUT
public Response updateSample(Sample sample) {
...
But this relies on Jersey being able to automatically marshall your XML data into a Sample object, which would require the JAXB annotations on the Sample class, as you pointed out, and since those are missing you are getting the error you describe.
instead, you can consume it as a String in your service, like so:
#PUT
public Response updateSample(String sampleStr) {
...
But now you're responsible for parsing your sampleStr data as xml and converting it into a Sample object (which is not necessarily a bad thing). But, since the Sample class is not annotated for XML, Jersey won't even be able to convert it into XML for your client to send.
See this article for more information on different ways to transfer data back and forth with Jersey REST services: http://usna86-techbits.blogspot.com/2013/08/restful-java-web-service-marshalling.html
You might have an easier time processing it manually on the server if you pass your data as JSON. Look at the JUnit test class towards the bottom of that article for ideas on how to do that.
Please include your service class if you need more assistance.

Can I add REST to my existing BlazeDS spring webservice?

I have existing blazeDS web-services which need to be preserved as is for various legacy reasons.
I now have the need to expose the same functional services via a rest api and marshall the previous binary VOs via json.
I want to know if I can somehow use both #RemotingDestination and #RequestMapping at the same time on the same class? Have it cater to both request types?
Thanks
The easiest way to expose the same functionality to both REST and Blaze is to create a wrapper methods for the REST endpoint and have it proxy through to the original Blaze exposed method.
Simple Example assuming a simple GET:
#Service("userService")
#RemotingDestination(channels={"my-amf","my-secure-amf"})
public class UserService {
#RemotingExclude
#RequestMapping("/user/{id}", method=RequestMethod.GET)
public String getUserByIdRest(#PathVariable String id) {
return this.getUserById(id);
}
#RemotingInclude
public String getUserById(String id) {
//..
return id;
}
}

How to expose services written in Java thru REST as well as locally?

I want to create a new system that will be built completely using services. I want to expose these services thru REST for client applications. But for performance reasons, I also want to make sure that other services can call a given service using local calls without paying the penalty of a remote call. Is there a framework that can help me do that.
Well, the way we have implemented this is by using something like Spring MVC where the controller just calls out to a Service class - our notion of Model. The Controller thus acts as "exposing the services" as RESTful services. The rest of the codebase accesses these Services just like any other object. Since we use spring, we leverage the IOC massively.
For example, we would have something like:
public class BillingService {
public void doSomething(String someParam) {}
}
public class BillingController {
#Autowired private BillingService billingService;
public void doSomething(#RequestParam String someParam) {
billingService.doSomething(someParam);
}
}
In the above examples, the annotations are all from Spring, but you get the picture. Any other class which wants to access the BillingService method, they can do so just by accessing that class's method.
I am not sure of any framework which is targeted at exactly this problem, but my guess is, you do not need one.

Categories

Resources