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

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

Introduction

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

Prototype

public static ContentType create(String str, String str2) throws UnsupportedCharsetException 

Source Link

Usage

From source file:org.fao.geonet.api.mapservers.GeoServerRest.java

/**
 * @param method      e.g. 'POST', 'GET', 'PUT' or 'DELETE'
 * @param urlParams   REST API parameter
 * @param postData    XML data//from ww  w  .j  a v a2  s . co  m
 * @param file        File to upload
 * @param contentType type of content in case of post data or file updload.
 */
public @CheckReturnValue int sendREST(String method, String urlParams, String postData, Path file,
        String contentType, Boolean saveResponse) throws IOException {

    response = "";
    String url = this.restUrl + urlParams;
    if (Log.isDebugEnabled(LOGGER_NAME)) {
        Log.debug(LOGGER_NAME, "url:" + url);
        Log.debug(LOGGER_NAME, "method:" + method);
        if (postData != null)
            Log.debug(LOGGER_NAME, "postData:" + postData);
    }

    HttpRequestBase m;
    if (method.equals(METHOD_PUT)) {
        m = new HttpPut(url);
        if (file != null) {
            ((HttpPut) m)
                    .setEntity(new PathHttpEntity(file, ContentType.create(contentType, Constants.ENCODING)));
        }

        if (postData != null) {
            final StringEntity entity = new StringEntity(postData,
                    ContentType.create(contentType, Constants.ENCODING));
            ((HttpPut) m).setEntity(entity);
        }
    } else if (method.equals(METHOD_DELETE)) {
        m = new HttpDelete(url);
    } else if (method.equals(METHOD_POST)) {
        m = new HttpPost(url);
        if (postData != null) {
            final StringEntity entity = new StringEntity(postData,
                    ContentType.create(contentType, Constants.ENCODING));
            ((HttpPost) m).setEntity(entity);
        }
    } else {
        m = new HttpGet(url);
    }

    if (contentType != null && !"".equals(contentType)) {
        m.setHeader("Content-type", contentType);
    }

    m.setConfig(RequestConfig.custom().setAuthenticationEnabled(true).build());

    // apparently this is needed to preemptively send the auth, for servers that dont require it but
    // dont send the same data if you're authenticated or not.
    try {
        m.addHeader(new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), m));
    } catch (AuthenticationException a) {
        Log.warning(LOGGER_NAME, "Failed to add the authentication Header, error is: " + a.getMessage());
    }
    ;

    final ClientHttpResponse httpResponse = factory.execute(m,
            new UsernamePasswordCredentials(username, password), AuthScope.ANY);

    try {
        status = httpResponse.getRawStatusCode();
        if (Log.isDebugEnabled(LOGGER_NAME)) {
            Log.debug(LOGGER_NAME, "status:" + status);
        }
        if (saveResponse) {
            this.response = IOUtils.toString(httpResponse.getBody());
        }
    } finally {
        httpResponse.close();
    }

    return status;
}

From source file:com.xebialabs.overthere.cifs.winrm.WinRmClient.java

/**
 * Create the HttpEntity to send in the request.
 *///from   www .j  av  a  2  s.c o m
protected HttpEntity createEntity(final String requestDocAsString) {
    return new StringEntity(requestDocAsString, ContentType.create("application/soap+xml", "UTF-8"));
}

From source file:de.hska.ld.oidc.client.SSSClient.java

public SSSLivingDocResponseDto getLDocEmailsById(Long documentId, String accessToken)
        throws IOException, AuthenticationNotValidException {
    String url = null;//from  w  w  w .ja v  a2  s  .  co m
    if (getSssAPIVersion() == 1) {
        url = env.getProperty("sss.server.endpoint") + "/livingdocs/livingdocs/filtered/" + URLEncoder.encode(
                URLEncoder.encode(env.getProperty("sss.document.name.prefix") + documentId, "UTF-8"), "UTF-8");
    } else {
        url = env.getProperty("sss.server.endpoint") + "/rest/livingdocs/filtered/" + URLEncoder.encode(
                URLEncoder.encode(env.getProperty("sss.document.name.prefix") + documentId, "UTF-8"), "UTF-8");
    }

    StringEntity stringEntity = new StringEntity("{\"setUsers\": true}",
            ContentType.create("application/json", "UTF-8"));
    PostClientRequest postClientRequest = new PostClientRequest(url, "getLDocEmailsById1");
    try {
        postClientRequest.execute(stringEntity, accessToken);
    } catch (Exception e) {
        exceptionLogger.log("getLDocEmailsById1 Statuscode", e);
    }
    SSSLivingDocResponseDto sssLivingDocResponseDto = postClientRequest
            .getParsedBody(SSSLivingDocResponseDto.class);
    if (sssLivingDocResponseDto == null) {
        // TODO HACK this is a workaround because the configuration in the production system was set wrong and the
        // ids can't be changed in a quick way
        String url2 = null;
        if (getSssAPIVersion() == 1) {
            url2 = env.getProperty("sss.server.endpoint") + "/livingdocs/livingdocs/filtered/" + URLEncoder
                    .encode(URLEncoder.encode("http://178.62.62.23:9000/" + documentId, "UTF-8"), "UTF-8");
        } else {
            url2 = env.getProperty("sss.server.endpoint") + "/rest/livingdocs/filtered/" + URLEncoder
                    .encode(URLEncoder.encode("http://178.62.62.23:9000/" + documentId, "UTF-8"), "UTF-8");
        }

        PostClientRequest postClientRequest2 = new PostClientRequest(url2, "getLDocEmailsById2");
        StringEntity stringEntity2 = new StringEntity("{}", ContentType.create("application/json", "UTF-8"));
        try {
            postClientRequest2.execute(stringEntity2, accessToken);
        } catch (Exception e) {
            exceptionLogger.log("getLDocEmailsById2 Statuscode", e);
        }
        return postClientRequest2.getParsedBody(SSSLivingDocResponseDto.class);
    } else {
        return sssLivingDocResponseDto;
    }
}

