Hystrix getting access to the current execution state within fallback - spring-cloud

I successfully configured spring-cloud (via spring-cloud-starter-hystrix) to wrap a call to a service.
This all works fine and looks like the following:
#Component
public class MyService {
#HystrixCommand(fallbackMethod = "fallback")
public void longRunning() {
// this could fail
}
public void fallback() {
// fallback code
}
}
My question now is, I would like to log some statistics about the execution error in longRunning()
Trying to access HystrixRequestLog.getCurrentRequest() within the fallback method throws
java.lang.IllegalStateException: HystrixRequestContext.initializeContext() must be called at the beginning of each request before RequestVariable functionality can be used.
I am looking for a simple way to log the exception of longRunning if the fallback is called.
testing with v1.0.0.RC2

To see a stack trace you can just enable DEBUG logging in com.netflix.hystrix.
As far as I can tell, to use the HystrixRequestContext the caller of MyService has to call HystrixRequestContext.initializeContext() before using the service. That sucks, so if anyone has a better idea, I'm interested.

Starting from Javanica v1.4.21, it allows fallback method to have an argument of Throwable type for accessing the command execution exception like so:
public void fallback(Throwable e) {
// fallback code
LOGGER.error(e.getMessage());
}
To get this feature, your build config needs to override the older version of Javanica pulled in by Spring Cloud.

Related

GWT Session timeout with Timer

I am trying to implement session timeout with help of a GWT Timer which will make a RPC call to server to check whether the session is valid or expired by using lastaccessedtime. but every time i make a RPC call it updates the lastaccessedtime (understandable as i am making a RPC call), any way i can prevent my Timer RPC call from updating the lastaccessedtime?
wrote some server side logic to get the lastaccessedtime and try to find out session is valid or not
com.google.gwt.user.client.Timer elapsedTimer;
public void onModuleLoad() {
elapsedTimer = new Timer () {
public void run() {
validateSession();
}};
//giving time delay of 1sec to call the batches
elapsedTimer.scheduleRepeating(60000);
}
public void validateSession(){
//Problem code every time i make this call it updates the last accessed time
viewService.validateSessionGWT(new AsyncCallback<ModuleData>() {
#Override
public void onFailure(Throwable e) {
//do something
}
#Override
public void onSuccess(ModuleData data) {
if(data.getSessionExpired()){
//redirect to login page
}
}
});
}
any idea how to overcome this problem or any other idea to implement Session management in GWT
NOTE: already gone through this which is similar to my approach
https://itsecrets.wordpress.com/2011/07/20/session-timeouts-with-gwt-rpc-calls/
Your GWT servlets extend the RemoteServiceServlet. So you can override processPost and add a custom last call timestamp in you http session. Every request updates this field.
I suggest to implement an abstract servlet that is extended by all your gwt servlets. Additionally you should not only set the custom last access field, but check it just before and only call the super method if everything is fine.
Then your timer and the servlet request you already have should only check this Session field.
Perhaps not the best solution but this should work.

How to configure Citrus LogginReporter to show full stack trace when there is an ActionTimeoutException?

