Asynchronous Servlet processing in Spring Web Flow - spring-mvc

Is there any way to make use of Java EE Asynchronous Web Servlet processing in Spring Web Flow? I see a fair amount about Spring MVC support, but nothing about Web Flow. Where ideally I'd want only certain transitions or actions to use the approach.
Would you have to use the DeferredResult approach? Although that seems to be intended for doing the work somewhere unaware of the web container context, which Web Flow isn't.
I can get the native HttpServletRequest, of course, and from there call:
AsyncContext acontext = startAsync();
But since Web Flow isn't dealing with low level HTTP request/response objects, I don't know how I'd tie the two together.
I'd love to see a working example. I'm hoping I don't have to exit Web Flow in order to do the Asynchronous request processing.

Related

What are differences between ASP.NET4 and ASP.NET5 Http pipelines?

I have had a read on what's new in .NET4.6 and one of the things is ASP.NET 5 which I am quite excited about.
One of the new things is New modular HTTP request pipeline, however there is no more info on how exactly is it going to change.
The only reference in the article is
ASP.NET 5 introduces a new HTTP request pipeline that is lean and
fast. This pipeline is modular so you can add only the components that
you need. By reducing the overhead in the pipeline, your app will
experience better throughput. The new pipeline also supports OWIN.
What are major differences between ASP.NET4.5 and ASP.NET5 Http pipelines? How modularity will be controlled?
The biggest difference in my opinion is the modularity of the new request pipeline. In the past, the application lifecycle followed a relatively strict path that you could hook into via classes implementing IHttpModule. This would allow you to affect the request, but only at certain points along the way by subscribing to the different events that occur (e.g. BeginRequest, AuthenticateRequest, etc.).
The full descriptions of these can be found on MSDN: IIS 5 & 6 or IIS 7, and a walkthrough of creating such a module can be found here.
In the new ASP.NET 5 world, the request pipeline is decoupled from System.Web and IIS. Instead of a pre-defined path, it uses the concept of middleware. If you are familiar with OWIN, the idea is nearly identical, but the basic idea is that these Middleware Components are registered and then the request passes through them in the order that they are registered.
Each middleware component is provided a RequestDelegate (the next middleware component in the pipeline) and the current HttpContext per-request. On each request, the component is invoked, and then has the opportunity to pass the request along to the next in the chain if applicable. For example, an authentication component might opt not to pass the request along to the next component if authentication fails. Using this system, you can really handle a request any way you choose, and can be as light-weight or as feature-rich as you need it to be.
This example is a little bit dated now (e.g. IBuilder has been renamed to IApplicationBuilder), but it is still a great overview of how building and registering these components looks.

Use Spring Web Flow without state on the server

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

Heavy load on spring controller?

What happen even many request comes through one spring controller?
Does Spring pipe it?
How about add #Transactinal on controller?
Is it have a benefit to use on controller layer?
Basically you are asking 2 questions
How are multiple, concurrent, requests handled by a handler.
Should we add #Transactional to a handler.
Multiple concurrent requests are handled concurrently. Each thread has its own callstack and location in memory and doesn't share a thing. In general no problem (used Spring MVC in very high concurrent applications) unless you start, for some reason, sharing state in your singleton, or forget to clean-up ThreadLocals.
Adding #Transactional is something bad, IMHO. The transactional layer is NOT your web but your service layer. So don't add transactions to your web but add them to your service layer.

Silverlight,asynchronous,lazy loading what's the best way?

