Number of Threads per each request in struts 2 - struts2

I am trying to understand the architecture of Struts 2 as it is provided in this link.
I think the Servlet container creates a new thread for each request and it is the controller(a servlet which is the entry point to struts 2) that should fill in the HttpServletResponse. But in this diagram it is shown that the HttpServletResponse is sent to the client (browser) by the ActionInvocation (not the controller). The entry point to Struts 2 is the Controller (see the figure in the link mentioned). I think for each request from the client the Servlet Container creates a new thread and calls the service method of the Controller.
Does the Sturts2 framework also creates one more thread ActionInvocation that sends the response to the client or it is the Controller that sends the HttpServletResponse to the client?
I am new to Struts 2 and trying to understand the flow. Please help me in understanding this. Thanks.

Does the Sturts2 framework also creates one more thread ActionInvocation that sends the response to the client
No, it uses the same thread as request.
If you need to learn more about objects and how they were scoped in struts2 container see this answer.

Related

Are all Zuul filters for one request executed in same thread?

I have a proxy service based on netflix Zuul. For any logs, from my custom filters or Zuul built in filters, I want to have a request header called Flow-Id to be part of my log. I can do this by setting the value of this header in the MDC context using a pre filter. But this works only if all the filters are executed in same thread.
Are all Zuul filters for one request executed in same thread?
And will this thread run anything else while this request is still in progress?
I looked into the code and figured out Zuul proxy is using a servlet. And the spring cloud wrap this servlet in a ServletWrappingController.
So to answer my own question, all filters are executed in one thread.
And to make sure that MDC context is set as early as possible, I did it in a servlet filter and added a spring bean.

Create a new Thread and send messagges only to a user which called the Controller