From source file:de.hska.ld.recommendation.client.SSSClient.java

private void addTagToUserUser(String url, User user, List<String> tagStringList, String accessToken)
        throws IOException {
    String userPrefix = env.getProperty("sss.user.name.prefix");

    RecommUpdateDto recommUpdateDto = new RecommUpdateDto();
    recommUpdateDto.setRealm(env.getProperty("sss.recomm.realm"));
    recommUpdateDto.setForUser(userPrefix + user.getId());
    recommUpdateDto.setEntity(userPrefix + user.getId());
    recommUpdateDto.setTags(tagStringList);

    HttpClient client = getHttpClientFor(url);
    HttpPut put = new HttpPut(url);
    addHeaderInformation(put, accessToken);

    String recommUpdateDtoString = mapper.writeValueAsString(recommUpdateDto);
    StringEntity stringEntity = new StringEntity(recommUpdateDtoString,
            ContentType.create("application/json", "UTF-8"));
    put.setEntity(stringEntity);/*from  www  . j  a v  a  2  s . c  o m*/
    BufferedReader rd = null;

    HttpResponse response = client.execute(put);
    System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

    if (response.getStatusLine().getStatusCode() != 200) {
        if (response.getStatusLine().getStatusCode() == 403) {
            throw new UserNotAuthorizedException();
        }
    }

    try {
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuilder result = new StringBuilder();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        if (result.toString().contains("\"error_description\":\"Invalid access token:")) {
            throw new ValidationException("access token is invalid");
        }
        mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        RecommUpdateResponseDto recommUpdateResponseDto = mapper.readValue(result.toString(),
                RecommUpdateResponseDto.class);
        if (!recommUpdateResponseDto.isWorked()) {
            throw new Exception("Updating recommendations didn't work!");
        } else {
            user = userService.findById(user.getId());
            UserRecommInfo userRecommInfo = new UserRecommInfo();
            userRecommInfo.setUser(user);
            userRecommInfo.setInitialImportToSSSDone(true);
            entityManager.persist(userRecommInfo);
        }
        return;
    } catch (ValidationException ve) {
        throw ve;
    } catch (Exception e) {
        return;
    } finally {
        if (rd != null) {
            rd.close();
        }
    }
}

From source file:org.dspace.identifier.doi.DataCiteConnector.java

private DataCiteResponse sendMetadataPostRequest(String doi, String metadata) throws DOIIdentifierException {
    // post mds/metadata/
    // body must contain metadata in DataCite-XML.
    URIBuilder uribuilder = new URIBuilder();
    uribuilder.setScheme("https").setHost(HOST).setPath(METADATA_PATH);

    HttpPost httppost = null;/*w ww .j  ava 2  s  .co m*/
    try {
        httppost = new HttpPost(uribuilder.build());
    } catch (URISyntaxException e) {
        log.error("The URL we constructed to check a DOI "
                + "produced a URISyntaxException. Please check the configuration parameters!");
        log.error("The URL was {}.", "https://" + HOST + DOI_PATH + "/" + doi.substring(DOI.SCHEME.length()));
        throw new RuntimeException("The URL we constructed to check a DOI "
                + "produced a URISyntaxException. Please check the configuration parameters!", e);
    }

    // assemble request content:
    HttpEntity reqEntity = null;
    try {
        ContentType contentType = ContentType.create("application/xml", "UTF-8");
        reqEntity = new StringEntity(metadata, contentType);
        httppost.setEntity(reqEntity);

        return sendHttpRequest(httppost, doi);
    } finally {
        // release ressources
        try {
            EntityUtils.consume(reqEntity);
        } catch (IOException ioe) {
            log.info("Caught an IOException while releasing an HTTPEntity:" + ioe.getMessage());
        }
    }
}

From source file:de.hska.ld.oidc.client.SSSClient.java

