Search in sources :

Example 56 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project chuck by jgilfelt.

the class ChuckInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    HttpTransaction transaction = new HttpTransaction();
    transaction.setRequestDate(new Date());
    transaction.setMethod(request.method());
    transaction.setUrl(request.url().toString());
    transaction.setRequestHeaders(request.headers());
    if (hasRequestBody) {
        if (requestBody.contentType() != null) {
            transaction.setRequestContentType(requestBody.contentType().toString());
        }
        if (requestBody.contentLength() != -1) {
            transaction.setRequestContentLength(requestBody.contentLength());
        }
    }
    transaction.setRequestBodyIsPlainText(!bodyHasUnsupportedEncoding(request.headers()));
    if (hasRequestBody && transaction.requestBodyIsPlainText()) {
        BufferedSource source = getNativeSource(new Buffer(), bodyGzipped(request.headers()));
        Buffer buffer = source.buffer();
        requestBody.writeTo(buffer);
        Charset charset = UTF8;
        MediaType contentType = requestBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        if (isPlaintext(buffer)) {
            transaction.setRequestBody(readFromBuffer(buffer, charset));
        } else {
            transaction.setResponseBodyIsPlainText(false);
        }
    }
    Uri transactionUri = create(transaction);
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        transaction.setError(e.toString());
        update(transaction, transactionUri);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    // includes headers added later in the chain
    transaction.setRequestHeaders(response.request().headers());
    transaction.setResponseDate(new Date());
    transaction.setTookMs(tookMs);
    transaction.setProtocol(response.protocol().toString());
    transaction.setResponseCode(response.code());
    transaction.setResponseMessage(response.message());
    transaction.setResponseContentLength(responseBody.contentLength());
    if (responseBody.contentType() != null) {
        transaction.setResponseContentType(responseBody.contentType().toString());
    }
    transaction.setResponseHeaders(response.headers());
    transaction.setResponseBodyIsPlainText(!bodyHasUnsupportedEncoding(response.headers()));
    if (HttpHeaders.hasBody(response) && transaction.responseBodyIsPlainText()) {
        BufferedSource source = getNativeSource(response);
        source.request(Long.MAX_VALUE);
        Buffer buffer = source.buffer();
        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            try {
                charset = contentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
                update(transaction, transactionUri);
                return response;
            }
        }
        if (isPlaintext(buffer)) {
            transaction.setResponseBody(readFromBuffer(buffer.clone(), charset));
        } else {
            transaction.setResponseBodyIsPlainText(false);
        }
        transaction.setResponseContentLength(buffer.size());
    }
    update(transaction, transactionUri);
    return response;
}
Also used : Buffer(okio.Buffer) HttpTransaction(com.readystatesoftware.chuck.internal.data.HttpTransaction) Request(okhttp3.Request) Charset(java.nio.charset.Charset) Uri(android.net.Uri) Date(java.util.Date) 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) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 57 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project Payara by payara.

the class RequestUtil method parseSessionVersionString.

/**
 * Parses the given session version string into its components.
 *
 * @param sessionVersion The session version string to parse
 *
 * @return The mappings from context paths to session version numbers
 * that were parsed from the given session version string
 */
public static final HashMap<String, String> parseSessionVersionString(String sessionVersion) {
    if (sessionVersion == null) {
        return null;
    }
    StringTokenizer st = new StringTokenizer(sessionVersion, SESSION_VERSION_SEPARATOR);
    HashMap<String, String> result = new HashMap<String, String>(st.countTokens());
    while (st.hasMoreTokens()) {
        String hexPath = st.nextToken();
        if (st.hasMoreTokens()) {
            try {
                String contextPath = new String(HexUtils.convert(hexPath), Charsets.UTF8_CHARSET);
                result.put(contextPath, st.nextToken());
            } catch (UnsupportedCharsetException ex) {
                // should not be here
                throw new IllegalArgumentException(ex);
            }
        }
    }
    return result;
}
Also used : StringTokenizer(java.util.StringTokenizer) HashMap(java.util.HashMap) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException)

Example 58 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project wso2-axis2-transports by wso2.

the class MSMQSender method createMSMQMessage.

/**
 * Generating MSMQ message wrapper in order to communicate with JNI
 * @param msgCtx
 * @param contentTypeProperty
 * @param queuName
 * @return
 * @throws AxisFault
 */