When the client calls a Controller, a new Thread is created, which takes a long time. The View is intimidatingly returned to the user. The user should stay informed over the progress of the work, so SignalR is used.
How can send updates only to the user which called the Controller.
If I create a new Thread the HTTP Context get's lost, so I don't know how I can tell SignalR to which client it should send the information.
When you spawn your thread you should pass to it a user identifier, and then from the thread get a hub context and call something like:
var context = GlobalHost.ConnectionManager.GetHubContext<YourHub>();
context.Clients.User(userId).whatever();
on it. By default the user id would match the user name you get from your principal before calling the thread (so your HTTP context is still valid), but you can also check the IUserIdProvider interface for alternate ways of handling it.
If nature of long running operation allows it (ie you don't need to render any view or something specific to MVC), you can just implement your "long running work" inside the hub method (always use Task<T> and await to do that) and report progress back to client as shown here. Sample code is missing client side part. For that, take a look at this SO question.
This approach has another benefit. If your controller\action performing long running operation is using ASP.NET Session (which is default behavior), no other MVC actions\requests can run on server until the long running request finishes because of the Session lock - take a look here for more details. SignalR on the other side do not use Session by default so there is one less problem to worry about...
Oh BTW: Do not create your own Threads - its very inefficient. Use ThreadPool.QueueUserWorkItem or better Task<T> API...

Difference between ASP.NET MVC 3 and 4? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Is there a comprehensive list that explains all of the new features of MVC4 and what all has changed from MVC3?
(The release notes are not much helpful)
Copied and pasted from MVC4 Release Notes:
•Modern HTTP programming model: Directly access and manipulate HTTP requests and responses in your Web APIs using a new, strongly typed HTTP object model. The same programming model and HTTP pipeline is symmetrically available on the client through the new HttpClient type.
•Full support for routes: ASP.NET Web API supports the full set of route capabilities of ASP.NET Routing, including route parameters and constraints. Additionally, use simple conventions to map actions to HTTP methods.
•Content negotiation: The client and server can work together to determine the right format for data being returned from a web API. ASP.NET Web API provides default support for XML, JSON, and Form URL-encoded formats and you can extend this support by adding your own formatters, or even replace the default content negotiation strategy.
•Model binding and validation: Model binders provide an easy way to extract data from various parts of an HTTP request and convert those message parts into .NET objects which can be used by the Web API actions. Validation is also performed on action parameters based on data annotations.
•Filters: ASP.NET Web API supports filters including well-known filters such as the [Authorize] attribute. You can author and plug in your own filters for actions, authorization and exception handling.
•Query composition: Use the [Queryable] filter attribute on an action that returns IQueryable to enable support for querying your web API via the OData query conventions.
•Improved testability: Rather than setting HTTP details in static context objects, web API actions work with instances of HttpRequestMessage and HttpResponseMessage. Create a unit test project along with your Web API project to get started quickly writing unit tests for your Web API functionality.
•Code-based configuration: ASP.NET Web API configuration is accomplished solely through code, leaving your config files clean. Use the provide service locator pattern to configure extensibility points.
•Improved support for Inversion of Control (IoC) containers: ASP.NET Web API provides great support for IoC containers through an improved dependency resolver abstraction
•Self-host: Web APIs can be hosted in your own process in addition to IIS while still using the full power of routes and other features of Web API.
•Create custom help and test pages: You now can easily build custom help and test pages for your web APIs by using the new IApiExplorer service to get a complete runtime description of your web APIs.
•Monitoring and diagnostics: ASP.NET Web API now provides light weight tracing infrastructure that makes it easy to integrate with existing logging solutions such as System.Diagnostics, ETW and third party logging frameworks. You can enable tracing by providing an ITraceWriter implementation and adding it to your web API configuration.
•Link generation: Use the ASP.NET Web API UrlHelper to generate links to related resources in the same application.
•Web API project template: Select the new Web API project form the New MVC 4 Project wizard to quickly get up and running with ASP.NET Web API.
•Scaffolding: Use the Add Controller dialog to quickly scaffold a web API controller based on an Entity Framework based model type.
Copy and paste from Whats new in MVC4 - MVC3 Vs MVC4
Whats new in MVC4 - MVC3 Vs MVC4
Enhancements to Default Project Templates
The template that is used to create new ASP.NET MVC 4 projects has been updated to create a more modern-looking website
Mobile Project Template
If you’re starting a new project and want to create a site specifically for mobile and tablet browsers, you can use the new Mobile Application project template. This is based on jQuery Mobile, an open-source library for building touch-optimized UI
Display Modes
The new Display Modes feature lets an application select views depending on the browser that's making the request. For example, if a desktop browser requests the Home page, the application might use the Views\Home\Index.cshtml template. If a mobile browser requests the Home page, the application might return the Views\Home\Index.mobile.cshtml template.
DisplayModes.Modes.Insert(0, new DefaultDisplayMode("iPhone")
{
ContextCondition = (context => context.Request.UserAgent.IndexOf
("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)
});
jQuery Mobile, the View Switcher, and Browser Overriding
jQuery Mobile is an open source library for building touch-optimized web UI. If you want to use jQuery Mobile with an ASP.NET MVC 4 application, you can download and install a NuGet package that helps you get started. To install it from the Visual Studio Package Manager Console, type the following command:
Install-Package jQuery.Mobile.MVC
This installs jQuery Mobile and some helper files, including the following:
Views/Shared/Layout.Mobile.cshtml, which is a jQuery Mobile-based layout.
A view-switcher component, which consists of the Views/Shared/ViewSwitcher.cshtml partial view and the ViewSwitcherController.cs controller.
After you install the package, run your application using a mobile browser (or equivalent, like the Firefox User Agent Switcher add-on). You'll see that your pages look quite different, because jQuery Mobile handles layout and styling. To take advantage of this, you can do the following
If visitors click the link, they’re switched to the desktop version of the same page.
Because your desktop layout will not include a view switcher by default, visitors won't have a way to get to mobile mode. To enable this, add the following reference to
_ViewSwitcher to your desktop layout, just inside the element:
#Html.Partial("_ViewSwitcher")
...
Browser Overriding is a core feature of ASP.NET MVC 4 and is available even if you don't install the jQuery.Mobile.MVC package. However, it affects only view, layout, and partial-view selection — it does not affect any other ASP.NET feature that depends on the Request.Browser object.
Recipes for Code Generation in Visual Studio
The new Recipes feature enables Visual Studio to generate solution-specific code based on packages that you can install using NuGet. The Recipes framework makes it easy for developers to write code-generation plugins, which you can also use to replace the built-in code generators for Add Area, Add Controller, and Add View. Because recipes are deployed as NuGet packages, they can easily be checked into source control and shared with all developers on the project automatically. They are also available on a per-solution basis.
Task Support for Asynchronous Controllers
You can now write asynchronous action methods as single methods that return an object of type Task or Task.
For example, if you're using Visual C# 5 (or using the Async CTP), you can create an asynchronous action method that looks like the following:
public async Task Index(string city) {
var newsService = new NewsService();
var sportsService = new SportsService();
return View("Common", new PortalViewModel {
NewsHeadlines = await newsService.GetHeadlinesAsync(),
SportsScores = await sportsService.GetScoresAsync()
});
}
In the previous action method, the calls to newsService.GetHeadlinesAsync and sportsService.GetScoresAsync are called asynchronously and do not block a thread from the thread pool.
Asynchronous action methods that return Task instances can also support timeouts. To make your action method cancellable, add a parameter of type CancellationToken to the action method signature. The following example shows an asynchronous action method that has a timeout of 2500 milliseconds and that displays a TimedOut view to the client if a timeout occurs.
[AsyncTimeout(2500)]
[HandleError(ExceptionType = typeof(TaskCanceledException), View = "TimedOut")]
public async Task Index(string city, CancellationToken cancellationToken) {
var newsService = new NewsService();
var sportsService = new SportsService();
return View("Common", new PortalViewModel {
NewsHeadlines = await newsService.GetHeadlinesAsync(cancellationToken),
SportsScores = await sportsService.GetScoresAsync(cancellationToken)
});
}
Hope this helps. Thanks
Please go through the URL for all MVC 4 new features
MVC 3
Integrated Scaffolding system extensible via NuGet
HTML 5 enabled project templates
Expressive Views including the new Razor View
Engine
Powerful hooks with Dependency Injection and
Global Action Filters
Rich JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding
MVC 4
ASP.NET Web API
Refreshed and modernized default project
templates
New mobile project template
Many new features to support mobile apps
Enhanced support for asynchronous methods
Ref : http://dotnet-developers-cafe.blogspot.in/2013/09/difference-between-aspnet-mvc-3-and-mvc.html
Please check the below links to find out the differences.
http://forums.asp.net/t/1753017.aspx
http://www.askamoeba.com/Answer/130/Whats-new-in-MVC4-MVC3-Vs-MVC4
http://forums.asp.net/t/1918539.aspx?Main+difference+between+regular+webapplication+mvc3+and+mvc4+
One of the important feature introduced in MVC 4.0 was of Asynchronous controllers which enables to write the asynchronous action methods. Asynchronous controller allows an operation to get performed without making the working thread idle.
When an asynchronous action is invoked, the following steps occur:
The Web server gets a thread from the thread pool (the worker thread) and schedules it to handle an incoming request. This worker thread initiates an asynchronous operation.
The worker thread is returned to the thread pool to service another Web request.
When the asynchronous operation is complete, it notifies ASP.NET.
The Web server gets a worker thread from the thread pool (which might be a different thread from the thread that started the asynchronous operation) to process the remainder of the request, including rendering the response.
Converting Synchronous Action Methods to Asynchronous Action Methods
Following is the example of synchronous action method and the its asynchronous equivalent version.
Synchronous Controller:
public class TestController : Controller
{
public ActionResult Index()
{
return View();
}
}
Asynchronous variant of above operation:
public class TestController : AsyncController
{
public void IndexAsync()
{
return View();
}
public ActionResult IndexCompleted()
{
return View();
}
}
Steps:
Synchronous Controllers are the classes derived from the Controller
class to implement an AsyncController instead of deriving the
controller from Controller, derive it from AsyncController class.
Controllers that derive from AsyncController enable ASP.NET to
process asynchronous requests, and they can still service synchronous
action methods.
Corresponding to the synchronous action method in Synchronous
controller you need to create two methods for the action in
asynchronous controller.First method that initiates the asynchronous
process must have a name that consists of the action and the suffix
"Async". The other method that is invoked when the asynchronous
process finishes (the callback method) must have a name that consists
of the action and the suffix "Completed".
In the above sample example, the Index action has been turned into
two methods in asynchronous controller: IndexAsync and
IndexCompleted.
The IndexAsync method returns void while the IndexCompleted method
returns an ActionResult instance. Although the action consists of two
methods, it is accessed using the same URL as for a synchronous
action method (for example, Controller/Index).
Note the following about asynchronous action methods:
If the action name is Sample, the framework will look for SampleAsync and SampleCompleted methods.
View pages should be named Sample.aspx rather than SampleAsync.aspx or SampleCompleted.aspx. (The action name is Sample, not SampleAsync)
A controller cannot contain an asynchronous method named SampleAsync and a synchronous method named Sample. If it does, an AmbiguousMatchException exception is thrown because the SampleAsync action method and the Sample action method have the same request signature.
For more details click here : http://www.counsellingbyabhi.com/2014/05/asynchronous-controllers-in-aspnet-mvc.html

Grails 2.0 - how to use createLinkTo in Bootstrap or background thread

I'm using Grails 2.0.0, and trying to prepopulate some test data from Bootstrap.groovy. This data requires createLinkTo from Grails taglib.
Btw, when i'm trying to call g.createLinkTo(...) I getting:
Message: No thread-bound request found: Are you referring to request attributes outside
of an actual web request, or processing a request outside of the originally receiving
thread? If you are actually operating within a web request and still receive this message,
your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this
case, use RequestContextListener or RequestContextFilter to expose the current request.
And also, this app is going to use createLinkTo in background threads (event processing, send mails, etc). So I need it not only in Bootstrap.
As I understand I need to make an mock request, and bind it to current thread, but how I can do that?
Or maybe there is another way to make app links?
In grails 2 you can use the LinkGenerator
Have a look here in the Link Generation API section.

Orbeon XForms: Reuse http service for several actions

The seperation between http services and actions in Orbeon forms would enable to reuse a http service for several actions. But according to https://github.com/orbeon/orbeon-forms/blob/master/src/resources/forms/orbeon/builder/form/dialog-actions.xml#L67 this advantage has been disabled - each action needs its own http service. I can't see any reason for this, why are used submissions filtered out?
Thank you!
Initially, this was done for, let's say, historical reasons! I agree that it's an unwanted limitation.
However practically you can't just remove the restriction in the dialog: the reason is that each action has code like this:
<action ev:event="xforms-submit-done" ev:observer="my-service-submission">
This means that if you create more than one action, each action will register an event handler for the completion of the same service, and both actions' handlers will run, which would be incorrect behavior.
What's needed here is something along these lines:
each action, when starting the service, passes a unique identifier (for example the id of the action) to the service
upon completion, the unique id is passed to xforms-submit-done
the event handler for each action can filter on this id
only the handler for the action that started the service runs
This would require an enhancement to the XForms engine to implement this feature, which has been already suggested for XForms 2.0, by the way.

Resources