play.mvc.Http.Response Java Examples

The following examples show how to use play.mvc.Http.Response. 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: Utils.java    From NationStatesPlusPlus with MIT License 6 votes vote down vote up
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;
}
 
Example #2
Source File: RMBController.java    From NationStatesPlusPlus with MIT License 6 votes vote down vote up
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 #3
Source File: FunctionalTest.java    From restcommander with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: FunctionalTest.java    From restcommander with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #5
Source File: FunctionalTest.java    From restcommander with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #6
Source File: FunctionalTest.java    From restcommander with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #7
Source File: FunctionalTest.java    From restcommander with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #8
Source File: Evolutions.java    From restcommander with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #9
Source File: DBPlugin.java    From restcommander with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #10
Source File: PlayHandler.java    From restcommander with Apache License 2.0 5 votes vote down vote up
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");
    }

}
 
Example #11
Source File: PlayHandler.java    From restcommander with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #12
Source File: PlayHandler.java    From restcommander with Apache License 2.0 5 votes vote down vote up
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 #13
Source File: ServletWrapper.java    From restcommander with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #14
Source File: RenderXml.java    From restcommander with Apache License 2.0 5 votes vote down vote up
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 #15
Source File: RenderTemplate.java    From restcommander with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #16
Source File: RenderHtml.java    From restcommander with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #17
Source File: RedirectToStatic.java    From restcommander with Apache License 2.0 5 votes vote down vote up
public void apply(Request request, Response response) {
    try {
        response.status = Http.StatusCode.FOUND;
        response.setHeader("Location", file);
    } catch (Exception e) {
        throw new UnexpectedException(e);
    }
}
 
Example #18
Source File: RenderJson.java    From restcommander with Apache License 2.0 5 votes vote down vote up
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 #19
Source File: Redirect.java    From restcommander with Apache License 2.0 5 votes vote down vote up
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 #20
Source File: RenderText.java    From restcommander with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #21
Source File: PlayHandler.java    From restcommander with Apache License 2.0 5 votes vote down vote up
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");
    }
}
 
Example #22
Source File: PlayHandler.java    From restcommander with Apache License 2.0 5 votes vote down vote up
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 #23
Source File: PlayHandler.java    From restcommander with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #24
Source File: PlayHandler.java    From restcommander with Apache License 2.0 5 votes vote down vote up
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 #25
Source File: TestBasicClientFunctionality.java    From openseedbox with GNU General Public License v3.0 5 votes vote down vote up
@Ignore("java.lang.NullPointerException\n" +
		"\tat controllers.Auth.authenticate(Auth.java:35)\n")
@Test
public void testAddTorrent() {
	String torrentUrls = "magnet:?xt=urn:btih:PIRCY5TF6KUX4QYD4I5XEV7PGTF7CMZF&tr=http://tracker.mininova.org/announce\n" +
			  "magnet:?xt=urn:btih:RTXYHEE43V2EJWAQWT3J3WOE27QIURFT&tr=http://tracker.mininova.org/announce";
	Response res = POST("/client/addTorrent", Util.convertToMap(new String[] { "urlOrMagnet", torrentUrls }));
	assertStatus(302, res);
	res = GET(res.getHeader("Location"), true);
	assertContentMatch("2 left to add", res);
}
 
Example #26
Source File: FunctionalTest.java    From restcommander with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #27
Source File: FunctionalTest.java    From restcommander with Apache License 2.0 5 votes vote down vote up
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 #28
Source File: FunctionalTest.java    From restcommander with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #29
Source File: CorePlugin.java    From restcommander with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #30
Source File: TestLogin.java    From openseedbox with GNU General Public License v3.0 5 votes vote down vote up
@Ignore("java.lang.NullPointerException\n" +
		"\tat controllers.Auth.authenticate(Auth.java:35)\n")
@Test
public void testLoggingIn() {
	Response res = POST("/auth/authenticate", Util.convertToMap(new String[] { "email", "[email protected]"}));
	assertStatus(302, res);
	String clientPage = res.getHeader("Location");
	assertEquals("/client", clientPage);
	Response res1 = GET("/client", true);
	assertIsOk(res1);		
	assertContentMatch(Pattern.quote("Erin Drummond"), res1);		
}