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:com.appdynamics.connectors.vcd.VappClient.java

public IMachine createVm(IImage image, IMachineDescriptor machineDescriptor, IComputeCenter computeCenter)
        throws ConnectorException {

    String vmName = createName(Utils.VM_PREFIX);

    try {/* ww  w .  j  a v  a2s .  c  om*/
        //
        // Getting appropriate information for creating recompose body
        //
        String response = doGet(vAppLink);

        Document doc = RestClient.stringToXmlDocument(response);
        Element childrenElement = (Element) doc.getElementsByTagName(Constants.CHILDREN).item(0);
        Element vmElement = (Element) childrenElement.getElementsByTagName(Constants.VM).item(0);

        String vmType = vmElement.getAttribute(Constants.TYPE);
        String vmRef = vmElement.getAttribute(Constants.HREF);

        //
        // Create RecomposeVAppParams body
        //
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        doc = docBuilder.newDocument();
        Element rootElement = doc.createElement(Constants.RECOMPOSE_VAPP);
        doc.appendChild(rootElement);

        rootElement.setAttribute("name", getvAppName());
        rootElement.setAttribute("xmlns", Constants.XMLNS);
        rootElement.setAttribute("xmlns:xsi", Constants.XMLNS_XSI);
        rootElement.setAttribute("xmlns:ovf", Constants.XMLNS_OVF);

        Element sourcedItem = doc.createElement(Constants.SOURCED_ITEM);
        sourcedItem.setAttribute(Constants.SOURCE_DELETE, "false");

        Element source = doc.createElement(Constants.SOURCE);
        source.setAttribute(Constants.TYPE, vmType);
        source.setAttribute(Constants.NAME, vmName);
        source.setAttribute(Constants.HREF, vmRef);

        sourcedItem.appendChild(source);
        rootElement.appendChild(sourcedItem);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource dSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);

        transformer.transform(dSource, result);
        String xmlBody = writer.toString();

        //
        // sending a POST request
        //

        StringEntity entity = new StringEntity(xmlBody);
        entity.setContentType(Constants.RECOMPOSE_VAPP_LINK);
        String createResponse = doPost(vAppLink + Constants.RECOMPOSE_ACTION, entity);

        IMachine machine = controllerServices.createMachineInstance(vmName, vmName, computeCenter,
                machineDescriptor, image, controllerServices.getDefaultAgentPort());
        return machine;
    } catch (Exception e) {
        throw new ConnectorException(e.getMessage());
    }
}

From source file:org.alfresco.dataprep.SiteService.java

/**
 * Create Record Management site/*from w  w w.  ja v a  2 s. co m*/
 * 
 * @param userName String identifier
 * @param password String password
 * @param title String site title
 * @param description String site description
 * @param compliance RMSiteCompliance site compliance
 * @return true if site is created
 */
@SuppressWarnings("unchecked")
public boolean createRMSite(final String userName, final String password, final String title,
        final String description, final RMSiteCompliance compliance) {
    if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password) || StringUtils.isEmpty(title)) {
        throw new IllegalArgumentException("Parameter missing");
    }
    AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject();
    String reqUrl = client.getApiUrl() + "sites";
    HttpPost post = new HttpPost(reqUrl);
    JSONObject body = new JSONObject();
    body.put("visibility", "PUBLIC");
    body.put("title", title);
    body.put("shortName", "rm");
    body.put("description", description);
    body.put("sitePreset", "rm-site-dashboard");
    body.put("compliance", compliance.compliance);
    body.put("type", compliance.compliance);
    post.setEntity(client.setMessageBody(body));
    HttpClient clientWithAuth = client.getHttpClientWithBasicAuth(userName, password);
    try {
        HttpResponse response = clientWithAuth.execute(post);
        switch (response.getStatusLine().getStatusCode()) {
        case HttpStatus.SC_OK:
            String secondPostUrl = client.getAlfrescoUrl()
                    + "alfresco/service/remoteadm/createmulti?s=sitestore";
            HttpPost secondPost = new HttpPost(secondPostUrl);
            secondPost.setHeader("Content-Type", "application/xml;charset=UTF-8");
            StringEntity xmlEntity = new StringEntity(readContentRmSite(), "UTF-8");
            xmlEntity.setContentType("application/xml");
            secondPost.setEntity(xmlEntity);
            response = clientWithAuth.execute(secondPost);
            secondPost.releaseConnection();
            String url = client.getAlfrescoUrl()
                    + "alfresco/service/slingshot/doclib2/doclist/all/site/rm/documentLibrary/";
            HttpGet get = new HttpGet(url);
            response = clientWithAuth.execute(get);
            if (200 == response.getStatusLine().getStatusCode()) {
                if (logger.isTraceEnabled()) {
                    logger.info("Successfully created RM site");
                }
                return true;
            } else {
                if (logger.isTraceEnabled()) {
                    logger.error("Failed to open RM site");
                }
                return false;
            }
        case HttpStatus.SC_BAD_REQUEST:
            throw new RuntimeException("RM Site already created");
        case HttpStatus.SC_UNAUTHORIZED:
            throw new RuntimeException("Invalid credentials");
        default:
            logger.error("Unable to create RM site: " + response.toString());
            break;
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to execute the request");
    } finally {
        post.releaseConnection();
        client.close();
    }
    return false;
}

