Search in sources :

Example 26 with MediaType

use of com.google.common.net.MediaType in project guava by hceylan.

the class MediaTypeTest method testGetCharset_unsupportedCharset.

public void testGetCharset_unsupportedCharset() {
    MediaType mediaType = MediaType.parse("text/plain; charset=utf-wtf");
    try {
        mediaType.charset();
        fail();
    } catch (UnsupportedCharsetException expected) {
    }
}
Also used : UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) MediaType(com.google.common.net.MediaType)

Example 27 with MediaType

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

the class StringResponseHandler method handle.

@Override
public StringResponse handle(Request request, Response response) {
    byte[] bytes = readResponseBytes(request, response);
    Charset charset = Optional.ofNullable(response.getHeader(CONTENT_TYPE)).map(MediaType::parse).flatMap(mediaType -> mediaType.charset().toJavaUtil()).orElse(UTF_8);
    return new StringResponse(response.getStatusCode(), response.getHeaders(), new String(bytes, charset));
}
Also used : MediaType(com.google.common.net.MediaType) List(java.util.List) Charset(java.nio.charset.Charset) ResponseHandlerUtils.readResponseBytes(io.airlift.http.client.ResponseHandlerUtils.readResponseBytes) ListMultimap(com.google.common.collect.ListMultimap) StringResponse(io.airlift.http.client.StringResponseHandler.StringResponse) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) ResponseHandlerUtils.propagate(io.airlift.http.client.ResponseHandlerUtils.propagate) Optional(java.util.Optional) CONTENT_TYPE(com.google.common.net.HttpHeaders.CONTENT_TYPE) Nullable(javax.annotation.Nullable) Charset(java.nio.charset.Charset) MediaType(com.google.common.net.MediaType) StringResponse(io.airlift.http.client.StringResponseHandler.StringResponse)

Example 28 with MediaType

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

the class ProvidenceServlet method doPost.

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    long startTime = System.nanoTime();
    AtomicReference<PServiceCall> callRef = new AtomicReference<>();
    AtomicReference<PServiceCall> responseRef = new AtomicReference<>();
    PProcessor processor = new WrappedProcessor(processorProvider.processorForRequest(req), (c, r) -> {
        callRef.set(c);
        responseRef.set(r.handleCall(c));
        return responseRef.get();
    });
    try {
        Serializer requestSerializer = serializerProvider.getDefault();
        if (req.getContentType() != null) {
            try {
                MediaType mediaType = MediaType.parse(req.getContentType());
                requestSerializer = serializerProvider.getSerializer(mediaType.withoutParameters().toString());
            } catch (IllegalArgumentException e) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown content-type: " + req.getContentType());
                LOGGER.warn("Unknown content type in request", e);
                return;
            }
        } else {
            LOGGER.debug("Request is missing content type.");
        }
        Serializer responseSerializer = requestSerializer;
        String acceptHeader = req.getHeader("Accept");
        if (acceptHeader != null) {
            String[] entries = acceptHeader.split("[,]");
            for (String entry : entries) {
                entry = entry.trim();
                if (entry.isEmpty()) {
                    continue;
                }
                if ("*/*".equals(entry)) {
                    // Then responding same as request is good.
                    break;
                }
                try {
                    MediaType mediaType = MediaType.parse(entry);
                    responseSerializer = serializerProvider.getSerializer(mediaType.withoutParameters().toString());
                    break;
                } catch (IllegalArgumentException ignore) {
                // Ignore. Bad header input is pretty common.
                }
            }
        }
        MessageReader reader = new IOMessageReader(req.getInputStream(), requestSerializer);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        MessageWriter writer = new IOMessageWriter(baos, responseSerializer);
        getHandler(processor).process(reader, writer);
        resp.setStatus(HttpServletResponse.SC_OK);
        if (baos.size() > 0) {
            resp.setContentType(responseSerializer.mediaType());
            resp.setContentLength(baos.size());
            resp.getOutputStream().write(baos.toByteArray());
            resp.getOutputStream().flush();
        }
        long endTime = System.nanoTime();
        double duration = ((double) (endTime - startTime)) / NS_IN_MILLIS;
        try {
            instrumentation.onComplete(duration, callRef.get(), responseRef.get());
        } catch (Throwable th) {
            LOGGER.error("Exception in service instrumentation", th);
        }
    } catch (EOFException e) {
        // output stream closed before write is complete.
        // So we cannot even try to respond.
        long endTime = System.nanoTime();
        double duration = ((double) (endTime - startTime)) / NS_IN_MILLIS;
        try {
            instrumentation.onTransportException(e, duration, callRef.get(), responseRef.get());
        } catch (Throwable th) {
            LOGGER.error("Exception in service instrumentation", th);
        }
    } catch (Exception e) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error: " + e.getMessage());
        } catch (IOException ioEx) {
            e.addSuppressed(ioEx);
        }
        long endTime = System.nanoTime();
        double duration = ((double) (endTime - startTime)) / NS_IN_MILLIS;
        try {
            instrumentation.onTransportException(e, duration, callRef.get(), responseRef.get());
        } catch (Throwable th) {
            LOGGER.error("Exception in service instrumentation", th);
        }
    }
}
Also used : PProcessor(net.morimekta.providence.PProcessor) IOMessageReader(net.morimekta.providence.mio.IOMessageReader) AtomicReference(java.util.concurrent.atomic.AtomicReference) MessageReader(net.morimekta.providence.mio.MessageReader) IOMessageReader(net.morimekta.providence.mio.IOMessageReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) EOFException(java.io.EOFException) IOMessageWriter(net.morimekta.providence.mio.IOMessageWriter) PServiceCall(net.morimekta.providence.PServiceCall) EOFException(java.io.EOFException) MediaType(com.google.common.net.MediaType) MessageWriter(net.morimekta.providence.mio.MessageWriter) IOMessageWriter(net.morimekta.providence.mio.IOMessageWriter) Serializer(net.morimekta.providence.serializer.Serializer)

