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

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

Introduction

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

Prototype

public static ContentType getOrDefault(HttpEntity httpEntity)
            throws ParseException, UnsupportedCharsetException 

Source Link

Usage

From source file:com.dougtest.restTest.basicRestTests.java

/**
 * This test will verify that when using a "format=text" the Rest API will the correct MIME Type There is a bug in this and should be logged. This test fails 
 * @throws ClientProtocolException//w  w w.  j a v a 2s  .co m
 * @throws IOException 
 */

@Test
public void verifyBadType() throws ClientProtocolException, IOException {
    final String jsonMimeType = "application/xml";
    final HttpUriRequest request = new HttpGet(txturl + "CR-Franklin");

    final HttpResponse response = HttpClientBuilder.create().build().execute(request);

    final String mimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
    assertEquals(jsonMimeType, mimeType);
}

From source file:de.unioninvestment.eai.portal.portlet.crud.scripting.domain.container.rest.AbstractParser.java

/**
 * @param response/*from  w ww . j a  v a  2 s . c om*/
 *            the ReST Response
 * @return a reader providing the HTTP payload and respecting the response
 *         encoding
 * @throws IOException
 */
protected Reader getReader(HttpResponse response) throws IOException {
    ContentType contentType = ContentType.getOrDefault(response.getEntity());
    InputStream stream = response.getEntity().getContent();
    InputStreamReader reader = new InputStreamReader(stream, getResponseCharset(contentType));
    return reader;
}

From source file:com.dougtest.restTest.basicRestTests.java

/**
 * Used to verify that the API will give the correct response for a bad "SchedStop name" in this case I used "CR-Moon" instead of a valid name.
 * @throws ClientProtocolException/* w  w  w. ja  v  a  2  s. c o  m*/
 * @throws IOException 
 */

@Test
public void verifyBadRoute() throws ClientProtocolException, IOException {
    final String jsonMimeType = "application/json";
    final HttpUriRequest request = new HttpGet(url + "CR-Moon");

    final HttpResponse response = HttpClientBuilder.create().build().execute(request);
    final String mimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
    assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_NOT_FOUND));
    assertEquals(jsonMimeType, mimeType);
}

From source file:com.example.restexpmongomvn.controller.VehicleControllerTest.java

/**
 * Test of read method, of class VehicleController.
 * @throws com.fasterxml.jackson.core.JsonProcessingException
 * @throws java.io.IOException//w w  w.j av a2  s  .  c  o  m
 */
@Test
public void testRead() throws JsonProcessingException, IOException {
    System.out.println("read");

    Vehicle testVehicle = new Vehicle(2015, "Test", "Vehicle", Color.Red, "4-Door Sedan");
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(Include.NON_EMPTY);
    String testVehicleString = objectMapper.writeValueAsString(testVehicle);

    StringEntity postEntity = new StringEntity(testVehicleString,
            ContentType.create("application/json", "UTF-8"));
    postEntity.setChunked(true);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost(BASE_URL + "/restexpress/vehicles");
    httppost.setEntity(postEntity);
    CloseableHttpResponse response = httpclient.execute(httppost);

    String responseString = new BasicResponseHandler().handleResponse(response);
    responseString = responseString.replaceAll("^\"|\"$", "");

    // Get vehicle based on MongoDB id
    HttpGet httpget = new HttpGet(BASE_URL + "/restexpress/vehicle/" + responseString);
    CloseableHttpResponse response2 = httpclient.execute(httpget);

    String responseString2 = new BasicResponseHandler().handleResponse(response2);

    ResponseHandler<Vehicle> rh = new ResponseHandler<Vehicle>() {

        @Override
        public Vehicle handleResponse(final HttpResponse response) throws IOException {
            StatusLine statusLine = response.getStatusLine();
            HttpEntity entity = response.getEntity();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }
            if (entity == null) {
                throw new ClientProtocolException("Response contains no content");
            }
            Gson gson = new GsonBuilder().setPrettyPrinting().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
                    .create();
            ContentType contentType = ContentType.getOrDefault(entity);
            Charset charset = contentType.getCharset();
            Reader reader = new InputStreamReader(entity.getContent(), "UTF-8");

            //                String inputStreamString = new Scanner(entity.getContent(), "UTF-8").useDelimiter("\\A").next();
            //                System.out.println(inputStreamString);

            return gson.fromJson(reader, Vehicle.class);
        }
    };
    Vehicle vehicle = httpclient.execute(httpget, rh);
    System.out.println("b");

    //        MongodbEntityRepository<Vehicle> vehicleRepository;
    //        VehicleController instance = new VehicleController(vehicleRepository);
    //        Vehicle result = instance.read(request, response);
    //        assertEquals(parseMongoId(responseString), true);
}

