Example usage for org.apache.commons.httpclient.methods PostMethod setRequestEntity

List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PostMethod setRequestEntity.

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:ca.uvic.cs.tagsea.statistics.svn.jobs.SVNCommentScanningJob.java

/**
 * @param files/*w w w .j ava2 s  .c  o m*/
 */
private IStatus sendFile(File file) {
    String uploadScript = "http://stgild.cs.uvic.ca/cgi-bin/tagSEAUpload.cgi";
    int id = TagSEAPlugin.getDefault().getUserID();
    if (id < 0) {
        id = askForID();
        if (id == 0) {
            //just do nothing.
            return Status.OK_STATUS;
        }
    }
    HttpClient client = new HttpClient();
    IStatus s = Status.OK_STATUS;
    String message = "";

    try {
        PostMethod post = new PostMethod(uploadScript);
        Part[] parts = { new StringPart("KIND", "subversion"),
                new FilePart("MYLAR" + id, file.getName(), file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        int status = client.executeMethod(post);
        String resp = getData(post.getResponseBodyAsStream());
        if (status != 200) {
            message += resp + ";";
            s = new Status(IStatus.ERROR, SVNStatistics.PLUGIN_ID, status, message, null);
        }
    } catch (IOException e) {
        message += file.getAbsolutePath() + " could not be sent;";
        s = new Status(IStatus.ERROR, SVNStatistics.PLUGIN_ID, 0, message, e);
    }

    return s;
}

From source file:com.vmware.aurora.vc.vcservice.VcService.java

/**
 * This sends a URL POST request to the Extension vService guest API to
 * register a new extension. Upon success, set vcExtensionRegistered to true.
 * Note that the extension will not be fully configured until we log in to VC
 * as this extension and make some VMODL calls to finish the job.
 *
 * Note also that we only need to do this once per CMS install, not once per
 * CMS startup, but it doesn't seem to hurt to do it every time.
 *
 * @synchronized for preventing concurrent call to register EVS.
 *//*from   w w w .  j  ava 2 s. co  m*/
private static synchronized void registerExtensionVService() {
    if (vcExtensionRegistered) {
        return;
    }
    logger.debug("Register extension vService at: " + evsURL + " token=" + evsToken);
    Writer output = null;
    BufferedReader input = null;
    try {
        /**
         *  Initialize our own trust manager
         */
        ThumbprintTrustManager thumbprintTrustManager = new ThumbprintTrustManager();
        thumbprintTrustManager.add(vcThumbprint);

        TrustManager[] trustManagers = new TrustManager[] { thumbprintTrustManager };

        HttpClient httpClient = new HttpClient();

        TlsSocketFactory tlsSocketFactory = new TlsSocketFactory(trustManagers);

        Protocol.registerProtocol("https",
                new Protocol("https", (ProtocolSocketFactory) tlsSocketFactory, 443));

        PostMethod method = new PostMethod(evsURL);
        method.setRequestHeader("evs-token", evsToken);

        Certificate cert = CmsKeyStore.getCertificate(CmsKeyStore.VC_EXT_KEY);
        String evsSchema = "http://www.vmware.com/schema/vservice/ExtensionVService";
        String payload = "<RegisterExtension xmlns=\"" + evsSchema + "\">\n" + "  <Key>" + extKey + "</Key>\n"
                + "  <Certificate>\n" + CertificateToPem(cert) + "\n" + "  </Certificate>\n"
                + "</RegisterExtension>\n";

        RequestEntity requestEntity = new StringRequestEntity(payload, "text/plain", "UTF-8");
        method.setRequestEntity(requestEntity);
        int statusCode = httpClient.executeMethod(method);

        logger.info("status code: " + statusCode);
        for (Header e : method.getResponseHeaders()) {
            logger.debug("Response Header: " + e.getName() + " :" + e.getValue());
        }

        input = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        for (String str = input.readLine(); str != null; str = input.readLine()) {
            logger.debug("Response: " + str);
        }

        if (statusCode == 200) {
            vcExtensionRegistered = true;
            logger.info("Extension registration request sent successfully");
        } else {
            logger.error("Extension registration request sent error");
        }
    } catch (Exception e) {
        logger.error("Failed Extension registration to " + evsURL, e);
    } finally {
        Configuration.setBoolean(SERENGETI_EXTENSION_REGISTERED, true);
        Configuration.save();
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                logger.error("Failed to close output Writer", e);
            }
        }
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                logger.error("Failed to close input Reader", e);
            }
        }
    }
}

