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

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

Introduction

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

Prototype

public static ContentType parse(String str) throws ParseException, UnsupportedCharsetException 

Source Link

Usage

From source file:com.groupon.odo.bmp.http.BrowserMobHttpClient.java

private void setTextOfEntry(HarEntry entry, ByteArrayOutputStream copy, String contentType) {
    ContentType contentTypeCharset = ContentType.parse(contentType);
    Charset charset = contentTypeCharset.getCharset();
    if (charset != null) {
        entry.getResponse().getContent().setText(new String(copy.toByteArray(), charset));
    } else {/*w  w  w . ja v a2s  .  com*/
        entry.getResponse().getContent().setText(new String(copy.toByteArray()));
    }
}

From source file:com.basistech.rosette.api.RosetteAPI.java

private void setupMultipartRequest(final DocumentRequest request, final ObjectWriter finalWriter,
        HttpPost post) {//from   w  ww  . ja  va  2  s  .c om

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMimeSubtype("mixed");
    builder.setMode(HttpMultipartMode.STRICT);

    FormBodyPartBuilder partBuilder = FormBodyPartBuilder.create("request",
            // Make sure we're not mislead by someone who puts a charset into the mime type.
            new AbstractContentBody(ContentType.parse(ContentType.APPLICATION_JSON.getMimeType())) {
                @Override
                public String getFilename() {
                    return null;
                }

                @Override
                public void writeTo(OutputStream out) throws IOException {
                    finalWriter.writeValue(out, request);
                }

                @Override
                public String getTransferEncoding() {
                    return MIME.ENC_BINARY;
                }

                @Override
                public long getContentLength() {
                    return -1;
                }
            });

    // Either one of 'name=' or 'Content-ID' would be enough.
    partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"request\"");
    partBuilder.setField("Content-ID", "request");

    builder.addPart(partBuilder.build());

    partBuilder = FormBodyPartBuilder.create("content",
            new InputStreamBody(request.getContentBytes(), ContentType.parse(request.getContentType())));
    partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"content\"");
    partBuilder.setField("Content-ID", "content");
    builder.addPart(partBuilder.build());
    builder.setCharset(StandardCharsets.UTF_8);

    HttpEntity entity = builder.build();
    post.setEntity(entity);
}

From source file:org.apache.solr.client.solrj.impl.HttpSolrServer.java

