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:com.springsource.hq.plugin.tcserver.serverconfig.web.services.SettingsLoaderImpl.java

public void saveConfigurationFile(String fileName, String config, RemoteSettings remoteSettings)
        throws SettingsLoaderException {
    try {//ww w. j  ava 2  s .  c o  m
        logger.debug(
                "Attempting to save '" + fileName + "' for '" + remoteSettings.getSettings().getEid() + "'");
        PostMethod method = new PostMethod(remoteSettings.getBasePath()
                + "/hqu/tomcatserverconfig/tomcatserverconfig/saveConfigurationFile.hqu");
        configureMethod(method, remoteSettings.getSettings().getEid(), remoteSettings.getSessionId(),
                remoteSettings.getCsrfNonce());
        Part[] parts = new Part[] { new StringPart("fileName", fileName), new StringPart("file", config) };
        method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
        httpClient.executeMethod(method);
        if (method.getStatusCode() >= 300 && method.getStatusCode() < 400) {
            logger.info("Unable to save '" + fileName + "' configuration for '"
                    + remoteSettings.getSettings().getEid() + "', HQ session expired");
            throw new SettingsLoaderException(SESSION_EXPIRED_MESSAGE);
        } else if (method.getStatusCode() >= 400) {
            logger.warn("Unable to save '" + fileName + "' configuration for '"
                    + remoteSettings.getSettings().getEid() + "', " + method.getStatusCode() + " "
                    + method.getStatusText());
            throw new SettingsLoaderException(method.getStatusText());
        }
        remoteSettings.setCsrfNonce(method.getResponseBodyAsString());
        logger.info("Saved '" + fileName + "' for '" + remoteSettings.getSettings().getEid() + "'");
    } catch (SSLHandshakeException e) {
        logger.error("Server SSL certificate is untrusted: " + e.getMessage(), e);
        throw new SettingsLoaderException(
                "Unable to save '" + fileName + "' because the server is using an untrusted SSL certificate.  "
                        + "Please check the documentation for more information.",
                e);
    } catch (IOException e) {
        logger.error("Unable to save '" + fileName + "' for '" + remoteSettings.getSettings().getEid() + "': "
                + e.getMessage(), e);
        throw new SettingsLoaderException(
                "Saving configuration file failed because of a server error, please check the logs for more details",
                e);
    }
}

From source file:edu.indiana.d2i.htrc.portal.HTRCPersistenceAPIClient.java

/**
 * Create workset//from w  ww  .  ja v a  2  s. c  o  m
 *
 * @param worksetContent , Give workset content as a String
 * @param isPublic
 */

public void createWorkset(String worksetContent, boolean isPublic) throws IOException {
    String url;

    if (isPublic) {
        url = PlayConfWrapper.registryEPR() + "/worksets" + "?public=true";
    } else {
        url = PlayConfWrapper.registryEPR() + "/worksets";
    }
    PostMethod post = new PostMethod(url);
    post.addRequestHeader("Authorization", "Bearer " + accessToken);
    post.setRequestEntity(new StringRequestEntity(worksetContent, "application/vnd.htrc-workset+xml", "UTF-8"));

    int response = client.executeMethod(post);
    if (response == 201) {
        // nothing
    } else {
        this.responseCode = response;
        throw new IOException(
                "Response code " + response + " for " + url + " message: \n " + post.getResponseBodyAsString());
    }
}

From source file:com.globalsight.everest.webapp.applet.admin.customer.FileSystemApplet.java

/**
 * Zip the selected files and send the zip to the server.
 * @param p_filesToBeZipped - A list of selected files to be uploaded.
 * @param p_targetURL - The target URL representing server URL.
 * @param p_targetLocation - A string representing the link to the next page.
 *///from  w ww .  ja  v  a 2  s .  c  o m