From source file:fr.opensagres.xdocreport.remoting.converter.server.ConverterServiceTestCase.java

@Test
public void convertPDF() throws Exception {

    PostMethod post = new PostMethod("http://localhost:" + PORT + "/convert");

    String ct = "multipart/mixed";
    post.setRequestHeader("Content-Type", ct);
    Part[] parts = new Part[4];
    String fileName = "ODTCV.odt";

    parts[0] = new FilePart("document", new File(root, fileName), "application/vnd.oasis.opendocument.text",
            "UTF-8");
    parts[1] = new StringPart("outputFormat", ConverterTypeTo.PDF.name());
    parts[2] = new StringPart("via", ConverterTypeVia.ODFDOM.name());
    parts[3] = new StringPart("download", "true");
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

    HttpClient httpclient = new HttpClient();

    try {//from  www  .  j a  v a 2 s.c o m
        int result = httpclient.executeMethod(post);
        Assert.assertEquals(200, result);
        Assert.assertEquals("attachment; filename=\"ODTCV_odt.pdf\"",
                post.getResponseHeader("Content-Disposition").getValue());

        byte[] convertedDocument = post.getResponseBody();
        Assert.assertNotNull(convertedDocument);

        File outFile = new File("target/ODTCV_odt.pdf");
        outFile.getParentFile().mkdirs();
        IOUtils.copy(new ByteArrayInputStream(convertedDocument), new FileOutputStream(outFile));

    } finally {

        post.releaseConnection();
    }
}

From source file:jeeves.utils.XmlRequest.java

private HttpMethodBase setupHttpMethod() throws UnsupportedEncodingException {
    HttpMethodBase httpMethod;//from   w w w .  j  a  va  2 s .  co  m

    if (method == Method.GET) {
        httpMethod = new GetMethod();

        if (query != null && !query.equals(""))
            httpMethod.setQueryString(query);

        else if (alSimpleParams.size() != 0)
            httpMethod.setQueryString(alSimpleParams.toArray(new NameValuePair[alSimpleParams.size()]));

        httpMethod.addRequestHeader("Accept", !useSOAP ? "application/xml" : "application/soap+xml");
        httpMethod.setFollowRedirects(true);
    } else {
        PostMethod post = new PostMethod();

        if (!useSOAP) {
            postData = (postParams == null) ? "" : Xml.getString(new Document(postParams));
            post.setRequestEntity(new StringRequestEntity(postData, "application/xml", "UTF8"));
        } else {
            postData = Xml.getString(new Document(soapEmbed(postParams)));
            post.setRequestEntity(new StringRequestEntity(postData, "application/soap+xml", "UTF8"));
        }

        httpMethod = post;
    }

    httpMethod.setPath(address);
    httpMethod.setDoAuthentication(useAuthent());

    return httpMethod;
}

From source file:de.mpg.escidoc.http.UserGroup.java

