Example usage for org.apache.http.util EntityUtils getContentMimeType

List of usage examples for org.apache.http.util EntityUtils getContentMimeType

Introduction

In this page you can find the example usage for org.apache.http.util EntityUtils getContentMimeType.

Prototype

@Deprecated
    public static String getContentMimeType(HttpEntity httpEntity) throws ParseException 

Source Link

Usage

From source file:org.mobicents.servlet.restcomm.util.HttpUtils.java

public static Map<String, String> toMap(final HttpEntity entity) throws IllegalStateException, IOException {

    String contentType = null;/*from   w  w w  .ja  va 2  s .  c o m*/
    String charset = null;

    contentType = EntityUtils.getContentMimeType(entity);
    charset = EntityUtils.getContentCharSet(entity);

    List<NameValuePair> parameters = null;
    if (contentType != null && contentType.equalsIgnoreCase(CONTENT_TYPE)) {
        parameters = URLEncodedUtils.parse(entity);
    } else {
        final String content = EntityUtils.toString(entity, HTTP.ASCII);
        if (content != null && content.length() > 0) {
            parameters = new ArrayList<NameValuePair>();
            URLEncodedUtils.parse(parameters, new Scanner(content), charset);
        }
    }

    final Map<String, String> map = new HashMap<String, String>();
    for (final NameValuePair parameter : parameters) {
        map.put(parameter.getName(), parameter.getValue());
    }
    return map;
}

From source file:org.openstack.burrow.backend.http.BaseHttp.java

/**
 * Processes an HttpResponse. First gets all necessary information from the
 * response's JSONObject and then builds the List of Accounts
 * //w  w w .j a  v  a2 s .  c om
 * @param response An HttpResponse from the server that should contain
 *          requested Accounts
 * @return A List of Accounts requested
 * @throws HttpProtocolException Thrown if an issue with processes
 *           HttpResponse occurs
 * @throws AccountNotFoundException Thrown if the requested Account was not
 *           found
 */
static List<Account> handleMultipleAccountHttpResponse(HttpResponse response)
        throws HttpProtocolException, AccountNotFoundException {
    StatusLine status = response.getStatusLine();
    HttpEntity entity = response.getEntity();
    if (entity == null)
        return null; // Is this actually the right thing to do?
    String mimeType = EntityUtils.getContentMimeType(entity);
    switch (status.getStatusCode()) {
    case SC_OK:
        if (mimeType.equals("application/json")) {
            try {
                String body = EntityUtils.toString(entity);
                JSONArray arrayJson = new JSONArray(body);
                List<Account> accounts = new ArrayList<Account>(arrayJson.length());
                try {
                    // Assume the response is an array of JSON Objects.
                    for (int idx = 0; idx < arrayJson.length(); idx++) {
                        JSONObject accountJson = arrayJson.getJSONObject(idx);
                        Account account = new AccountResponse(accountJson);
                        accounts.add(idx, account);
                    }
                } catch (JSONException e) {
                    // The response was not an array of JSON Objects. Try again,
                    // assuming it was an array of strings.
                    for (int idx = 0; idx < arrayJson.length(); idx++) {
                        String accountId = arrayJson.getString(idx);
                        Account account = new AccountResponse(accountId);
                        accounts.add(idx, account);
                    }
                }
                return accounts;
            } catch (IOException e) {
                try {
                    // Consume the entity to release HttpClient resources.
                    EntityUtils.consume(entity);
                } catch (IOException e1) {
                    // If we ever stop throwing an exception in the outside block,
                    // this needs to be handled.
                }
                throw new HttpProtocolException("IOException reading http response");
            } catch (JSONException e) {
                // It is not necessary to consume the entity because at the
                // first point where this exception can be thrown,
                // the entity has already been consumed by toString();
                throw new HttpProtocolException("JSONException reading response");
            }
        } else {
            // This situation cannot be handled.
            try {
                // Consume the entity to release HttpClient resources.
                EntityUtils.consume(entity);
            } catch (IOException e1) {
                // If we ever stop throwing an exception in the outside block,
                // this needs to be handled.
            }
            throw new HttpProtocolException("Non-Json response");
        }
    case SC_NOT_FOUND:
        try {
            // Consume the entity to release HttpClient resources.
            EntityUtils.consume(entity);
        } catch (IOException e1) {
            // If we ever stop throwing an exception in the outside block,
            // this needs to be handled.
        }
        throw new AccountNotFoundException("No accounts found");
    default:
        // This is probably an error.
        try {
            // Consume the entity to release HttpClient resources.
            EntityUtils.consume(entity);
        } catch (IOException e1) {
            // If we ever stop throwing an exception in the outside block,
            // this needs to be handled.
        }
        throw new HttpProtocolException("Unhandled http response code " + status.getStatusCode());
    }
}

