Use Spring Web Flow without state on the server - http

I'm reading the Spring Web Flow chapter in the book Pro Spring MVC. Unfortunately there's no explicit information, where the state during a flow execution is persisted. I assume it is saved in the JVM Heap and associated with the session.
Now HTTP is a stateless protocol (REST...) and I'd like to use Spring Web Flow without saving state on the server (besides the one and only state that a session might be authenticated).
One strategy is to send all parameters of the entire flow with every HTTP request of the flow (hidden input) and thus accumulating all necessary parameters until the flow has finished.
The overhead of re-validating parameters can be avoided with signatures over already validated parameters.
Do you know, whether it might be possible to use Spring Web Flow in this way? Has anybody already done this?
Update: Why?
Persisting state is not only a violation of the principles of HTTP as a stateless protocol but has practical problems too:
If the user browses with multiple browser tabs then this can lead to inconsistent state, race conditions or data loss.
Storing state on the server makes load balancing over several servers more complicate.
Testing and debugging becomes more complicate, because requests can not be tested or analyzed in isolation but only in the context of previous requests.
Cookies must be enabled to correlate servers sessions to requests.
The server needs to synchronize access to the server-side state.
The url of a request that also depends on server state does not contain all information necessary to bookmark the state inside a flow or to make sense of it in a bug report.
I've not yet looked at the details of Web Flow but I'm confident that one could have the same programming experience and still keep all information in the request parameters.
Update: I've now learned that my requested style of flow handling has a name: Continuations. The term continuation is more common in functional programming but it's apparently not uncommon to adapt the idea to HTTP interactions.

You might be interested in checking my bean flow FSM project (restflow):
https://github.com/alfonso-presa/restflow
Although it doesn't use Spring WebFlow, I think it may help answering the spirit of the question, as it allows the implementation of a stateless server orchestrated flow. I started this project because I wanted to make almost the same as you with spring WebFlow but I found it was not possible as state is stored in session (and also REST/json serialization is not built in).
It's main purpose is making an state-machine (just like WebFlow does) but with it's state stored in a bean, which you can persist in a distributed store, or easily sign or encrypt and send back to the client as continuation for next requests.
I hope you find it useful.
edit: I created a showcase project here: https://github.com/alfonso-presa/restflow-spring-web-sample

Related

Session info across EJB (Stateful Session Beans ) vs HTTP Session vs modern frameworks

