Can't get security context from scheduled task - cuba-platform

I get the error
org.springframework.scheduling.support.TaskUtils$LoggingErrorHandler - Unexpected error occurred in scheduled task.
java.lang.SecurityException: No security context bound to the current thread
using a scheduled task on the core module to execute a task once at application start:
<task:scheduled-tasks scheduler="scheduler">
<task:scheduled ref="app_OlapService" method="initialize" fixed-rate="9223372036854775807"/>
</task:scheduled-tasks>
I've tried both the #Authenticated annotation and authentication.begin() on injected Authentication instance.
It looks like an error triggered by the scheduling alone, I'm also having the same error with an empty method body.
I'm also open to alternative approaches, considering that I need to use a transaction and #PostConstruct AppContext.Listener don't allow me to.

Perhaps you are invoking a method of a service. Such invocations are intercepted and checked for the presence of a valid user session, so it should already exist at the moment of invocation. It works when a service is invoked from a client or from an already authenticated middleware code.
In your case, I would recommend extracting logic from service to a managed bean and invoke it both from service and scheduler.
As for AppContext.Listener, in the applicationStarted() method you can do whatever you want including programmatic transaction management.

Related

NServiceBus Unit Of Work - get which handler is called?

I'm trying to write a Unit Of Work for NServiceBus that will be called before and after each message handler to measure the time it takes for that handler to run and write it in to a database.
I was able to successfully write the Unit Of Work, but at the Begin() method implementation, how can I tell which handler is being called?
You can use ServiceInsight to get this kind of information. See docs on ServiceControl and ServiceInsight for more info. another channel may be NServiceBus.Performance Counters.
I'd look into the decorator pattern and deal with this by dependency injection
example
https://code.google.com/p/autofac/wiki/AdaptersAndDecorators
You could create a decorator for the IHandleMessages interface and configure all message handlers to return a proxy to the real message handler which adds the required instrumentation logic.

NHibernate Session issue with NServiceBus

We have a simple nservicebus (v4) setup in which a web app sends various messages to a backend endpoint for processing. Everything was going smoothly until ramping up the concurrency level. Often, but not all of the time we'll get the following exception -
System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.
I'm guessing this has to be an issue with the NHibernate(v3.1) Session management. Right now, we create a new session factory and session with a singleton lifecycle in each of the handlers (so each handler should have it's own session, right?). My best guess based on this exception is that the connection on the session is being used by another handler?
Can anyone shed some light? Why is this an inconsistent problem?
Found the problem. I was initializing the structuremap ObjectFactory in every handler so every new message would would overwrite what another message (on a another thread) originally initialized. This meant that all of the threads were using the session that the most recent message created. Bootstrapping in the Init() method from IWantCustomInitialization seems to have fixed the issue.

How can I disable MessageInspector of my condition

I inpesct WCF Service With IDisptachMessageInspector and then I call service operation at BeforeSendReply Method which changes context of message. But it when I call service , Inspector runs again. I want to not run inspector. Do you know any way to do that scenerio?
The purpose of a message inspector is to allow you to modify the message before or after the rest of the service model layer processes it
BeforeSendReply is called after the operation has been invoked already, AfterReceiveRequest is called before the operation is invoked.
The behavior you are seeing is that your message inspector is being fired after the operation. You are then firing another operation which then ends up calling your message inspector again. BeforeSendReply is often used to manipulate the response message to some format that WCF has problems with generating using its default serialization, etc. Its not going to be able to give you the behavior you are looking for
To decide on which operation is invoked you normally implement an IDispatchOperationSelector. The specific idea of this extension point looks like it will be exactly what you need
Answer is implementing IOperationInvoker

WCF using Enterprise Library Validation Application Block - how to get hold of invalid messages?