From source file:org.openstack.burrow.backend.http.SingleMessageResponseConsumer.java

/**
 * Processes the response as it is received from the server and sets the
 * class's exception field as needed//  w  w w.ja  va  2s  .co m
 * 
 * @param response An HttpResponse object that contains the information
 *          requested
 */
@Override
protected void onResponseReceived(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    int statusCode = status.getStatusCode();
    switch (statusCode) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
        mimeType = EntityUtils.getContentMimeType(response.getEntity());
        if (("application/json".equals(mimeType)) || ("application/octet-stream".equals(mimeType))) {
            accumulator = new StringBuilder();
        } else if (mimeType != null) {
            exception = new HttpProtocolException("Unhandled response mime type: " + mimeType);
        }
        return;
    case HttpStatus.SC_NO_CONTENT:
        // This is not an error condition, but we do not care about the body
        // and thus do not set up the accumulator.
        return;
    case HttpStatus.SC_NOT_FOUND:
        // This is an error condition, and we do not care about the body.
        exception = new MessageNotFoundException();
        return;
    default:
        // This is an error condition.
        exception = new HttpProtocolException("Unhandled response status code: " + statusCode);
        return;
    }
}

From source file:org.openstack.burrow.backend.http.MessageListResponseConsumer.java

/**
 * Processes the response as it is received from the server and sets the
 * class's exception field as needed/*from   w w w  . j  av a2s  . co  m*/
 * 
 * @param response An HttpResponse object that contains the information
 *          requested
 */
@Override
protected void onResponseReceived(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    int statusCode = status.getStatusCode();
    switch (statusCode) {
    case HttpStatus.SC_OK:
        mimeType = EntityUtils.getContentMimeType(response.getEntity());
        if ("application/json".equals(mimeType)) {
            accumulator = new StringBuilder();
        } else if (mimeType != null) {
            exception = new HttpProtocolException("Unhandled response mime type: " + mimeType);
        }
        return;
    case HttpStatus.SC_NO_CONTENT:
        // This is not an error condition, but we do not care about the body
        // and thus do not set up the accumulator.
        return;
    case HttpStatus.SC_NOT_FOUND:
        // This is an error condition, and we do not care about the body.
        exception = new QueueNotFoundException();
        return;
    default:
        // This is an error condition.
        exception = new HttpProtocolException("Unhandled response status code: " + statusCode);
        return;
    }
}

From source file:com.flicklib.service.HttpClientSourceLoader.java

private Source buildSource(String url, HttpResponse response, HttpRequestBase httpMethod, HttpContext ctx)
        throws IOException {
    LOGGER.info("Finished loading at " + httpMethod.getURI().toString());
    final HttpEntity entity = response.getEntity();
    String responseCharset = EntityUtils.getContentCharSet(entity);
    String contentType = EntityUtils.getContentMimeType(entity);
    LOGGER.info("Response charset = " + responseCharset);
    String content = EntityUtils.toString(entity);

    HttpUriRequest req = (HttpUriRequest) ctx.getAttribute(ExecutionContext.HTTP_REQUEST);
    HttpHost target = (HttpHost) ctx.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    URI resultUri;/*from  w  w w .j av  a2s. co m*/
    try {
        resultUri = (target != null && req != null) ? new URI(target.toURI() + req.getURI().toString())
                : httpMethod.getURI();
    } catch (URISyntaxException e) {
        e.printStackTrace();
        resultUri = httpMethod.getURI();
    }
    // String contentType = URLConnection.guessContentTypeFromName(url)
    return new Source(resultUri.toString(), content, contentType, url);
}

From source file:org.openstack.burrow.backend.http.QueueListResponseConsumer.java

/**
 * Processes the response as it is received from the server and sets the
 * class's exception field as needed//from   ww  w . j av a 2 s.com
 * 
 * @param response An HttpResponse object that contains the information
 *          requested
 */
