Search in sources :

Example 1 with Request

use of play.mvc.Http.Request in project japid42 by branaway.

the class GlobalSettingsWithJapid method beforeActionInvocation.

public static void beforeActionInvocation(Context ctx, Method actionMethod) {
    Request request = ctx.request();
    play.mvc.Http.Flash flash = ctx.flash();
    Map<String, String[]> headers = request.headers();
    String property = dumpRequest;
    if (property != null && property.length() > 0) {
        if (!"false".equals(property) && !"no".equals(property)) {
            if ("yes".equals(property) || "true".equals(property)) {
                JapidFlags.log("action ->: " + actionMethod.toString());
            } else {
                if (request.uri().matches(property)) {
                    JapidFlags.log("action ->: " + actionMethod.toString());
                }
            }
        }
    }
    String string = flash.get(RenderResultCache.READ_THRU_FLASH);
    if (string != null) {
        RenderResultCache.setIgnoreCache(true);
    } else {
        // cache-control in lower case, lower-case for some reason
        String[] header = headers.get("cache-control");
        if (header != null) {
            List<String> list = Arrays.asList(header);
            if (list.contains(NO_CACHE)) {
                RenderResultCache.setIgnoreCache(true);
            }
        } else {
            header = headers.get("pragma");
            if (header != null) {
                List<String> list = Arrays.asList(header);
                if (list.contains(NO_CACHE)) {
                    RenderResultCache.setIgnoreCache(true);
                }
            } else {
                // just in case
                RenderResultCache.setIgnoreCacheInCurrentAndNextReq(false);
            }
        }
    }
}
Also used : Request(play.mvc.Http.Request)

Example 2 with Request

use of play.mvc.Http.Request in project Japid by branaway.

the class ActionBridge method invokeMethod.

/**
	 * this is really to do the reverse url lookup
	 * 
	 * @param actionString
	 * @param param
	 * @return
	 */
public ActionDefinition invokeMethod(String actionString, Object param) {
    try {
        // forms: Controller.action, action, package.Controller.action
        String action = actionString;
        //			String methodName = actionString;
        if (actionString.indexOf(".") > 0) {
        //				int lastIndexOf = actionString.lastIndexOf('.');
        ////				methodName = actionString.substring(lastIndexOf + 1);
        //				controllerName = actionString.substring(0, lastIndexOf);
        //				// fell spec with controller name
        } else {
            Request req = Request.current();
            if (req != null) {
                action = req.controller + "." + actionString;
            }
        }
        try {
            Map<String, Object> args = new HashMap<String, Object>();
            Method actionMethod = (Method) ActionInvoker.getActionMethod(action)[1];
            //				String[] names = (String[]) actionMethod
            //						.getDeclaringClass()
            //						.getDeclaredField("$" + actionMethod.getName() + computeMethodHash(actionMethod.getParameterTypes())).get(null);
            String[] names = Java.parameterNames(actionMethod);
            if (param instanceof Object[]) {
                Object[] arrayParam = (Object[]) param;
                // error. we must warn him.
                if (names.length < arrayParam.length) {
                    throw new NoRouteFoundException(action, null);
                }
                Annotation[] annos = actionMethod.getAnnotations();
                for (int i = 0; i < arrayParam.length; i++) {
                    Object arrayParamElem = arrayParam[i];
                    if (arrayParamElem instanceof Router.ActionDefinition && arrayParamElem != null) {
                        Unbinder.unBind(args, arrayParamElem.toString(), i < names.length ? names[i] : "", annos);
                    } else if (isSimpleParam(actionMethod.getParameterTypes()[i])) {
                        if (arrayParamElem != null) {
                            Unbinder.unBind(args, arrayParamElem.toString(), i < names.length ? names[i] : "", annos);
                        }
                    } else {
                        Unbinder.unBind(args, arrayParamElem, i < names.length ? names[i] : "", annos);
                    }
                }
            }
            Router.ActionDefinition def = Router.reverse(action, args);
            if (absolute) {
                def.absolute();
            }
            // if (template.template.name.endsWith(".html") ||
            // template.template.name.endsWith(".xml")) {
            def.url = def.url.replace("&", "&amp;");
            // }
            return def;
        } catch (ActionNotFoundException e) {
            //				throw new NoRouteFoundException(action, null);
            throw new ReverseRouteException(action);
        }
    } catch (Exception e) {
        if (e instanceof PlayException) {
            throw (PlayException) e;
        }
        if (e instanceof JapidRuntimeException) {
            throw (JapidRuntimeException) e;
        }
        throw new UnexpectedException(e);
    }
}
Also used : JapidRuntimeException(cn.bran.japid.exceptions.JapidRuntimeException) UnexpectedException(play.exceptions.UnexpectedException) HashMap(java.util.HashMap) Request(play.mvc.Http.Request) Router(play.mvc.Router) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) PlayException(play.exceptions.PlayException) JapidRuntimeException(cn.bran.japid.exceptions.JapidRuntimeException) NoRouteFoundException(play.exceptions.NoRouteFoundException) ActionNotFoundException(play.exceptions.ActionNotFoundException) UnexpectedException(play.exceptions.UnexpectedException) ReverseRouteException(cn.bran.play.exceptions.ReverseRouteException) ActionNotFoundException(play.exceptions.ActionNotFoundException) NoRouteFoundException(play.exceptions.NoRouteFoundException) ActionDefinition(play.mvc.Router.ActionDefinition) PlayException(play.exceptions.PlayException) ReverseRouteException(cn.bran.play.exceptions.ReverseRouteException)