I've got some WCF services (hosted in IIS 6) which use the Enterprise Library (4.0) Validation Application Block. If a client submits a message which fails validation (i.e. gets thrown back in a ValidationFault exception), I'd quite like to be able to log the message XML somewhere (using code, no IIS logs). All the validation happens before the service implementation code kicks in.
I'm sure it's possible to set up some class to get run before the service implementation (presumably this is how the Validation Application Block works), but I can't remember how, or work out exactly what to search for.
Is it possible to create a class and associated configuration that will give me access to either the whole SOAP request message, or at least the message body?
Take a look at using the Policy Injection Application Block...
I'm currently developing an application in which I intercept (using PIAB) all requests incoming to the server and based on the type of request I apply different validation behavior using the VAB.
Here's an article about integrating PIAB with WCF:
http://msdn.microsoft.com/en-us/magazine/cc136759.aspx
You can create different inteception mechanisms such as attributes applied to exposed operations.
You could log the whole WCF Message:
http://msdn.microsoft.com/en-us/library/ms730064.aspx
Or you could combine it with Enterprise Library Logging Application Block.
I found a blog post which seems to do what I want - you create a class that implements IDispatchMessageInspector. In the AfterReceiveRequest method, you have access to the whole incoming message, so can log away. This occurs after authentication, so you also have access to the user name - handy for logging. You can create supporting classes that let you assign this behaviour to services via attributes and/or configuration.
IDispatchMessageInspector also gives you a BeforeSendReply method, so you could log (or alter) your response message.
Now when customers attempt to literally hand-craft SOAP request messages (not even using some kind of DOM object) to our services, we have easy-to-access proof that they are sending rubbish!

Implement 'Ping' functionality using Message Inspector causes WCF runtime to throw NullReferenceException

I'm using WCF to implement a web service. This web service requires a 'ping' feature as a health monitor for each service. This functionality has been implemented using IDispatchMessageInspector and is configured for each endpoint of a service. This is due to a business requirement for the 'ping' to be as near the actual service code as possible. At the same time, I did not want to tie it to each service implementation's code and IDispatchMessageInspector seems to be a good fit.
The service uses a Request-Reply MEP. Each request message contains an element that specifies what processing is required. The service will then use this value to determine how to process the data in the message. The same element is used to define a request message as a 'heartbeat' check.
The 'ping' message inspector will pre-process a request message in the AfterReceiveRequest() method and if it determines the request is a 'heartbeat', it will then generate the correct response and pass that on to the BeforeSendReply() method via a correlation object returned from AfterReceiveRequest(). The request message parameter of AfterReceiveRequest(), which is by reference, is then set to null to prevent the message from being processed by the service implementation code.
The technique of setting request message to null was found in a web site or blog which I can't remember nor find the URL for. This technique works great on it's own and I can prevent service implementation code from being executed if it's a 'heartbeat' request.
Unfortunately, setting the request message to null in a message inspector will cause the WCF runtime to always throw a NullReferenceException. From the stack trace, I gather the runtime will still pass the message object (which will be null after going through 'Ping' message inspector) to the dispatcher and when the dispatcher tries to deserialise a null message object, causes the NullReferenceException.
However, my system also implements IErrorHandler to catch any unhandled exceptions in the service and log it. This means every successful 'heartbeat' request will generate a log entry for the NullReferenceException and the 'heartbeat' could be as frequent as every minute.
The Question :
What can I do to prevent logging of 'useless' NullReferenceException thrown when 'Ping' prevents service implementation code from running by setting request to null.
Many thanks in advance.
~hg
Not the most graceful solution but potential workarounds (that i've not tested), but where you detect your ping calls in the inspector code, could you not throw your own custom exception type i.e. PingRequestException, and handle this when it returns to the client? Would that avoid you hitting the WCF Runtime code, thus avoiding the logging of unhandled exceptions.
Otherwise you could try to use a base service, inherited by all of your services (the other side of the wcf runtime code) that detects and handles ping requests in the constructor before hitting the actual service code.