Example usage for org.apache.http.entity StringEntity setContentType

List of usage examples for org.apache.http.entity StringEntity setContentType

Introduction

In this page you can find the example usage for org.apache.http.entity StringEntity setContentType.

Prototype

public void setContentType(Header header) 

Source Link

Usage

From source file:zswi.protocols.communication.core.HTTPSConnection.java

/**
   This method provides updating entered VCard,
   @param card target ServerVCard object 
   @return true if update was successful
 *//*www  .jav  a2s.  c om*/
public boolean updateVCard(ServerVCard card) throws URISyntaxException, ClientProtocolException, IOException {
    VCardWriter wr = new VCardWriter();
    wr.setVCard(card.getVcard());

    StringEntity se = new StringEntity(wr.buildVCardString(), "UTF-8");
    se.setContentType(TYPE_VCARD);
    return this.updateVCard(se, card.geteTag(), card.getPath());
}

From source file:net.maritimecloud.identityregistry.utils.KeycloakServiceAccountUtil.java

/**
 * Creates or updates an IDP./*from w w w .  ja  v a2 s  .c o m*/
 * 
 * @param name          name of the IDP
 * @param wellKnownUrl  the url where info on the IDP can be obtained
 * @param clientId      the id used for the MC in the IDP
 * @param clientSecret  the secret used for the MC in the IDP
 */
