@Override public Result getJsonResponse(Object obj, int code, Response response) { StringWriter w = new StringWriter(); try { getMapper().writeValue(w, obj); } catch (Exception e) { String message = "Error while marshalling the application response"; ApiLog.log.error(message, e); try { getMapper().writeValue(w, new ApiError(message)); } catch (Exception exp) { throw new RuntimeException("Unexpected error while mashalling an ApiError message"); } code = ERROR_API_RESPONSE_CODE; } response.setContentType("application/json"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Headers", authorizedHeaders); return Controller.status(code, w.toString()); }
void check() { try { if (bais == null) { if (text == null) { text = getText(); } BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); DefaultWordRenderer renderer = new DefaultWordRenderer(textColor, fonts); bi = background.addBackground(bi); renderer.render(text, bi); if (noise != null) { new CurvedLineNoiseProducer(noise, 3.0f).makeNoise(bi); } gimpy.gimp(bi); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bi, "png", baos); bais = new ByteArrayInputStream(baos.toByteArray()); // Response.current().contentType = "image/png"; } } catch (Exception e) { throw new UnexpectedException(e); } }
@Override public boolean rawInvocation(Request request, Response response) throws Exception { if (Play.mode.isDev() && request.path.equals("/@db")) { response.status = Http.StatusCode.MOVED; // For H2 embeded database, we'll also start the Web console if (h2Server != null) { h2Server.stop(); } h2Server = org.h2.tools.Server.createWebServer(); h2Server.start(); response.setHeader("Location", "http://localhost:8082/"); return true; } return false; }
@Override public boolean rawInvocation(Request request, Response response) throws Exception { // Mark an evolution as resolved if (Play.mode.isDev() && request.method.equals("POST") && request.url.matches("^/@evolutions/force/[0-9]+$")) { int revision = Integer.parseInt(request.url.substring(request.url.lastIndexOf("/") + 1)); resolve(revision); new Redirect("/").apply(request, response); return true; } // Apply the current evolution script if (Play.mode.isDev() && request.method.equals("POST") && request.url.equals("/@evolutions/apply")) { applyScript(true); new Redirect("/").apply(request, response); return true; } return super.rawInvocation(request, response); }
/** * 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); }
/** * 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); }
/** * Sends a PUT 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 data to send * @return the response */ public static Response PUT(Request request, Object url, String contenttype, String 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 = "PUT"; request.contentType = contenttype; request.url = turl; request.path = path; request.querystring = queryString; request.body = new ByteArrayInputStream(body.getBytes()); return makeRequest(request); }
/** * 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); }
public static Response makeRequest(final Request request) { Response response = newResponse(); makeRequest(request, response); if (response.status == 302) { // redirect // if Location-header is pressent, fix it to "look like" a functional-test-url Http.Header locationHeader = response.headers.get("Location"); if (locationHeader != null) { String locationUrl = locationHeader.value(); if (locationUrl.startsWith("http://localhost/")) { locationHeader.values.clear(); locationHeader.values.add( locationUrl.substring(16));//skip 'http://localhost' } } } return response; }
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())); } }; }
public static Result handleDefaultGetHeaders(Request request, Response response, String calculatedEtag, String seconds) { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, HEAD"); response.setHeader("Access-Control-Max-Age", seconds); response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); response.setHeader("Cache-Control", "public, max-age=" + seconds); response.setHeader("Expires", new DateTime().plusHours(1).plusSeconds(Integer.parseInt(seconds)).toString(Utils.HTTP_DATE_TIME)); response.setHeader("Last-Modified", new DateTime().plusHours(-1).plusSeconds(-Integer.parseInt(seconds)).toString(Utils.HTTP_DATE_TIME)); response.setHeader("Vary", "Accept-Encoding"); if (calculatedEtag != null) { response.setHeader("ETag", calculatedEtag); String eTag = request.getHeader("If-None-Match"); if (calculatedEtag != null && calculatedEtag.equals(eTag)) { return Results.status(304); } } return null; }
private Promise<Result> returnUnauthorized(final String message, final Response response) { return Promise.promise(new Function0<Result>() { @Override public Result apply() throws Throwable { return getApiControllerUtilsService().getJsonErrorResponse(new ApiError(HttpURLConnection.HTTP_UNAUTHORIZED, message), response); } }); }
public F.Promise<Result> call(Context context) throws Throwable { Response response = context.response(); response.setHeader("Cache-Control","no-cache, no-store, must-revalidate"); response.setHeader("Pragma","no-cache"); response.setHeader("Expires","0"); return delegate.call(context); }
public F.Promise<Result> call(Context context) throws Throwable { Response response = context.response(); response.setHeader("Access-Control-Allow-Origin",configuration.value()); if ( context.request().method().equals("OPTIONS")) { response.setHeader("Access-Control-Allow-Methods","POST, DELETE"); response.setHeader("Access-Control-Max-Age","3600"); response.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization, Call-Origin"); return F.Promise.pure((Result)ok()); } response.setHeader("Access-Control-Allow-Headers","X-Requested-With"); return delegate.call(context); }
@Override protected void doSetHeader(String name, String value) { throwIfWritten(); // https://github.com/playframework/playframework/issues/2726 if (name.equalsIgnoreCase(Response.CONTENT_TYPE)) { name = Response.CONTENT_TYPE; } response.setHeader(name, value); }
/** * {@link Request} and {@link Response} are available. */ @Override public <T> T unwrap(Class<T> clazz) { return Request.class.isAssignableFrom(clazz) ? clazz.cast(request) : Response.class.isAssignableFrom(clazz) ? clazz.cast(response) : null; }
private static String getAppstatsIdFromResponse() { String result = "nada"; Response request = Response.current(); if (request != null) { Header header = request.headers.get("X-TraceUrl"); if (header != null) { String value = header.value(); result = value; if (StringUtils.isNotEmpty(value)) { String[] parts = value.split("\\?")[1].split("&"); for (String part : parts) { String[] nameValue = part.split("="); if ("time".equals(nameValue[0])) { result = nameValue[1]; Logger.info("profiler: appstats " + result); } } } } } return result; }
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); } }
public void apply(Request request, Response response) { try { final String contentType = MimeTypes.getContentType(name, "text/plain"); response.out.write(content.getBytes(getEncoding())); setContentTypeIfNotSet(response, contentType); } catch (Exception e) { throw new UnexpectedException(e); } }
public void apply(Request request, Response response) { try { setContentTypeIfNotSet(response, "text/plain; charset=" + Http.Response.current().encoding); response.out.write(text.getBytes(getEncoding())); } catch(Exception e) { throw new UnexpectedException(e); } }
public void apply(Request request, Response response) { try { setContentTypeIfNotSet(response, "text/html"); response.out.write(text.getBytes(getEncoding())); } catch(Exception e) { throw new UnexpectedException(e); } }
public void apply(Request request, Response response) { try { response.status = Http.StatusCode.FOUND; response.setHeader("Location", file); } catch (Exception e) { throw new UnexpectedException(e); } }
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); } }
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); } }
public void serveStatic(HttpServletResponse servletResponse, HttpServletRequest servletRequest, RenderStatic renderStatic) throws IOException { VirtualFile file = Play.getVirtualFile(renderStatic.file); if (file == null || file.isDirectory() || !file.exists()) { serve404(servletRequest, servletResponse, new NotFound("The file " + renderStatic.file + " does not exist")); } else { servletResponse.setContentType(MimeTypes.getContentType(file.getName())); boolean raw = Play.pluginCollection.serveStatic(file, Request.current(), Response.current()); if (raw) { copyResponse(Request.current(), Response.current(), servletRequest, servletResponse); } else { if (Play.mode == Play.Mode.DEV) { servletResponse.setHeader("Cache-Control", "no-cache"); servletResponse.setHeader("Content-Length", String.valueOf(file.length())); if (!servletRequest.getMethod().equals("HEAD")) { copyStream(servletResponse, file.inputstream()); } else { copyStream(servletResponse, new ByteArrayInputStream(new byte[0])); } } else { long last = file.lastModified(); String etag = "\"" + last + "-" + file.hashCode() + "\""; if (!isModified(etag, last, servletRequest)) { servletResponse.setHeader("Etag", etag); servletResponse.setStatus(304); } else { servletResponse.setHeader("Last-Modified", Utils.getHttpDateFormatter().format(new Date(last))); servletResponse.setHeader("Cache-Control", "max-age=" + Play.configuration.getProperty("http.cacheControl", "3600")); servletResponse.setHeader("Etag", etag); copyStream(servletResponse, file.inputstream()); } } } } }
public void serve404(HttpServletRequest servletRequest, HttpServletResponse servletResponse, NotFound e) { Logger.warn("404 -> %s %s (%s)", servletRequest.getMethod(), servletRequest.getRequestURI(), e.getMessage()); servletResponse.setStatus(404); servletResponse.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; servletResponse.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(servletRequest.getHeader("X-Requested-With")) && (format == null || format.equals("html"))) { format = "txt"; } if (format == null) { format = "txt"; } servletResponse.setContentType(MimeTypes.getContentType("404." + format, "text/plain")); String errorHtml = TemplateLoader.load("errors/404." + format).render(binding); try { servletResponse.getOutputStream().write(errorHtml.getBytes(Response.current().encoding)); } catch (Exception fex) { Logger.error(fex, "(encoding ?)"); } }
public ServletInvocation(Request request, Response response, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { this.httpServletRequest = httpServletRequest; this.httpServletResponse = httpServletResponse; this.request = request; this.response = response; request.args.put(ServletWrapper.SERVLET_REQ, httpServletRequest); request.args.put(ServletWrapper.SERVLET_RES, httpServletResponse); }
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; }
protected static void addToResponse(Response response, HttpResponse nettyResponse) { Map<String, Http.Header> headers = response.headers; for (Map.Entry<String, Http.Header> entry : headers.entrySet()) { Http.Header hd = entry.getValue(); for (String value : hd.values) { nettyResponse.setHeader(entry.getKey(), value); } } Map<String, Http.Cookie> cookies = response.cookies; for (Http.Cookie cookie : cookies.values()) { CookieEncoder encoder = new CookieEncoder(true); Cookie c = new DefaultCookie(cookie.name, cookie.value); c.setSecure(cookie.secure); c.setPath(cookie.path); if (cookie.domain != null) { c.setDomain(cookie.domain); } if (cookie.maxAge != null) { c.setMaxAge(cookie.maxAge); } c.setHttpOnly(cookie.httpOnly); encoder.addCookie(c); nettyResponse.addHeader(SET_COOKIE, encoder.encode()); } if (!response.headers.containsKey(CACHE_CONTROL) && !response.headers.containsKey(EXPIRES)) { nettyResponse.setHeader(CACHE_CONTROL, "no-cache"); } }
protected static void writeResponse(ChannelHandlerContext ctx, Response response, HttpResponse nettyResponse, HttpRequest nettyRequest) { if (Logger.isTraceEnabled()) { Logger.trace("writeResponse: begin"); } byte[] content = null; final boolean keepAlive = isKeepAlive(nettyRequest); if (nettyRequest.getMethod().equals(HttpMethod.HEAD)) { content = new byte[0]; } else { content = response.out.toByteArray(); } ChannelBuffer buf = ChannelBuffers.copiedBuffer(content); nettyResponse.setContent(buf); if (Logger.isTraceEnabled()) { Logger.trace("writeResponse: content length [" + response.out.size() + "]"); } setContentLength(nettyResponse, response.out.size()); ChannelFuture f = ctx.getChannel().write(nettyResponse); // Decide whether to close the connection or not. if (!keepAlive) { // Close the connection when the whole content is written out. f.addListener(ChannelFutureListener.CLOSE); } if (Logger.isTraceEnabled()) { Logger.trace("writeResponse: end"); } }
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"); } }
public void writeChunk(Object chunk) throws Exception { String message = chunk == null ? "" : chunk.toString(); StringWriter writer = new StringWriter(); Integer l = message.getBytes(Response.current().encoding).length + 2; writer.append(Integer.toHexString(l)).append("\r\n").append(message).append("\r\n\r\n"); nextChunks.offer(writer.toString()); }
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); } }
public void closeChunked(Request playRequest, Response playResponse, ChannelHandlerContext ctx, HttpRequest nettyRequest) { try { ((LazyChunkedInput) playResponse.direct).close(); chunkedWriteHandler.resumeTransfer(); } catch (Exception e) { throw new UnexpectedException(e); } }
/** * sends a GET request to the application under tests. * @param url relative url such as <em>"/products/1234"</em> * @param followRedirect indicates if request have to follow redirection (status 302) * @return the response */ public static Response GET(Object url, boolean followRedirect) { Response response = GET(url); if (Http.StatusCode.FOUND == response.status && followRedirect) { Http.Header redirectedTo = response.headers.get("Location"); java.net.URL redirectedUrl = null; try { redirectedUrl = new java.net.URL(redirectedTo.value()); } catch (MalformedURLException e) { throw new RuntimeException(e); } response = GET(redirectedUrl.getPath()); } return response; }
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); } }
/** * obtains the response body as a string * @param response server response * @return the response body as an <em>utf-8 string</em> */ public static String getContent(Response response) { byte[] data = response.out.toByteArray(); try { return new String(data, response.encoding); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } }
/** * Intercept /@status and check that the Authorization header is valid. * Then ask each plugin for a status dump and send it over the HTTP response. * * You can ask the /@status using the authorization header and putting your status secret key in it. * Prior to that you would be required to start play with a -DstatusKey=yourkey */ @Override public boolean rawInvocation(Request request, Response response) throws Exception { if (Play.mode == Mode.DEV && request.path.equals("/@kill")) { System.out.println("@KILLED"); if (Play.standalonePlayServer) { System.exit(0); } else { Logger.error("Cannot execute @kill since Play is not running as standalone server"); } } if (request.path.equals("/@status") || request.path.equals("/@status.json")) { if(!Play.started) { response.print("Application is not started"); response.status = 503; return true; } response.contentType = request.path.contains(".json") ? "application/json" : "text/plain"; Header authorization = request.headers.get("authorization"); if (authorization != null && (Crypto.sign("@status").equals(authorization.value()) || System.getProperty("statusKey", Play.secretKey).equals(authorization.value()))) { response.print(computeApplicationStatus(request.path.contains(".json"))); response.status = 200; return true; } response.status = 401; if (response.contentType.equals("application/json")) { response.print("{\"error\": \"Not authorized\"}"); } else { response.print("Not authorized"); } return true; } return super.rawInvocation(request, response); }
@Test public void testThatIndexPageWorks() { Response response = GET("/"); assertIsOk(response); assertContentType("text/html", response); assertCharset(play.Play.defaultWebEncoding, response); }
@Override public void apply(final Request request, final Response response) { try { response.status = 206; Header rangeHeader = request.headers.get("range"); String rangeValue = rangeHeader.value().trim().substring("bytes=".length()); long fileLength = this.file.length(); long start, end; if (rangeValue.startsWith("-")) { end = fileLength - 1; start = fileLength - 1 - Long.parseLong(rangeValue.substring("-".length())); } else { String[] range = rangeValue.split("-"); start = Long.parseLong(range[0]); end = range.length > 1 ? Long.parseLong(range[1]) : fileLength - 1; } if (end > fileLength - 1) { end = fileLength - 1; } if (start <= end) { long contentLength = end - start + 1; Loggers.Play.debug("Partial download, start: " + start + ", contentLength: " + contentLength); response.setHeader("Content-Length", contentLength + ""); response.setHeader("Content-Range", "bytes " + start + "-" + end + "/" + fileLength); response.setHeader("Content-Type", mime); RandomAccessFile raf = new RandomAccessFile(this.file, "r"); response.direct = new ChunkedFile(raf, start, contentLength, 8192); } } catch (Exception e) { throw new UnexpectedException(e); } }