/** * an action call with cache * * @param ac the action invocation wrapper * @param key user specified key, the user needs to explicitly compose a key from the action and * arguments. The template transformer can put the action calling string as prefix of the key, * e.g., if the acton is Application.show(post), the key should be compose of * "Application.show()-" + post.toString(). Note we cannot use "post" literally since post as * the var name can be anything that the template author chooses to use. Problem: Application * needs to be imported or all controllers package must be imported. Controllers in sub * packages needs special care in importing since a simple import controllers.* won't work for * controllers in sub packages. * @param ttl expiration Ex: 10s, 3mn, 8h */ public void render(String key, String ttl, Body body) { String co = (String) Cache.get(key); if (co == null) { co = body.render(); Cache.set(key, co, Time.parseDuration(ttl)); } p(co); return; }
static Session restore() { try { Session session = new Session(); Http.Cookie cookie = Http.Request.current().cookies.get(COOKIE_PREFIX + "_SESSION"); final int duration = Time.parseDuration(COOKIE_EXPIRE); final long expiration = (duration * 1000l); if (cookie != null && Play.started && cookie.value != null && !cookie.value.trim().equals("")) { String value = cookie.value; int firstDashIndex = value.indexOf("-"); if (firstDashIndex > -1) { String sign = value.substring(0, firstDashIndex); String data = value.substring(firstDashIndex + 1); if (CookieDataCodec.safeEquals(sign, Crypto.sign(data, Play.secretKey.getBytes()))) { CookieDataCodec.decode(session.data, data); } } if (COOKIE_EXPIRE != null) { // Verify that the session contains a timestamp, and that it's not expired if (!session.contains(TS_KEY)) { session = new Session(); } else { if ((Long.parseLong(session.get(TS_KEY))) < System.currentTimeMillis()) { // Session expired session = new Session(); } } session.put(TS_KEY, System.currentTimeMillis() + expiration); } else { // Just restored. Nothing changed. No cookie-expire. session.changed = false; } } else { // no previous cookie to restore; but we may have to set the timestamp in the new cookie if (COOKIE_EXPIRE != null) { session.put(TS_KEY, (System.currentTimeMillis() + expiration)); } } return session; } catch (Exception e) { throw new UnexpectedException( "Corrupted HTTP session from " + Http.Request.current().remoteAddress, e); } }
void save() { if (Http.Response.current() == null) { // Some request like WebSocket don't have any response return; } if (!changed && SESSION_SEND_ONLY_IF_CHANGED && COOKIE_EXPIRE == null) { // Nothing changed and no cookie-expire, consequently send nothing back. return; } if (isEmpty()) { // The session is empty: delete the cookie if (Http.Request.current().cookies.containsKey(COOKIE_PREFIX + "_SESSION") || !SESSION_SEND_ONLY_IF_CHANGED) { Http.Response.current() .setCookie( COOKIE_PREFIX + "_SESSION", "", null, "/", 0, COOKIE_SECURE, SESSION_HTTPONLY); } return; } try { String sessionData = CookieDataCodec.encode(data); String sign = Crypto.sign(sessionData, Play.secretKey.getBytes()); if (COOKIE_EXPIRE == null) { Http.Response.current() .setCookie( COOKIE_PREFIX + "_SESSION", sign + "-" + sessionData, null, "/", null, COOKIE_SECURE, SESSION_HTTPONLY); } else { Http.Response.current() .setCookie( COOKIE_PREFIX + "_SESSION", sign + "-" + sessionData, null, "/", Time.parseDuration(COOKIE_EXPIRE), COOKIE_SECURE, SESSION_HTTPONLY); } } catch (Exception e) { throw new UnexpectedException("Session serializationProblem", e); } }
public static void scheduleForCRON(Job job) { if (job.getClass().isAnnotationPresent(On.class)) { String cron = ((On) (job.getClass().getAnnotation(On.class))).value(); if (cron.startsWith("cron.")) { cron = Play.configuration.getProperty(cron); } if (cron != null && !cron.equals("")) { try { Date now = new Date(); Date nextDate = Time.parseCRONExpression(cron); long delay = nextDate.getTime() - now.getTime(); executor.schedule((Callable) job, delay, TimeUnit.MILLISECONDS); job.executor = executor; } catch (Exception ex) { throw new UnexpectedException(ex); } } else { Logger.info("Skipping job %s, cron expression is not defined", job.getClass().getName()); } } }
@Override public void afterApplicationStart() { List<Class<?>> jobs = new ArrayList<Class<?>>(); for (Class clazz : Play.classloader.getAllClasses()) { if (Job.class.isAssignableFrom(clazz)) { jobs.add(clazz); } } scheduledJobs = new ArrayList<Job>(); for (final Class<?> clazz : jobs) { // @OnApplicationStart if (clazz.isAnnotationPresent(OnApplicationStart.class)) { // check if we're going to run the job sync or async OnApplicationStart appStartAnnotation = clazz.getAnnotation(OnApplicationStart.class); if (!appStartAnnotation.async()) { // run job sync try { Job<?> job = ((Job<?>) clazz.newInstance()); scheduledJobs.add(job); job.run(); if (job.wasError) { if (job.lastException != null) { throw job.lastException; } throw new RuntimeException("@OnApplicationStart Job has failed"); } } catch (InstantiationException e) { throw new UnexpectedException("Job could not be instantiated", e); } catch (IllegalAccessException e) { throw new UnexpectedException("Job could not be instantiated", e); } catch (Throwable ex) { if (ex instanceof PlayException) { throw (PlayException) ex; } throw new UnexpectedException(ex); } } else { // run job async try { Job<?> job = ((Job<?>) clazz.newInstance()); scheduledJobs.add(job); // start running job now in the background @SuppressWarnings("unchecked") Callable<Job> callable = (Callable<Job>) job; executor.submit(callable); } catch (InstantiationException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } catch (IllegalAccessException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } } } // @On if (clazz.isAnnotationPresent(On.class)) { try { Job<?> job = ((Job<?>) clazz.newInstance()); scheduledJobs.add(job); scheduleForCRON(job); } catch (InstantiationException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } catch (IllegalAccessException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } } // @Every if (clazz.isAnnotationPresent(Every.class)) { try { Job job = (Job) clazz.newInstance(); scheduledJobs.add(job); String value = job.getClass().getAnnotation(Every.class).value(); if (value.startsWith("cron.")) { value = Play.configuration.getProperty(value); } value = Expression.evaluate(value, value).toString(); if (!"never".equalsIgnoreCase(value)) { executor.scheduleWithFixedDelay( job, Time.parseDuration(value), Time.parseDuration(value), TimeUnit.SECONDS); } } catch (InstantiationException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } catch (IllegalAccessException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } } } }
/** * set a RenderResult in cache * * @param key * @param rr * @param ttl */ public static void set(String key, RenderResult rr, String ttl) { int tl = Time.parseDuration(ttl) * 1000; CachedItemStatus cachedItemStatus = new CachedItemStatus(tl); cacheset(key, ttl, new CachedRenderResult(cachedItemStatus, rr)); // cacheTacker.put(key, cachedItemStatus); }
@Override public void afterApplicationStart() { List<Class> jobs = new ArrayList(); for (Class clazz : Play.classloader.getAllClasses()) { if (Job.class.isAssignableFrom(clazz)) { jobs.add(clazz); } } scheduledJobs = new ArrayList(); for (final Class clazz : jobs) { // @OnApplicationStart if (clazz.isAnnotationPresent(OnApplicationStart.class)) { try { Job job = ((Job) clazz.newInstance()); scheduledJobs.add(job); job.run(); if (job.wasError) { if (job.lastException != null) { throw job.lastException; } throw new RuntimeException("@OnApplicationStart Job has failed"); } } catch (InstantiationException e) { throw new UnexpectedException("Job could not be instantiated", e); } catch (IllegalAccessException e) { throw new UnexpectedException("Job could not be instantiated", e); } catch (Throwable ex) { if (ex instanceof PlayException) { throw (PlayException) ex; } throw new UnexpectedException(ex); } } // @On if (clazz.isAnnotationPresent(On.class)) { try { Job job = ((Job) clazz.newInstance()); scheduledJobs.add(job); scheduleForCRON(job); } catch (InstantiationException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } catch (IllegalAccessException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } } // @Every if (clazz.isAnnotationPresent(Every.class)) { try { Job job = (Job) clazz.newInstance(); scheduledJobs.add(job); String value = ((Every) (job.getClass().getAnnotation(Every.class))).value(); executor.scheduleWithFixedDelay( job, Time.parseDuration(value), Time.parseDuration(value), TimeUnit.SECONDS); } catch (InstantiationException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } catch (IllegalAccessException ex) { throw new UnexpectedException("Cannot instanciate Job " + clazz.getName()); } } } }