While running test (with Citrus or not) an exception may occurs if the test expects a message on a queue but the message isn't received before the timeout expires.
In this case I'd like know which line throws the Exception.
Unfortunatelly citrus doesn't show this information.
Here's my code :
#Test
#CitrusTest
public void testFail() {
sequential().actions(
mycheckNoError1(),
mycheckNoError2(),
mycheckNoError3(), //this one fails , we want to know it and which line throws the ActionTimeoutException
mycheckNoError4()
);
}
protected AbstractActionContainer mycheckNoError3() {
AbstractActionContainer aCatch = catchException().exception(ActionTimeoutException.class)
.when(receive("for_soap_q")
.timeout(100L)
.validationCallback(validationCallbackFunc()
))
.addTestAction(timeoutException(Thread.currentThread().getStackTrace()));
return aCatch;
}
And here's the stacktrace of citrus, that doesn't show the line that throws the exception:
...
INFO .c.r.LoggingReporter|
ERROR .c.r.LoggingReporter| TEST FAILED MyTest.test <package.test> Nested exception is:
com.consol.citrus.exceptions.ActionTimeoutException: Action timed out while receiving JMS message on 'testQueue'
at com.consol.citrus.jms.endpoint.JmsConsumer.receive(JmsConsumer.java:95) ~[citrus-jms-2.7.5.jar:na]
at com.consol.citrus.jms.endpoint.JmsConsumer.receive(JmsConsumer.java:60) ~[citrus-jms-2.7.5.jar:na]
at com.consol.citrus.jms.endpoint.JmsSyncConsumer.receive(JmsSyncConsumer.java:60) ~[citrus-jms-2.7.5.jar:na]
...
The only way I found was to pass the stacktrace as parameter of a method timeoutException() I wrote:
private TestAction timeoutException(StackTraceElement[] methodName) {
System.out.println("++++++++++ timeout Exception at line " + methodName[1].getLineNumber() + " in method: [" + methodName[1].getMethodName() + "]");
return null;
}
But I guess there is a better way to do this.
Is there a way to configure properly citrus and/or override the LoggingReporter to show the line number that make the exception happen ?
(in this case, this is the line: when(receive("for_soap_q")...)
thanks.
You can overwrite the default Logging reporter by placing a bean named 'loggingReporter' in the Spring application context. In addition to that you can add custom reporters and test listeners when choosing different bean naming. Just add the custom listeners to the Spring application context and they will get test events and throwable errors for reporting.
Also make sure to use the TestRunner fluent API instead of the TestDesigner fluent API. Designer is slightly more straight forward but runner will execute the test actions immediately while building the test case with the fluent API. So you will get more detailed stack traces with correct line numbers and the ability to set breakpoints for better debugging.

Force ASP .Net Web API to block HTTP requests with Error (403)

I would like to configure my project to not allow http requests with the following restrictions:
It must be a global restriction for all APIs (via web.config, script in the installer, etc.)
It must be hard coded(not pressing "Require SSL" on the APP in the IIS)
No "redirect"- just return error (403)
my ideal option would be to configure "Require SSL" by a script which runs in the installer.
This can be accomplished by writing a simple ActionFilter that inspects the request and responds when the scheme is not set to ssl. A very minimal implementation may look something like:
public class RequireHttpsAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
}
}
}
To make this apply everywhere, you'll likely want to register it as a global filter in the WebAPI configuration when your application is bootstrapping. That would look something like:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new RequireHttpsAttribute());
// ... More configuration ...
}
}
If you search the web a bit, you can find many examples of similar filters with more robust logic that may better meet your needs.

How can I determine why onFailure is triggered in GWT-RPC?

I have a project that does 2 RPC calls and then saves the data that the user provided in tha datastore. The first RPC call works ok, but from the second I always recieve the onFailure() message. How can I determine why the onFailure() is triggered? I tried caught.getCause() but it doesn't return anything.
feedbackService.saveFeedback(email,studentName,usedTemplates,
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
caught.getCause();
Window.alert("Failure!");
}
public void onSuccess(String result) {
Window.alert("Saved!");
}
});
Throwable instance is instance of an Exception. You can check if it is a custom Exception like this:
if (caught instanceOf CustomException){
or if you want to show the message of exception you can use the getMessage():
Window.alert("Failure: " + caught.getMessage());
GWT-rpc is not not easy to ebug if an error occurs.
The easiest part is th check if the Exception is part of StatusCodeException.
A Statuscode of 404 means, you are pointing to a wrong endpoint
0 means, that
The searver is unreachable
You don't have permissions to check, if the server is available (X-domain-request)
You can use the Chrome-Web-Inspector to bedug GWT-RPC
You should be able to see all calls from the browser to you backend.
The most common failures are because of serialization of object. You have to ensure, that all dtransferred object implement java.io.Serializable
Most of the time it will just be a server side exception being raised which fires the onFailure() method.
Try putting breakpoints on your server side. That should help you pinpoint what's going wrong.

Overrided broadcast(Object message, GwtAtmosphereResource resource) method in Atmosphere with GWT not working

We are trying to handle a scenario that when a user in quitting a room ,we send a message using MetaBroadcaster to all room .We implemented this feature by override broadcast method of AtmosphereGwtHandler .
The feature is good when we testing in development mode, but when we test it in Jetty8 production mode, telling by log, the override method is void which never get called.
So anybody know what's wrong with it, or do we have a better solution to this feature.
here is our code snippet:
public class ChatHandler extends AtmosphereGwtHandler {
...
#Override
public void broadcast(Object message, GwtAtmosphereResource resource) {
MsgType msgtype=((ChatMessage)message).getMsgtype();
if(msgtype==MsgType.Broad){
MetaBroadcaster.getDefault().broadcastTo(((ChatMessage)message).getChanel(), message);
System.out.println("Doing to all room);
}else{
super.broadcast(message, resource);
System.out.println("Doing to myself);
}
}
}
Can't really give an answer on the info provided.
Where have you configured your handler?
web.xml or atmosphere.xml
What servlet are you using Meteor/Atmosphere?
What version of Atmosphere?