public void createIdentityProvider(String name, String wellKnownUrl, String clientId, String clientSecret) {
    // Get IDP info by parsing info from wellKnownUrl json
    IdentityProviderRepresentation idp = getIdpFromWellKnownUrl(wellKnownUrl);
    if (idp == null) {
        return;
    }
    // Insert data into IDP data structure
    idp.setAlias(name);
    Map<String, String> IDPConf = idp.getConfig();
    IDPConf.put("clientId", clientId);
    IDPConf.put("clientSecret", clientSecret);
    idp.setConfig(IDPConf);

    // Check if the IDP already exists
    IdentityProviderRepresentation oldIdp = null;
    try {
        oldIdp = this.getIDP(clientId);
    } catch (Exception e) {
    }

    CloseableHttpClient client = HttpClientBuilder.create().build();
    // If the IDP already exists, update it, otherwise create it.
    if (oldIdp == null) {
        // Now POST the IDP data to keycloak 
        try {
            HttpPost post = new HttpPost(deployment.getAuthServerBaseUrl() + "/admin/realms/" + realm
                    + "/identity-provider/instances");
            if (token != null) {
                post.addHeader("Authorization", "Bearer " + token);
            }
            System.out.println("idp creating json: " + JsonSerialization.writeValueAsString(idp));
            StringEntity input = new StringEntity(JsonSerialization.writeValueAsString(idp));
            input.setContentType("application/json");
            post.setEntity(input);
            HttpResponse response = client.execute(post);
            int status = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (status != 201) {
                String json = getContent(entity);
                String error = "IDP creation failed. Bad status: " + status + " response: " + json;
                System.out.println(error);
                //req.setAttribute(ERROR, error);
            } else {
                System.out.println("IDP created! " + getContent(entity));
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    } else {
        // Now PUT the IDP data to keycloak 
        try {
            HttpPut put = new HttpPut(deployment.getAuthServerBaseUrl() + "/admin/realms/" + realm
                    + "/identity-provider/instances/" + clientId);
            if (token != null) {
                put.addHeader("Authorization", "Bearer " + token);
            }
            System.out.println("idp update json: " + JsonSerialization.writeValueAsString(idp));
            StringEntity input = new StringEntity(JsonSerialization.writeValueAsString(idp));
            input.setContentType("application/json");
            put.setEntity(input);
            HttpResponse response = client.execute(put);
            int status = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (status != 201) {
                String json = getContent(entity);
                String error = "IDP update failed. Bad status: " + status + " response: " + json;
                System.out.println(error);
                //req.setAttribute(ERROR, error);
            } else {
                System.out.println("IDP updated! " + getContent(entity));
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:org.clinical3po.backendservices.server.handler.RestHandlerTest.java

/**
 * Delete test user in order to run the same signUp again and again.
 * @throws Exception/*from w ww.  j av  a 2s .c  o m*/
 */
private void cleanUpUser() throws Exception {
    StatusLine statusLine = null;
    // getUser and check status
    HttpPost httpPost = new HttpPost("http://example:8080/api/rs");
    StringEntity input = new StringEntity(getUserByUserId);
    input.setContentType("application/json");
    httpPost.setEntity(input);
    httpPost.setHeader("Authorization", ownerToken);

    CloseableHttpResponse response = httpclient.execute(httpPost);

    try {
        statusLine = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
        String json = "";
        String line = "";
        while ((line = rd.readLine()) != null) {
            json = json + line;
        }
        EntityUtils.consume(entity);
    } finally {
        response.close();
    }

    // delete user if it exists.
    if (statusLine.getStatusCode() == 200) {
        delUser();
    }
}

From source file:TestHTTPSource.java

@Test
public void testInvalid() throws Exception {
    StringEntity input = new StringEntity("[{\"a\": \"b\",[\"d\":\"e\"],\"body\": \"random_body\"},"
            + "{\"e\": \"f\",\"body\": \"random_body2\"}]");
    input.setContentType("application/json");
    postRequest.setEntity(input);/*  ww w.  ja v  a 2  s .  c  o m*/
    HttpResponse response = httpClient.execute(postRequest);

    Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatusLine().getStatusCode());

}

From source file:zswi.protocols.communication.core.HTTPSConnection.java

/**
   This method provides updating entered VCard,
   @param card target ServerVCard object 
   @return true if update was successful
 *//*from w  ww . ja va  2 s. c om*/
public boolean updateVEvent(ServerVEvent event)
        throws URISyntaxException, ClientProtocolException, IOException {
    // vEvent must be enclosed in Calendar, otherwise is not added
    Calendar calendarForEvent = new Calendar();
    calendarForEvent.getComponents().add(event.getVevent());

    StringEntity se = new StringEntity(calendarForEvent.toString(), "UTF-8");
    se.setContentType(TYPE_VEVENT);

    return this.updateVCard(se, event.geteTag(), event.getPath());
}

From source file:zswi.protocols.communication.core.HTTPSConnection.java

/**
   This method provides adding VEvent to calendar passed in the second argument.
   @param event   VEvent object//from   www  .  j  a v a2 s  .  c o m
   @param calendar destination for adding VEvent 
   @return true if adding was successful, otherwise return false
 */
public boolean addVEvent(VEvent event, ServerCalendar calendar)
        throws ClientProtocolException, IOException, URISyntaxException {

    // vEvent must be enclosed in Calendar, otherwise is not added
    Calendar calendarForEvent = new Calendar();
    calendarForEvent.getComponents().add(event);

    StringEntity se = new StringEntity(calendarForEvent.toString(), "UTF-8");
    se.setContentType(TYPE_VEVENT);
    String path;
    if (calendar == null) {
        path = defaultCalendarPath;
    } else {
        path = calendar.getPath();
    }
    return this.addVEvent(se, path);
}

From source file:gpsalarm.app.service.PostMonitor.java

private void updateLocation(Account myAccount2) {
    String baseURI = "http://" + targetDomain + ":" + targetPort + "/wsdbServiceWAR/position";
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpHost targetHost = new HttpHost(targetDomain, targetPort, "http");
    Serializer s = new Persister();

    try {//  w ww  . j  a v a 2 s . c  o  m
        curr = rdb.getPosition(myAccount2.user);
        if (curr == null)
            return;
        if ((prev == null) || (curr.distance(prev) > 20)) {
            if (curr.getUsername() == null)
                return;
            String urlToSendRequest = baseURI + "/new";
            // Using POST here
            HttpPut httpput = new HttpPut(urlToSendRequest);
            // Make sure the server knows what kind of a response we will accept
            httpput.addHeader("Accept", "text/xml");
            // Also be sure to tell the server what kind of content we are sending
            httpput.addHeader("Content-Type", "application/xml");

            StringEntity entity = new StringEntity(curr.getXML(), "UTF-8");
            entity.setContentType("application/xml");
            httpput.setEntity(entity);

            // execute is a blocking call, it's best to call this code in a thread separate from the ui's
            httpClient.execute(targetHost, httpput);
            prev = curr;
        }

    } catch (Exception ex) {
        Log.e(TAG, ex.toString(), ex);
    } finally {
        rdb.close();
    }

    //Who is near where
}

From source file:zswi.protocols.communication.core.HTTPSConnection.java

/**
   This method provides sending report request to server.
   @param filename name of a file containing report request
   @param path request target path//  w w  w  .j  a v  a 2 s .  com
   @param depth report depth
   @return server response
 */
private String report(String filename, String path, int depth)
        throws ClientProtocolException, IOException, URISyntaxException {
    ReportRequest req = new ReportRequest(initUri(path), depth);

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream is = classLoader.getResourceAsStream(filename);

    StringEntity se = new StringEntity(convertStreamToString(is), "UTF-8");

    se.setContentType(TYPE_XML);
    req.setEntity(se);

    HttpResponse resp = client.execute(req);

    String response = "";
    response += EntityUtils.toString(resp.getEntity(), "UTF-8");

    EntityUtils.consume(resp.getEntity());

    return response;
}

From source file:zswi.protocols.communication.core.HTTPSConnection.java

/**
   This method provides sending propfind request to server.
   @param fileName name of a file containing propfinde request
   @param uriName propfind uri//from   w ww  . j a v a 2 s .co m
   @return server response
 */
private String propfind(String fileName, String uriName)
        throws URISyntaxException, ClientProtocolException, IOException {

    PropfindRequest req = new PropfindRequest(initUri(uriName));
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream is = classLoader.getResourceAsStream(fileName);

    StringEntity se = new StringEntity(convertStreamToString(is), "UTF-8");

    se.setContentType(TYPE_XML);
    req.setEntity(se);

    HttpResponse resp = client.execute(req);

    String response = "";
    response += EntityUtils.toString(resp.getEntity(), "UTF-8");

    EntityUtils.consume(resp.getEntity());

    return response;

}