public void sendZipFile(File[] p_filesToBeZipped, String p_targetURL, final String p_targetLocation)
        throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.append("GS_");
    sb.append(System.currentTimeMillis());
    sb.append(".zip");

    File targetFile = getFile(sb.toString());
    ZipIt.addEntriesToZipFile(targetFile, p_filesToBeZipped);
    m_progressBar.setValue(30);

    PostMethod filePost = new PostMethod(p_targetURL + "&doPost=true");
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    filePost.setDoAuthentication(true);
    try {
        Part[] parts = { new FilePart(targetFile.getName(), targetFile) };

        m_progressBar.setValue(40);
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        HttpClient client = new HttpClient();
        setUpClientForProxy(client);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        m_progressBar.setValue(50);
        int status = client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            //no need to ask for auth again since the first upload was fine
            s_authPrompter.setAskForAuthentication(false);

            m_progressBar.setValue(60);
            InputStream is = filePost.getResponseBodyAsStream();
            m_progressBar.setValue(70);
            ObjectInputStream inputStreamFromServlet = new ObjectInputStream(is);
            Vector incomingData = (Vector) inputStreamFromServlet.readObject();

            inputStreamFromServlet.close();
            if (incomingData != null) {
                if (incomingData.elementAt(0) instanceof ExceptionMessage) {
                    resetProgressBar();
                    AppletHelper.displayErrorPage((ExceptionMessage) incomingData.elementAt(0), this);
                }
            } else {
                boolean deleted = targetFile.delete();
                m_progressBar.setValue(100);
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
                // now move to some other page...
                goToTargetPage(p_targetLocation);
            }
        } else {
            //authentication may have failed, reset the need to ask
            s_authPrompter.setAskForAuthentication(true);
            resetProgressBar();
            String errorMessage = "Upload failed because: (" + status + ") " + HttpStatus.getStatusText(status);
            if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                errorMessage = "Incorrect NTDomain\\username or password entered. Hit 'upload' again to re-try.";
            }
            AppletHelper.getErrorDlg(errorMessage, null);
        }
    } catch (Exception ex) {
        //authentication may have failed, reset the need to ask
        s_authPrompter.setAskForAuthentication(true);

        resetProgressBar();
        System.err.println(ex);
        AppletHelper.getErrorDlg(ex.getMessage(), null);
    } finally {
        filePost.releaseConnection();
    }

}

From source file:com.mercatis.lighthouse3.commons.commons.HttpRequest.java

/**
 * This method performs a file upload via multipart POST request.
 *
 * @param url            the URL against which the file upload is performed
 * @param file           the file to upload
 * @param postParameters any additional parameters to add to the POST request
 * @return the data returned by the web server
 * @throws HttpException in case a communication error occurred.
 *//*from   w w w .ja v a  2  s . c o  m*/
public String postFileUpload(String url, File file, Map<String, String> postParameters) {

    PostMethod filePost = null;

    try {
        filePost = new PostMethod(url);
        Part[] mimeParts = new Part[postParameters.size() + 1];
        mimeParts[0] = new FilePart(file.getName(), file);
        int p = 1;
        for (String parameterName : postParameters.keySet()) {
            mimeParts[p] = new StringPart(parameterName, postParameters.get(parameterName));
            p++;
        }

        filePost.setRequestEntity(new MultipartRequestEntity(mimeParts, filePost.getParams()));
    } catch (Exception anyProblem) {
        throw new HttpException("A problem occurred while constructing file upload request", anyProblem);
    }

    int resultCode = 0;
    String resultBody = null;

    try {
        resultCode = this.httpClient.executeMethod(filePost);
        resultBody = filePost.getResponseBodyAsString();

        if (resultCode != 200) {
            throw new HttpException(resultBody, null);
        }
    } catch (HttpException httpException) {
        throw new HttpException("HTTP file upload failed", httpException);
    } catch (IOException ioException) {
        throw new HttpException("HTTP file upload failed", ioException);
    } finally {
        filePost.releaseConnection();
    }

    return resultBody;
}

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