Example 3 with Request

use of play.mvc.Http.Request in project japid42 by branaway.

the class GlobalSettingsWithJapid method onRequest.

@Override
public Action<?> onRequest(Request request, final Method actionMethod) {
    final String actionName = actionMethod.getDeclaringClass().getName() + "." + actionMethod.getName();
    final Map<String, String> threadData = JapidController.threadData.get();
    if (!cacheResponse) {
        return new Action.Simple() {

            public Promise<SimpleResult> call(Context ctx) throws Throwable {
                // pass the FQN to the japid controller to determine the
                // template to use
                // will be cleared right when the value is retrieved in the
                // japid controller
                // assuming the delegate call will take place in the same
                // thread
                threadData.put(ACTION_METHOD, actionName);
                Promise<SimpleResult> call = delegate.call(ctx);
                threadData.remove(ACTION_METHOD);
                return call;
            }
        };
    }
    return new Action<Cached>() {

        public Promise<SimpleResult> call(Context ctx) {
            try {
                beforeActionInvocation(ctx, actionMethod);
                SimpleResult result = null;
                Request req = ctx.request();
                String method = req.method();
                int duration = 0;
                String key = null;
                Cached cachAnno = actionMethod.getAnnotation(Cached.class);
                // Check the cache (only for GET or HEAD)
                if ((method.equals("GET") || method.equals("HEAD")) && cachAnno != null) {
                    key = cachAnno.key();
                    if ("".equals(key) || key == null) {
                        key = "urlcache:" + req.uri() + ":" + req.queryString();
                    }
                    duration = cachAnno.duration();
                    result = (SimpleResult) Cache.get(key);
                }
                if (result == null) {
                    // pass the action name hint to japid controller
                    threadData.put(ACTION_METHOD, actionName);
                    Promise<SimpleResult> ps = delegate.call(ctx);
                    threadData.remove(ACTION_METHOD);
                    if (!StringUtils.isEmpty(key) && duration > 0) {
                        result = ps.get(1, TimeUnit.MILLISECONDS);
                        Cache.set(key, result, duration);
                    }
                    onActionInvocationResult(ctx);
                    return ps;
                } else {
                    onActionInvocationResult(ctx);
                    return Promise.pure(result);
                }
            } catch (RuntimeException e) {
                throw e;
            } catch (Throwable t) {
                throw new RuntimeException(t);
            }
        }
    };
// return new Action.Simple() {
// public Result call(Context ctx) throws Throwable {
// beforeActionInvocation(ctx, actionMethod);
// dumpIt(ctx.request(), actionMethod);
// Result call = delegate.call(ctx);
// onActionInvocationResult(ctx);
// return call;
// }
// };
}
Also used : Context(play.mvc.Http.Context) Action(play.mvc.Action) Request(play.mvc.Http.Request) Cached(play.cache.Cached) SimpleResult(play.mvc.SimpleResult)