Example 29 with MediaType

use of com.google.common.net.MediaType in project spf4j by zolyfarkas.

the class Configs method read.

@Nullable
public static <T> T read(final Class<T> type, final SchemaResolver schemaResolver, final Reader reader) throws IOException {
    SpecificData sd = SpecificData.get();
    Schema rSchema = sd.getSchema(type);
    ConfigHeader header = parseHeader(reader, rSchema, schemaResolver);
    Schema wSchema = header.getwSchema();
    Reader content = header.getReader();
    MediaType mt = header.getMediaType();
    DatumReader<T> dr = new SpecificDatumReader<>(wSchema, rSchema);
    Decoder decoder;
    Adapter adapter = AvroCompatUtils.getAdapter();
    if ("application".equals(mt.type()) && "json".equals(mt.subtype())) {
        decoder = adapter.getJsonDecoder(wSchema, content);
    } else if ("text".equals(mt.type()) && "yaml".equals(mt.subtype())) {
        decoder = adapter.getYamlDecoder(wSchema, content);
    } else {
        throw new IllegalArgumentException("Unsupported media type " + mt);
    }
    return dr.read(null, decoder);
}
Also used : SpecificData(org.apache.avro.specific.SpecificData) Schema(org.apache.avro.Schema) Reader(java.io.Reader) SpecificDatumReader(org.apache.avro.specific.SpecificDatumReader) DatumReader(org.apache.avro.io.DatumReader) StringReader(java.io.StringReader) PushbackReader(org.spf4j.io.PushbackReader) BufferedReader(java.io.BufferedReader) MediaType(com.google.common.net.MediaType) SpecificDatumReader(org.apache.avro.specific.SpecificDatumReader) Decoder(org.apache.avro.io.Decoder) Nullable(javax.annotation.Nullable)

Aggregations

MediaType (com.google.common.net.MediaType)29 HttpEntity (org.apache.http.HttpEntity)6 IOException (java.io.IOException)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 Charset (java.nio.charset.Charset)3 HttpResponse (org.apache.http.HttpResponse)3 HttpUriBuilder (io.airlift.http.client.HttpUriBuilder)2 StringResponse (io.airlift.http.client.StringResponseHandler.StringResponse)2 BufferedReader (java.io.BufferedReader)2 Reader (java.io.Reader)2 StringReader (java.io.StringReader)2 Nullable (javax.annotation.Nullable)2 Serializer (net.morimekta.providence.serializer.Serializer)2 Schema (org.apache.avro.Schema)2 DatumReader (org.apache.avro.io.DatumReader)2 SpecificDatumReader (org.apache.avro.specific.SpecificDatumReader)2 PushbackReader (org.spf4j.io.PushbackReader)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