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;
}
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;
}
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;
}
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;
}
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;
}
Aggregations