public NamedList<Object> request(final SolrRequest request, final ResponseParser processor)
        throws SolrServerException, IOException {
    HttpRequestBase method = null;/*from  w  ww. j  a  v  a  2  s  .com*/
    InputStream is = null;
    SolrParams params = request.getParams();
    Collection<ContentStream> streams = requestWriter.getContentStreams(request);
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
        path = DEFAULT_PATH;
    }

    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
        parser = this.parser;
    }

    // The parser 'wt=' and 'version=' params are used instead of the original
    // params
    ModifiableSolrParams wparams = new ModifiableSolrParams(params);
    if (parser != null) {
        wparams.set(CommonParams.WT, parser.getWriterType());
        wparams.set(CommonParams.VERSION, parser.getVersion());
    }
    if (invariantParams != null) {
        wparams.add(invariantParams);
    }

    int tries = maxRetries + 1;
    try {
        while (tries-- > 0) {
            // Note: since we aren't do intermittent time keeping
            // ourselves, the potential non-timeout latency could be as
            // much as tries-times (plus scheduling effects) the given
            // timeAllowed.
            try {
                if (SolrRequest.METHOD.GET == request.getMethod()) {
                    if (streams != null) {
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
                    }
                    method = new HttpGet(baseUrl + path + ClientUtils.toQueryString(wparams, false));
                } else if (SolrRequest.METHOD.POST == request.getMethod()) {

                    String url = baseUrl + path;
                    boolean hasNullStreamName = false;
                    if (streams != null) {
                        for (ContentStream cs : streams) {
                            if (cs.getName() == null) {
                                hasNullStreamName = true;
                                break;
                            }
                        }
                    }
                    boolean isMultipart = (this.useMultiPartPost || (streams != null && streams.size() > 1))
                            && !hasNullStreamName;

                    // only send this list of params as query string params
                    ModifiableSolrParams queryParams = new ModifiableSolrParams();
                    for (String param : this.queryParams) {
                        String[] value = wparams.getParams(param);
                        if (value != null) {
                            for (String v : value) {
                                queryParams.add(param, v);
                            }
                            wparams.remove(param);
                        }
                    }

                    LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>();
                    if (streams == null || isMultipart) {
                        HttpPost post = new HttpPost(url + ClientUtils.toQueryString(queryParams, false));
                        post.setHeader("Content-Charset", "UTF-8");
                        if (!isMultipart) {
                            post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                        }

                        List<FormBodyPart> parts = new LinkedList<FormBodyPart>();
                        Iterator<String> iter = wparams.getParameterNamesIterator();
                        while (iter.hasNext()) {
                            String p = iter.next();
                            String[] vals = wparams.getParams(p);
                            if (vals != null) {
                                for (String v : vals) {
                                    if (isMultipart) {
                                        parts.add(new FormBodyPart(p,
                                                new StringBody(v, Charset.forName("UTF-8"))));
                                    } else {
                                        postParams.add(new BasicNameValuePair(p, v));
                                    }
                                }
                            }
                        }

                        if (isMultipart && streams != null) {
                            for (ContentStream content : streams) {
                                String contentType = content.getContentType();
                                if (contentType == null) {
                                    contentType = BinaryResponseParser.BINARY_CONTENT_TYPE; // default
                                }
                                String name = content.getName();
                                if (name == null) {
                                    name = "";
                                }
                                parts.add(new FormBodyPart(name, new InputStreamBody(content.getStream(),
                                        contentType, content.getName())));
                            }
                        }

                        if (parts.size() > 0) {
                            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
                            for (FormBodyPart p : parts) {
                                entity.addPart(p);
                            }
                            post.setEntity(entity);
                        } else {
                            //not using multipart
                            post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));
                        }

                        method = post;
                    }
                    // It is has one stream, it is the post body, put the params in the URL
                    else {
                        String pstr = ClientUtils.toQueryString(wparams, false);
                        HttpPost post = new HttpPost(url + pstr);

                        // Single stream as body
                        // Using a loop just to get the first one
                        final ContentStream[] contentStream = new ContentStream[1];
                        for (ContentStream content : streams) {
                            contentStream[0] = content;
                            break;
                        }
                        if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
                            post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
                                @Override
                                public Header getContentType() {
                                    return new BasicHeader("Content-Type", contentStream[0].getContentType());
                                }

                                @Override
                                public boolean isRepeatable() {
                                    return false;
                                }

                            });
                        } else {
                            post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) {
                                @Override
                                public Header getContentType() {
                                    return new BasicHeader("Content-Type", contentStream[0].getContentType());
                                }

                                @Override
                                public boolean isRepeatable() {
                                    return false;
                                }
                            });
                        }
                        method = post;
                    }
                } else {
                    throw new SolrServerException("Unsupported method: " + request.getMethod());
                }
            } catch (NoHttpResponseException r) {
                method = null;
                if (is != null) {
                    is.close();
                }
                // If out of tries then just rethrow (as normal error).
                if (tries < 1) {
                    throw r;
                }
            }
        }
    } catch (IOException ex) {
        throw new SolrServerException("error reading streams", ex);
    }

    // XXX client already has this set, is this needed?
    method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects);
    method.addHeader("User-Agent", AGENT);

    InputStream respBody = null;
    boolean shouldClose = true;
    boolean success = false;
    try {
        // Execute the method.
        final HttpResponse response = httpClient.execute(method);
        int httpStatus = response.getStatusLine().getStatusCode();

        // Read the contents
        respBody = response.getEntity().getContent();
        Header ctHeader = response.getLastHeader("content-type");
        String contentType;
        if (ctHeader != null) {
            contentType = ctHeader.getValue();
        } else {
            contentType = "";
        }

        // handle some http level checks before trying to parse the response
        switch (httpStatus) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_BAD_REQUEST:
        case HttpStatus.SC_CONFLICT: // 409
            break;
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_MOVED_TEMPORARILY:
            if (!followRedirects) {
                throw new SolrServerException(
                        "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ").");
            }
            break;
        default:
            if (processor == null) {
                throw new RemoteSolrException(httpStatus,
                        "Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:"
                                + response.getStatusLine().getReasonPhrase(),
                        null);
            }
        }
        if (processor == null) {

            // no processor specified, return raw stream
            NamedList<Object> rsp = new NamedList<Object>();
            rsp.add("stream", respBody);
            // Only case where stream should not be closed
            shouldClose = false;
            success = true;
            return rsp;
        }

        String procCt = processor.getContentType();
        if (procCt != null) {
            String procMimeType = ContentType.parse(procCt).getMimeType().trim().toLowerCase(Locale.ROOT);
            String mimeType = ContentType.parse(contentType).getMimeType().trim().toLowerCase(Locale.ROOT);
            if (!procMimeType.equals(mimeType)) {
                // unexpected mime type
                String msg = "Expected mime type " + procMimeType + " but got " + mimeType + ".";
                Header encodingHeader = response.getEntity().getContentEncoding();
                String encoding;
                if (encodingHeader != null) {
                    encoding = encodingHeader.getValue();
                } else {
                    encoding = "UTF-8"; // try UTF-8
                }
                try {
                    msg = msg + " " + IOUtils.toString(respBody, encoding);
                } catch (IOException e) {
                    throw new RemoteSolrException(httpStatus,
                            "Could not parse response with encoding " + encoding, e);
                }
                RemoteSolrException e = new RemoteSolrException(httpStatus, msg, null);
                throw e;
            }
        }

        //      if(true) {
        //        ByteArrayOutputStream copy = new ByteArrayOutputStream();
        //        IOUtils.copy(respBody, copy);
        //        String val = new String(copy.toByteArray());
        //        System.out.println(">RESPONSE>"+val+"<"+val.length());
        //        respBody = new ByteArrayInputStream(copy.toByteArray());
        //      }

        NamedList<Object> rsp = null;
        String charset = EntityUtils.getContentCharSet(response.getEntity());
        try {
            rsp = processor.processResponse(respBody, charset);
        } catch (Exception e) {
            throw new RemoteSolrException(httpStatus, e.getMessage(), e);
        }
        if (httpStatus != HttpStatus.SC_OK) {
            String reason = null;
            try {
                NamedList err = (NamedList) rsp.get("error");
                if (err != null) {
                    reason = (String) err.get("msg");
                    // TODO? get the trace?
                }
            } catch (Exception ex) {
            }
            if (reason == null) {
                StringBuilder msg = new StringBuilder();
                msg.append(response.getStatusLine().getReasonPhrase());
                msg.append("\n\n");
                msg.append("request: " + method.getURI());
                reason = java.net.URLDecoder.decode(msg.toString(), UTF_8);
            }
            throw new RemoteSolrException(httpStatus, reason, null);
        }
        success = true;
        return rsp;
    } catch (ConnectException e) {
        throw new SolrServerException("Server refused connection at: " + getBaseURL(), e);
    } catch (SocketTimeoutException e) {
        throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(),
                e);
    } catch (IOException e) {
        throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e);
    } finally {
        if (respBody != null && shouldClose) {
            try {
                respBody.close();
            } catch (Throwable t) {
            } // ignore
            if (!success) {
                method.abort();
            }
        }
    }
}