private Message createMSMQMessage(MessageContext msgCtx, String messageContentType, String queuName) throws AxisFault {
    String msgBody = null;
    byte[] msgByteBody = null;
    String msgType = getProperty(msgCtx, MSMQConstants.MSMQ_MESSAGE_TYPE);
    // String msgLable = "L:" + queuName+"["+contentType+"]"; // TODO
    // check the first element of the SOAP body, do we have content wrapped
    // using the
    // default wrapper elements for binary
    // (BaseConstants.DEFAULT_BINARY_WRAPPER) or
    // text (BaseConstants.DEFAULT_TEXT_WRAPPER) ? If so, do not create SOAP
    // messages
    // for MSMQ but just get the payload in its native format
    String msmqMessageType = guessMessageType(msgCtx);
    if (msmqMessageType == null) {
        OMOutputFormat format = BaseUtils.getOMOutputFormat(msgCtx);
        MessageFormatter messageFormatter = null;
        try {
            messageFormatter = MessageProcessorSelector.getMessageFormatter(msgCtx);
        } catch (AxisFault axisFault) {
            handleException("Unable to get the message formatter to use", axisFault);
        }
        String contentType = messageFormatter != null ? messageFormatter.getContentType(msgCtx, format, msgCtx.getSoapAction()) : "";
        boolean useBytesMessage = msgType != null && MSMQConstants.MSMQ_BYTE_MESSAGE.equals(msgType) || contentType.indexOf(HTTPConstants.HEADER_ACCEPT_MULTIPART_RELATED) > -1;
        OutputStream out = null;
        StringWriter sw = null;
        if (useBytesMessage) {
        // TODO: handle MSMQ byte message here
        } else {
            sw = new StringWriter();
            try {
                out = new WriterOutputStream(sw, format.getCharSetEncoding());
            } catch (UnsupportedCharsetException ex) {
                handleException("Unsupported encoding " + format.getCharSetEncoding(), ex);
            }
        }
        try {
            if (out != null) {
                messageFormatter.writeTo(msgCtx, format, out, true);
                out.close();
            }
        } catch (IOException e) {
            handleException("IO Error while creating BytesMessage", e);
        }
        if (!useBytesMessage) {
            msgBody = sw.toString();
        }
    } else if (MSMQConstants.MSMQ_BYTE_MESSAGE.equals(msmqMessageType)) {
    // TODO. handle .net byte messages here.
    } else if (MSMQConstants.MSMQ_TEXT_MESSAGE.equals(msmqMessageType)) {
        msgBody = msgCtx.getEnvelope().getBody().getFirstChildWithName(BaseConstants.DEFAULT_TEXT_WRAPPER).getText();
    }
    try {
        // Keep message correlation empty will be deciding later on the process
        Message message = new Message(msgBody != null ? msgBody : "", "", "");
        return message;
    } catch (UnsupportedEncodingException e) {
        log.error("Unsported message has been received: ", e);
        handleEexception("Unsported message has been received: ", e);
    }
    return null;
}
Also used : AxisFault(org.apache.axis2.AxisFault) Message(org.apache.axis2.transport.msmq.util.Message) OutputStream(java.io.OutputStream) WriterOutputStream(org.apache.commons.io.output.WriterOutputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MessageFormatter(org.apache.axis2.transport.MessageFormatter) IOException(java.io.IOException) WriterOutputStream(org.apache.commons.io.output.WriterOutputStream) StringWriter(java.io.StringWriter) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Example 59 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project wso2-axis2-transports by wso2.

the class MqttSender method createMqttMessage.

private MqttMessage createMqttMessage(MessageContext messageContext) {
    OMOutputFormat format = BaseUtils.getOMOutputFormat(messageContext);
    MessageFormatter messageFormatter;
    try {
        messageFormatter = MessageProcessorSelector.getMessageFormatter(messageContext);
    } catch (AxisFault axisFault) {
        throw new AxisMqttException("Unable to get the message formatter to use");
    }
    OutputStream out;
    StringWriter sw = new StringWriter();
    try {
        out = new WriterOutputStream(sw, format.getCharSetEncoding());
    } catch (UnsupportedCharsetException ex) {
        throw new AxisMqttException("Unsupported encoding " + format.getCharSetEncoding(), ex);
    }
    try {
        messageFormatter.writeTo(messageContext, format, out, true);
        out.close();
    } catch (IOException e) {
        throw new AxisMqttException("IO Error while creating BytesMessage", e);
    }
    MqttMessage mqttMessage = new MqttMessage();
    mqttMessage.setPayload(sw.toString().getBytes());
    return mqttMessage;
}
Also used : AxisFault(org.apache.axis2.AxisFault) StringWriter(java.io.StringWriter) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) OutputStream(java.io.OutputStream) WriterOutputStream(org.apache.commons.io.output.WriterOutputStream) MessageFormatter(org.apache.axis2.transport.MessageFormatter) IOException(java.io.IOException) OMOutputFormat(org.apache.axiom.om.OMOutputFormat) WriterOutputStream(org.apache.commons.io.output.WriterOutputStream)