@Override
public void notifyScoreUpdate(ScoreRecord record) throws LpRestException {
    String contentType = "application/xml";
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/cw/bridge/scores", DefaultRestResource.REST_URI);
    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, contentType);

    try {/* w ww.  j  a  va2 s . co m*/
        JAXBContext jc = JAXBContext.newInstance(ScoreRecord.class);
        Writer marshalledRecord = new StringWriter();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(record, marshalledRecord);

        postMethod.setRequestEntity(new StringRequestEntity(marshalledRecord.toString(), contentType, "UTF-8"));

        httpClient.executeMethod(postMethod);
    } catch (JAXBException e1) {
        e1.printStackTrace();
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java

@Override
public CreateUserResponse createUser(CreateUserRequest request) {
    PostMethod method = new PostMethod(baseUrl + CREATE_USER);
    try {/*from   w  w  w  . ja  va 2  s.c o  m*/
        String data = serialize(request);
        method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, CreateUserResponse.class);

        } else {
            throw new RuntimeException("Failed to create user, RESPONSE CODE: " + statusCode);
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.avego.cloudinary.Cloudinary.java

private String postJsonToCloudinary(PostMethod post, StringBuilder payload) throws CloudinaryException {

    HttpClient client = new HttpClient();

    StringRequestEntity body;//from   ww w . j  a va 2 s  . c om
    try {
        body = new StringRequestEntity(payload.toString(), "application/json", "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new CloudinaryException("JSON is not supported by Implementation of String Request Entity.", e);
    }
    post.setRequestEntity(body);

    int status;
    try {
        status = client.executeMethod(post);
    } catch (IOException e) {
        throw new CloudinaryException("A HTTP Exception Occurred while attempting to POST JSON to CLoudinary.",
                e);
    }

    String response = null;
    try {
        response = post.getResponseBodyAsString();
    } catch (IOException e) {
        throw new CloudinaryException("Failed to Retrieve response from POST Method.", e);
    }

    if (status != 200) {

        throw new CloudinaryException("Cloudinary Operation was Unsuccessful.  Response was: " + response);
    }

    LOGGER.info("POST was successfully sent to Cloudinary, response was: " + response);
    return response;
}

From source file:com.cloud.network.nicira.NiciraNvpApi.java

private <T> T executeCreateObject(T newObject, Type returnObjectType, String uri,
        Map<String, String> parameters) throws NiciraNvpApiException {
    String url;/*from   w  w  w . jav  a 2 s  .c  o m*/
    try {
        url = new URL(_protocol, _host, uri).toString();
    } catch (MalformedURLException e) {
        s_logger.error("Unable to build Nicira API URL", e);
        throw new NiciraNvpApiException("Unable to build Nicira API URL", e);
    }

    Gson gson = new Gson();

    PostMethod pm = new PostMethod(url);
    pm.setRequestHeader("Content-Type", "application/json");
    try {
        pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), "application/json", null));
    } catch (UnsupportedEncodingException e) {
        throw new NiciraNvpApiException("Failed to encode json request body", e);
    }

    executeMethod(pm);

    if (pm.getStatusCode() != HttpStatus.SC_CREATED) {
        String errorMessage = responseToErrorMessage(pm);
        pm.releaseConnection();
        s_logger.error("Failed to create object : " + errorMessage);
        throw new NiciraNvpApiException("Failed to create object : " + errorMessage);
    }

    T result;
    try {
        result = (T) gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType());
    } catch (IOException e) {
        throw new NiciraNvpApiException("Failed to decode json response body", e);
    } finally {
        pm.releaseConnection();
    }

    return result;
}

From source file:ch.gadp.alfresco.OAuthSSOAuthenticationFilter.java

/**
 * Gets an Alfresco authentication ticket to handle user creation and update
 * @return The new ticket// w  ww. ja v  a 2 s .  com
 * @throws IOException
 */
protected String getAdminAlfrescoTicket() throws IOException {
    logger.warn("getAdminAlfrescoTicket");
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(getAPIUri(REPOSITORY_API_LOGIN));

    String input = "{ " + "\"username\" : \"" + getConfigurationValue(REPOSITORY_ADMIN_USER) + "\", "
            + "\"password\" : \"" + getConfigurationValue(REPOSITORY_ADMIN_PASSWORD) + "\" " + "}";
    method.setRequestEntity(new StringRequestEntity(input, "application/json", "utf-8"));
    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
        return null;
    }

    Gson ticketJSON = new Gson();
    TicketInfo ticket = ticketJSON.fromJson(method.getResponseBodyAsString(), TicketInfo.class);
    return ticket.data.ticket;
}

From source file:be.fedict.eid.applet.service.signer.time.TSPTimeStampService.java