From source file:com.soundcloud.playerapi.Request.java

/**
 * Adds string content to the request (used with POST/PUT)
 * @param content the content to POST/PUT
 * @param contentType the content type//from  w ww .  j a  v  a2  s . c  o  m
 * @return this
 */
public Request withContent(String content, String contentType) {
    try {
        StringEntity stringEntity = new StringEntity(content, UTF_8);
        if (contentType != null) {
            stringEntity.setContentType(contentType);
        }
        return withEntity(stringEntity);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.appdynamics.connectors.vcd.VappClient.java

public String newvAppFromTemplate(String vAppName, String templateLink, String catalogLink, String vdcLink,
        String network) throws Exception {
    // Step 1/*from w  w  w . jav  a  2 s  .  c o m*/
    String response = doGet(templateLink);

    // Step 2 - look for NetowrkConnection element in the Vms contained
    Document doc = RestClient.stringToXmlDocument(response);
    Element childrenElement = (Element) doc.getElementsByTagName(Constants.CHILDREN).item(0);
    Element vmElement = (Element) childrenElement.getElementsByTagName(Constants.VM).item(0);
    Element netElement = (Element) vmElement.getElementsByTagName("NetworkConnectionSection").item(0);

    String ovfInfo = doc.getElementsByTagName("ovf:Info").item(0).getTextContent();
    String networkName = netElement.getElementsByTagName("NetworkConnection").item(0).getAttributes()
            .getNamedItem("network").getTextContent().trim();

    String vdcResponse = doGet(vdcLink);
    String parentNetwork;
    if (network.isEmpty()) {
        parentNetwork = findElement(vdcResponse, Constants.NETWORK, Constants.NETWORK_LINK, null);
    } else {
        parentNetwork = findElement(vdcResponse, Constants.NETWORK, Constants.NETWORK_LINK, network);
    }

    // Step 3 - create an InstantiateVAppTemplate Params element
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root elements
    doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("InstantiateVAppTemplateParams");
    doc.appendChild(rootElement);

    rootElement.setAttribute("name", vAppName);
    rootElement.setAttribute("xmlns", Constants.XMLNS);
    rootElement.setAttribute("deploy", "true");
    rootElement.setAttribute("powerOn", "false");
    rootElement.setAttribute("xmlns:xsi", Constants.XMLNS_XSI);
    rootElement.setAttribute("xmlns:ovf", Constants.XMLNS_OVF);

    Element descElement = doc.createElement("Description");
    descElement.appendChild(doc.createTextNode("Created through Appdynamics controller"));
    rootElement.appendChild(descElement);

    Element paramsElement = doc.createElement("InstantiationParams");

    Element configElement = doc.createElement("Configuration");

    Element parentNetElement = doc.createElement("ParentNetwork");
    parentNetElement.setAttribute("href", parentNetwork);
    configElement.appendChild(parentNetElement);

    Element fenceElement = doc.createElement("FenceMode");
    fenceElement.appendChild(doc.createTextNode("bridged"));
    configElement.appendChild(fenceElement);

    Element netconfigSectionElement = doc.createElement("NetworkConfigSection");

    Element ovfInfoElement = doc.createElement("ovf:Info");
    ovfInfoElement.appendChild(doc.createTextNode(ovfInfo));
    netconfigSectionElement.appendChild(ovfInfoElement);

    Element netConfElement = doc.createElement("NetworkConfig");
    netConfElement.setAttribute("networkName", networkName);
    netConfElement.appendChild(configElement);
    netconfigSectionElement.appendChild(netConfElement);

    paramsElement.appendChild(netconfigSectionElement);
    rootElement.appendChild(paramsElement);

    Element sourceElement = doc.createElement("Source");
    sourceElement.setAttribute("href", templateLink);
    rootElement.appendChild(sourceElement);

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    DOMSource source = new DOMSource(doc);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);

    transformer.transform(source, result);
    String xmlBody = writer.toString();

    // Step 4 - make a POST 

    String instantiateVAppLink = findElement(vdcResponse, Constants.LINK, Constants.INSTANTIATE_VAPP, null);

    StringEntity entity = new StringEntity(xmlBody);
    entity.setContentType(Constants.INSTANTIATE_VAPP);

    return doPost(instantiateVAppLink, entity);
}

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

private void pollForReminderUpdates(Account account, String team) {

    String baseURI = "http://" + targetDomain + ":" + targetPort + "/wsdbServiceWAR/tasks/";
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpHost targetHost = new HttpHost(targetDomain, targetPort, "http");
    Serializer s = new Persister();

    List<Reminder> rlist = new ArrayList<Reminder>();
    try {//from w ww  . ja  va  2  s  .  co  m
        // INSERT in SERVER
        rlist = rdb.getReminders(" syncflag='I' and g_id is NULL ", null);
        if (rlist != null) {
            String urlToSendRequest = baseURI + "new";
            HttpPut httpput = new HttpPut(urlToSendRequest);
            httpput.addHeader("Accept", "text/xml");
            httpput.addHeader("Content-Type", "application/xml");
            for (Reminder r : rlist) {
                if (r.getAuthor() == null)
                    continue;
                StringEntity entity = new StringEntity(r.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
                HttpResponse response = httpClient.execute(targetHost, httpput);
                if (response.getStatusLine().getStatusCode() == 201) {
                    HttpEntity en = response.getEntity();
                    if (en != null) {
                        String str = convertStreamToString(en.getContent());
                        StringTokenizer st = new StringTokenizer(str, "||");
                        if (st.hasMoreTokens()) {
                            Long g_id = Long.valueOf(st.nextToken());
                            Long g_timestamp = null;
                            if (st.hasMoreTokens())
                                g_timestamp = Long.valueOf(st.nextToken());
                            r.setG_id(g_id);
                            r.setG_timestamp(g_timestamp);
                            r.setSyncflag("");
                            rdb.updateWithRowid(r, r.getRowid().toString());
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
        Log.e(TAG, ex.toString(), ex);
    } finally {
        rdb.close();
    }
    try {
        // UPDATE SERVER
        rlist = rdb.getReminders(" syncflag='E' ", null);
        HttpPost httppost = null;
        if (rlist != null) {
            for (Reminder r : rlist) {
                String urlToSendRequest = baseURI + r.getG_id() + "/";
                httppost = new HttpPost(urlToSendRequest);
                httppost.addHeader("Accept", "application/xml");
                httppost.addHeader("Content-Type", "application/xml");
                StringEntity entity = new StringEntity(r.getXML(), "UTF-8");
                entity.setContentType("application/xml");
                httppost.setEntity(entity);
                HttpResponse response = httpClient.execute(targetHost, httppost);

                if (response.getStatusLine().getStatusCode() == 204) {
                    r.setSyncflag("");
                    rdb.updateWithG_Id(r, r.getG_id().toString());
                }
            }
        }
    } catch (Exception ex) {
        Log.e(TAG, ex.toString(), ex);
    } finally {
        rdb.close();
    }

    try {
        // DELETE IN SERVER.
        // wants to remove the reminder.
        rlist = rdb.getReminders(" syncflag='D' ", null);
        HttpDelete httpdelete = null;
        if (rlist != null) {
            for (Reminder r : rlist) {
                String urlToSendRequest = baseURI + r.getG_id() + "/";
                httpdelete = new HttpDelete(urlToSendRequest);
                httpdelete.addHeader("Accept", "text/xml");
                httpdelete.addHeader("Content-Type", "application/xml");
                HttpResponse response = httpClient.execute(targetHost, httpdelete);

                if (response.getStatusLine().getStatusCode() == 204) {
                    rdb.delete(r.getG_id().toString()); // After marking
                    // server record
                    // with 'D' remove
                    // local record
                }
            }
        }
    } catch (Exception ex) {
        Log.e(TAG, ex.toString(), ex);
    } finally {
        rdb.close();
    }

    try {
        //GET FROM SERVER
        // rlist = rdb.getReminders(" syncflag='D' ", null);
        HttpGet httpget = null;
        String urlToSendRequest = baseURI + "recent?team=" + team + "&author=" + account.user;
        httpget = new HttpGet(urlToSendRequest);
        httpget.addHeader("Accept", "text/xml");
        httpget.addHeader("Content-Type", "application/xml");
        HttpResponse response = httpClient.execute(targetHost, httpget);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity en = response.getEntity();
            if (en != null) {
                String str = convertStreamToString(en.getContent());
                gpsalarm.app.datatype.Reminders rList = s.read(gpsalarm.app.datatype.Reminders.class, str);
                List<Reminder> list = rList.getProperties();
                if (list == null)
                    return;
                for (Reminder r : list) {
                    String syncType = r.getSyncflag();
                    Reminder rlocal = rdb.getReminderByGid(r.getG_id().toString());
                    if (syncType.equals("I") && rlocal == null) {
                        r.setSyncflag("");
                        rdb.insert(r);
                    } else if (syncType.equals("E") && rlocal != null) {
                        if (rlocal.getG_timestamp() != r.getG_timestamp()) {
                            r.setSyncflag("");
                            rdb.updateWithG_Id(r, r.getG_id().toString());
                        }
                    } else if (syncType.equals("D") && rlocal != null) {
                        r.setSyncflag("");
                        rdb.delete(r.getG_id().toString()); // server
                        // instruction
                        // to remove
                        // record.
                        // remove.
                    }
                }
            }

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

From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java

@Test
public void testPut() throws Exception {

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPut httpPut = new HttpPut(
            "https://xs01ca06b6163.ap1.hana.ondemand.com/jncpf2/wsb01.xsodata/WineSmallProduction('5BCA672AA43184D2B242BE2749B54B13')");
    httpPut.addHeader("Content-Type", "application/json;charset=UTF-8");
    HttpContext httpContext = new BasicHttpContext();

    JSONObject jsonParam = new JSONObject();
    jsonParam.put("containerID", "45F72A9B1873CBAC87322769D594DAB7");
    jsonParam.put("boxID", "DFE74C483C4D9AB51CEC8AE1FBFACC9F");
    jsonParam.put("bottleEID", "448F881AECF7647331AEF66D996173BE");
    jsonParam.put("bottleIID", "3FF40C650FEA476DACB3ED3A9764929E");
    jsonParam.put("bottleVID", "EE410D11");
    jsonParam.put("status", 6);

    StringEntity entity = new StringEntity(jsonParam.toString(), "UTF-8");// ?
    entity.setContentEncoding("UTF-8");
    entity.setContentType("application/json");

    httpPut.setEntity(entity);//from   ww w.  ja va 2s  .c o  m

    HttpResponse response = httpClient.execute(httpPut, httpContext);

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();

    System.out.println(statusCode);
}

From source file:org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBuildInfoClient.java

/**
 * Push build to bintray/*from  ww w .  j  a  v a  2  s .c o  m*/
 *
 * @param buildName         name of the build to push
 * @param buildNumber       number of the build to push
 * @param signMethod        flags if this artifacts should be signed or not
 * @param passphrase        passphrase in case that the artifacts should be signed
 * @param bintrayUploadInfo request body which contains the upload info
 * @return http Response with the response outcome
 * @throws IOException On any connection error
 * @see org.jfrog.build.api.release.BintrayUploadInfoOverride;
 */
public BintrayResponse pushToBintray(String buildName, String buildNumber, String signMethod, String passphrase,
        BintrayUploadInfoOverride bintrayUploadInfo) throws IOException, URISyntaxException {
    if (StringUtils.isBlank(buildName)) {
        throw new IllegalArgumentException("Build name is required for promotion.");
    }
    if (StringUtils.isBlank(buildNumber)) {
        throw new IllegalArgumentException("Build number is required for promotion.");
    }

    String requestUrl = createRequestUrl(buildName, buildNumber, signMethod, passphrase);
    String requestBody = createJsonRequestBody(bintrayUploadInfo);
    HttpPost httpPost = new HttpPost(requestUrl);
    StringEntity entity = new StringEntity(requestBody);
    entity.setContentType("application/json");
    httpPost.setEntity(entity);
    HttpResponse response = httpClient.getHttpClient().execute(httpPost);
    return parseResponse(response);
}

From source file:org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBuildInfoClient.java

public HttpResponse stageBuild(String buildName, String buildNumber, Promotion promotion) throws IOException {
    if (StringUtils.isBlank(buildName)) {
        throw new IllegalArgumentException("Build name is required for promotion.");
    }/*from  w  ww.  jav  a 2 s  . c om*/
    if (StringUtils.isBlank(buildNumber)) {
        throw new IllegalArgumentException("Build number is required for promotion.");
    }

    StringBuilder urlBuilder = new StringBuilder(artifactoryUrl).append(BUILD_REST_URL).append("/promote/")
            .append(encodeUrl(buildName)).append("/").append(encodeUrl(buildNumber));

    String promotionJson = toJsonString(promotion);

    HttpPost httpPost = new HttpPost(urlBuilder.toString());

    StringEntity stringEntity = new StringEntity(promotionJson);
    stringEntity.setContentType("application/vnd.org.jfrog.artifactory.build.PromotionRequest+json");
    httpPost.setEntity(stringEntity);

    log.info("Promoting build " + buildName + ", #" + buildNumber);
    return httpClient.getHttpClient().execute(httpPost);
}

From source file:org.alfresco.dataprep.WorkflowService.java

/**
 * Update the status of a task//  www.  java2  s  .  com
 * 
 * @param assignedUser String user assigned to the task
 * @param password String password
 * @param workflowId String workflow Id
 * @param status TaskStatus the status
 * @return true if 201 code is returned
 */
public boolean updateTaskStatus(final String assignedUser, final String password, final String workflowId,
        final TaskStatus status) {
    AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject();
    String taskId = checkTaskId(assignedUser, password, workflowId);
    String api = client.getAlfrescoUrl() + "alfresco/api/" + version + "tasks/" + taskId + "/variables";
    HttpPost post = new HttpPost(api);
    String jsonInput = "[{" + "\"name\": \"bpm_status\",\"value\": \"" + status.getStatus()
            + "\", \"scope\": \"local\"";
    jsonInput = (jsonInput + "}]");
    StringEntity se = new StringEntity(jsonInput.toString(), AlfrescoHttpClient.UTF_8_ENCODING);
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, AlfrescoHttpClient.MIME_TYPE_JSON));
    post.setEntity(se);
    HttpResponse response = client.executeRequest(assignedUser, password, post);
    switch (response.getStatusLine().getStatusCode()) {
    case HttpStatus.SC_CREATED:
        if (logger.isTraceEnabled()) {
            logger.trace("Successfuly updated the task status");
        }
        return true;
    case HttpStatus.SC_NOT_FOUND:
        throw new RuntimeException("Invalid process id: " + workflowId);
    default:
        logger.error("Unable to change the task status " + response.toString());
        break;
    }
    return false;
}