Make sure the result is a regular game.

I am trying to make a slightly better @Cached annotation by telling her about the parameters of the function that I call in my controllers.

so i have this action:

public class ContextualCachedAction extends Action<ContextualCached> { @Override public Result call(Context ctx) throws Throwable { try { String key = makeKey(ctx); Integer duration = configuration.duration(); Result result = (Result) Cache.get(key); if (result == null) { result = delegate.call(ctx); //TODO find a way to cache only successful calls Cache.set(key, result, duration); } return result; } catch (RuntimeException e) { throw e; } catch (Throwable t) { throw new RuntimeException(t); } } private String makeKey(Context ctx) { //makes the key from some parameters in the ctx.request() } } 

My question is this: I would like to cache the result of delegate.call () only if it is Ok (). How can I check this? Is there any property? a util? or I need Ok (). getClass (). isInstance (result)?

Thanks for any answers and tips.

PS: Why do I want to do this? Because I have several calls that generate several types of different results. Quite a few results that caching them might be an option since I don't want to

+7
source share
4 answers

The result of ok is actually play.mvc.Results.Status , which wraps it with a Scala analogue to play.api.mvc.Results.Status , which, in turn, has its status code set to 200.

So, you call result.getWrappedResult() and check if the type is correct, draw it on PlainResult (the lowest common denominator) and call status .

It looks very ugly:

  play.api.mvc.Result wrappedResult = result.getWrappedResult(); if (wrappedResult instanceof play.api.mvc.PlainResult) { play.api.mvc.PlainResult plainResult = (play.api.mvc.PlainResult)wrappedResult; int code = plainResult.header().status(); if (code == OK) // Cache } 
+6
source

Less juicy approach:

 import org.junit.*; import static org.fest.assertions.Assertions.assertThat; import static play.test.Helpers.*; /* do stuff */ Result result = doSomethingWithController(); assertThat(status(result)).isEqualTo(OK); 

Works with 2.2.2.

+8
source

Just refresh this page with the latest version 2.3+ of Playframework.

 Result result = //..... int httpStatus = result.toScala().header().status(); 

easy enough.

+3
source

If you know that your Result is an instance of play.mvc.Results.Status (which is, if you created it using any of the static helper methods from the play.mvc.Results class), you can direct it to Status and get a SimpleResult directly using getWrappedSimpleResult() :

 Status result = (Status) YourController.actionHandler(); int expected = Results.ok() .getWrappedSimpleResult().header().status(); int actual = result.getWrappedSimpleResult().header().status(); Assert.assertEquals(expected, actual); 
+2
source

All Articles