Cloud foundry service broker - implementing REST endpoints - java

I have a general question on a topic I am starting to learn, but having difficulty imagining the specific implementations for.
I want to implement a service broker for Cloud Foundry. The service broker API is as follows:
http://docs.cloudfoundry.org/services/api.html
I'm new to web programming. I have worked with web applications where I publish html files which reference servlets. But I'm not sure how one goes about implementing, for example:
Route
GET /v2/catalog
I was wondering if someone could give a high level rundown of what is involved in doing this. How do I implement a "path" like this? Let's say I wrote a servlet which hangs around at site.com/Servlet. The service broker will call site.com/Servlet/v2/catalog. How would my Servlet understand this? Would this URI even direct to my Servlet as written? I'm using Liberty (Websphere), but any answer would be useful.

I suggest using the Spring framework - website at https://spring.io/. It might take a bit of learning to understand what Spring is (it has many components that do different things), but Spring provides tools to make writing REST APIs very easy. Spring is well documented, has tons of users, and is quite modern.
For a REST API in Spring, you'd define a "Controller" class that controls incoming HTTP calls to the port you program is listening on.
For your concerns about how your programs understands a GET call to a particular endpoint - Spring provides the #RequestMapping annotation to do exactly this task. Within a class you've annotated with #Controller, you will have the #RequestMapping annotation over a method like this:
#Controller
public class CloudFoundryController {
...
#RequestMapping(value = {"/servlet/v2/catalog"}, method = RequestMethod.GET
public HttpResponse getV2Catalogue() {
...
}
}
When this application detects an HTTP GET request with "/servlet/v2/catalog" as the URL endpoint, then Spring will ensure that the getV2Catalogue() method is called. When the method returns, Spring sends back, over the network, an object of whatever type you've defined in the method header as an http response.
Building a REST service with Spring: https://spring.io/guides/gs/rest-service/

Related

How to expose the business logic as a RESTful web service to be consumed by a mobile application?

