Search in sources :

Example 1 with MediaType

use of com.google.common.net.MediaType in project moco by dreamhead.

the class MocoJsonStandaloneTest method should_return_expected_json_response_based_on_specified_json_request_shortcut.

@Test
public void should_return_expected_json_response_based_on_specified_json_request_shortcut() throws IOException {
    runWithConfiguration("json.json");
    HttpResponse response = helper.getResponse(remoteUrl("/json_response_shortcut"));
    HttpEntity entity = response.getEntity();
    byte[] bytes = ByteStreams.toByteArray(entity.getContent());
    assertThat(new String(bytes), is("{\"foo\":\"bar\"}"));
    MediaType mediaType = MediaType.parse(entity.getContentType().getValue());
    assertThat(mediaType.type(), is("application"));
    assertThat(mediaType.subtype(), is("json"));
}
Also used : HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) MediaType(com.google.common.net.MediaType) Test(org.junit.Test)

Example 2 with MediaType

use of com.google.common.net.MediaType in project airlift by airlift.

the class TestHttpServerModule method assertResource.

private void assertResource(URI baseUri, HttpClient client, String path, String contents) {
    HttpUriBuilder uriBuilder = uriBuilderFrom(baseUri);
    StringResponse data = client.execute(prepareGet().setUri(uriBuilder.appendPath(path).build()).build(), createStringResponseHandler());
    assertEquals(data.getStatusCode(), HttpStatus.OK.code());
    MediaType contentType = MediaType.parse(data.getHeader(CONTENT_TYPE));
    assertTrue(PLAIN_TEXT_UTF_8.is(contentType), "Expected text/plain but got " + contentType);
    assertEquals(data.getBody().trim(), contents);
}
Also used : HttpUriBuilder(io.airlift.http.client.HttpUriBuilder) MediaType(com.google.common.net.MediaType) StringResponse(io.airlift.http.client.StringResponseHandler.StringResponse)

Example 3 with MediaType

use of com.google.common.net.MediaType in project airlift by airlift.

the class TestTestingHttpServer method assertResource.

private static void assertResource(URI baseUri, HttpClient client, String path, String contents) {
    HttpUriBuilder uriBuilder = uriBuilderFrom(baseUri);
    StringResponseHandler.StringResponse data = client.execute(prepareGet().setUri(uriBuilder.appendPath(path).build()).build(), createStringResponseHandler());
    assertEquals(data.getStatusCode(), HttpStatus.OK.code());
    MediaType contentType = MediaType.parse(data.getHeader(HttpHeaders.CONTENT_TYPE));
    assertTrue(PLAIN_TEXT_UTF_8.is(contentType), "Expected text/plain but got " + contentType);
    assertEquals(data.getBody().trim(), contents);
}
Also used : StringResponseHandler(io.airlift.http.client.StringResponseHandler) StringResponseHandler.createStringResponseHandler(io.airlift.http.client.StringResponseHandler.createStringResponseHandler) HttpUriBuilder(io.airlift.http.client.HttpUriBuilder) MediaType(com.google.common.net.MediaType)

Example 4 with MediaType

use of com.google.common.net.MediaType in project providence by morimekta.

the class HttpClientHandler method handleCall.