Example 4 with Request

use of play.mvc.Http.Request in project play-cookbook by spinscale.

the class RenderPDF method getTemplateFile.

private VirtualFile getTemplateFile(Object... args) {
    final Http.Request request = Http.Request.current();
    String templateName = null;
    List<String> renderNames = LocalVariablesNamesTracer.getAllLocalVariableNames(args[0]);
    if (args.length > 0 && args[0] instanceof String && renderNames.isEmpty()) {
        templateName = args[0].toString();
    } else {
        templateName = request.action.replace(".", "/") + ".fo";
    }
    if (templateName.startsWith("@")) {
        templateName = templateName.substring(1);
        if (!templateName.contains(".")) {
            templateName = request.controller + "." + templateName;
        }
        templateName = templateName.replace(".", "/") + ".fo";
    }
    VirtualFile file = VirtualFile.search(Play.templatesPath, templateName);
    return file;
}
Also used : VirtualFile(play.vfs.VirtualFile) Request(play.mvc.Http.Request) Http(play.mvc.Http)

Example 5 with Request

use of play.mvc.Http.Request in project play-cookbook by spinscale.

the class CachingTest method testThatEtagCachingWorks.

@Test
public void testThatEtagCachingWorks() {
    Response response = GET("/etagCache/123");
    assertIsOk(response);
    assertContentEquals("Learn to use etags, dumbass!", response);
    Request request = newRequest();
    String etag = String.valueOf("123".hashCode());
    Header noneMatchHeader = new Header("if-none-match", etag);
    request.headers.put("if-none-match", noneMatchHeader);
    DateTime ago = new DateTime().minusHours(12);
    String agoStr = Utils.getHttpDateFormatter().format(ago.toDate());
    Header modifiedHeader = new Header("if-modified-since", agoStr);
    request.headers.put("if-modified-since", modifiedHeader);
    response = GET(request, "/etagCache/123");
    assertStatus(304, response);
}
Also used : Response(play.mvc.Http.Response) Header(play.mvc.Http.Header) Request(play.mvc.Http.Request) DateTime(org.joda.time.DateTime) FunctionalTest(play.test.FunctionalTest) Test(org.junit.Test)

Aggregations

Request (play.mvc.Http.Request)5 JapidRuntimeException (cn.bran.japid.exceptions.JapidRuntimeException)1 ReverseRouteException (cn.bran.play.exceptions.ReverseRouteException)1 Annotation (java.lang.annotation.Annotation)1 Method (java.lang.reflect.Method)1 HashMap (java.util.HashMap)1 DateTime (org.joda.time.DateTime)1 Test (org.junit.Test)1 Cached (play.cache.Cached)1 ActionNotFoundException (play.exceptions.ActionNotFoundException)1 NoRouteFoundException (play.exceptions.NoRouteFoundException)1 PlayException (play.exceptions.PlayException)1 UnexpectedException (play.exceptions.UnexpectedException)1 Action (play.mvc.Action)1 Http (play.mvc.Http)1 Context (play.mvc.Http.Context)1 Header (play.mvc.Http.Header)1 Response (play.mvc.Http.Response)1 Router (play.mvc.Router)1 ActionDefinition (play.mvc.Router.ActionDefinition)1