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:Servlet.Notification.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w w .  j ava 2 s . c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        //grabbing the event parameter
        String eventUrl = request.getParameter("eventUrl");
        System.out.print(eventUrl);

        //Obtaining authority of event
        OAuthConsumer consumer = new DefaultOAuthConsumer("test6-40942", "oQ4q4oBiv9y4jPr7");
        URL url = new URL(eventUrl);
        HttpURLConnection requestUrl = (HttpURLConnection) url.openConnection();
        consumer.sign(requestUrl);
        requestUrl.connect();

        //Reading in the xml file as a string
        String result = null;
        StringBuilder sb = new StringBuilder();
        InputStream is = new BufferedInputStream(requestUrl.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String inputLine = "";
        while ((inputLine = br.readLine()) != null) {
            sb.append(inputLine);
        }

        result = sb.toString();

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(result));

        Document doc = builder.parse(src);
        String creatorName = doc.getElementsByTagName("fullName").item(0).getTextContent();
        String companyName = doc.getElementsByTagName("name").item(0).getTextContent();
        String edition = doc.getElementsByTagName("editionCode").item(0).getTextContent();
        String returnUrl = doc.getElementsByTagName("returnUrl").item(0).getTextContent();

        //parsing elements by name tags from event url
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost xmlResponse = new HttpPost(returnUrl);
        StringEntity input = new StringEntity(
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><result><success>true</success><message>Account change successful</message>");
        input.setContentType("text/xml");
        xmlResponse.setEntity(input);
        httpClient.execute(xmlResponse);

    } catch (OAuthMessageSignerException ex) {
        Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthExpectationFailedException ex) {
        Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthCommunicationException ex) {
        Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.enigmabridge.log.distributor.forwarder.splunk.HttpEventCollectorSender.java

public void postEvents(final List<HttpEventCollectorEventInfo> events,
        final HttpEventCollectorMiddleware.IHttpSenderCallback callback) {
    startHttpClient(); // make sure http client is started
    final String encoding = "utf-8";
    // convert events list into a string
    StringBuilder eventsBatchString = new StringBuilder();
    for (HttpEventCollectorEventInfo eventInfo : events)
        eventsBatchString.append(serializeEventInfo(eventInfo));
    // create http request
    final HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader(AuthorizationHeaderTag, String.format(AuthorizationHeaderScheme, token));
    StringEntity entity = new StringEntity(eventsBatchString.toString(), encoding);
    entity.setContentType(HttpContentType);
    httpPost.setEntity(entity);//w  w  w  . ja  va 2 s. co m
    httpClient.execute(httpPost, new FutureCallback<HttpResponse>() {
        @Override
        public void completed(HttpResponse response) {
            String reply = "";
            int httpStatusCode = response.getStatusLine().getStatusCode();
            // read reply only in case of a server error
            if (httpStatusCode != 200) {
                try {
                    reply = EntityUtils.toString(response.getEntity(), encoding);
                } catch (IOException e) {
                    reply = e.getMessage();
                }
            }
            callback.completed(httpStatusCode, reply);
        }

        @Override
        public void failed(Exception ex) {
            callback.failed(ex);
        }

        @Override
        public void cancelled() {
        }
    });
}

From source file:org.biouno.figshare.FigShareClient.java

/**
 * Create an article./*from  w w  w. ja  v  a2s  .  c  o  m*/
 *
 * @param title title
 * @param description description 
 * @param definedType defined type (e.g. dataset)
 * @return an {@link Article}
 */
public Article createArticle(final String title, final String description, final String definedType) {
    HttpClient httpClient = null;
    try {
        final String method = "my_data/articles";
        // create an HTTP request to a protected resource
        final String url = getURL(endpoint, version, method);
        // create an HTTP request to a protected resource
        final HttpPost request = new HttpPost(url);
        Gson gson = new Gson();
        JsonObject payload = new JsonObject();
        payload.addProperty("title", title);
        payload.addProperty("description", description);
        payload.addProperty("defined_type", definedType);
        String jsonRequest = gson.toJson(payload);
        StringEntity entity = new StringEntity(jsonRequest);
        entity.setContentType(JSON_CONTENT_TYPE);
        request.setEntity(entity);

        // sign the request
        consumer.sign(request);

        // send the request
        httpClient = HttpClientBuilder.create().build();
        HttpResponse response = httpClient.execute(request);
        HttpEntity responseEntity = response.getEntity();
        String json = EntityUtils.toString(responseEntity);
        Article article = readArticleFromJson(json);
        return article;
    } catch (OAuthCommunicationException e) {
        throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
    } catch (OAuthMessageSignerException e) {
        throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
    } catch (OAuthExpectationFailedException e) {
        throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
    } catch (ClientProtocolException e) {
        throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
    }
}

From source file:Servlet.Cancel.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww w .  j  av a2 s.  com
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {

        String eventUrl = request.getParameter("eventUrl");
        System.out.print(eventUrl);

        String valid = "valid";

        OAuthConsumer consumer = new DefaultOAuthConsumer("test6-40942", "oQ4q4oBiv9y4jPr7");
        URL url = new URL(eventUrl);
        HttpURLConnection requestUrl = (HttpURLConnection) url.openConnection();
        consumer.sign(requestUrl);
        requestUrl.connect();

        GetResponse gr = new GetResponse();
        gr.validateUrl(valid);

        String result = null;
        StringBuilder sb = new StringBuilder();
        requestUrl.setRequestMethod("GET");
        BufferedReader br = new BufferedReader(new InputStreamReader(requestUrl.getInputStream()));
        String inputLine = "";
        while ((inputLine = br.readLine()) != null) {
            sb.append(inputLine);
        }

        result = sb.toString();

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(result));

        //parsing elements by name tags from event url
        Document doc = builder.parse(src);
        String creatorName = doc.getElementsByTagName("fullName").item(0).getTextContent();
        String companyName = doc.getElementsByTagName("name").item(0).getTextContent();
        String edition = doc.getElementsByTagName("editionCode").item(0).getTextContent();
        String returnUrl = doc.getElementsByTagName("returnUrl").item(0).getTextContent();

        System.out.print(creatorName);
        System.out.print(companyName);
        System.out.print(edition);
        System.out.print(returnUrl);

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost xmlResponse = new HttpPost(returnUrl);
        StringEntity input = new StringEntity(
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><result><success>true</success><message>Account change successful</message>");
        input.setContentType("text/xml");
        xmlResponse.setEntity(input);
        httpClient.execute(xmlResponse);

    } catch (OAuthMessageSignerException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthExpectationFailedException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthCommunicationException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:models.MessageBusHandler.java

public boolean addTopic(String topic) throws Exception {
    String path = "catalog/topics";
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(serverUrl + path);
    try {//from ww w . ja  v a 2  s  . co m

        JSONObject topicObject = new JSONObject();
        topicObject.put("topic", topic);

        JSONArray jsonMetaArray = new JSONArray();
        jsonMetaArray.put(addFieldToTopic("value", "Float"));
        jsonMetaArray.put(addFieldToTopic("deviceId", "String"));
        jsonMetaArray.put(addFieldToTopic("timeStamp", "Integer"));

        topicObject.put("metadata", jsonMetaArray);

        StringEntity entity = new StringEntity(topicObject.toString(), HTTP.UTF_8);
        //System.err.println(topicObject.toString());
        entity.setContentType("application/json");

        post.setEntity(entity);

        HttpResponse response = client.execute(post);

        //Reading Content
        String output = "";
        String line = "";
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        while ((line = rd.readLine()) != null) {
            output += line;
        }
        if (output.equals(""))
            return true;

    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:net.maritimecloud.identityregistry.keycloak.spi.eventprovider.McEventListenerProvider.java

private void sendUserUpdate(User user, String orgShortName) {
    CloseableHttpClient client = buildHttpClient();
    if (client == null) {
        return;/*from www  .  j a  v a  2s. c om*/
    }
    HttpPost post = new HttpPost(serverRoot + "/x509/api/org/" + orgShortName + "/user-sync/");
    CloseableHttpResponse response = null;
    try {
        String serializedUser = JsonSerialization.writeValueAsString(user);
        StringEntity input = new StringEntity(serializedUser, ContentType.APPLICATION_JSON);
        input.setContentType("application/json");
        post.setEntity(input);
        log.info("user json: " + serializedUser);
        response = client.execute(post);
        int status = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        if (status != 200) {
            String json = getContent(entity);
            String error = "User sync failed. Bad status: " + status + " response: " + json;
            log.error(error);
        } else {
            log.info("User sync'ed!");
        }
    } catch (ClientProtocolException e) {
        log.error("Threw exception", e);
    } catch (IOException e) {
        log.error("Threw exception", e);
    } finally {
        try {
            if (response != null) {
                response.close();
            }
            client.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            log.error("Threw exception", e);
        }
    }
}

From source file:com.impetus.kundera.ycsb.benchmark.CouchDBNativeClient.java

@Override
public int insert(String table, String key, HashMap<String, ByteIterator> values) {
    HttpResponse response = null;/*ww w  .ja  v  a2  s .  c  o  m*/
    try {
        System.out.println("Inserting ....");
        JsonObject object = new JsonObject();
        for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
            object.addProperty(entry.getKey(), entry.getValue().toString());
        }
        URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                CouchDBConstants.URL_SAPRATOR + database.toLowerCase() + CouchDBConstants.URL_SAPRATOR + table
                        + key,
                null, null);

        HttpPut put = new HttpPut(uri);

        StringEntity stringEntity = null;
        object.addProperty("_id", table + key);
        stringEntity = new StringEntity(object.toString(), Constants.CHARSET_UTF8);
        stringEntity.setContentType("application/json");
        put.setEntity(stringEntity);

        response = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            return 1;
        }
        return 0;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        // CouchDBUtils.closeContent(response);
    }
}

From source file:com.adobe.acs.commons.adobeio.service.impl.EndpointServiceImpl.java

private JsonObject processRequestWithBody(@NotNull final HttpEntityEnclosingRequestBase base,
        @NotNull final JsonObject payload, String[] headers) throws IOException {

    StopWatch stopWatch = new StopWatch();
    LOGGER.debug("STARTING STOPWATCH processRequestWithBody");
    stopWatch.start();/*from   w  w  w . j  a  v a  2 s  . c o m*/

    base.setHeader(AUTHORIZATION, BEARER + integrationService.getAccessToken());
    base.setHeader(CACHE_CONTRL, NO_CACHE);
    base.setHeader(X_API_KEY, integrationService.getApiKey());
    base.setHeader(CONTENT_TYPE, CONTENT_TYPE_APPLICATION_JSON);
    if (headers == null || headers.length == 0) {
        addHeaders(base, specificServiceHeaders);
    } else {
        addHeaders(base, convertServiceSpecificHeaders(headers));
    }

    StringEntity input = new StringEntity(payload.toString());
    input.setContentType(CONTENT_TYPE_APPLICATION_JSON);

    if (!base.getClass().isInstance(HttpGet.class)) {
        base.setEntity(input);
    }

    LOGGER.debug("Process call. uri = {}. payload = {}", base.getURI().toString(), payload);

    try (CloseableHttpClient httpClient = helper.getHttpClient(integrationService.getTimeoutinMilliSeconds())) {
        CloseableHttpResponse response = httpClient.execute(base);
        final JsonObject result = responseAsJson(response);

        LOGGER.debug("STOPPING STOPWATCH processRequestWithBody");
        stopWatch.stop();
        LOGGER.debug("Stopwatch time processRequestWithBody: {}", stopWatch);
        stopWatch.reset();
        return result;
    }
}