Example usage for org.apache.http.entity ContentType getCharset

List of usage examples for org.apache.http.entity ContentType getCharset

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType getCharset.

Prototype

public Charset getCharset() 

Source Link

Usage

From source file:org.eclipse.californium.proxy.HttpTranslator.java

/**
 * Method to map the http entity of a http message in a coherent payload for
 * the coap message. The method simply gets the bytes from the entity and,
 * if needed changes the charset of the obtained bytes to UTF-8.
 * //from  w  ww. ja  v  a2  s .  co  m
 * @param httpEntity
 *            the http entity
 * 
 * @return byte[]
 * @throws TranslationException
 *             the translation exception
 */
public static byte[] getCoapPayload(HttpEntity httpEntity) throws TranslationException {
    if (httpEntity == null) {
        throw new IllegalArgumentException("httpEntity == null");
    }

    byte[] payload = null;
    try {
        // get the bytes from the entity
        payload = EntityUtils.toByteArray(httpEntity);
        if (payload != null && payload.length > 0 && looksLikeUTF8(payload)) {

            //modifica il payload per sostituire i riferimenti a http://proxyIP:8080/proxy/

            String body = "";
            try {
                body = new String(payload, "UTF-8");
            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            body = body.replace("http://" + proxyIP + ":8080/proxy/", "coap://");

            payload = body.getBytes();

            // the only supported charset in CoAP is UTF-8
            Charset coapCharset = UTF_8;

            // get the charset for the http entity
            ContentType httpContentType = ContentType.getOrDefault(httpEntity);
            Charset httpCharset = httpContentType.getCharset();

            // check if the charset is the one allowed by coap
            if (httpCharset != null && !httpCharset.equals(coapCharset)) {
                // translate the payload to the utf-8 charset
                payload = changeCharset(payload, httpCharset, coapCharset);
            }
        } else {
            int i = 0;
        }

    } catch (IOException e) {
        LOGGER.warning("Cannot get the content of the http entity: " + e.getMessage());
        throw new TranslationException("Cannot get the content of the http entity", e);
    } finally {
        try {
            // ensure all content has been consumed, so that the
            // underlying connection could be re-used
            EntityUtils.consume(httpEntity);
        } catch (IOException e) {

        }
    }

    return payload;
}

From source file:org.eclipse.californium.proxy.HttpTranslator.java

/**
 * Generates an HTTP entity starting from a CoAP request. If the coap
 * message has no payload, it returns a null http entity. It takes the
 * payload from the CoAP message and encapsulates it in an entity. If the
 * content-type is recognized, and a mapping is present in the properties
 * file, it is translated to the correspondent in HTTP, otherwise it is set
 * to application/octet-stream. If the content-type has a charset, namely it
 * is printable, the payload is encapsulated in a StringEntity, if not it a
 * ByteArrayEntity is used./*from   w  w  w.  j  av a2  s.com*/
 * 
 * 
 * @param coapMessage
 *            the coap message
 * 
 * 
 * @return null if the request has no payload * @throws TranslationException
 *         the translation exception
 */
public static HttpEntity getHttpEntity(Message coapMessage) throws TranslationException {
    if (coapMessage == null) {
        throw new IllegalArgumentException("coapMessage == null");
    }

    // the result
    HttpEntity httpEntity = null;

    // check if coap request has a payload
    byte[] payload = coapMessage.getPayload();
    if (payload != null && payload.length != 0) {

        ContentType contentType = null;

        // if the content type is not set, translate with octect-stream
        if (!coapMessage.getOptions().hasContentFormat()) {
            contentType = ContentType.APPLICATION_OCTET_STREAM;
        } else {
            int coapContentType = coapMessage.getOptions().getContentFormat();
            // search for the media type inside the property file
            String coapContentTypeString = HTTP_TRANSLATION_PROPERTIES
                    .getProperty(KEY_COAP_MEDIA + coapContentType);

            // if the content-type has not been found in the property file,
            // try to get its string value (expressed in mime type)
            if (coapContentTypeString == null || coapContentTypeString.isEmpty()) {
                coapContentTypeString = MediaTypeRegistry.toString(coapContentType);

                // if the coap content-type is printable, it is needed to
                // set the default charset (i.e., UTF-8)
                if (MediaTypeRegistry.isPrintable(coapContentType)) {
                    coapContentTypeString += "; charset=UTF-8";
                }
            }

            // parse the content type
            try {
                contentType = ContentType.parse(coapContentTypeString);
            } catch (UnsupportedCharsetException e) {
                LOGGER.finer("Cannot convert string to ContentType: " + e.getMessage());
                contentType = ContentType.APPLICATION_OCTET_STREAM;
            }
        }

        // get the charset
        Charset charset = contentType.getCharset();

        // if there is a charset, means that the content is not binary
        if (charset != null) {
            String body = "";
            try {
                body = new String(payload, "UTF-8");
            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            body = body.replace("coap://", "http://" + proxyIP + ":8080/proxy/");
            payload = body.getBytes();
            // according to the class ContentType the default content-type
            // with UTF-8 charset is application/json. If the content-type
            // parsed is different and is not iso encoded, a translation is
            // needed
            Charset isoCharset = ISO_8859_1;
            /*if (!charset.equals(isoCharset) && !contentType.getMimeType().equals(ContentType.APPLICATION_JSON.getMimeType())) {
               byte[] newPayload = changeCharset(payload, charset, isoCharset);
                    
               // since ISO-8859-1 is a subset of UTF-8, it is needed to
               // check if the mapping could be accomplished, only if the
               // operation is succesful the payload and the charset should
               // be changed
               if (newPayload != null) {
                  payload = newPayload;
                  // if the charset is changed, also the entire
                  // content-type must change
                  contentType = ContentType.create(contentType.getMimeType(), isoCharset);
               }
            }*/

            // create the content
            String payloadString = new String(payload, contentType.getCharset());

            // create the entity
            httpEntity = new StringEntity(payloadString,
                    ContentType.create(contentType.getMimeType(), contentType.getCharset()));
        } else {
            // create the entity
            httpEntity = new ByteArrayEntity(payload);
        }

        // set the content-type
        ((AbstractHttpEntity) httpEntity).setContentType(contentType.getMimeType());
    }

    return httpEntity;
}

From source file:org.elasticsearch.client.RequestLogger.java

/**
 * Creates curl output for given response
 *//*from w w  w . j av a2s .  co  m*/
static String buildTraceResponse(HttpResponse httpResponse) throws IOException {
    StringBuilder responseLine = new StringBuilder();
    responseLine.append("# ").append(httpResponse.getStatusLine());
    for (Header header : httpResponse.getAllHeaders()) {
        responseLine.append("\n# ").append(header.getName()).append(": ").append(header.getValue());
    }
    responseLine.append("\n#");
    HttpEntity entity = httpResponse.getEntity();
    if (entity != null) {
        if (entity.isRepeatable() == false) {
            entity = new BufferedHttpEntity(entity);
        }
        httpResponse.setEntity(entity);
        ContentType contentType = ContentType.get(entity);
        Charset charset = StandardCharsets.UTF_8;
        if (contentType != null && contentType.getCharset() != null) {
            charset = contentType.getCharset();
        }
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset))) {
            String line;
            while ((line = reader.readLine()) != null) {
                responseLine.append("\n# ").append(line);
            }
        }
    }
    return responseLine.toString();
}

From source file:org.structr.rest.common.HttpHelper.java

public static String charset(final HttpResponse response) {

    final ContentType contentType = ContentType.get(response.getEntity());
    String charset = "UTF-8";
    if (contentType != null && contentType.getCharset() != null) {

        charset = contentType.getCharset().toString();
    }/*from   w  w  w.j  a  v a2  s  .com*/

    return charset;
}