@Override
protected void onResponseReceived(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    int statusCode = status.getStatusCode();
    switch (statusCode) {
    case HttpStatus.SC_OK:
        mimeType = EntityUtils.getContentMimeType(response.getEntity());
        if ("application/json".equals(mimeType)) {
            accumulator = new StringBuilder();
        } else if (mimeType != null) {
            exception = new ProtocolException("Unhandled response mime type: " + mimeType);
        }
        return;
    case HttpStatus.SC_NO_CONTENT:
        // This is not an error condition, but we do not care about the body
        // and thus do not set up the accumulator.
        return;
    case HttpStatus.SC_NOT_FOUND:
        // This is an error condition, and we do not care about the body.
        exception = new AccountNotFoundException();
        return;
    default:
        // This is an error condition.
        exception = new ProtocolException("Unhandled response status code: " + statusCode);
        return;
    }
}

From source file:org.openstack.burrow.backend.http.AccountListResponseConsumer.java

/**
 * Processes the response as it is received from the server and sets the
 * class's exception field as needed/*  w w w  .j  av a  2  s.c o  m*/
 * 
 * @param response An HttpResponse object that contains the information
 *          requested
 */
@Override
protected void onResponseReceived(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    int statusCode = status.getStatusCode();
    switch (statusCode) {
    case HttpStatus.SC_OK:
        mimeType = EntityUtils.getContentMimeType(response.getEntity());
        if ("application/json".equals(mimeType)) {
            accumulator = new StringBuilder();
        } else if (mimeType != null) {
            exception = new HttpProtocolException("Unhandled response mime type: " + mimeType);
        }
        return;
    case HttpStatus.SC_NO_CONTENT:
        // This is not an error condition, but we do not care about the body
        // and thus do not set up the accumulator.
        return;
    case HttpStatus.SC_NOT_FOUND:
        // This is an error condition, and we do not care about the body.
        exception = new CommandException("No accounts exist on the server");
        return;
    default:
        // This is an error condition.
        exception = new HttpProtocolException("Unhandled response status code: " + statusCode);
        return;
    }
}

From source file:de.yaio.services.metaextract.server.controller.MetaExtractFacade.java

/**
 * extract metadata from the url//from  w ww  .ja  va  2  s  . co  m
 *
 * @param url                   url to read and extract the metadata from
 * @param lang                  language-key to support extraction
 * @return                      extracted metadata from the different extractors
 * @throws IOException          possible errors while reading and copying tmpFiles
 * @throws ExtractorException   possible errors while running extractor
 */
public ExtractedMetaData extractMetaData(final String url, final String lang)
        throws PermissionException, IOException, IOExceptionWithCause, ExtractorException {
    // check url
    getNetFirewall().throwExceptionIfNotAllowed(url);

    // call url
    HttpResponse response = HttpUtils.callGetUrlPure(url, "anonymous", "anonymous", null);
    HttpEntity entity = response.getEntity();

    // check response
    int retCode = response.getStatusLine().getStatusCode();
    if (retCode < 200 || retCode > 299) {
        throw new IOExceptionWithCause("cant read from url", url, new IOException("illegal reponse:"
                + response.getStatusLine() + " for url:" + url + " response:" + EntityUtils.toString(entity)));
    }

    // generate filename from contenttype
    String mimetype = EntityUtils.getContentMimeType(entity);
    MimeTypes allMimeTypes = MimeTypes.getDefaultMimeTypes();
    String fileName;
    try {
        MimeType mime = allMimeTypes.forName(mimetype);
        fileName = "download." + mime.getExtension();

    } catch (MimeTypeException ex) {
        fileName = "download.unknown";
    }

    InputStream input = new ByteArrayInputStream(EntityUtils.toByteArray(entity));
    LOGGER.info("done download data for url:" + url + " with mime:" + mimetype + " to " + fileName);

    return extractMetaData(input, fileName, lang);
}

From source file:com.mgmtp.perfload.core.client.web.http.DefaultHttpClientManager.java

/**
 * Executes an HTTP request using the internal {@link HttpClient} instance encapsulating the
 * Http response in the returns {@link ResponseInfo} object. This method takes to time
 * measurements around the request execution, one after calling
 * {@link HttpClient#execute(org.apache.http.client.methods.HttpUriRequest, HttpContext)} (~
 * first-byte measurment) and the other one later after the complete response was read from the
 * stream. These measurements are return as properties of the {@link ResponseInfo} object.
 *///ww w  .  j  av a  2 s . c o m