From source file:org.apereo.portal.portlet.container.PortletResourceResponseContextImpl.java

/**
 * Handles resource response specific headers. Returns true if the header was consumed by this method and requires no further processing
 * /* w w w  .j a v  a 2s.  c om*/
 * @return
 */
protected boolean handleResourceHeader(String key, String value) {
    if (ResourceResponse.HTTP_STATUS_CODE.equals(key)) {
        this.portletResourceOutputHandler.setStatus(Integer.parseInt(value));
        return true;
    }
    if ("Content-Type".equals(key)) {
        final ContentType contentType = ContentType.parse(value);
        final Charset charset = contentType.getCharset();
        if (charset != null) {
            this.portletResourceOutputHandler.setCharacterEncoding(charset.name());
        }
        this.portletResourceOutputHandler.setContentType(contentType.getMimeType());
        return true;
    }
    if ("Content-Length".equals(key)) {
        this.portletResourceOutputHandler.setContentLength(Integer.parseInt(value));
        return true;
    }
    if ("Content-Language".equals(key)) {
        final HeaderElement[] parts = BasicHeaderValueParser.parseElements(value, null);
        if (parts.length > 0) {
            final String localeStr = parts[0].getValue();
            final Locale locale = LocaleUtils.toLocale(localeStr);
            this.portletResourceOutputHandler.setLocale(locale);
            return true;
        }
    }

    return false;
}

From source file:org.callimachusproject.behaviours.SqlDatasourceSupport.java

