Example usage for com.google.common.net MediaType withCharset

List of usage examples for com.google.common.net MediaType withCharset

Introduction

In this page you can find the example usage for com.google.common.net MediaType withCharset.

Prototype

public MediaType withCharset(Charset charset) 

Source Link

Document

Returns a new instance with the same type and subtype as this instance, with the charset parameter set to the Charset#name name of the given charset.

Usage

From source file:google.registry.request.RequestModule.java

@Provides
@JsonPayload//from  w  w w  .ja v  a2 s  . co  m
@SuppressWarnings("unchecked")
static Map<String, Object> provideJsonPayload(@Header("Content-Type") MediaType contentType,
        @Payload String payload) {
    if (!JSON_UTF_8.is(contentType.withCharset(UTF_8))) {
        throw new UnsupportedMediaTypeException(
                String.format("Expected %s Content-Type", JSON_UTF_8.withoutParameters()));
    }
    try {
        return (Map<String, Object>) JSONValue.parseWithException(payload);
    } catch (ParseException e) {
        throw new BadRequestException("Malformed JSON", new VerifyException("Malformed JSON:\n" + payload, e));
    }
}

From source file:org.openqa.selenium.remote.server.Passthrough.java

@Override
public void handle(HttpRequest req, HttpResponse resp) throws IOException {
    URL target = new URL(upstream.toExternalForm() + req.getUri());
    HttpURLConnection connection = (HttpURLConnection) target.openConnection();
    connection.setInstanceFollowRedirects(true);
    connection.setRequestMethod(req.getMethod().toString());
    connection.setDoInput(true);//from  w  w w.j  a  va 2  s.  co m
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    for (String name : req.getHeaderNames()) {
        if (IGNORED_REQ_HEADERS.contains(name.toLowerCase())) {
            continue;
        }

        for (String value : req.getHeaders(name)) {
            connection.addRequestProperty(name, value);
        }
    }
    // None of this "keep alive" nonsense.
    connection.setRequestProperty("Connection", "close");

    if (POST == req.getMethod()) {
        // We always transform to UTF-8 on the way up.
        String contentType = req.getHeader("Content-Type");
        contentType = contentType == null ? JSON_UTF_8.toString() : contentType;

        MediaType type = MediaType.parse(contentType);
        connection.setRequestProperty("Content-Type", type.withCharset(UTF_8).toString());

        Charset charSet = req.getContentEncoding();

        StringWriter logWriter = new StringWriter();
        try (InputStream is = req.consumeContentStream();
                Reader reader = new InputStreamReader(is, charSet);
                Reader in = new TeeReader(reader, logWriter);
                OutputStream os = connection.getOutputStream();
                Writer out = new OutputStreamWriter(os, UTF_8)) {
            CharStreams.copy(in, out);
        }
        LOG.info("To upstream: " + logWriter.toString());
    }

    resp.setStatus(connection.getResponseCode());
    // clear response defaults.
    resp.setHeader("Date", null);
    resp.setHeader("Server", null);

    connection.getHeaderFields().entrySet().stream()
            .filter(entry -> entry.getKey() != null && entry.getValue() != null)
            .filter(entry -> !IGNORED_REQ_HEADERS.contains(entry.getKey().toLowerCase())).forEach(entry -> {
                entry.getValue().stream().filter(Objects::nonNull)
                        .forEach(value -> resp.addHeader(entry.getKey(), value));
            });
    InputStream in = connection.getErrorStream();
    if (in == null) {
        in = connection.getInputStream();
    }

    String charSet = connection.getContentEncoding() != null ? connection.getContentEncoding() : UTF_8.name();
    try (Reader reader = new InputStreamReader(in, charSet)) {
        String content = CharStreams.toString(reader);
        LOG.info("To downstream: " + content);
        resp.setContent(content.getBytes(charSet));
    } finally {
        in.close();
    }
}