@SuppressWarnings("deprecation")
public Boolean activateUserGroup() {
    String userGroupID = Util.input("Enter UserGroupID which you want to activate:");
    // String userGroupID = "escidoc:27004";
    Document userGroupXML = this.getUserGroupXML(userGroupID);
    if (userGroupXML == null) {
        return false;
    }//from   w w  w .  j  a v a 2  s .c o m
    Element rootElement = userGroupXML.getRootElement();
    String lastModificationDate = rootElement.getAttributeValue("last-modification-date");
    if (this.USER_HANDLE != null) {
        PostMethod post = new PostMethod(this.FRAMEWORK_URL + "/aa/user-group/" + userGroupID + "/activate");
        post.setRequestHeader("Cookie", "escidocCookie=" + this.USER_HANDLE);
        try {
            System.out.println("Request body sent to Server: ");
            post.setRequestEntity(new StringRequestEntity(
                    Util.getParamXml(Util.OPTION_REMOVE_SELECTOR, lastModificationDate, "")));
            this.client.executeMethod(post);
            if (post.getStatusCode() != 200) {
                System.out.println("Server StatusCode: " + post.getStatusCode());
                return false;
            }
            System.out.println("Usergroup " + userGroupID + " activated");
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        System.out.println("Error in activateUserGroup: No userHandle available");
    }
    this.getUserGroupXML(userGroupID);
    return true;
}

From source file:de.mpg.escidoc.http.UserGroup.java

@SuppressWarnings("deprecation")
public Boolean deactivateUserGroup() {
    String userGroupID = Util.input("Enter UserGroupID which you want to deactivate:");
    // String userGroupID = "escidoc:27004";
    Document userGroupXML = this.getUserGroupXML(userGroupID);
    if (userGroupXML == null) {
        return false;
    }/* w w w.j  av  a 2  s .  c om*/
    Element rootElement = userGroupXML.getRootElement();
    String lastModificationDate = rootElement.getAttributeValue("last-modification-date");
    if (this.USER_HANDLE != null) {
        PostMethod post = new PostMethod(this.FRAMEWORK_URL + "/aa/user-group/" + userGroupID + "/deactivate");
        post.setRequestHeader("Cookie", "escidocCookie=" + this.USER_HANDLE);
        try {
            System.out.println("Request body sent to Server: ");
            post.setRequestEntity(new StringRequestEntity(
                    Util.getParamXml(Util.OPTION_REMOVE_SELECTOR, lastModificationDate, "")));
            this.client.executeMethod(post);
            if (post.getStatusCode() != 200) {
                System.out.println("Server StatusCode: " + post.getStatusCode());
                return false;
            }
            System.out.println("Usergroup " + userGroupID + " deactivated");
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        System.out.println("Error in deactivateUserGroup: No userHandle available");
    }
    this.getUserGroupXML(userGroupID);
    return true;
}

From source file:edu.harvard.iq.dvn.core.web.dvnremote.ICPSRauth.java

public String obtainAuthCookie(String username, String password, String fileDownloadUrl) {

    PostMethod loginPostMethod = null;

    if (username == null || password == null) {
        return null;
    }//from w  ww.ja  va 2s .co  m

    int status = 0;
    String icpsrAuthCookie = null;

    try {
        dbgLog.fine("entering ICPSR auth;");

        HttpClient httpclient = getClient();

        loginPostMethod = new PostMethod(icpsrLoginUrl);

        Part[] parts = { new StringPart("email", username), new StringPart("password", password),
                new StringPart("path", "ICPSR"), new StringPart("request_uri", fileDownloadUrl) };

        loginPostMethod.setRequestEntity(new MultipartRequestEntity(parts, loginPostMethod.getParams()));

        status = httpclient.executeMethod(loginPostMethod);

        dbgLog.fine("executed POST method; status=" + status);

        if (status != 200) {
            loginPostMethod.releaseConnection();
            return null;
        }

        String regexpTicketCookie = "(Ticket=[^;]*)";
        Pattern patternTicketCookie = Pattern.compile(regexpTicketCookie);

        for (int i = 0; i < loginPostMethod.getResponseHeaders().length; i++) {
            String headerName = loginPostMethod.getResponseHeaders()[i].getName();
            if (headerName.equalsIgnoreCase("set-cookie")) {
                String cookieHeader = loginPostMethod.getResponseHeaders()[i].getValue();
                Matcher cookieMatcher = patternTicketCookie.matcher(cookieHeader);
                if (cookieMatcher.find()) {
                    icpsrAuthCookie = cookieMatcher.group(1);
                    dbgLog.fine("detected ICPSR ticket cookie: " + cookieHeader);
                }
            }
        }

        loginPostMethod.releaseConnection();
        return icpsrAuthCookie;

    } catch (IOException ex) {
        dbgLog.info("ICPSR auth: caught IO exception.");
        ex.printStackTrace();

        if (loginPostMethod != null) {
            loginPostMethod.releaseConnection();
        }
        return null;
    }
}

From source file:eu.learnpad.core.impl.ca.XwikiBridgeInterfaceRestResource.java

@Override
public String putValidateCollaborativeContent(CollaborativeContentAnalysis contentFile) throws LpRestException {
    HttpClient httpClient = this.getAnonymousClient();
    String uri = String.format("%s/learnpad/ca/bridge/validatecollaborativecontent", this.restPrefix);
    PostMethod postMethod = new PostMethod(uri);

    postMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML);
    try {/*from ww  w .j  av a  2s.com*/
        StringWriter contentWriter = new StringWriter();
        JAXBContext context = JAXBContext.newInstance(CollaborativeContentAnalysis.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.marshal(contentFile, contentWriter);

        RequestEntity entity = new StringRequestEntity(contentWriter.toString(), MediaType.APPLICATION_XML,
                null);
        postMethod.setRequestEntity(entity);
    } catch (JAXBException | UnsupportedEncodingException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }

    try {
        httpClient.executeMethod(postMethod);
        return postMethod.getResponseBodyAsString();
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
}

From source file:com.google.appsforyourdomain.provisioning.ProvisioningClient.java

/**
 * Obtains an authorization token for the specified domain
 * administrator.  The adminEmail and adminPassword
 * parameteters are always required.  captchaToken and
 * captchaResponse should be the empty string unless
 * a CAPTCHA response is required.//from   w w  w.j  a va  2  s .  c  o  m
 * 
 * @param adminEmail Admin email address
 * @param adminPassword Admin password
 * @param captchaToken CAPTCHA token
 * @param captchaResponse CAPTCHA response
 * @return Authentication token
 * @throws AppsForYourDomainException
 */
public String getAuthenticationToken(String adminEmail, String adminPassword, String captchaToken,
        String captchaResponse) throws AppsForYourDomainException {
    try {
        String authToken = "";
        // Construct content
        String postContent = generateAuthenticationRequest(adminEmail, adminPassword, captchaToken,
                captchaResponse);
        // Send content
        String url = CLIENT_LOGIN_URL;
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        StringRequestEntity sre = new StringRequestEntity(postContent);
        method.setRequestEntity(sre);

        int statusCode = client.executeMethod(method);
        if (statusCode != 200) {
            throw new AuthenticationException(statusCode + ": " + method.getResponseBodyAsString());
        } else {
            String response = method.getResponseBodyAsString();
            if (response.startsWith("SID=")) {
                authToken = response.substring(4, response.indexOf('\n'));
            }
        }
        return authToken;
    } catch (IOException e) {
        // error in URL Connection
        throw new ConnectionException(e.getMessage());
    }
}

From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public void addCurrency(Currency currency) {
    String uri = baseUrl + CURRENCIES;
    PostMethod method = createPostMethod(uri);

    try {// w w w  .ja va2 s  . c  om
        String data = serialize(currency);
        method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING));

        // Execute the method.
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return;
        }
        assertResponseCodeOK(method, statusCode);
    } catch (Exception e) {
        throw new RuntimeException("Failed adding currency via url " + uri, e);
    } finally {
        method.releaseConnection();
    }
}