play.mvc.Http.Request Java Examples
The following examples show how to use
play.mvc.Http.Request.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ActionInvoker.java From restcommander with Apache License 2.0 | 6 votes |
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); } }
Example #2
Source File: BaseController.java From sunbird-lms-service with MIT License | 6 votes |
private static Map<String, Object> generateTelemetryInfoForError(Request request) { try { Map<String, Object> map = new HashMap<>(); String reqContext = request.flash().get(JsonKey.CONTEXT); Map<String, Object> requestInfo = objectMapper.readValue(reqContext, new TypeReference<Map<String, Object>>() {}); if (requestInfo != null) { Map<String, Object> contextInfo = (Map<String, Object>) requestInfo.get(JsonKey.CONTEXT); map.put(JsonKey.CONTEXT, contextInfo); } Map<String, Object> params = new HashMap<>(); params.put(JsonKey.ERR_TYPE, JsonKey.API_ACCESS); map.put(JsonKey.PARAMS, params); return map; } catch (Exception ex) { ProjectCommonException.throwServerErrorException(ResponseCode.SERVER_ERROR); } return Collections.emptyMap(); }
Example #3
Source File: UploadBinder.java From restcommander with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") public Object bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { if (value == null || value.trim().length() == 0) { return null; } try { List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS"); for (Upload upload : uploads) { if (upload.getFieldName().equals(value) && upload.getSize() > 0) { return upload; } } if (Params.current().get(value + "_delete_") != null) { return null; } return Binder.MISSING; } catch (Exception e) { Logger.error("", e); throw new UnexpectedException(e); } }
Example #4
Source File: FileArrayBinder.java From restcommander with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") public File[] bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { if (value == null || value.trim().length() == 0) { return null; } List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS"); List<File> fileArray = new ArrayList<File>(); for (Upload upload : uploads) { if (upload.getFieldName().equals(value)) { File file = upload.asFile(); if (file.length() > 0) { fileArray.add(file); } } } return fileArray.toArray(new File[fileArray.size()]); }
Example #5
Source File: FileBinder.java From restcommander with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") public File bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { if (value == null || value.trim().length() == 0) { return null; } List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS"); for (Upload upload : uploads) { if (upload.getFieldName().equals(value)) { File file = upload.asFile(); if (file.length() > 0) { return file; } return null; } } return null; }
Example #6
Source File: BaseController.java From sunbird-lms-service with MIT License | 6 votes |
/** * Common exception response handler method. * * @param e Exception * @param request play.mvc.Http.Request * @return Result */ public Result createCommonExceptionResponse(Exception e, Request request) { Request req = request; ProjectCommonException exception = null; if (e instanceof ProjectCommonException) { exception = (ProjectCommonException) e; } else { exception = new ProjectCommonException( ResponseCode.internalError.getErrorCode(), ResponseCode.internalError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } generateExceptionTelemetry(request, exception); // cleaning request info ... return Results.status( exception.getResponseCode(), Json.toJson(createResponseOnException(req, exception))); }
Example #7
Source File: BinaryBinder.java From restcommander with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") public Object bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { if (value == null || value.trim().length() == 0) { return null; } try { Model.BinaryField b = (Model.BinaryField) actualClass.newInstance(); List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS"); for (Upload upload : uploads) { if (upload.getFieldName().equals(value) && upload.getSize() > 0) { b.set(upload.asStream(), upload.getContentType()); return b; } } if (Params.current().get(value + "_delete_") != null) { return null; } return Binder.MISSING; } catch (Exception e) { throw new UnexpectedException(e); } }
Example #8
Source File: Controller.java From restcommander with Apache License 2.0 | 6 votes |
/** * Render a specific template. * * @param templateName The template name. * @param args The template data. */ protected static void renderTemplate(String templateName, Map<String,Object> args) { // Template datas Scope.RenderArgs templateBinding = Scope.RenderArgs.current(); templateBinding.data.putAll(args); templateBinding.put("session", Scope.Session.current()); templateBinding.put("request", Http.Request.current()); templateBinding.put("flash", Scope.Flash.current()); templateBinding.put("params", Scope.Params.current()); templateBinding.put("errors", Validation.errors()); try { Template template = TemplateLoader.load(template(templateName)); throw new RenderTemplate(template, templateBinding.data); } catch (TemplateNotFoundException ex) { if (ex.isSourceAvailable()) { throw ex; } StackTraceElement element = PlayException.getInterestingStrackTraceElement(ex); if (element != null) { throw new TemplateNotFoundException(templateName, Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber()); } else { throw ex; } } }
Example #9
Source File: FunctionalTest.java From restcommander with Apache License 2.0 | 6 votes |
/** * Sends a DELETE request to the application under tests. * @param request * @param url relative url eg. <em>"/products/1234"</em> * @return the response */ public static Response DELETE(Request request, Object url) { String path = ""; String queryString = ""; String turl = url.toString(); if (turl.contains("?")) { path = turl.substring(0, turl.indexOf("?")); queryString = turl.substring(turl.indexOf("?") + 1); } else { path = turl; } request.method = "DELETE"; request.url = turl; request.path = path; request.querystring = queryString; if (savedCookies != null) request.cookies = savedCookies; request.body = new ByteArrayInputStream(new byte[0]); return makeRequest(request); }
Example #10
Source File: BaseController.java From sunbird-lms-service with MIT License | 6 votes |
protected CompletionStage<Result> handleRequest( String operation, JsonNode requestBodyJson, java.util.function.Function requestValidatorFn, String pathId, String pathVariable, boolean isJsonBodyRequired, Request httpRequest) { return handleRequest( operation, requestBodyJson, requestValidatorFn, pathId, pathVariable, null, isJsonBodyRequired, httpRequest); }
Example #11
Source File: RaygunPlayJavaRequestMessage.java From raygun4java with MIT License | 6 votes |
public RaygunPlayJavaRequestMessage(Request request) { try { httpMethod = request.method(); ipAddress = request.remoteAddress(); hostName = request.host(); url = request.uri(); headers = flattenMap(request.headers()); Map<String, String[]> queryMap = request.queryString(); if (queryMap != null) { queryString = flattenMap(queryMap); } Map<String, String[]> formMap = request.body().asFormUrlEncoded(); if (formMap != null) { form = flattenMap(formMap); } } catch (NullPointerException e) { Logger.getLogger("Raygun4Java-Play2").info("Couldn't get all request params: " + e.getMessage()); } }
Example #12
Source File: RMBController.java From NationStatesPlusPlus with MIT License | 6 votes |
private static Function<JsonNode, Promise<Result>> getAsyncResult(final Request request, final Response response, final String cacheLen) { return new Function<JsonNode, Promise<Result>>() { @Override public Promise<Result> apply(final JsonNode node) throws Throwable { return Promise.wrap(akka.dispatch.Futures.future((new Callable<Result>() { @Override public Result call() throws Exception { Result result = Utils.handleDefaultGetHeaders(request, response, String.valueOf(node.hashCode()), cacheLen); if (result != null) { return result; } return Results.ok(node).as("application/json"); } }), Akka.system().dispatcher())); } }; }
Example #13
Source File: FunctionalTest.java From restcommander with Apache License 2.0 | 6 votes |
/** * Sends a POST request to the application under tests. * @param request * @param url relative url such as <em>"/products/1234"</em> * @param contenttype content-type of the request * @param body posted data * @return the response */ public static Response POST(Request request, Object url, String contenttype, InputStream body) { String path = ""; String queryString = ""; String turl = url.toString(); if (turl.contains("?")) { path = turl.substring(0, turl.indexOf("?")); queryString = turl.substring(turl.indexOf("?") + 1); } else { path = turl; } request.method = "POST"; request.contentType = contenttype; request.url = turl; request.path = path; request.querystring = queryString; request.body = body; if (savedCookies != null) request.cookies = savedCookies; return makeRequest(request); }
Example #14
Source File: FunctionalTest.java From restcommander with Apache License 2.0 | 6 votes |
/** * sends a GET request to the application under tests. * @param request * @param url relative url such as <em>"/products/1234"</em> * @return the response */ public static Response GET(Request request, Object url) { String path = ""; String queryString = ""; String turl = url.toString(); if (turl.contains("?")) { path = turl.substring(0, turl.indexOf("?")); queryString = turl.substring(turl.indexOf("?") + 1); } else { path = turl; } request.method = "GET"; request.url = turl; request.path = path; request.querystring = queryString; request.body = new ByteArrayInputStream(new byte[0]); if (savedCookies != null) request.cookies = savedCookies; return makeRequest(request); }
Example #15
Source File: FunctionalTest.java From restcommander with Apache License 2.0 | 5 votes |
public static void makeRequest(final Request request, final Response response) { final Future invocationResult = TestEngine.functionalTestsExecutor.submit(new Invoker.Invocation() { @Override public void execute() throws Exception { renderArgs.clear(); ActionInvoker.invoke(request, response); if(RenderArgs.current().data != null) { renderArgs.putAll(RenderArgs.current().data); } } @Override public InvocationContext getInvocationContext() { ActionInvoker.resolve(request, response); return new InvocationContext(Http.invocationType, request.invokedMethod.getAnnotations(), request.invokedMethod.getDeclaringClass().getAnnotations()); } }); try { invocationResult.get(30, TimeUnit.SECONDS); if (savedCookies == null) { savedCookies = new HashMap<String, Http.Cookie>(); } for(Map.Entry<String,Http.Cookie> e : response.cookies.entrySet()) { // If Max-Age is unset, browsers discard on exit; if // 0, they discard immediately. if(e.getValue().maxAge == null || e.getValue().maxAge > 0) { savedCookies.put(e.getKey(), e.getValue()); } } response.out.flush(); } catch (Exception ex) { throw new RuntimeException(ex); } }
Example #16
Source File: PlayHandler.java From restcommander with Apache License 2.0 | 5 votes |
public static void serve404(NotFound e, ChannelHandlerContext ctx, Request request, HttpRequest nettyRequest) { if (Logger.isTraceEnabled()) { Logger.trace("serve404: begin"); } HttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); nettyResponse.setHeader(SERVER, signature); nettyResponse.setHeader(CONTENT_TYPE, "text/html"); Map<String, Object> binding = getBindingForErrors(e, false); String format = Request.current().format; if (format == null) { format = "txt"; } nettyResponse.setHeader(CONTENT_TYPE, (MimeTypes.getContentType("404." + format, "text/plain"))); String errorHtml = TemplateLoader.load("errors/404." + format).render(binding); try { byte[] bytes = errorHtml.getBytes(Response.current().encoding); ChannelBuffer buf = ChannelBuffers.copiedBuffer(bytes); setContentLength(nettyResponse, bytes.length); nettyResponse.setContent(buf); ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse); writeFuture.addListener(ChannelFutureListener.CLOSE); } catch (UnsupportedEncodingException fex) { Logger.error(fex, "(encoding ?)"); } if (Logger.isTraceEnabled()) { Logger.trace("serve404: end"); } }
Example #17
Source File: RenderXml.java From restcommander with Apache License 2.0 | 5 votes |
public void apply(Request request, Response response) { try { setContentTypeIfNotSet(response, "text/xml"); response.out.write(xml.getBytes(getEncoding())); } catch(Exception e) { throw new UnexpectedException(e); } }
Example #18
Source File: PlayGrizzlyAdapter.java From restcommander with Apache License 2.0 | 5 votes |
public void serve404(GrizzlyRequest request, GrizzlyResponse response, NotFound e) { Logger.warn("404 -> %s %s (%s)", request.getMethod(), request.getRequestURI(), e.getMessage()); response.setStatus(404); response.setContentType("text/html"); Map<String, Object> binding = new HashMap<String, Object>(); binding.put("result", 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) { // } String format = Request.current().format; response.setStatus(404); // Do we have an ajax request? If we have then we want to display some text even if it is html that is requested if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With")) && (format == null || format.equals("html"))) { format = "txt"; } if (format == null) { format = "txt"; } response.setContentType(MimeTypes.getContentType("404." + format, "text/plain")); String errorHtml = TemplateLoader.load("errors/404." + format).render(binding); try { response.getOutputStream().write(errorHtml.getBytes("utf-8")); } catch (Exception fex) { Logger.error(fex, "(utf-8 ?)"); } }
Example #19
Source File: ByteArrayArrayBinder.java From restcommander with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public byte[][] bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { if (value == null || value.trim().length() == 0) { return null; } List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS"); List<byte[]> byteList = new ArrayList<byte[]>(); for (Upload upload : uploads) { if (upload.getFieldName().equals(value)) { byteList.add(upload.asBytes()); } } return byteList.toArray(new byte[byteList.size()][]); }
Example #20
Source File: BaseController.java From sunbird-lms-service with MIT License | 5 votes |
protected CompletionStage<Result> handleSearchRequest( String operation, JsonNode requestBodyJson, Function requestValidatorFn, String pathId, String pathVariable, Map<String, String> headers, String esObjectType, Request httpRequest) { try { org.sunbird.common.request.Request request = null; if (null != requestBodyJson) { request = createAndInitRequest(operation, requestBodyJson, httpRequest); } else { ProjectCommonException.throwClientErrorException(ResponseCode.invalidRequestData, null); } if (pathId != null) { request.getRequest().put(pathVariable, pathId); request.getContext().put(pathVariable, pathId); } if (requestValidatorFn != null) requestValidatorFn.apply(request); if (headers != null) request.getContext().put(JsonKey.HEADER, headers); if (StringUtils.isNotBlank(esObjectType)) { List<String> esObjectTypeList = new ArrayList<>(); esObjectTypeList.add(esObjectType); ((Map) (request.getRequest().get(JsonKey.FILTERS))) .put(JsonKey.OBJECT_TYPE, esObjectTypeList); } request.getRequest().put(JsonKey.REQUESTED_BY, httpRequest.flash().get(JsonKey.USER_ID)); return actorResponseHandler(getActorRef(), request, timeout, null, httpRequest); } catch (Exception e) { ProjectLogger.log( "BaseController:handleRequest: Exception occurred with error message = " + e.getMessage(), e); return CompletableFuture.completedFuture(createCommonExceptionResponse(e, httpRequest)); } }
Example #21
Source File: Controller.java From restcommander with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") protected static <T> T await(Future<T> future) { if(future != null) { Request.current().args.put(ActionInvoker.F, future); } else if(Request.current().args.containsKey(ActionInvoker.F)) { // Since the continuation will restart in this code that isn't intstrumented by javaflow, // we need to reset the state manually. StackRecorder.get().isCapturing = false; StackRecorder.get().isRestoring = false; StackRecorder.get().value = null; future = (Future<T>)Request.current().args.get(ActionInvoker.F); // Now reset the Controller invocation context ControllerInstrumentation.stopActionCall(); storeOrRestoreDataStateForContinuations( true ); } else { throw new UnexpectedException("Lost promise for " + Http.Request.current() + "!"); } if(future.isDone()) { try { return future.get(); } catch(Exception e) { throw new UnexpectedException(e); } } else { Request.current().isNew = false; verifyContinuationsEnhancement(); storeOrRestoreDataStateForContinuations( false ); Continuation.suspend(future); return null; } }
Example #22
Source File: PlayHandler.java From restcommander with Apache License 2.0 | 5 votes |
public NettyInvocation(Request request, Response response, ChannelHandlerContext ctx, HttpRequest nettyRequest, MessageEvent e) { this.ctx = ctx; this.request = request; this.response = response; this.nettyRequest = nettyRequest; this.event = e; }
Example #23
Source File: UploadArrayBinder.java From restcommander with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public Upload[] bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { if (value == null || value.trim().length() == 0) { return null; } List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS"); List<Upload> uploadArray = new ArrayList<Upload>(); for (Upload upload : uploads) { if (upload.getFieldName().equals(value)) { uploadArray.add(upload); } } return uploadArray.toArray(new Upload[uploadArray.size()]); }
Example #24
Source File: RaygunPlayMessageBuilder.java From raygun4java with MIT License | 5 votes |
public IRaygunPlayMessageBuilder setRequestDetails(Request javaRequest, play.api.mvc.Request scalaRequest, RequestHeader scalaRequestHeader, play.mvc.Http.RequestHeader javaRequestHeader) { if (javaRequest != null) { raygunServletMessage.getDetails().setRequest(new RaygunPlayJavaRequestMessage(javaRequest)); } else if (scalaRequest != null) { raygunServletMessage.getDetails().setRequest(new RaygunPlayScalaRequestMessage(scalaRequest)); } else if (scalaRequestHeader != null) { raygunServletMessage.getDetails().setRequest(new RaygunPlayScalaRequestHeaderMessage(scalaRequestHeader)); } else if (javaRequestHeader != null) { raygunServletMessage.getDetails().setRequest(new RaygunPlayJavaRequestHeaderMessage(javaRequestHeader)); } return this; }
Example #25
Source File: PlayHandler.java From restcommander with Apache License 2.0 | 5 votes |
@Override public boolean init() { Http.Request.current.set(request); Http.Inbound.current.set(inbound); Http.Outbound.current.set(outbound); return super.init(); }
Example #26
Source File: Redirect.java From restcommander with Apache License 2.0 | 5 votes |
public void apply(Request request, Response response) { try { if (url.startsWith("http")) { // } else if (url.startsWith("/")) { url = String.format("http%s://%s%s%s", request.secure ? "s" : "", request.domain, (request.port == 80 || request.port == 443) ? "" : ":" + request.port, url); } else { url = String.format("http%s://%s%s%s%s", request.secure ? "s" : "", request.domain, (request.port == 80 || request.port == 443) ? "" : ":" + request.port, request.path, request.path.endsWith("/") ? url : "/" + url); } response.status = code; response.setHeader("Location", url); } catch (Exception e) { throw new UnexpectedException(e); } }
Example #27
Source File: PlayHandler.java From restcommander with Apache License 2.0 | 5 votes |
public void writeChunk(Request playRequest, Response playResponse, ChannelHandlerContext ctx, HttpRequest nettyRequest, Object chunk) { try { if (playResponse.direct == null) { playResponse.setHeader("Transfer-Encoding", "chunked"); playResponse.direct = new LazyChunkedInput(); copyResponse(ctx, playRequest, playResponse, nettyRequest); } ((LazyChunkedInput) playResponse.direct).writeChunk(chunk); chunkedWriteHandler.resumeTransfer(); } catch (Exception e) { throw new UnexpectedException(e); } }
Example #28
Source File: RenderJson.java From restcommander with Apache License 2.0 | 5 votes |
public void apply(Request request, Response response) { try { String encoding = getEncoding(); setContentTypeIfNotSet(response, "application/json; charset="+encoding); response.out.write(json.getBytes(encoding)); } catch (Exception e) { throw new UnexpectedException(e); } }
Example #29
Source File: Controller.java From restcommander with Apache License 2.0 | 5 votes |
/** * Used to store data before Continuation suspend and restore after. * * If isRestoring == null, the method will try to resolve it. * * important: when using isRestoring == null you have to KNOW that continuation suspend * is going to happen and that this method is called twice for this single * continuation suspend operation for this specific request. * * @param isRestoring true if restoring, false if storing, and null if you don't know */ private static void storeOrRestoreDataStateForContinuations(Boolean isRestoring) { if (isRestoring==null) { // Sometimes, due to how continuations suspends/restarts the code, we do not // know when calling this method if we're suspending or restoring. final String continuationStateKey = "__storeOrRestoreDataStateForContinuations_started"; if ( Http.Request.current().args.remove(continuationStateKey)!=null ) { isRestoring = true; } else { Http.Request.current().args.put(continuationStateKey, true); isRestoring = false; } } if (isRestoring) { //we are restoring after suspend // localVariablesState Stack<Map<String, Object>> localVariablesState = (Stack<Map<String, Object>>) Http.Request.current().args.remove(ActionInvoker.CONTINUATIONS_STORE_LOCAL_VARIABLE_NAMES); LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.setLocalVariablesStateAfterAwait(localVariablesState); // renderArgs Scope.RenderArgs renderArgs = (Scope.RenderArgs) Request.current().args.remove(ActionInvoker.CONTINUATIONS_STORE_RENDER_ARGS); Scope.RenderArgs.current.set( renderArgs); } else { // we are storing before suspend // localVariablesState Request.current().args.put(ActionInvoker.CONTINUATIONS_STORE_LOCAL_VARIABLE_NAMES, LocalVariablesNamesTracer.getLocalVariablesStateBeforeAwait()); // renderArgs Request.current().args.put(ActionInvoker.CONTINUATIONS_STORE_RENDER_ARGS, Scope.RenderArgs.current()); } }
Example #30
Source File: Controller.java From restcommander with Apache License 2.0 | 5 votes |
protected static <T> void await(Future<T> future, F.Action<T> callback) { Request.current().isNew = false; Request.current().args.put(ActionInvoker.F, future); Request.current().args.put(ActionInvoker.A, callback); Request.current().args.put(ActionInvoker.CONTINUATIONS_STORE_RENDER_ARGS, Scope.RenderArgs.current()); throw new Suspend(future); }