From source file:keywhiz.FileAssetServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*from www  .j a va2 s  . co m*/
        ByteSource asset = loadAsset(req.getRequestURI());
        if (asset == null) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        final String mimeTypeOfExtension = req.getServletContext().getMimeType(req.getRequestURI());
        MediaType mediaType = DEFAULT_MEDIA_TYPE;

        if (mimeTypeOfExtension != null) {
            try {
                mediaType = MediaType.parse(mimeTypeOfExtension);
                if (mediaType.is(MediaType.ANY_TEXT_TYPE)) {
                    mediaType = mediaType.withCharset(DEFAULT_CHARSET);
                }
            } catch (IllegalArgumentException ignore) {
            }
        }

        resp.setContentType(mediaType.type() + "/" + mediaType.subtype());

        if (mediaType.charset().isPresent()) {
            resp.setCharacterEncoding(mediaType.charset().get().toString());
        }

        try (OutputStream output = resp.getOutputStream()) {
            asset.copyTo(output);
        }
    } catch (RuntimeException ignored) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.khannedy.sajikeun.servlet.AssetServlet.java

protected void doHttp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*from w w w.  j a v a 2s  .c  o  m*/

        final StringBuilder builder = new StringBuilder(req.getServletPath());
        if (req.getPathInfo() != null) {
            builder.append(req.getPathInfo());
        }
        final Asset asset = loadAsset(builder.toString());
        if (asset == null) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        if (cache) {
            if (isCachedClientSide(req, asset)) {
                resp.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }
        }

        resp.setDateHeader(HttpHeaders.LAST_MODIFIED, asset.getLastModified());
        resp.setHeader(HttpHeaders.ETAG, asset.getETag());

        final String mimeTypeOfExtension = req.getServletContext().getMimeType(req.getRequestURI());
        MediaType mediaType = DEFAULT_MEDIA_TYPE;

        if (mimeTypeOfExtension != null) {
            try {
                mediaType = MediaType.parse(mimeTypeOfExtension);
                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());
        }

        try (ServletOutputStream output = resp.getOutputStream()) {
            output.write(asset.getResource());
        }
    } catch (RuntimeException | URISyntaxException ignored) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.ardverk.dropwizard.assets.AssetsDirectoryServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestURI = request.getRequestURI();

    try {//from w w w .j a va  2  s  .c  om
        AssetsDirectory.Entry entry = directory.getFileEntry(requestURI);

        if (isCurrent(request, entry)) {
            response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }

        response.setDateHeader(HttpHeaders.LAST_MODIFIED, entry.getLastModified());
        response.setHeader(HttpHeaders.ETAG, entry.getETag());

        MediaType mediaType = DEFAULT_MEDIA_TYPE;

        Buffer mimeType = mimeTypes.getMimeByExtension(requestURI);
        if (mimeType != null) {
            try {
                mediaType = MediaType.parse(mimeType.toString());
                if (charset != null && mediaType.is(MediaType.ANY_TEXT_TYPE)) {
                    mediaType = mediaType.withCharset(charset);
                }
            } catch (IllegalArgumentException ignore) {
            }
        }

        response.setContentType(mediaType.type() + "/" + mediaType.subtype());

        if (mediaType.charset().isPresent()) {
            response.setCharacterEncoding(mediaType.charset().get().toString());
        }

        long contentLength = entry.length();
        if (contentLength >= 0L && contentLength < Integer.MAX_VALUE) {
            response.setContentLength((int) contentLength);
        }

        OutputStream out = response.getOutputStream();
        entry.writeTo(out);
        out.flush();

    } catch (FileNotFoundException err) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.github.dirkraft.dropwizard.fileassets.FileAssetServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*from  ww  w  . j  a  v  a2 s .  c o m*/
        final StringBuilder builder = new StringBuilder(req.getServletPath());
        if (req.getPathInfo() != null) {
            builder.append(req.getPathInfo());
        }
        final CachedAsset cachedAsset = loadAsset(builder.toString());
        if (cachedAsset == null) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        if (isCachedClientSide(req, cachedAsset)) {
            resp.sendError(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }

        resp.setDateHeader(HttpHeaders.LAST_MODIFIED, cachedAsset.getLastModifiedTime());
        resp.setHeader(HttpHeaders.ETAG, cachedAsset.getETag());

        final String mimeTypeOfExtension = req.getServletContext().getMimeType(req.getRequestURI());
        MediaType mediaType = DEFAULT_MEDIA_TYPE;

        if (mimeTypeOfExtension != null) {
            try {
                mediaType = MediaType.parse(mimeTypeOfExtension);
                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());
        }

        try (ServletOutputStream output = resp.getOutputStream()) {
            output.write(cachedAsset.getResource());
        }
    } catch (RuntimeException | URISyntaxException ignored) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}