Example 60 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project mobile-sdk-android by meniga.

the class MenigaHttpLogger method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    if (logLevel == LogLevel.NONE) {
        return chain.proceed(request);
    }
    boolean logBody = logType == LogType.BODY_ONLY || logType == LogType.BODY_AND_HEADERS;
    boolean logHeaders = logType == LogType.HEADERS_ONLY || logType == LogType.BODY_AND_HEADERS;
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    String reqUrl = request.url().toString();
    String requestStartMessage = request.method() + REQUEST_START + reqUrl;
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    log(requestStartMessage);
    if (logHeaders) {
        if (hasRequestBody) {
            // them to be included (when available) so their values are known.
            if (requestBody.contentType() != null) {
                log(getHeaderString("Content-Type", requestBody.contentType().toString()));
            }
            if (requestBody.contentLength() != -1) {
                log(getHeaderString("Content-Length", Long.toString(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)) {
                log(getHeaderString(name, headers.value(i)));
            }
        }
    }
    if (!logBody) {
        log(REQUEST_END + request.method());
    } else if (!hasRequestBody) {
        log(BODY);
        log(NO_BODY);
    } else if (bodyEncoded(request.headers())) {
        log(REQUEST_END + request.method() + " (encoded body omitted)");
    } else {
        Buffer buffer = new Buffer();
        try {
            requestBody.writeTo(buffer);
        } catch (ConcurrentModificationException ex) {
            log("Error logging body - got ConcurrentModificationException");
        }
        Charset charset = UTF8;
        MediaType contentType = requestBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        log(BODY);
        if (isPlaintext(buffer)) {
            log(buffer.readString(charset));
            log(REQUEST_END + request.method() + " (" + requestBody.contentLength() + "-byte body)");
        } else {
            log("<" + requestBody.contentLength() + "-BYTE BINARY BODY OMITTED");
            log(REQUEST_END + request.method());
        }
    }
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        log("<---- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    log(RESPONSE_START + reqUrl);
    log("(" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ")");
    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            log(getHeaderString(headers.name(i), headers.value(i)));
        }
    }
    if (!logBody) {
        log(RESPONSE_END);
    } else if (!HttpHeaders.hasBody(response)) {
        log(BODY);
        log(NO_BODY);
        log(RESPONSE_END);
    } else if (bodyEncoded(response.headers())) {
        log(BODY);
        log("<ENCODED BODY OMITTED>");
        log(RESPONSE_END);
    } else {
        BufferedSource source = responseBody.source();
        // Buffer the entire body.
        source.request(Long.MAX_VALUE);
        Buffer buffer = source.buffer();
        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            try {
                charset = contentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
                log(BODY);
                log("<ERROR DECODING BODY; CHARSET IS LIKELY MALFORMED.>");
                log(RESPONSE_END);
                return response;
            }
        }
        if (!isPlaintext(buffer)) {
            log(BODY);
            log("<BINARY " + buffer.size() + "-BYTE BODY OMITTED>");
            log(RESPONSE_END);
            return response;
        }
        if (contentLength != 0) {
            log(BODY + " (" + buffer.size() + "-byte body)");
            log(buffer.clone().readString(charset));
        }
        log(RESPONSE_END);
    }
    return response;
}
Also used : Buffer(okio.Buffer) ConcurrentModificationException(java.util.ConcurrentModificationException) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Request(okhttp3.Request) Charset(java.nio.charset.Charset) IOException(java.io.IOException) EOFException(java.io.EOFException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) ConcurrentModificationException(java.util.ConcurrentModificationException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) MediaType(okhttp3.MediaType) 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