From source file:de.elomagic.carafile.client.CaraCloud.java

private FileChangesList getRemoteChangeList(long lastMillis) throws IOException {
    URI uri = CaraFileUtils.buildURI(client.getRegistryURI(), "cloud", "changes", Long.toString(lastMillis));
    HttpResponse response = client.executeRequest(Request.Get(uri)).returnResponse();

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException("HTTP responce code " + response.getStatusLine().getStatusCode() + " "
                + response.getStatusLine().getReasonPhrase());
    }/*from w  ww . jav  a  2  s  .  c  o  m*/

    Charset charset = ContentType.getOrDefault(response.getEntity()).getCharset();

    FileChangesList changeList = JsonUtil
            .read(new InputStreamReader(response.getEntity().getContent(), charset), FileChangesList.class);

    LOG.debug("Folder contains " + changeList.getChangeList() + " item(s)");

    return changeList;
}

From source file:com.mirth.connect.client.core.ConnectServiceUtil.java

public static int getNotificationCount(String serverId, String mirthVersion,
        Map<String, String> extensionVersions, Set<Integer> archivedNotifications, String[] protocols,
        String[] cipherSuites) {//w  w w  .  j  a va2 s  . co m
    CloseableHttpClient client = null;
    HttpPost post = new HttpPost();
    CloseableHttpResponse response = null;

    int notificationCount = 0;

    try {
        ObjectMapper mapper = new ObjectMapper();
        String extensionVersionsJson = mapper.writeValueAsString(extensionVersions);
        NameValuePair[] params = { new BasicNameValuePair("op", NOTIFICATION_COUNT_GET),
                new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion),
                new BasicNameValuePair("extensionVersions", extensionVersionsJson) };
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT)
                .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();

        post.setURI(URI.create(URL_CONNECT_SERVER + URL_NOTIFICATION_SERVLET));
        post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8")));

        HttpClientContext postContext = HttpClientContext.create();
        postContext.setRequestConfig(requestConfig);
        client = getClient(protocols, cipherSuites);
        response = client.execute(post, postContext);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if ((statusCode == HttpStatus.SC_OK)) {
            HttpEntity responseEntity = response.getEntity();
            Charset responseCharset = null;
            try {
                responseCharset = ContentType.getOrDefault(responseEntity).getCharset();
            } catch (Exception e) {
                responseCharset = ContentType.TEXT_PLAIN.getCharset();
            }

            List<Integer> notificationIds = mapper.readValue(
                    IOUtils.toString(responseEntity.getContent(), responseCharset).trim(),
                    new TypeReference<List<Integer>>() {
                    });
            for (int id : notificationIds) {
                if (!archivedNotifications.contains(id)) {
                    notificationCount++;
                }
            }
        }
    } catch (Exception e) {
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(client);
    }
    return notificationCount;
}

From source file:edu.si.services.beans.edansidora.EdanApiBean.java

/**
 * Perform a EDAN http request//  w ww  .j  ava  2 s . com
 *
 * @param exchange Camel exchange containing the edanServiceEndpoint and edanQueryParams that gets appended to the
 *                    service url
 */