@Override
public <Request extends PMessage<Request, RequestField>, Response extends PMessage<Response, ResponseField>, RequestField extends PField, ResponseField extends PField> PServiceCall<Response, ResponseField> handleCall(PServiceCall<Request, RequestField> call, PService service) throws IOException {
    if (call.getType() == PServiceCallType.EXCEPTION || call.getType() == PServiceCallType.REPLY) {
        throw new PApplicationException("Request with invalid call type: " + call.getType(), PApplicationExceptionType.INVALID_MESSAGE_TYPE);
    }
    long startTime = System.nanoTime();
    PServiceCall<Response, ResponseField> reply = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        requestSerializer.serialize(baos, call);
        ByteArrayContent content = new ByteArrayContent(requestSerializer.mediaType(), baos.toByteArray());
        @Nonnull GenericUrl url = urlSupplier.get();
        try {
            HttpRequest request = factory.buildPostRequest(url, content);
            request.getHeaders().setAccept(requestSerializer.mediaType());
            HttpResponse response = request.execute();
            try {
                if (call.getType() == PServiceCallType.CALL) {
                    Serializer responseSerializer = requestSerializer;
                    if (response.getContentType() != null) {
                        try {
                            MediaType mediaType = MediaType.parse(response.getContentType());
                            responseSerializer = serializerProvider.getSerializer(mediaType.withoutParameters().toString());
                        } catch (IllegalArgumentException e) {
                            throw new PApplicationException("Unknown content-type in response: " + response.getContentType(), PApplicationExceptionType.INVALID_PROTOCOL).initCause(e);
                        }
                    }
                    // non 200 responses should have triggered a HttpResponseException,
                    // so this is safe.
                    reply = responseSerializer.deserialize(response.getContent(), service);
                    if (reply.getType() == PServiceCallType.CALL || reply.getType() == PServiceCallType.ONEWAY) {
                        throw new PApplicationException("Reply with invalid call type: " + reply.getType(), PApplicationExceptionType.INVALID_MESSAGE_TYPE);
                    }
                    if (reply.getSequence() != call.getSequence()) {
                        throw new PApplicationException("Reply sequence out of order: call = " + call.getSequence() + ", reply = " + reply.getSequence(), PApplicationExceptionType.BAD_SEQUENCE_ID);
                    }
                }
                long endTime = System.nanoTime();
                double duration = ((double) (endTime - startTime)) / NS_IN_MILLIS;
                try {
                    instrumentation.onComplete(duration, call, reply);
                } catch (Exception ignore) {
                }
                return reply;
            } finally {
                // Ignore whatever is left of the response when returning, in
                // case we did'nt read the whole response.
                response.ignore();
            }
        } catch (HttpHostConnectException e) {
            throw e;
        } catch (ConnectException e) {
            // The native exception is not helpful (for when using NetHttpTransport).
            throw new HttpHostConnectException(e, new HttpHost(url.getHost(), url.getPort(), url.getScheme()));
        }
    } catch (Exception e) {
        long endTime = System.nanoTime();
        double duration = ((double) (endTime - startTime)) / NS_IN_MILLIS;
        try {
            instrumentation.onTransportException(e, duration, call, reply);
        } catch (Throwable ie) {
            e.addSuppressed(ie);
        }
        throw e;
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) Nonnull(javax.annotation.Nonnull) HttpResponse(com.google.api.client.http.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) GenericUrl(com.google.api.client.http.GenericUrl) PApplicationException(net.morimekta.providence.PApplicationException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) HttpResponse(com.google.api.client.http.HttpResponse) HttpHost(org.apache.http.HttpHost) PApplicationException(net.morimekta.providence.PApplicationException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) MediaType(com.google.common.net.MediaType) ByteArrayContent(com.google.api.client.http.ByteArrayContent) Serializer(net.morimekta.providence.serializer.Serializer) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) ConnectException(java.net.ConnectException)

Example 5 with MediaType

use of com.google.common.net.MediaType in project dropwizard-configurable-assets-bundle by bazaarvoice.

the class AssetServlet method doGet.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {
        final StringBuilder builder = new StringBuilder(req.getServletPath());
        if (req.getPathInfo() != null) {
            builder.append(req.getPathInfo());
        }
        Asset asset = cache.getUnchecked(builder.toString());
        if (asset == null) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        // Check the etag...
        if (asset.getETag().equals(req.getHeader(HttpHeaders.IF_NONE_MATCH))) {
            resp.sendError(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }
        // Check the last modified time...
        if (asset.getLastModifiedTime() <= req.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)) {
            resp.sendError(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }
        resp.setDateHeader(HttpHeaders.LAST_MODIFIED, asset.getLastModifiedTime());
        resp.setHeader(HttpHeaders.ETAG, asset.getETag());
        MediaType mediaType = DEFAULT_MEDIA_TYPE;
        String mimeType = mimeTypes.getMimeByExtension(req.getRequestURI());
        if (mimeType != null) {
            try {
                mediaType = MediaType.parse(mimeType);
                if (defaultCharset != null && mediaType.is(MediaType.ANY_TEXT_TYPE)) {
                    mediaType = mediaType.withCharset(defaultCharset);
                }
            } catch (IllegalArgumentException ignore) {
            }
        }
        resp.setContentType(mediaType.type() + "/" + mediaType.subtype());
        if (mediaType.charset().isPresent()) {
            resp.setCharacterEncoding(mediaType.charset().get().toString());
        }
        final ServletOutputStream output = resp.getOutputStream();
        try {
            output.write(asset.getResource());
        } finally {
            output.close();
        }
    } catch (RuntimeException ignored) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) MediaType(com.google.common.net.MediaType)

Aggregations

MediaType (com.google.common.net.MediaType)26 HttpEntity (org.apache.http.HttpEntity)6 IOException (java.io.IOException)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 HttpResponse (org.apache.http.HttpResponse)3 HttpUriBuilder (io.airlift.http.client.HttpUriBuilder)2 Charset (java.nio.charset.Charset)2 Serializer (net.morimekta.providence.serializer.Serializer)2 ByteArrayContent (com.google.api.client.http.ByteArrayContent)1 GenericUrl (com.google.api.client.http.GenericUrl)1 HttpRequest (com.google.api.client.http.HttpRequest)1 HttpResponse (com.google.api.client.http.HttpResponse)1 ByteSource (com.google.common.io.ByteSource)1 StringResponseHandler (io.airlift.http.client.StringResponseHandler)1 StringResponse (io.airlift.http.client.StringResponseHandler.StringResponse)1 StringResponseHandler.createStringResponseHandler (io.airlift.http.client.StringResponseHandler.createStringResponseHandler)1 EOFException (java.io.EOFException)1 OutputStream (java.io.OutputStream)1 Field (java.lang.reflect.Field)1 ConnectException (java.net.ConnectException)1