public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
    // digest the message
    MessageDigest messageDigest = MessageDigest.getInstance(this.digestAlgo);
    byte[] digest = messageDigest.digest(data);

    // generate the TSP request
    BigInteger nonce = new BigInteger(128, new SecureRandom());
    TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();
    requestGenerator.setCertReq(true);/*  w ww . j  av  a 2 s . c o  m*/
    if (null != this.requestPolicy) {
        requestGenerator.setReqPolicy(this.requestPolicy);
    }
    TimeStampRequest request = requestGenerator.generate(this.digestAlgoOid, digest, nonce);
    byte[] encodedRequest = request.getEncoded();

    // create the HTTP client
    HttpClient httpClient = new HttpClient();
    if (null != this.username) {
        Credentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    if (null != this.proxyHost) {
        httpClient.getHostConfiguration().setProxy(this.proxyHost, this.proxyPort);
    }

    // create the HTTP POST request
    PostMethod postMethod = new PostMethod(this.tspServiceUrl);
    RequestEntity requestEntity = new ByteArrayRequestEntity(encodedRequest, "application/timestamp-query");
    postMethod.addRequestHeader("User-Agent", this.userAgent);
    postMethod.setRequestEntity(requestEntity);

    // invoke TSP service
    int statusCode = httpClient.executeMethod(postMethod);
    if (HttpStatus.SC_OK != statusCode) {
        LOG.error("Error contacting TSP server " + this.tspServiceUrl);
        throw new Exception("Error contacting TSP server " + this.tspServiceUrl);
    }

    // HTTP input validation
    Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type");
    if (null == responseContentTypeHeader) {
        throw new RuntimeException("missing Content-Type header");
    }
    String contentType = responseContentTypeHeader.getValue();
    if (!contentType.startsWith("application/timestamp-reply")) {
        LOG.debug("response content: " + postMethod.getResponseBodyAsString());
        throw new RuntimeException("invalid Content-Type: " + contentType);
    }
    if (0 == postMethod.getResponseContentLength()) {
        throw new RuntimeException("Content-Length is zero");
    }

    // TSP response parsing and validation
    InputStream inputStream = postMethod.getResponseBodyAsStream();
    TimeStampResponse timeStampResponse = new TimeStampResponse(inputStream);
    timeStampResponse.validate(request);

    if (0 != timeStampResponse.getStatus()) {
        LOG.debug("status: " + timeStampResponse.getStatus());
        LOG.debug("status string: " + timeStampResponse.getStatusString());
        PKIFailureInfo failInfo = timeStampResponse.getFailInfo();
        if (null != failInfo) {
            LOG.debug("fail info int value: " + failInfo.intValue());
            if (PKIFailureInfo.unacceptedPolicy == failInfo.intValue()) {
                LOG.debug("unaccepted policy");
            }
        }
        throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus());
    }
    TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
    SignerId signerId = timeStampToken.getSID();
    BigInteger signerCertSerialNumber = signerId.getSerialNumber();
    X500Principal signerCertIssuer = new X500Principal(signerId.getIssuer().getEncoded());
    LOG.debug("signer cert serial number: " + signerCertSerialNumber);
    LOG.debug("signer cert issuer: " + signerCertIssuer);

    // TSP signer certificates retrieval
    CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection",
            BouncyCastleProvider.PROVIDER_NAME);
    Collection<? extends Certificate> certificates = certStore.getCertificates(null);
    X509Certificate signerCert = null;
    Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>();
    for (Certificate certificate : certificates) {
        X509Certificate x509Certificate = (X509Certificate) certificate;
        if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal())
                && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) {
            signerCert = x509Certificate;
        }
        String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate));
        certificateMap.put(ski, x509Certificate);
        LOG.debug("embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski);
    }

    // TSP signer cert path building
    if (null == signerCert) {
        throw new RuntimeException("TSP response token has no signer certificate");
    }
    List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>();

    X509Certificate tsaIssuer = loadCertificate(
            "be/fedict/eid/applet/service/CA POLITICA SELLADO DE TIEMPO - COSTA RICA.crt");
    X509Certificate rootCA = loadCertificate("be/fedict/eid/applet/service/CA RAIZ NACIONAL COSTA RICA.cer");
    LOG.debug("adding to certificate chain: " + signerCert.getSubjectX500Principal());
    tspCertificateChain.add(signerCert);
    LOG.debug("adding to certificate chain: " + tsaIssuer.getSubjectX500Principal());
    tspCertificateChain.add(tsaIssuer);
    LOG.debug("adding to certificate chain: " + rootCA.getSubjectX500Principal());
    tspCertificateChain.add(rootCA);

    // verify TSP signer signature
    timeStampToken.validate(tspCertificateChain.get(0), BouncyCastleProvider.PROVIDER_NAME);

    // verify TSP signer certificate
    this.validator.validate(tspCertificateChain, revocationData);

    LOG.debug("time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());

    byte[] timestamp = timeStampToken.getEncoded();
    return timestamp;
}