public static String stringSearchParamOrEmpty(Http.Request request, String param) { if (request.getQueryString(param) == null || request.getQueryString(param).isEmpty()) { return ""; } else { return request.getQueryString(param); } }
public static Object invokeControllerMethod(Method method, Object[] forceArgs) throws Exception { if (Modifier.isStatic(method.getModifiers()) && !method.getDeclaringClass().getName().matches("^controllers\\..*\\$class$")) { return invoke( method, null, forceArgs == null ? getActionMethodArgs(method, null) : forceArgs); } else if (Modifier.isStatic(method.getModifiers())) { Object[] args = getActionMethodArgs(method, null); args[0] = Http.Request.current().controllerClass.getDeclaredField("MODULE$").get(null); return invoke(method, null, args); } else { Object instance = null; try { instance = method.getDeclaringClass().getDeclaredField("MODULE$").get(null); } catch (Exception e) { Annotation[] annotations = method.getDeclaredAnnotations(); String annotation = Utils.getSimpleNames(annotations); if (!StringUtils.isEmpty(annotation)) { throw new UnexpectedException( "Method public static void " + method.getName() + "() annotated with " + annotation + " in class " + method.getDeclaringClass().getName() + " is not static."); } // TODO: Find a better error report throw new ActionNotFoundException(Http.Request.current().action, e); } return invoke( method, instance, forceArgs == null ? getActionMethodArgs(method, instance) : forceArgs); } }
public static Object invokeControllerMethod(Method method, Object[] forceArgs) throws Exception { boolean isStatic = Modifier.isStatic(method.getModifiers()); String declaringClassName = method.getDeclaringClass().getName(); boolean isProbablyScala = declaringClassName.contains("$"); Http.Request request = Http.Request.current(); if (!isStatic && request.controllerInstance == null) { request.controllerInstance = request.controllerClass.newInstance(); } Object[] args = forceArgs != null ? forceArgs : getActionMethodArgs(method, request.controllerInstance); if (isProbablyScala) { try { Object scalaInstance = request.controllerClass.getDeclaredField("MODULE$").get(null); if (declaringClassName.endsWith("$class")) { args[0] = scalaInstance; // Scala trait method } else { request.controllerInstance = (Controller) scalaInstance; // Scala // object // method } } catch (NoSuchFieldException e) { // not Scala } } return invoke(method, request.controllerInstance, args); }
public static int intSearchParamOrEmpty(Http.Request request, String param) { if (request.getQueryString(param) == null || request.getQueryString(param).isEmpty()) { return 0; } else { try { return Integer.parseInt(request.getQueryString(param)); } catch (NumberFormatException e) { return 0; } } }
public RequestContext(Http.Request request) { final ProtectedData protectedData = GlobalHost.getDependencyResolver().getService(ProtectedData.class); final String connectionToken = request.getQueryString("connectionToken"); final String decryptedToken = protectedData.unprotect(connectionToken, Purposes.ConnectionToken).get(); connectionId = UUID.fromString(decryptedToken.substring(0, decryptedToken.lastIndexOf(':'))); username = decryptedToken.substring(decryptedToken.indexOf(':') + 1); final String connectionData = request.getQueryString("connectionData"); hubName = getHubName(connectionData); queryString = getQueryParams(request.queryString()); messageId = Optional.empty(); }
// Gets baseUrl from current request or application.baseUrl in application.conf protected static String getBaseUrl() { if (Http.Request.current() == null) { // No current request is present - must get baseUrl from config String appBaseUrl = Play.configuration.getProperty("application.baseUrl", "application.baseUrl"); if (appBaseUrl.endsWith("/")) { // remove the trailing slash appBaseUrl = appBaseUrl.substring(0, appBaseUrl.length() - 1); } return appBaseUrl; } else { return Http.Request.current().getBase(); } }
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); } }
/** * リクエストハンドリング * * @param request * @param method * @return */ @SuppressWarnings("rawtypes") @Override public Action onRequest(Http.Request request, Method method) { // System.out.println("onRequest"); Logger.info(Json.toJson(request.headers()).toString()); return super.onRequest(request, method); }
public void checkAndParse() { if (!requestIsParsed) { Http.Request request = Http.Request.current(); if (request == null) { throw new UnexpectedException("Current request undefined"); } else { String contentType = request.contentType; if (contentType != null) { DataParser dataParser = DataParser.parsers.get(contentType); if (dataParser != null) { _mergeWith(dataParser.parse(request.body)); } else { if (contentType.startsWith("text/")) { _mergeWith(new TextParser().parse(request.body)); } } } try { request.body.close(); } catch (Exception e) { // } requestIsParsed = true; } } }
static void save() { if (Http.Response.current() == null) { // Some request like WebSocket don't have any response return; } if (Validation.errors().isEmpty()) { // Only send "delete cookie" header when the cookie was present in the request if (Http.Request.current().cookies.containsKey(Scope.COOKIE_PREFIX + "_ERRORS") || !Scope.SESSION_SEND_ONLY_IF_CHANGED) { Http.Response.current().setCookie(Scope.COOKIE_PREFIX + "_ERRORS", "", "0s"); } return; } try { StringBuilder errors = new StringBuilder(); if (Validation.current() != null && Validation.current().keep) { for (Error error : Validation.errors()) { errors.append("\u0000"); errors.append(error.key); errors.append(":"); errors.append(error.message); for (String variable : error.variables) { errors.append("\u0001"); errors.append(variable); } errors.append("\u0000"); } } String errorsData = URLEncoder.encode(errors.toString(), "utf-8"); Http.Response.current().setCookie(Scope.COOKIE_PREFIX + "_ERRORS", errorsData); } catch (Exception e) { throw new UnexpectedException("Errors serializationProblem", e); } }
/** * Generates the error json required for ajax calls calls when the user is not authorized to * execute the action * * @return */ protected static Promise<Result> notAuthorizedResult(Http.Context ctx) { Http.Request req = ctx.request(); Result result; if (req.accepts("text/html")) { result = forbidden(notAuthorizedPage(ctx)); } else if (req.accepts("application/json")) { ObjectNode node = Json.newObject(); node.put("error", "Not authorized"); result = forbidden(node); } else { result = forbidden("Not authorized"); } return Promise.pure(result); }
/** * Generates the error json required for ajax calls calls when the user is not authenticated * * @return */ protected static Promise<Result> notAuthenticatedResult(Http.Context ctx) { Http.Request req = ctx.request(); Result result; if (req.accepts("text/html")) { ctx.flash().put("error", play.i18n.Messages.get("securesocial.loginRequired")); ctx.session().put(ORIGINAL_URL, ctx.request().uri()); result = redirect(env().routes().loginPageUrl(ctx._requestHeader())); } else if (req.accepts("application/json")) { ObjectNode node = Json.newObject(); node.put("error", "Credentials required"); result = unauthorized(node); } else { result = unauthorized("Credentials required"); } return Promise.pure(result); }
private void renderDocuments(Map<String, Object> args) { for (PDFDocument doc : docs.documents) { Request request = Http.Request.current(); String templateName = PDF.resolveTemplateName(doc.template, request, request.format); Template template = TemplateLoader.load(templateName); doc.content = template.render(new HashMap<String, Object>(args)); loadHeaderAndFooter(doc, args); } }
/** * 현재 사용자가 선호하는 언어를 갱신한다. * * <p>쿠키나 Accept-Language HTTP 헤더에 선호하는 언어가 설정되어 있는 경우, 그것을 현재 로그인한 사용자가 선호하는 언어로 설정한다. */ public static void updatePreferredLanguage() { Http.Request request = Http.Context.current().request(); User user = UserApp.currentUser(); if (user.isAnonymous()) { return; } if (request.acceptLanguages().isEmpty() && request.cookie(Play.langCookieName()) == null) { return; } String code = StringUtils.left(Http.Context.current().lang().code(), 255); if (!code.equals(user.lang)) { user.lang = code; user.update(); } }
public GTRenderingResult internalGTRender(Map<String, Object> args) { Http.Request currentResponse = Http.Request.current(); if (currentResponse != null) { args.put("_response_encoding", currentResponse.encoding); } args.put("play", new Play()); args.put("messages", new Messages()); args.put("lang", Lang.get()); return renderGTTemplate(args); }
static Flash restore() { try { Flash flash = new Flash(); Http.Cookie cookie = Http.Request.current().cookies.get(COOKIE_PREFIX + "_FLASH"); if (cookie != null) { CookieDataCodec.decode(flash.data, cookie.value); } return flash; } catch (Exception e) { throw new UnexpectedException("Flash corrupted", e); } }
public void absolute() { boolean isSecure = Http.Request.current() == null ? false : Http.Request.current().secure; String base = getBaseUrl(); String hostPart = host; String domain = Http.Request.current() == null ? "" : Http.Request.current().get().domain; int port = Http.Request.current() == null ? 80 : Http.Request.current().get().port; if (port != 80 && port != 443) { hostPart += ":" + port; } // ~ if (!url.startsWith("http")) { if (StringUtils.isEmpty(host)) { url = base + url; } else if (host.contains("{_}")) { java.util.regex.Matcher matcher = java.util.regex.Pattern.compile("([-_a-z0-9A-Z]+([.][-_a-z0-9A-Z]+)?)$") .matcher(domain); if (matcher.find()) { url = (isSecure ? "https://" : "http://") + hostPart.replace("{_}", matcher.group(1)) + url; } else { url = (isSecure ? "https://" : "http://") + hostPart + url; } } else { url = (isSecure ? "https://" : "http://") + hostPart + url; } if (method.equals("WS")) { url = url.replaceFirst("https?", "ws"); } } }
public static String reverse(VirtualFile file, boolean absolute) { if (file == null || !file.exists()) { throw new NoRouteFoundException("File not found (" + file + ")"); } String path = file.relativePath(); path = path.substring(path.indexOf("}") + 1); for (Route route : routes) { String staticDir = route.staticDir; if (staticDir != null) { if (!staticDir.startsWith("/")) { staticDir = "/" + staticDir; } if (!staticDir.equals("/") && !staticDir.endsWith("/")) { staticDir = staticDir + "/"; } if (path.startsWith(staticDir)) { String to = route.path + path.substring(staticDir.length()); if (to.endsWith("/index.html")) { to = to.substring(0, to.length() - "/index.html".length() + 1); } if (absolute) { boolean isSecure = Http.Request.current() == null ? false : Http.Request.current().secure; String base = getBaseUrl(); if (!StringUtils.isEmpty(route.host)) { // Compute the host int port = Http.Request.current() == null ? 80 : Http.Request.current().get().port; String host = (port != 80 && port != 443) ? route.host + ":" + port : route.host; to = (isSecure ? "https://" : "http://") + host + to; } else { to = base + to; } } return to; } } } throw new NoRouteFoundException(file.relativePath()); }
@SuppressWarnings("unchecked") public static void resolve(Http.Request request, Http.Response response) throws NotFound, RenderStatic { if (!Play.started) { return; } Http.Request.current.set(request); Http.Response.current.set(response); Scope.Params.current.set(request.params); Scope.RenderArgs.current.set(new Scope.RenderArgs()); Scope.RouteArgs.current.set(new Scope.RouteArgs()); Scope.Session.current.set(Scope.Session.restore()); Scope.Flash.current.set(Scope.Flash.restore()); CachedBoundActionMethodArgs.init(); ControllersEnhancer.currentAction.set(new Stack<String>()); if (request.resolved) { return; } // Route and resolve format if not already done if (request.action == null) { Play.pluginCollection.routeRequest(request); Route route = Router.route(request); Play.pluginCollection.onRequestRouting(route); } request.resolveFormat(); // Find the action method try { Method actionMethod = null; Object[] ca = getActionMethod(request.action); actionMethod = (Method) ca[1]; request.controller = ((Class) ca[0]).getName().substring(12).replace("$", ""); request.controllerClass = ((Class) ca[0]); request.actionMethod = actionMethod.getName(); request.action = request.controller + "." + request.actionMethod; request.invokedMethod = actionMethod; if (Logger.isTraceEnabled()) { Logger.trace("------- %s", actionMethod); } request.resolved = true; } catch (ActionNotFoundException e) { // Logger.error(e, "%s action not found", e.getAction()); // bran: avoid excessive messages Logger.error("%s action not found", e.getAction()); throw new NotFound(String.format("%s action not found", e.getAction())); } }
/** * the content-type should be application/x-www-form-urlencoded * * @return */ public static Result publishPrivateTweet() { TweetResult tweetResult; Http.Request request = request(); Map<String, String[]> param = request.body().asFormUrlEncoded(); String content = null; // TODO i am not sure need to decode or not? // try { // content = URLDecoder.decode(param.get("content")[0], "utf-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } content = param.get("content")[0]; String device = param.get("device")[0]; String owner_id = session("id"); if (owner_id == null || owner_id.length() == 0) { return ok(Json.toJson(new TweetResult(1000, null))); } return publishPrivateTweet(owner_id, content, device); }
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); } }
// // NOTE: This file was generated from: japidviews/_tags/SampleTag.html // Change to this file will be lost next time the template file is compiled. // @cn.bran.play.NoEnhance public class SampleTag extends cn.bran.japid.template.JapidTemplateBase { public static final String sourceTemplate = "japidviews/_tags/SampleTag.html"; { headers.put("Content-Type", "text/html; charset=utf-8"); } // - add implicit fields with Play final Request request = Request.current(); final Response response = Response.current(); final Session session = Session.current(); final RenderArgs renderArgs = RenderArgs.current(); final Params params = Params.current(); final Validation validation = Validation.current(); final cn.bran.play.FieldErrors errors = new cn.bran.play.FieldErrors(validation); final play.Play _play = new play.Play(); // - end of implicit fields with Play public SampleTag() { super(null); } public SampleTag(StringBuilder out) { super(out); } private String a; public cn.bran.japid.template.RenderResult render(String a) { this.a = a; long t = -1; super.layout(); return new cn.bran.japid.template.RenderResult(this.headers, getOut(), t); } @Override protected void doLayout() { // ------ ; // line 1 p("Hi "); // line 1 p(a); // line 2 p("!\n"); // line 2 } }
// // NOTE: This file was generated from: japidviews/more/MyController/myLayout.html // Change to this file will be lost next time the template file is compiled. // @cn.bran.play.NoEnhance public abstract class myLayout extends cn.bran.japid.template.JapidTemplateBase { public static final String sourceTemplate = "japidviews/more/MyController/myLayout.html"; { putHeader("Content-Type", "text/html; charset=utf-8"); } // - add implicit fields with Play final Request request = Request.current(); final Response response = Response.current(); final Session session = Session.current(); final RenderArgs renderArgs = RenderArgs.current(); final Params params = Params.current(); final Validation validation = Validation.current(); final cn.bran.play.FieldErrors errors = new cn.bran.play.FieldErrors(validation); final play.Play _play = new play.Play(); // - end of implicit fields with Play public myLayout() { super(null); } public myLayout(StringBuilder out) { super(out); } @Override public void layout() { p("<p>"); // line 1 title(); // line 1 p("</p>\n" + "<p>"); // line 1 side(); // line 2 p("</p>\n" + "<p>\n"); // line 2 doLayout(); // line 4 p("</p>"); // line 4 } protected void title() {}; protected void side() {}; protected abstract void doLayout(); }
public List<ConstraintViolation> validateAction(Method actionMethod) throws Exception { List<ConstraintViolation> violations = new ArrayList<ConstraintViolation>(); Object instance = null; // Patch for scala defaults if (!Modifier.isStatic(actionMethod.getModifiers()) && actionMethod.getDeclaringClass().getSimpleName().endsWith("$")) { try { instance = actionMethod.getDeclaringClass().getDeclaredField("MODULE$").get(null); } catch (Exception e) { throw new ActionNotFoundException(Http.Request.current().action, e); } } Object[] rArgs = ActionInvoker.getActionMethodArgs(actionMethod, instance); validateMethodParameters(null, actionMethod, rArgs, violations); validateMethodPre(null, actionMethod, rArgs, violations); return violations; }
public static Route route(Http.Request request) { if (Logger.isTraceEnabled()) { Logger.trace("Route: " + request.path + " - " + request.querystring); } // request method may be overriden if a x-http-method-override parameter is given if (request.querystring != null && methodOverride.matches(request.querystring)) { Matcher matcher = methodOverride.matcher(request.querystring); if (matcher.matches()) { if (Logger.isTraceEnabled()) { Logger.trace( "request method %s overriden to %s ", request.method, matcher.group("method")); } request.method = matcher.group("method"); } } for (Route route : routes) { Map<String, String> args = route.matches(request.method, request.path, request.format, request.domain); if (args != null) { request.routeArgs = args; request.action = route.action; if (args.containsKey("format")) { request.format = args.get("format"); } if (request.action.indexOf("{") > -1) { // more optimization ? for (String arg : request.routeArgs.keySet()) { request.action = request.action.replace("{" + arg + "}", request.routeArgs.get(arg)); } } if (request.action.equals("404")) { throw new NotFound(route.path); } return route; } } // Not found - if the request was a HEAD, let's see if we can find a corresponding GET if (request.method.equalsIgnoreCase("head")) { request.method = "GET"; Route route = route(request); request.method = "HEAD"; if (route != null) { return route; } } throw new NotFound(request.method, request.path); }
@Override public Action onRequest(Http.Request request, Method method) { String ip = request.remoteAddress(); IPAddress ipAddress = IPAddress.findByIp(ip); if (ipAddress == null) { ipAddress = new IPAddress(ip, 1L, false); ipAddress.save(); } else { if (ipAddress.isBanned()) { return new Action.Simple() { @Override public F.Promise<SimpleResult> call(Http.Context ctx) throws Throwable { return F.Promise.pure((SimpleResult) status(0)); } }; } } return super.onRequest(request, method); }
static Validation restore() { try { Validation validation = new Validation(); Http.Cookie cookie = Http.Request.current().cookies.get(Scope.COOKIE_PREFIX + "_ERRORS"); if (cookie != null) { String errorsData = URLDecoder.decode(cookie.value, "utf-8"); Matcher matcher = errorsParser.matcher(errorsData); while (matcher.find()) { String[] g2 = matcher.group(2).split("\u0001"); String message = g2[0]; String[] args = new String[g2.length - 1]; System.arraycopy(g2, 1, args, 0, args.length); validation.errors.add(new Error(matcher.group(1), message, args)); } } return validation; } catch (Exception e) { return new Validation(); } }
protected static Map<String, Object> getBindingForErrors(Exception e, boolean isError) { Map<String, Object> binding = new HashMap<String, Object>(); if (!isError) { binding.put("result", e); } else { binding.put("exception", e); } binding.put("session", Scope.Session.current()); binding.put("request", Http.Request.current()); binding.put("flash", Scope.Flash.current()); binding.put("params", Scope.Params.current()); binding.put("play", new Play()); try { binding.put("errors", Validation.errors()); } catch (Exception ex) { // Logger.error(ex, "Error when getting Validation errors"); } return binding; }
void save() { if (Http.Response.current() == null) { // Some request like WebSocket don't have any response return; } if (out.isEmpty()) { if (Http.Request.current().cookies.containsKey(COOKIE_PREFIX + "_FLASH") || !SESSION_SEND_ONLY_IF_CHANGED) { Http.Response.current() .setCookie(COOKIE_PREFIX + "_FLASH", "", null, "/", 0, COOKIE_SECURE); } return; } try { String flashData = CookieDataCodec.encode(out); Http.Response.current() .setCookie(COOKIE_PREFIX + "_FLASH", flashData, null, "/", null, COOKIE_SECURE); } catch (Exception e) { throw new UnexpectedException("Flash serializationProblem", e); } } // ThreadLocal access
/** @see IdentityProvider#doAuth(java.util.Map) */ @Override protected SocialUser doAuth(Map<String, Object> authContext) { if (!OpenID.isAuthenticationResponse()) { OpenID openId = OpenID.id(getUser()); final String url = getFullUrl(); openId.returnTo(url); openId.forRealm(Http.Request.current().getBase()); configure(openId); if (!openId.verify()) { throw new AuthenticationException(); } } // OpenID.UserInfo verifiedUser = OpenID.getVerifiedID(); if (verifiedUser == null) { throw new AuthenticationException(); } authContext.put(USER_INFO, verifiedUser); SocialUser user = createUser(); user.id.id = verifiedUser.id; return user; }