private Charset getCharset(byte[] content, String contentType) throws IOException {
    ContentType type = ContentType.parse(contentType);
    Charset charset = type.getCharset();
    if (charset != null)
        return charset;
    ByteArrayInputStream in = new ByteArrayInputStream(content);
    try {//w w w .  ja  va  2  s.  c  o  m
        return new CharsetDetector().detect(in);
    } finally {
        in.close();
    }
}

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

/**
 * Gets the coap media type associated to the http entity. Firstly, it looks
 * for a valid mapping in the property file. If this step fails, then it
 * tries to explicitly map/parse the declared mime/type by the http entity.
 * If even this step fails, it sets application/octet-stream as
 * content-type.//from  w w w  .j  a  va2s  . c  om
 * 
 * @param httpMessage
 * 
 * 
 * @return the coap media code associated to the http message entity. * @see
 *         HttpHeader, ContentType, MediaTypeRegistry
 */
public static int getCoapMediaType(HttpMessage httpMessage) {
    if (httpMessage == null) {
        throw new IllegalArgumentException("httpMessage == null");
    }

    // get the entity
    HttpEntity httpEntity = null;
    if (httpMessage instanceof HttpResponse) {
        httpEntity = ((HttpResponse) httpMessage).getEntity();
    } else if (httpMessage instanceof HttpEntityEnclosingRequest) {
        httpEntity = ((HttpEntityEnclosingRequest) httpMessage).getEntity();
    }

    // check that the entity is actually present in the http message
    if (httpEntity == null) {
        throw new IllegalArgumentException("The http message does not contain any httpEntity.");
    }

    // set the content-type with a default value
    int coapContentType = MediaTypeRegistry.UNDEFINED;

    // get the content-type from the entity
    ContentType contentType = ContentType.get(httpEntity);
    if (contentType == null) {
        // if the content-type is not set, search in the headers
        Header contentTypeHeader = httpMessage.getFirstHeader("content-type");
        if (contentTypeHeader != null) {
            String contentTypeString = contentTypeHeader.getValue();
            contentType = ContentType.parse(contentTypeString);
        }
    }

    // check if there is an associated content-type with the current http
    // message
    if (contentType != null) {
        // get the value of the content-type
        String httpContentTypeString = contentType.getMimeType();
        // delete the last part (if any)
        httpContentTypeString = httpContentTypeString.split(";")[0];

        // retrieve the mapping from the property file
        String coapContentTypeString = HTTP_TRANSLATION_PROPERTIES
                .getProperty(KEY_HTTP_CONTENT_TYPE + httpContentTypeString);

        if (coapContentTypeString != null) {
            coapContentType = Integer.parseInt(coapContentTypeString);
        } else {
            // try to parse the media type if the property file has given to
            // mapping
            coapContentType = MediaTypeRegistry.parse(httpContentTypeString);
        }
    }

    // if not recognized, the content-type should be
    // application/octet-stream (draft-castellani-core-http-mapping 6.2)
    if (coapContentType == MediaTypeRegistry.UNDEFINED) {
        coapContentType = MediaTypeRegistry.APPLICATION_OCTET_STREAM;
    }

    return coapContentType;
}

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./* w w  w  .j a  v a  2  s . c om*/
 * 
 * 
 * @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.ldp4j.tutorial.client.CreateCommandProcessor.java

@Override
protected HttpUriRequest getRequest(CommandContext options, RequestConfig config) {
    console().message("Creating resource...%n").metadata("- Content-Type: ").data(this.contentType)
            .message("%n").metadata("- Content:%n").data(this.content).message("%n");

    HttpEntity entity = new StringEntity(this.content, ContentType.parse(this.contentType));

    HttpPost method = new HttpPost(this.location);
    method.setEntity(entity);// www.  j a v a2s  .  co m
    method.setConfig(config);
    return method;
}

From source file:org.ldp4j.tutorial.client.ModifyCommandProcessor.java

@Override
protected HttpUriRequest getRequest(CommandContext options, RequestConfig config) {
    console().message("Modifying resource...%n").metadata("- If-Match    : ").data(this.entityTag).message("%n")
            .metadata("- Content-Type: ").data(this.contentType).message("%n").metadata("- Content:%n")
            .data(this.content).message("%n");

    HttpEntity entity = new StringEntity(this.content, ContentType.parse(this.contentType));

    HttpPut method = new HttpPut(this.location);
    method.setHeader("If-Match", this.entityTag);
    method.setEntity(entity);/*from w  ww .j a v a  2s.c om*/
    method.setConfig(config);
    return method;
}