I am working on the server side of a mobile application. One of the requirements I have is to implement the server using Java EE, JPA, EJB, and JSON.
I am new to Java EE but I did some reading and so far managed to build the business logic by implementing the Pojos and the EJBs of the project.
Where I am encountering difficulties is in figuring out how to expose my EJBs as a RESTful web service that can be consumed by the client side of the application. I could find some documentation and tutorials but all of it was related to building a backend for a website as opposed to mobile.
What are the best practices in exposing the business logic as a RESTful web service to a mobile application in a Java EE environment?
I'm not sure what your app server is but with JavaEE 6 and 7, you can do this fairly easily. Take a look at this tutorial for a good starting point. In general, a simple service would look something like:
#Path("/login")
public class LoginService {
#Consumes({MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_JSON})
#POST
public Response login(LoginRequest loginRequest) throws Exception {
// your code
}
where LoginRequest in this case is simple Java POJO that has an equivalent in the JavaScript world.
Note that it doesn't matter what the client side is - the server just wants the JSON encoded object to come in and it can be a browser or a native mobile app.
A bit of an issue is how to initialize your app servers underlying Rest framework. Some use web.xml, some use a specially annotated class. That is a bit of a different question - let us know which app server you're using.
You can take a look at this sample https://github.com/AdamBien/airhacks/tree/master/javaee-sample .
This class is all that you need to bootstrap your rest application: https://github.com/AdamBien/airhacks/blob/master/javaee-sample/src/main/java/com/airhacks/JAXRSConfiguration.java
and this one expose a rest resource using a stateless EJB:
https://github.com/AdamBien/airhacks/blob/master/javaee-sample/src/main/java/com/airhacks/messaging/boundary/MessagesResource.java

Java web service architecture with REST

I am designing a Java web application that will be deployed to the Wildfly or Tomcat (not decided yet).
Basically it's about the offline java application that needs a REST interface for communication (to accept JSON data). The idea is that application runs all the time and processes the requests stored in redis cache (where the received JSON data is stored).
I used the Spring MVC framework for a web site in the past but I don't need the MVC pattern for the REST interface.
Is there a way you can point me to for using a Spring framework (or some other Java framework) to add the capability to recieve a POST requests to the existing offline application? Or it will be better to just write the REST service that will use the same cache as the existing application?
To illustrate my question I am attaching the simplified diagram of the architecture I am looking for:
As soon as you speak of receiving a POST request, you are automatically referring to a HTTP server.
The question is just whether that server is running as a service, or on-demand.
Is there a way you can point me to for using a Spring framework (or some other Java framework) to add the capability to recieve a POST requests to the existing offline application?
Not without introducing some sort of HTTP container, no.
Or it will be better to just write the REST service that will use the same cache as the existing application?
Yes, exactly. And as another mentioned, personally I'd stick with Spring MVC. But Jersey should also work very well for you for your usecase.
I think you should use any light ESB, like Camel, Mule or Spring Integration. If you have already worked with Spring probably the latter will be the easiest for you.
The purpose of this kind of apps is to facilitate the task of communicating anything with anything (on this case, an HTTP endpoint with your offline app).
Take a look at this:
https://www.google.ie/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=spring%20integration%20http-inbound
You can use Spring MVC for that.
The Model are your domain classes, the View is JSON in this case, and the Controllers handle the requests to perform logic operations, business as usual.
You can also take advantage of Spring's #RestController annotation to quickly create your endpoints, like in this java example:
#RestController
public class MovieController {
#Autowired
private MovieRepository movieRepository;
#RequestMapping(value = "/movies/{search}", method = RequestMethod.GET)
public List<Movie> findMovies(#PathVariable String search) {
return movieRepository.findByName(search);
}
#RequestMapping(value = "/movies", method = RequestMethod.POST)
public void postMovie(#RequestBody Movie movie) {
movieRepository.save(movie);
}
}
Answers from Andres, ESala and kervin pointed me to the right direction but the solution I found most suitable was:
implementation of REST services using Spring MVC and
transformation of the main process from the existing application to the Spring scheduled task.

How to mix spring-data-rest with spring websocket into a single implementation

I'd like to synchronize the state to all the clients interested in particular entity changes. So I'd like to achieve something like:
exposing CRUD API on entity (via HTTP/REST and websockets)
and routing the response (of the modifying calls) to websockets topic
So technically, I'd be interested in ideas to mix spring-data-rest with spring websockets implementation to achieve something like spring-data-websocket.
There are a two solutions coming to my mind, and in fact both would be:
spring-data-rest to expose my entities via REST/HTTP API
websocket controllers (used for the modification calls on entities)
The websocket controllers would look like this:
#Controller
public class EntityAWebSocketController {
#MessageMapping("/EntityA/update")
#SendTo("/topic/EntityA/update")
public EntityA update(EntityA entityA) throws Exception {
// persist,....
return entityA;
}
}
Scenario 1: Websocket API called from REST/HTTP API
Rules:
client request is always REST/HTTP API
response is REST/HTTP API for all the operations
moreover for modifying operations the websocket message comes as well
Technically, could be achieved, by:
calling the websocket controllers from the spring-rest-data events (namely in the AfterCreateEvent, AfterSaveEvent, AfterLinkSaveEvent, AfterDeleteEvent)
Still the solution seems quite sick to me, as I'd need to go for:
client A --HTTP request--> Server (spring-data-rest controller)
Server (AfterXXXEvent in the spring-data-rest controller) --websocket message--> Spring websocket controller
Spring websocket controller --websocket message via topic--> all Clients interested in the topic
Server (spring-data-rest controller) --HTTP response--> client A
Scenario 2: Websocket API independent from REST API
Rules:
client request is REST/HTTP API for non-modifying operations only
response is REST/HTTP API for non-modifying operations only
client sends websocket message for all the modifying operations
websocket message is sent to client for all the modifying operations only
Well, if no other ideas come up, I'd go for the later one, but still, it would be great if I could have somehow generated C(R)UD methods exposed via websockets as well, something like spring-data-websockets and handle only the routes in my implementation.
As I feel like I'd have to manually expose (via *WebSocketControllers) all the CUD methods for all my entities. And I might be too lazy for that.
Ideas?
Scenario 2 talks about, in the last step, a single client.But I thought your requirement was for a topic since you wanted multiple clients.
If I wanted to complete 2 for your stated requirement, then you might want to maintain a list of clients and implement your own queue or use a ForkJoinPool to message all your clients listening in on your WebSockets. Having said that, A topic is definitely more elegant here but overall looks too complicated with different interfaces
For all messages from client to server, just go with a simple wire protocol and use a collection to parameterize, it could be
RParam1.......
At the server, you need a controller to map these to different requests(and operations). Somehow does not look like too much work.
Hope this helps.
The same architecture has bugged my mind for a while now and it will be a long story if I want to mention all the drawbacks and advantages of it so let me jump into the implementation.
The second scenario is valid, but as you mentioned its better to perform the crud actions on same websocket session. This shall remove the need for HTTP handshakes on every request, and reduces the body size of messages, therefore you will have better latency. Meanwhile, you already have a persisting connection to a server, so why not make good use out of it?
I searched around for a while and after 6 years from your question, I still couldn't find any websocket protocols that can make this happen, so I decided to work on that by myself cause I needed it for another dummy project.
Another advantage of such protocol could be that it doesn't require much changes to your already written controllers. So it should be able to support Spring Framework (for example) annotations and make websocket endpoints out of it.
The hard part about implementing such protocol in another framework like spring is that as its not nice to create ServletRequest and ServletResponse and convert them to your own websocket protocol, you loose some advantages. For example, any http filter you have written in your application till that moment, will be meaningless because its not really easy to pass your websocket messages through those filters.
About the protocol itself: I decided everything to be passed through json format, alongside a unique id for each request so we can map callbacks on client side to the request id. And of course there is a filter chain to add your filters to it.
Another hard to deal thing here is Spring Security as that too works like http filters in some cases. In my own lib I could finally handle annotations like #PreAuthorize but if you are using antMatchers in your HTTP Security Config, it would be a problem.
Therefore, creating websocket adapter to call http controllers will have many drawbacks.
You can check out the project here: Rest Over Websocket. Its written for Spring Boot.

Spring RESTful server

I want to set up an application using RESTful principles and Spring. I found out the RESTemplate for the client-side but I don't know how to configure the server. First I want to create a simple application in which the server simply respond with an Hello {name} string after a myserverapp:8080/{name} request. Can someone help me, maybe with Java code? Thanks.
It really does sound like you need to read the Spring docs and have a look around for examples on the internet (there are a lot)!
Here is one which I think it very clear and straightforward to get you started.
You need to start researching a little bit via google.
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#rest-resttemplate
sample:
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String delete(#PathVariable("id") Integer id)
Might also want to look into using Jersey, allows you to decouple your web layer from your REST layer. Using Spring's method, you need to init a controller etc. can take away from what the purpose of a controller is serving.
I have used both technologies, and it really depends on what you want to do, currently I'm writing an app using backbone.js which uses Jersey to serve up the REST, and Spring MVC as a front end to render the jsp pages.

Creating Java Spring MVC 3 based application with services,

I am new to Spring MVC3 framework in java but I am familiar with java coding.
I want to write two application using this framework.
First application recieves requests through a SOAP web services and sends response in form of SOAP XML Object.
Second application have a simple servlet to recieve request and send responces.
I have studied Java MVC3 framework. It requires view to be called who are mapped against which controller will handles its request. But,
How I can do this using a webservice, so that when a specific method using SOAP services is called, I can forward that request to its relevant servlet and sends response back as a SOAP xml file.
How can I do this for my second application as well that recieves request through a servlet.
I hope all this make sense.
regards,
Aqif
If you want to stick with Spring, you can use Spring Web Services for application 1. Application 2 would be a more traditonal Spring Web app (uses a servlet, but framework does not require you to work in the servlet...instead you will work in more fine grained components).
If you dont want to stick with Spring for the web services, you can always use something like Apache Axis
The usual structure is as follows:
you have spring-mvc controllers to handle your browser requests
you have other components that handle the SOAP requests
both of the above invoke the same underlying services which serve them with the data that is to be sent to the user. The data is in java objects, which are later transformed to whatever is required
For the 2nd point you can pick some JAX-WS implementation, like CXF (it has nice spring support as well)
Spring Web Services specifically supports a Spring MVC-like model for responding to SOAP calls, as you describe.
the second one is Spring MVC directly. Heck, it sounds like - though I can't be sure without more information - that you're trying to build RESTful web services. There, too, Spring MVC is the right choice.

Categories

Resources