public void shareLDocWith(Long documentId, List<String> sssUserIdsTheLDocIsNotSharedWith, String accessToken)
        throws IOException {
    String url = null;/*from   w  w w  .j a  v a  2s. c  o  m*/
    if (getSssAPIVersion() == 1) {
        url = env.getProperty("sss.server.endpoint") + "/entities/entities/"
                + URLEncoder.encode(
                        URLEncoder.encode(env.getProperty("sss.document.name.prefix") + documentId, "UTF-8"),
                        "UTF-8")
                + "/share";
    } else {
        url = env.getProperty("sss.server.endpoint") + "/rest/entities/"
                + URLEncoder.encode(
                        URLEncoder.encode(env.getProperty("sss.document.name.prefix") + documentId, "UTF-8"),
                        "UTF-8")
                + "/share";
    }

    HttpClient client = getHttpClientFor(url);
    HttpPut put = new HttpPut(url);
    addHeaderInformation(put, accessToken);

    SSSShareEntityDto sssShareEntityDto = new SSSShareEntityDto();
    sssShareEntityDto.setUsers(sssUserIdsTheLDocIsNotSharedWith);

    String requestDtoString = mapper.writeValueAsString(sssShareEntityDto);
    StringEntity stringEntity = new StringEntity(requestDtoString,
            ContentType.create("application/json", "UTF-8"));
    put.setEntity(stringEntity);
    BufferedReader rd = null;

    HttpResponse response = client.execute(put);
    System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

    if (response.getStatusLine().getStatusCode() != 200) {
        if (response.getStatusLine().getStatusCode() == 403) {
            throw new UserNotAuthorizedException();
        }
    }

    try {
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuilder result = new StringBuilder();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        if (result.toString().contains("\"error_description\":\"Invalid access token:")) {
            throw new ValidationException("access token is invalid");
        }
    } catch (ValidationException ve) {
        throw ve;
    } catch (Exception e) {
        e.printStackTrace();
        //return null;
    } finally {
        if (rd != null) {
            rd.close();
        }
    }
}

From source file:org.esigate.DriverTest.java

/**
 * 0000135: Special characters are lost when including a fragment with no charset specified into UTF-8 page.
 * //from ww w  .  ja v  a2  s. c o m
 * @throws Exception
 * @see <a href="http://www.esigate.org/mantisbt/view.php?id=135">0000135</a>
 */
public void testSpecialCharacterInIncludeNoCharset() throws Exception {
    String now = DateUtils.formatDate(new Date());

    // Create master application
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost");
    HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "Ok");
    response.addHeader("Date", now);
    response.addHeader("Content-type", "Text/html;Charset=UTF-8");
    HttpEntity httpEntity = new StringEntity("<esi:include src=\"$(PROVIDER{provider})/\"/>", "UTF-8");
    response.setEntity(httpEntity);
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);

    // Create provider application
    properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost");
    mockConnectionManager = new MockConnectionManager();
    response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "Ok");
    response.addHeader("Date", now);
    response.addHeader("Content-type", "text/html");
    httpEntity = new ByteArrayEntity("".getBytes("ISO-8859-1"),
            ContentType.create("text/html", (String) null));
    response.setEntity(httpEntity);
    mockConnectionManager.setResponse(response);
    createMockDriver(properties, mockConnectionManager, "provider");

    // Do the include and check the result
    CloseableHttpResponse driverResponse = driver.proxy("/", request.build(), new EsiRenderer());
    assertEquals("", HttpResponseUtils.toString(driverResponse));
}

From source file:de.hska.ld.recommendation.client.SSSClient.java

public void userTouchSSSRecommendations(Long userId, String accessToken) throws IOException {
    String url = null;/*from   w  w w.  j ava 2 s. c  om*/
    if (getSssAPIVersion() == 1) {
        url = env.getProperty("sss.server.endpoint") + "/recomm/recomm/update";
    } else {
        url = env.getProperty("sss.server.endpoint") + "/rest/recomm/update";
    }

    RecommUpdateDto recommUpdateDto = new RecommUpdateDto();
    recommUpdateDto.setRealm(env.getProperty("sss.recomm.realm"));
    recommUpdateDto.setForUser("dummyDocument/" + userId);
    recommUpdateDto.setEntity("dummyDocument/" + userId);
    List<String> tagStringList = new ArrayList<>();
    recommUpdateDto.setTags(tagStringList);

    HttpClient client = getHttpClientFor(url);
    HttpPut put = new HttpPut(url);
    addHeaderInformation(put, accessToken);

    String recommUpdateDtoString = mapper.writeValueAsString(recommUpdateDto);
    StringEntity stringEntity = new StringEntity(recommUpdateDtoString,
            ContentType.create("application/json", "UTF-8"));
    put.setEntity(stringEntity);
    BufferedReader rd = null;

    HttpResponse response = client.execute(put);
    System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

    if (response.getStatusLine().getStatusCode() != 200) {
        if (response.getStatusLine().getStatusCode() == 403) {
            throw new UserNotAuthorizedException();
        }
    }

    try {
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuilder result = new StringBuilder();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        if (result.toString().contains("\"error_description\":\"Invalid access token:")) {
            throw new ValidationException("access token is invalid");
        }
        mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        RecommUpdateResponseDto recommUpdateResponseDto = mapper.readValue(result.toString(),
                RecommUpdateResponseDto.class);
        return;
    } catch (ValidationException ve) {
        throw ve;
    } catch (Exception e) {
        return;
    } finally {
        if (rd != null) {
            rd.close();
        }
    }
}