Search in sources :

Example 96 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project netty by netty.

the class HostsFileParserTest method testParseUnicode.

@Test
public void testParseUnicode() throws IOException {
    final Charset unicodeCharset;
    try {
        unicodeCharset = Charset.forName("unicode");
    } catch (UnsupportedCharsetException e) {
        return;
    }
    testParseFile(HostsFileParser.parse(ResourcesUtil.getFile(getClass(), "hosts-unicode"), unicodeCharset));
}
Also used : UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) Charset(java.nio.charset.Charset) Test(org.junit.jupiter.api.Test)

Example 97 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project netty by netty.

the class HttpPostRequestDecoderTest method testDecodeMalformedBadCharsetContentDispositionFieldParameters.

// https://github.com/netty/netty/pull/7265
@Test
public void testDecodeMalformedBadCharsetContentDispositionFieldParameters() throws Exception {
    final String boundary = "74e78d11b0214bdcbc2f86491eeb4902";
    final String body = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"file\"; filename*=not-a-charset''filename\r\n" + "\r\n" + "foo\r\n" + "\r\n" + "--" + boundary + "--";
    final DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "http://localhost", Unpooled.wrappedBuffer(body.getBytes()));
    req.headers().add(HttpHeaderNames.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
    final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false);
    try {
        new HttpPostRequestDecoder(inMemoryFactory, req);
        fail("Was expecting an ErrorDataDecoderException");
    } catch (HttpPostRequestDecoder.ErrorDataDecoderException e) {
        assertTrue(e.getCause() instanceof UnsupportedCharsetException);
    } finally {
        assertTrue(req.release());
    }
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) Test(org.junit.jupiter.api.Test)

Example 98 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project gerrit by GerritCodeReview.

the class Text method charset.

private static Charset charset(byte[] content, String encoding) {
    if (encoding == null) {
        UniversalDetector d = new UniversalDetector(null);
        d.handleData(content, 0, content.length);
        d.dataEnd();
        encoding = d.getDetectedCharset();
    }
    if (encoding == null) {
        return ISO_8859_1;
    }
    try {
        return Charset.forName(encoding);
    } catch (IllegalCharsetNameException err) {
        logger.atSevere().log("Invalid detected charset name '%s': %s", encoding, err.getMessage());
        return ISO_8859_1;
    } catch (UnsupportedCharsetException err) {
        logger.atSevere().log("Detected charset '%s' not supported: %s", encoding, err.getMessage());
        return ISO_8859_1;
    }
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) UniversalDetector(org.mozilla.universalchardet.UniversalDetector)

Example 99 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project open-ecard by ecsec.

the class HttpAppPluginActionHandler method getRequestBody.

private RequestBody getRequestBody(HttpRequest httpRequest, String resourceName) throws IOException {
    try {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) httpRequest;
        HttpEntity entity = entityRequest.getEntity();
        InputStream is = entity.getContent();
        // TODO: This assumes the content is UTF-8. Evaluate what is actually sent.
        String value = FileUtils.toString(is);
        String mimeType = ContentType.get(entity).getMimeType();
        // TODO: find out if we have a Base64 coded value
        boolean base64Content = false;
        RequestBody body = new RequestBody(resourceName, null);
        body.setValue(value, mimeType, base64Content);
        return body;
    } catch (UnsupportedCharsetException | ParseException e) {
        LOG.error("Failed to create request body.", e);
    }
    return null;
}
Also used : HttpEntity(org.openecard.apache.http.HttpEntity) InputStream(java.io.InputStream) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) HttpEntityEnclosingRequest(org.openecard.apache.http.HttpEntityEnclosingRequest) ParseException(org.openecard.apache.http.ParseException) RequestBody(org.openecard.addon.bind.RequestBody)

Example 100 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project TumCampusApp by TCA-Team.

the class TumHttpLoggingInterceptor method intercept.

@Override
public Response intercept(@NonNull Chain chain) throws IOException {
    Request request = chain.request();
    boolean logBody = true;
    boolean logHeaders = true;
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    Connection connection = chain.connection();
    Protocol protocol = connection == null ? Protocol.HTTP_1_1 : connection.protocol();
    String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);
    if (logHeaders) {
        if (hasRequestBody) {
            // them to be included (when available) so there values are known.
            if (requestBody.contentType() != null) {
                logger.log("Content-Type: " + requestBody.contentType());
            }
            if (requestBody.contentLength() != -1) {
                logger.log("Content-Length: " + requestBody.contentLength());
            }
        }
        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                logger.log(name + ": " + headers.value(i));
            }
        }
        if (logBody && hasRequestBody) {
            if (bodyEncoded(request.headers())) {
                logger.log("--> END " + request.method() + " (encoded body omitted)");
            } else {
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);
                Charset charset = UTF8;
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }
                logger.log("");
                if (isPlaintext(buffer)) {
                    logger.log(buffer.readString(charset));
                    logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
                } else {
                    logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)");
                }
            }
        } else {
            logger.log("--> END " + request.method());
        }
    }
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.log("<-- HTTP FAILED: " + e);
        throw e;
    }
    long startNs = System.nanoTime();
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength == -1 ? "unknown-length" : contentLength + "-byte";
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (logHeaders ? "" : ", " + bodySize + " body") + ')');
    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }
        if (logBody && HttpHeaders.hasBody(response)) {
            if (bodyEncoded(response.headers())) {
                logger.log("<-- END HTTP (encoded body omitted)");
            } else {
                BufferedSource source = responseBody.source();
                // Buffer the entire body.
                source.request(Long.MAX_VALUE);
                Charset charset = UTF8;
                MediaType contentType = responseBody.contentType();
                if (contentType != null) {
                    try {
                        charset = contentType.charset(UTF8);
                    } catch (UnsupportedCharsetException e) {
                        logger.log("");
                        logger.log("Couldn't decode the response body; charset is likely malformed.");
                        logger.log("<-- END HTTP");
                        return response;
                    }
                }
                Buffer buffer = source.buffer();
                if (!isPlaintext(buffer)) {
                    logger.log("");
                    logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                    return response;
                }
                if (contentLength != 0) {
                    logger.log("");
                    logger.log(buffer.clone().readString(charset));
                }
                logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
            }
        } else {
            logger.log("<-- END HTTP");
        }
    }
    return response;
}
Also used : Buffer(okio.Buffer) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Request(okhttp3.Request) Connection(okhttp3.Connection) Charset(java.nio.charset.Charset) IOException(java.io.IOException) EOFException(java.io.EOFException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Aggregations

UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)116 Charset (java.nio.charset.Charset)55 IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)43 IOException (java.io.IOException)35 File (java.io.File)11 ByteBuffer (java.nio.ByteBuffer)11 InputStream (java.io.InputStream)10 UnsupportedEncodingException (java.io.UnsupportedEncodingException)10 CoreException (org.eclipse.core.runtime.CoreException)10 CharacterCodingException (java.nio.charset.CharacterCodingException)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 HashMap (java.util.HashMap)7 MediaType (okhttp3.MediaType)7 Request (okhttp3.Request)7 Response (okhttp3.Response)7 ResponseBody (okhttp3.ResponseBody)7 Buffer (okio.Buffer)7 BufferedSource (okio.BufferedSource)7 InputStreamReader (java.io.InputStreamReader)6 OutputStream (java.io.OutputStream)6