I started to use silverlight/flex and immediately bumped into the asynchronous service calling. I'm used to solving the data access problems in an OO-way with one server fetch mechanism or another.
I have the following trivial code example:
public double ComputeOrderTotal(Order order)
{
double total = 0;
// OrderLines are lazy loaded
foreach (Orderline line in order.Orderlines)
{
// Article,customer are lazy loaded
total = total + line.Article.Price - order.Customer.discount;
}
return total;
}
If I understand correctly, this code is impossible in Flex/Silverlight. The lazy loading forces you to work with callbacks. IMO the simple expample above will be a BIG mess.
Can anyone give me a structured way to implement the above ?
Edit:
The problem is the same for Flex/Silverlight, pseudo code would
do fine
Its not really ORM related but most orms use lazy loading so i'll remove
that tag
The problem is lazy loading in the model
The above example would be very doable of all data was in memory but
we assume some has to be fetched from
the server
Closueres dont help since sometimes data is already loaded and no asynchronous fetch is needed
Yes I must agree that O/R mapping is usually done on the server-side of your application.
In SilverLight asynchronous way of execution is the desired pattern to use when working with services. Why services? Because as I said before there is no O/R mapping tool at the moment that could be used on the client-side (SilverLight). The best approach is to have your O/R mapped data exposed by a service that can be consumed by a SilverLight application. The best way at the moment is to use Ado.Net DataServices to transport the data, and on the client-side to manage the data using LINQ to Services. What is really interesting about ADS (former Astoria project) is that it is designed to be used with Entity Framework, but the good folks also implemented support for IQueriable so basically you can hook up any data provider that support LINQ. To name few you can consider Linq To Sql, Telerik OpenAccess, LLBLGen, etc. To push the updates back to the server the data source is required to support the ADS IUpdateable.
You can look just exactly how this could be done in a series of blogposts that I have prepared here: Getting Started with ADO.NET Data Services and Telerik Open Access
I can't speak to Silverlight but Flex is a web browser client technology and does not have any database driver embedded in the Flash runtime. You can do HTTP protocol interactions to a web server instead. It is there in the middle-tier web server where you will do any ORM with respect to a database connection, such as Java JDBC. Hibernate ORM and iBATIS are two popular choices in the Java middle-tier space.
Also, because of this:
Fallacies of Distributed Computing
You do not do synchronous interactions from a Flex client to its middle-tier services. Synchronous network operations have become verboten these days and are the hallmark signature of a poorly designed application - as due to reasons enumerated at the above link, the app can (and often will) exhibit a very bad user experience.
You instead make async calls to retrieve data, load the data into your client app's model object(s), and proceed to implement operations on the model. With Flex and BlazeDS you can also have the middle-tier push data to the client and update the client's model objects asynchronously. (Data binding is one way to respond to data being updated in an event driven manner.)
All this probably seems very far afield from the nature of inquiry in your posting - but your posting indicates you're off on an entirely incorrect footing as to how to understand client-side technologies that have asynchronous and event-driven programming baked into their fundamental architecture. These RIA client technologies are designed this way completely on purpose. So you will need to learn their mode of thinking if you want to have a good and productive experience using them.
I go into this in more detail, and with a Flex perspective, in this article:
Flex Async I/O vs Java and C# Explicit Threading
In my direct experience with Flex, I think this discussion is getting too complicated.
Your conceptual OO view is no different between sync and asynch. The only difference is that you use event handlers to deal with the host conversation in the DAL, rather than something returned from a method call. And that often happens entirely on the host side, and has nothing to do with Flex or Silverlight. (If you are using AIR for a workstation app, then it might be in client code, but the same applies. As well if you are using prolonged AJAX. Silverlight, of course, has no AIR equivalent.)
I've been able to design everything I need without any other changes required to accomodate asynch.
Flex has a single-threaded model. If you make a synchronous call to the web server, you'd block the entire GUI of the application. The user would have a frozen application until the call completes (or times out on a network error condition, etc.).
Of course real RIA programs aren't written that way. Their GUI remains accessible and responsive to the user via use of async calls. It also makes it possible to have real progress indicators that offer cancel buttons and such if the nature of the interaction warrants such.
Old, bad user experience web 1.0 applications exhibited the synchronous behaviour in their interactions with the web tier.
As my linked article points out, the async single-threaded model coupled with ActionScript3 closures is a good thing because it's a much simpler programming model than the alternative - writing multi-thread apps. Multi-threading was the approach of writing client-server Java Swing or C# .NET WinForm applications in order to achieve a similarly responsive, fluid-at-all-times user experience in the GUI.
Here's another article that delves into this whole subject matter of asynchronous, messaging/event-driven distributed app architecture:
Building Effective Enterprise Distributed Software Systems
data-driven communication vs behavior-driven communication
Silverlight is a client technology and the Object - Relational mapping happens completely in the server. So you have to forgot about the ORM in Silverlight.
Following your example what you have to do is to create a webservice (SOAP, REST...) that can give your silverlight client the complete "Order" object.
Once you have the object you can work with it with no communication with the server in a normal - synchronous way.
Speaking about Silverlight, you should definitely check RIA services.
Simply, it brings the DataContext from the server to the client from where you can asynchronously query it (there is no need to write WCF services by hand, it's all done by RIA).
C# 5
async / await construct will almost exactly what I want..
watch presentation by anders hejlsberg

What's the best way to implement an API in ASP.NET using MVC?

I've been a longtime ASP.NET developer in the web forms model, and am using a new project as an opportunity to get my feet wet with ASP.NET MVC.
The application will need an API so that a group of other apps can communicate with it. I've always built API's out just using a standard web service prior to this.
As a sidenote, I'm a little hesitant to plunge headfirst into the REST style of creating API's, for this particular instance at least. This application will likely need a concept of API versioning, and I think that the REST approach, where the API is essentially scattered across all the controllers of the site, is a little cumbersome in that regard. (But I'm not completely opposed to it if there is a good answer to the potential versioning potential requirement.)
So, what say ye, Stack Overflow denizens?
I'd agree with Kilhoffer. Try using a "Facade" wrapper class that inherits from an "IFacade". In your Facade class put your code to consume your web service. In this way your controllers will simply make calls to the Facade. The plus side of this being that you can swap a "DummyFacade" that implements the same IFacade interface in that doesn't actually talk to the web service and just returns static content. Lets you actually do some unit testing without hitting the service. Basically the same idea as the Repository pattern.
I would still recommend a service layer that can serve client side consumers or server side consumers. Possibly even returning data in a variety of formats, depending on the consuming caller.

Resources