@Override
public ResponseInfo executeRequest(final HttpRequestBase request, final HttpContext context,
        final UUID requestId) throws IOException {
    request.addHeader(EXECUTION_ID_HEADER, executionId.toString());
    request.addHeader(OPERATION_HEADER, operation);
    request.addHeader(REQUEST_ID_HEADER, requestId.toString());

    String uri = request.getURI().toString();
    String type = request.getMethod();

    TimeInterval tiBeforeBody = new TimeInterval();
    TimeInterval tiTotal = new TimeInterval();

    tiBeforeBody.start();
    tiTotal.start();
    long timestamp = System.currentTimeMillis();

    HttpResponse response = getHttpClient().execute(request, context);
    tiBeforeBody.stop();

    // This actually downloads the response body:
    HttpEntity entity = response.getEntity();
    byte[] body = EntityUtils.toByteArray(entity);
    tiTotal.stop();

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    String statusMsg = statusLine.getReasonPhrase();
    String responseCharset = EntityUtils.getContentCharSet(entity);
    String contentType = EntityUtils.getContentMimeType(entity);
    String bodyAsString = bodyAsString(contentType, responseCharset, body);

    Header[] headers = response.getAllHeaders();
    Map<String, String> responseHeaders = newHashMapWithExpectedSize(headers.length);
    for (Header header : headers) {
        responseHeaders.put(header.getName(), header.getValue());
    }

    return new ResponseInfo(type, uri, statusCode, statusMsg, responseHeaders, body, bodyAsString,
            responseCharset, contentType, timestamp, tiBeforeBody, tiTotal, executionId, requestId);
}

From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientRemoteStorage.java

@Override
public AbstractStorageItem retrieveItem(final ProxyRepository repository, final ResourceStoreRequest request,
        final String baseUrl) throws ItemNotFoundException, RemoteStorageException {
    final URL remoteURL = appendQueryString(getAbsoluteUrlFromBase(baseUrl, request.getRequestPath()),
            repository);/*  w w w  .  j  a v  a 2s.c  o m*/

    final HttpGet method = new HttpGet(remoteURL.toExternalForm());

    final HttpResponse httpResponse = executeRequest(repository, request, method);

    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

        if (method.getURI().getPath().endsWith("/")) {
            // this is a collection and not a file!
            // httpClient will follow redirections, and the getPath()
            // _should_
            // give us URL with ending "/"
            release(httpResponse);
            throw new ItemNotFoundException(
                    "The remoteURL we got to looks like is a collection, and Nexus cannot fetch collections over plain HTTP (remoteUrl=\""
                            + remoteURL.toString() + "\")",
                    request, repository);
        }

        InputStream is;
        try {
            is = httpResponse.getEntity().getContent();

            String mimeType = EntityUtils.getContentMimeType(httpResponse.getEntity());
            if (mimeType == null) {
                mimeType = getMimeSupport().guessMimeTypeFromPath(repository.getMimeRulesSource(),
                        request.getRequestPath());
            }

            final DefaultStorageFileItem httpItem = new DefaultStorageFileItem(repository, request, CAN_READ,
                    CAN_WRITE, new PreparedContentLocator(is, mimeType));

            if (httpResponse.getEntity().getContentLength() != -1) {
                httpItem.setLength(httpResponse.getEntity().getContentLength());
            }
            httpItem.setRemoteUrl(remoteURL.toString());
            httpItem.setModified(makeDateFromHeader(httpResponse.getFirstHeader("last-modified")));
            httpItem.setCreated(httpItem.getModified());
            httpItem.getItemContext().putAll(request.getRequestContext());

            return httpItem;
        } catch (IOException ex) {
            release(httpResponse);
            throw new RemoteStorageException("IO Error during response stream handling [repositoryId=\""
                    + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\""
                    + remoteURL.toString() + "\"]!", ex);
        } catch (RuntimeException ex) {
            release(httpResponse);
            throw ex;
        }
    } else {
        release(httpResponse);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            throw new ItemNotFoundException(
                    "The remoteURL we requested does not exists on remote server (remoteUrl=\""
                            + remoteURL.toString() + "\")",
                    request, repository);
        } else {
            throw new RemoteStorageException(
                    "The method execution returned result code " + httpResponse.getStatusLine().getStatusCode()
                            + ". [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                            + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString() + "\"]");
        }
    }
}