Earlier days when I used to do coding, I used mostly Stateless Session Beans and all the info needed to traverse across pages was put in HTTP Session object. Back then(and even now) I never understood the "USP" of EJB being "transparent" and "safe" for "business layer" implementation with its round about ways of dealing with Skeleton and Stub and other jargons which were an overkill masquerading in the name of ease of use/secure. I was just wondering why exactly one would have used Stateful Session EJB, if the same can be accomplished via a SLSB + HTTPSession? Please dont give me the high level example of Shopping cart or bank app, as I already know that. I am looking for some answer that would be detailed on why coders chose SFSB over SLSB+HttpSession. Plus how are these session related stuff handled in your experience recently?
You are supposing that the view layer always is a http client. But the view layer can be architected in other ways.
For example a Java Swing client application (Where the client server communication is done only with ejbs.
A question that helps diff SFSB vs HttpSession.
Stateful Session Bean and HTTP Session

What makes something be a request feature in ASP.NET Core?

There's one point in ASP.NET Core that I believe I didn't fully understand yet and that is the idea of request features. As explained in the docs:
Feature interfaces define specific HTTP features that a given request may support. Servers define collections of features, and the initial set of features supported by that server, but middleware can be used to enhance these features.
My initial understanding about this was that request features are all things a server should expose to be used on the application pipeline. That is, behaviors that a server should perform like sending a file.
On the other hand, there's, for example, the authentication request feature. Now, I'm not sure authentication falls into this category. It doesn't seem like some server behavior that the application should call, but rather, a concern of the application itself.
This makes me wonder what really makes something be a request feature. So, what makes something be a request feature in ASP.NET Core? Is my initial understanding wrong? What is behind the decision of making something a request feature?
My initial understanding about this was that request features are all things a server should expose to be used on the application pipeline. That is, behaviors that a server should perform like sending a file.
That's one use of http features. It's also a way to augment or light up behaviors on the HttpContext, like buffering, send file, authentication, websockets.
Middleware can also add features specific to that middleware, you can see examples of this:
The exception handler middleware flows the exception that occurred via a request feature - https://github.com/aspnet/Diagnostics/blob/dev/src/Microsoft.AspNetCore.Diagnostics.Abstractions/IExceptionHandlerFeature.cs.
The routing middleware adds route data to the current http context via a request feature - https://github.com/aspnet/Routing/blob/dev/src/Microsoft.AspNetCore.Routing.Abstractions/IRoutingFeature.cs
Generally it's a way to flow per request behavior and state from the server, through middleware, to the application.

What makes DbDataProvider not RESTful?

I have heard a few people make the comment that the default controller/provider for Entity Framework data in the new ASP.NET WebAPI (DbDataController) is not, strictly speaking, a REST based service, but more like an RPC-style service. I understand that the WebAPI framework allows you to make any kind of HTTP service, REST or otherwise, but can someone explain to me specifically what it is about the service exposed by a DbDataController that makes it not a true REST service?
The REST architectural style describes the following six constraints applied to the architecture, while leaving the implementation of the individual components free to design:
Client–server
A uniform interface separates clients from servers. This separation of
concerns means that, for example, clients are not concerned with data
storage, which remains internal to each server, so that the
portability of client code is improved. Servers are not concerned with
the user interface or user state, so that servers can be simpler and
more scalable. Servers and clients may also be replaced and developed
independently, as long as the interface between them is not altered.
Stateless
The client–server communication is further constrained by no client
context being stored on the server between requests. Each request from
any client contains all of the information necessary to service the
request, and any session state is held in the client. The server can
be stateful; this constraint merely requires that server-side state be
addressable by URL as a resource. This not only makes servers more
visible for monitoring, but also makes them more reliable in the face
of partial network failures as well as further enhancing their
scalability.
Cacheable
As on the World Wide Web, clients can cache responses. Responses must
therefore, implicitly or explicitly, define themselves as cacheable,
or not, to prevent clients reusing stale or inappropriate data in
response to further requests. Well-managed caching partially or
completely eliminates some client–server interactions, further
improving scalability and performance.
Layered system
A client cannot ordinarily tell whether it is connected directly to
the end server, or to an intermediary along the way. Intermediary
servers may improve system scalability by enabling load-balancing and
by providing shared caches. They may also enforce security policies.
Code on demand (optional)
Servers are able temporarily to extend or customize the functionality
of a client by the transfer of executable code. Examples of this may
include compiled components such as Java applets and client-side
scripts such as JavaScript.
Uniform interface
The uniform interface between clients and servers, discussed below,
simplifies and decouples the architecture, which enables each part to
evolve independently. The four guiding principles of this interface
are detailed below.
http://en.wikipedia.org/wiki/Representational_state_transfer#Constraints
"The only optional constraint of REST architecture is code on demand. If a service violates any other constraint, it cannot strictly be considered RESTful. DbDataController class exposes Entity Framework models as HTTP services. These services have a great feature overlap with WCF Data Services, such as CRUD support, metadata and request batching. They even partially mimic OData's query string format.But these services follow the RPC style they're not RESTful and they don't use OData." A qoute from this site:
WCF Data Services and ASP.NET Web API

HttpSession Session ID different to FlexSession ID

I have a Flex application which is served via a JSP page. In this page I output the session ID using HttpSession when the page is loaded:
System.out.println("Session ID: " + session.getId());
In a very simple remote object hosted in BlazeDS (called from the flex application using an AMF Channel and standard RemoteObject functionality) I also output the session ID but this time using FlexSession (which as I understand is supposed to wrap around HttpSession).
System.out.println("FlexSession ID: " + FlexContext.getFlexSession().getId());
I would expect both IDs to be the same but this is not the case. The session IDs differ which is causing problems as there is data stored in the HttpSession which I need to be able to access from my remote objects within BlazeDS.
I've exhausted the reading material on BlazeDS and FlexClient/FlexSession/FlexContext but can't see why the FlexSession is not being linked to the HttpSession. Any pointers greatly appreciated.
I feel I must be missing something fundemental here, am I accessing the
I do not think that it is related to the FlashPlayer..is more related to the concept of FlexSession and how BlazeDS/LCDS works. For example you can have an active session even when not using the http channels - when using NIO/RTMP you are bypassing the application server and the http protocol. So it make sense to have an abstract class FlexSession with various implementations.
However when using BlazeDS FlexSession will wrap an HttpSession object internally, and removeAttribute/getAttribute/setAttribute are in fact calling the the same methods from the HttpSession object..so you can access all the data from the HttpSession. If not please provide more details.
However, it will not work when using RTMP channels(which exists only in LCDS by the way), you need to change your design in this case.
Thanks to both answers above I finally found the root cause and thought I'd share it on here.
The reason for differing session IDs was to do with the use of SSL for authentication and the use of AMF Channel rather than Secure AMF. Using the channel for the first time caused a new session to be created (hence the different ID) as the existing session related to the secure version of the site.
Silly configuration mistake but worth passing on - make sure that if using SSL that you're also using Secure AMF connecting to the secure endpoint rather than standard AMF or you'll run into the same session ID problems I faced.
Unfortunately this is just how the Flash player works. I have seen this same behavior many times.
The best solution I found was to establish the HTTP session and pass back the session ID. On the client side, you can then pass the session ID to the Flex application. You then send that ID from Flash to the server and use it to look up the existing session or establish a second session.
You will need to do something like this though, I have not been able to find a way to reliably get Flash to use the same session.

What is the difference between HTTP and REST?

After reading a lot about the differences between REST and SOAP, I got the impression that REST is just another word for HTTP. Can someone explain what functionality REST adds to HTTP?
Note: I'm not looking for a comparison of REST versus SOAP.
No, REST is the way HTTP should be used.
Today we only use a tiny bit of the HTTP protocol's methods – namely GET and POST. The REST way to do it is to use all of the protocol's methods.
For example, REST dictates the usage of DELETE to erase a document (be it a file, state, etc.) behind a URI, whereas, with HTTP, you would misuse a GET or POST query like ...product/?delete_id=22.
HTTP is a protocol used for communication, usually used to communicate with internet resources or any application with a web browser client.
REST means that the main concept you are using while designing the application is the Resource: for each action you want to perform you need to define a resource on which you often do only CRUD operation, which is a simple task. For that it's very convenient to use four verbs used in HTTP protocol against the four CRUD operations (GET for Read, POST is for CREATE, PUT is for UPDATE and DELETE is for DELETE).
That's unlike the older concept of RPC (Remote Procedure Call), in which you have a set of actions you want to perform as a result of the user's call. if you think for example on how to describe a Facebook like on a post, with RPC you might create services called AddLikeToPost and RemoveLikeFromPost, and manage it along with all your other services related to FB posts, thus you won't need to create special object for Like.
With REST you will have a Like object which will be managed separately with Delete and Create functions. It also means it will describe a separate entity in your DB. That might look like a small difference, but working like that would usually yield a much simpler code and a much simpler application. With that design, most of the app's logic is obvious from the object's structure (model), unlike RPC with which you would usually have to explicitly add a lot more logic.
Designing a RESTful application is often a lot harder because it requires you to describe complicated things in a simple manner. Describing all functionalities using only CRUD functions is tricky, but after doing that your life would be a lot simpler, and you will find that you write a lot shorter methods.
One more restraint REST architecture presents is not to use a session context when communicating with a client (stateless), meaning all the information needed to understand who is the client and what he wants is passed with the web message. Each call to a function is self-descriptive, there is no previous conversation with the client which can be referenced in the message. Therefore, a client could not tell you "give me the next page" since you don't have a session to store what is the previous page and what kind of page you want, the client would have to say "my name is Yuval, get me page 2 of a specific post in a specific forum". This means a bit more data would have to transfer in the communication, but think of the difference between finding a bug reported from the "get me the next page" function in oppose to "get me page 2 of question ID 2190836 in stack overflow".
Of course there is a lot more to it, but to my humble opinion these are the main concepts in a teaspoon.
REST enforces the use of the available HTTP commands as they were meant to be used.
For example, I could do:
GET
http://example.com?method=delete&item=xxx
But with rest I would use the "DELETE" request method, removing the need for the "method" query param
DELETE
http://example.com?item=xxx
HTTP is an application protocol. REST is a set of rules, that when followed, enable you to build a distributed application that has a specific set of desirable constraints.
If you are looking for the most significant constraints of REST that distinguish a RESTful application from just any HTTP application, I would say the "self-description" constraint and the hypermedia constraint (aka Hypermedia as the Engine of Application State (HATEOAS)) are the most important.
The self-description constraint requires a RESTful request to be completely self descriptive in the users intent. This allows intermediaries (proxies and caches) to act on the message safely.
The HATEOAS constraint is about turning your application into a web of links where the client's current state is based on its place in that web. It is a tricky concept and requires more time to explain than I have right now.
HTTP is a contract, a communication protocol and REST is a concept, an architectural style which may use HTTP, FTP or other communication protocols but is widely used with HTTP.
REST implies a series of constraints about how Server and Client should interact. HTTP is a communication protocol with a given mechanism for server-client data transfer, it's most commonly used in REST API just because REST was inspired by WWW (world wide web) which largely used HTTP before REST was defined, so it's easier to implement REST API style with HTTP.
There are three major constraints in REST (but there are more):
Interaction between server and client should be described via hypertext only.
Server and client should be loosely coupled and make no assumptions about each other. Client should only know resource entry point. Interaction data should be provided by the server in the response.
Server shouldn't store any information about request context. Requests must be independent and idempotent (means if same request is repeated infinitely, exactly same result is retrieved)
And HTTP is just a communication protocol (a tool) that can help to achieve this.
For more info check these links:
https://martinfowler.com/articles/richardsonMaturityModel.html
http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
REST = Representational State Transfer
REST is a set of rules, that when followed, enable you to build a distributed application that has a specific set of desirable constraints.
REST is a protocol to exchange any(XML, JSON etc ) messages that can use HTTP to transport those messages.
Features:
It is stateless which means that ideally no connection should be maintained between the client and server.
It is the responsibility of the client to pass its context to the server and then the server can store this context to process the client's further request. For example, session maintained by server is identified by session identifier passed by the client.
Advantages of Statelessness:
Web Services can treat each method calls separately.
Web Services need not maintain the client's previous interaction.
This in turn simplifies application design.
HTTP is itself a stateless protocol unlike TCP and thus RESTful Web Services work seamlessly with the HTTP protocols.
Disadvantages of Statelessness:
One extra layer in the form of heading needs to be added to every request to preserve the client's state.
For security we need to add a header info to every request.
HTTP Methods supported by REST:
GET: /string/someotherstring
It is idempotent and should ideally return the same results every time a call is made
PUT:
Same like GET. Idempotent and is used to update resources.
POST: should contain a url and body
Used for creating resources. Multiple calls should ideally return different results and should create multiple products.
DELETE:
Used to delete resources on the server.
HEAD:
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The meta information contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request.
OPTIONS:
This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.
HTTP Responses
Go here for all the responses.
Here are a few important ones:
200 - OK
3XX - Additional information needed from the client and url redirection
400 - Bad request
401 - Unauthorized to access
403 - Forbidden
The request was valid, but the server is refusing action. The user might not have the necessary permissions for a resource, or may need an account of some sort.
404 - Not Found
The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.
405 - Method Not Allowed
A request method is not supported for the requested resource; for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.
404 - Request not found
500 - Internal Server Failure
502 - Bad Gateway Error
Not quite...
http://en.wikipedia.org/wiki/Representational_State_Transfer
REST was initially described in the
context of HTTP, but is not limited to
that protocol. RESTful architectures
can be based on other Application
Layer protocols if they already
provide a rich and uniform vocabulary
for applications based on the transfer
of meaningful representational state.
RESTful applications maximise the use
of the pre-existing, well-defined
interface and other built-in
capabilities provided by the chosen
network protocol, and minimise the
addition of new application-specific
features on top of it.
http://www.looselycoupled.com/glossary/SOAP
(Simple Object Access Protocol) The
standard for web services messages.
Based on XML, SOAP defines an envelope
format and various rules for
describing its contents. Seen (with
WSDL and UDDI) as one of the three
foundation standards of web services,
it is the preferred protocol for
exchanging web services, but by no
means the only one; proponents of REST
say that it adds unnecessary
complexity.
REST is a specific way of approaching the design of big systems (like the web).
It's a set of 'rules' (or 'constraints').
HTTP is a protocol that tries to obey those rules.
From You don't know the difference between HTTP and REST
So REST architecture and HTTP 1.1 protocol are independent from each
other, but the HTTP 1.1 protocol was built to be the ideal protocol to
follow the principles and constraints of REST. One way to look at the
relationship between HTTP and REST is, that REST is the design, and
HTTP 1.1 is an implementation of that design.
HTTP is a communications protocol that transports messages over a network.
SOAP is a protocol to exchange XML-based messages that can use HTTP to transport those messages.
Rest is a protocol to exchange any(XML or JSON) messages that can use HTTP to transport those messages.
REST is not necessarily tied to HTTP. RESTful web services are just web services that follow a RESTful architecture.
What is Rest -
1- Client-server
2- Stateless
3- Cacheable
4- Layered system
5- Code on demand
6- Uniform interface
REST APIs must be hypertext-driven
From Roy Fielding's blog here's a set of ways to check if you're building a HTTP API or a REST API:
API designers, please note the following rules before calling your creation a REST API:
A REST API should not be dependent on any single communication protocol, though its successful mapping to a given protocol may be dependent on the availability of metadata, choice of methods, etc. In general, any protocol element that uses a URI for identification must allow any URI scheme to be used for the sake of that identification. [Failure here implies that identification is not separated from interaction.]
A REST API should not contain any changes to the communication protocols aside from filling-out or fixing the details of underspecified bits of standard protocols, such as HTTP’s PATCH method or Link header field. Workarounds for broken implementations (such as those browsers stupid enough to believe that HTML defines HTTP’s method set) should be defined separately, or at least in appendices, with an expectation that the workaround will eventually be obsolete. [Failure here implies that the resource interfaces are object-specific, not generic.]
A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. Any effort spent describing what methods to use on what URIs of interest should be entirely defined within the scope of the processing rules for a media type (and, in most cases, already defined by existing media types). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]
A REST API must not define fixed resource names or hierarchies (an obvious coupling of client and server). Servers must have the freedom to control their own namespace. Instead, allow servers to instruct clients on how to construct appropriate URIs, such as is done in HTML forms and URI templates, by defining those instructions within media types and link relations. [Failure here implies that clients are assuming a resource structure due to out-of band information, such as a domain-specific standard, which is the data-oriented equivalent to RPC’s functional coupling].
A REST API should never have “typed” resources that are significant to the client. Specification authors may use resource types for describing server implementation behind the interface, but those types must be irrelevant and invisible to the client. The only types that are significant to a client are the current representation’s media type and standardized relation names. [ditto]
A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types that are appropriate for the intended audience (i.e., expected to be understood by any client that might use the API). From that point on, all application state transitions must be driven by client selection of server-provided choices that are present in the received representations or implied by the user’s manipulation of those representations. The transitions may be determined (or limited by) the client’s knowledge of media types and resource communication mechanisms, both of which may be improved on-the-fly (e.g., code-on-demand). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]
REST is a light version of SOAP, with no sugars or colors agents added.
The goal of both SOAP and REST is to allow the communication between Information Systems that may be written in different languages and use different communiation protocols.
While SOAP uses API contracts to expose it's services and define the way a client can call a service, what Parameters should be sent and what results are to be expected, REST on the other hand has uses no API contracts, for a client to know what services exist and how to call them it should look into the Rest API documentation (this can be defined in a yml file with a OpenAPI or Swagger).
Second SOAP is verbose, it reyes on XML to send a request and describe the services, parameteres and the results returned. On the other hand REST relyed on simple JSON Objects to send requests and receive results. JSON is simple to undersand, lightweight and does not use too much bandwith when sending requests or receiving results.

Resources