public void sendRequest(Exchange exchange, @Header("edanServiceEndpoint") String edanServiceEndpoint,
        @Header(Exchange.HTTP_QUERY) String edanQueryParams) throws EdanIdsException {

    out = exchange.getIn();

    try {
        setEdanAuth(edanQueryParams);

        if (client == null) {
            throw new EdanIdsException("EdanApiBean Client IS NULL");
        } else {
            System.setProperty("http.agent", "");
            String uri = server + edanServiceEndpoint + "?" + edanQueryParams;
            LOG.debug("EdanApiBean uri: {}", uri);

            HttpGet httpget = new HttpGet(uri);
            httpget.setHeader("X-AppId", app_id);
            httpget.setHeader("X-Nonce", nonce);
            httpget.setHeader("X-RequestDate", sdfDate);
            httpget.setHeader("X-AuthContent", authContent);
            httpget.setHeader("X-AppVersion", "EDANInterface-0.10.1");
            httpget.setHeader("Accept", "*/*");
            httpget.setHeader("Accept-Encoding", "identity");
            httpget.setHeader("User-Agent", "unknown");

            LOG.debug("EdanApiBean httpGet headers: " + Arrays.toString(httpget.getAllHeaders()));

            try (CloseableHttpResponse response = client.execute(httpget)) {
                HttpEntity entity = response.getEntity();

                LOG.debug("CloseableHttpResponse response.toString(): {}", response.toString());

                Integer responseCode = response.getStatusLine().getStatusCode();
                String statusLine = response.getStatusLine().getReasonPhrase();
                String entityResponse = EntityUtils.toString(entity, "UTF-8");

                //set the response
                out.setBody(entityResponse);

                //copy response headers to camel
                org.apache.http.Header[] headers = response.getAllHeaders();
                String contentType = null;
                for (org.apache.http.Header header : response.getAllHeaders()) {
                    String name = header.getName();
                    // mapping the content-type
                    if (name.toLowerCase().equals("content-type")) {
                        name = Exchange.CONTENT_TYPE;
                        contentType = header.getValue();
                    }
                    out.setHeader(name, header.getValue());

                }
                out.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode);
                out.setHeader(Exchange.HTTP_RESPONSE_TEXT, statusLine);

                if (responseCode != 200) {
                    LOG.debug("Edan response: " + Exchange.HTTP_RESPONSE_CODE + "= {}, "
                            + Exchange.HTTP_RESPONSE_TEXT + "= {}", responseCode, statusLine);
                    LOG.error("Edan response entity: {}", entityResponse);
                } else {
                    LOG.debug("Edan response: " + Exchange.HTTP_RESPONSE_CODE + "= {}, "
                            + Exchange.HTTP_RESPONSE_TEXT + "= {}", responseCode, statusLine);
                }

                if (!ContentType.getOrDefault(entity).getMimeType().equalsIgnoreCase("application/json")) {
                    throw new EdanIdsException(
                            "The EDAN response did not contain and JSON! Content-Type is " + contentType);
                }
            } catch (Exception e) {
                throw new EdanIdsException("EdanApiBean error sending Edan request", e);
            }
        }
    } catch (Exception e) {
        throw new EdanIdsException(e);
    }
}

From source file:org.springframework.boot.cli.command.init.InitializrService.java

private String getContent(HttpEntity entity) throws IOException {
    ContentType contentType = ContentType.getOrDefault(entity);
    Charset charset = contentType.getCharset();
    charset = (charset != null ? charset : UTF_8);
    byte[] content = FileCopyUtils.copyToByteArray(entity.getContent());
    return new String(content, charset);
}

From source file:org.eclipse.ebr.maven.AboutFilesUtil.java

private String downloadLicenseFile(final File licenseOutputDir, final License license, final URL licenseUrl)
        throws IOException {
    String licenseFileName = "about_files/" + sanitizeFileName(license.getName()).toUpperCase();
    final String existingLicense = findExistingLicenseFile(licenseOutputDir, licenseFileName);
    if (existingLicense != null) {
        if (!forceDownload) {
            getLog().info(format("Found existing license file at '%s'. %s", existingLicense,
                    REQUIRES_FORCE_DOWNLOAD_MESSAGE));
            return existingLicense;
        } else if (getMavenSession().isOffline()) {
            getLog().warn(format("Re-using existing license file at '%s'. Maven is offline.", existingLicense));
            return existingLicense;
        }/*ww  w.ja va2 s  .  com*/
    } else if (getMavenSession().isOffline())
        throw new IOException("Maven is offline.");
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        final HttpGet get = new HttpGet(licenseUrl.toExternalForm());
        get.setHeader("Accept", "text/plain,text/html");
        try (final CloseableHttpResponse response = client.execute(get)) {
            if (response.getStatusLine().getStatusCode() != 200)
                throw new IOException(format("Download failed: %s", response.getStatusLine().toString()));
            final HttpEntity entity = response.getEntity();
            if (entity == null)
                throw new IOException("Download faild. Empty respose.");

            try (final InputStream is = entity.getContent()) {
                final ContentType contentType = ContentType.getOrDefault(entity);
                if (StringUtils.equalsIgnoreCase(contentType.getMimeType(), "text/plain")) {
                    licenseFileName = licenseFileName + ".txt";
                } else if (StringUtils.equalsIgnoreCase(contentType.getMimeType(), "text/html")) {
                    licenseFileName = licenseFileName + ".html";
                } else {
                    getLog().warn(format(
                            "Unexpected content type (%s) returned by remote server. Falling back to text/plain.",
                            contentType));
                    licenseFileName = licenseFileName + ".txt";
                }

                final FileOutputStream os = FileUtils
                        .openOutputStream(new File(licenseOutputDir, licenseFileName));
                try {
                    IOUtils.copy(is, os);
                } finally {
                    IOUtils.closeQuietly(os);
                }
            }
        }
    }
    return licenseFileName;
}