Example usage for org.apache.commons.httpclient.methods FileRequestEntity FileRequestEntity

List of usage examples for org.apache.commons.httpclient.methods FileRequestEntity FileRequestEntity

Introduction

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

Prototype

public FileRequestEntity(final File file, final String contentType) 

Source Link

Usage

From source file:com.hw13c.HttpClientPost.java

private void postFile(File file, PostMethod method) throws IOException {
    method.setRequestEntity(new FileRequestEntity(file, null));
    doRequest(file, method);/*from  w w w.  j  av a 2  s  . c om*/
}

From source file:com.example.CrmTest.java

/**
 * HTTP POST http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
 * the add_customer.json file to add a new customer to the system.
 * <p/>/*www .ja  va  2 s.co m*/
 * On the server side, it matches the CustomerService's addCustomer() method
 *
 * @throws Exception
 */
@Test
public void postCustomerTestJson() throws IOException {
    LOG.info("Sent HTTP POST request to add customer");
    String inputFile = this.getClass().getResource("/add_customer.json").getFile();
    File input = new File(inputFile);
    PostMethod post = new PostMethod(CUSTOMER_SERVICE_URL);
    post.addRequestHeader("Accept", "application/json");
    RequestEntity entity = new FileRequestEntity(input, "application/json; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    String res = "";

    try {
        int result = httpclient.executeMethod(post);
        LOG.info("Response status code: " + result);
        LOG.info("Response body: ");
        res = post.getResponseBodyAsString();
        LOG.info(res);
    } catch (IOException e) {
        LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL);
        LOG.error(
                "You should build the 'cxf-cdi' quick start and deploy it to a local Fabric8 before running this test");
        LOG.error("Please read the README.md file in 'cxf-cdi' quick start root");
        Assert.fail("Connection error");
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
    Assert.assertTrue(res.contains("Jack"));

}

From source file:example.crm.CrmIT.java

/**
 * HTTP POST http://localhost:9003/customers is used to upload the contents of
 * the add_customer.json file to add a new customer to the system.
 * <p/>//  w ww . java  2  s.com
 * On the server side, it matches the CustomerService's addCustomer() method
 *
 * @throws Exception
 */
@Test
public void postCustomerTestJson() throws IOException {
    LOG.info("Sent HTTP POST request to add customer");
    String inputFile = this.getClass().getResource("/add_customer.json").getFile();
    File input = new File(inputFile);
    PostMethod post = new PostMethod(CUSTOMER_SERVICE_URL);
    post.addRequestHeader("Accept", "application/json");
    RequestEntity entity = new FileRequestEntity(input, "application/json; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    String res = "";

    try {
        int result = httpclient.executeMethod(post);
        LOG.info("Response status code: " + result);
        LOG.info("Response body: ");
        res = post.getResponseBodyAsString();
        LOG.info(res);
    } catch (IOException e) {
        LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL);
        LOG.error(
                "You should build the 'camel-netty4-http' quick start and deploy it to a local Fabric8 before running this test");
        LOG.error("Please read the README.md file in 'camel-netty4-http' quick start root");
        Assert.fail("Connection error");
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
    Assert.assertTrue(res.contains("Jack"));

}

From source file:au.org.ala.spatial.util.UploadSpatialResource.java

public static String assignSld(String url, String extra, String username, String password, String data) {
    System.out.println("assignSld url:" + url);
    System.out.println("data:" + data);

    String output = "";

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(10000);//from  ww w .jav a 2 s . co  m
    client.setTimeout(60000);

    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    PutMethod put = new PutMethod(url);
    put.setDoAuthentication(true);

    // Execute the request
    try {
        // Request content will be retrieved directly
        // from the input stream
        File file = File.createTempFile("sld", "xml");
        System.out.println("file:" + file.getPath());
        FileWriter fw = new FileWriter(file);
        fw.append(data);
        fw.close();
        RequestEntity entity = new FileRequestEntity(file, "text/xml");
        put.setRequestEntity(entity);

        int result = client.executeMethod(put);

        output = result + ": " + put.getResponseBodyAsString();

    } catch (Exception e) {
        output = "0: " + e.getMessage();
        e.printStackTrace(System.out);
    } finally {
        // Release current connection to the connection pool once you are done
        put.releaseConnection();
    }

    return output;
}

From source file:io.fabric8.quickstarts.restdsl.spark.CrmIT.java

/**
 * HTTP POST http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
 * the add_customer.json file to add a new customer to the system.
 * <p/>/*from  ww w .j  a  v a 2s.  c o m*/
 * On the server side, it matches the CustomerService's addCustomer() method
 *
 * @throws Exception
 */
@Test
@Ignore
public void postCustomerTestJson() throws IOException {
    LOG.info("Sent HTTP POST request to add customer");
    String inputFile = this.getClass().getResource("/add_customer.json").getFile();
    File input = new File(inputFile);
    PostMethod post = new PostMethod(CUSTOMER_SERVICE_URL);
    post.addRequestHeader("Accept", "application/json");
    RequestEntity entity = new FileRequestEntity(input, "application/json; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    String res = "";

    try {
        int result = httpclient.executeMethod(post);
        LOG.info("Response status code: " + result);
        LOG.info("Response body: ");
        res = post.getResponseBodyAsString();
        LOG.info(res);
    } catch (IOException e) {
        LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL);
        LOG.error(
                "You should build the 'rest' quick start and deploy it to a local Fabric8 before running this test");
        LOG.error("Please read the README.md file in 'rest' quick start root");
        Assert.fail("Connection error");
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
    Assert.assertTrue(res.contains("Jack"));

}

From source file:io.fabric8.quickstarts.fabric.rest.secure.CrmSecureTest.java

/**
 * HTTP POST http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
 * the add_customer.xml file to add a new customer to the system.
 * <p/>/*from   w w w.  j ava 2  s  . co m*/
 * On the server side, it matches the CustomerService's addCustomer() method
 *
 * @throws Exception
 */
@Test
public void postCustomerTest() throws IOException {
    LOG.info("============================================");
    LOG.info("Sent HTTP POST request to add customer");
    String inputFile = this.getClass().getResource("/add_customer.xml").getFile();
    File input = new File(inputFile);
    PostMethod post = new PostMethod(CUSTOMER_SERVICE_URL);
    post.getHostAuthState().setAuthScheme(scheme);
    post.addRequestHeader("Accept", "text/xml");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);

    String res = "";

    try {
        int result = httpClient.executeMethod(post);
        LOG.info("Response status code: " + result);
        LOG.info("Response body: ");
        res = post.getResponseBodyAsString();
        LOG.info(res);
    } catch (IOException e) {
        LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL);
        LOG.error(
                "You should build the 'rest' quick start and deploy it to a local Fabric8 before running this test");
        LOG.error("Please read the README.md file in 'rest' quick start root");
        Assert.fail("Connection error");
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
    Assert.assertTrue(res.contains("Jack"));

}

From source file:it.geosolutions.geonetwork.util.HTTPUtils.java

/**
 * PUTs a File to the given URL.//from  w  ww.j  av a 2  s  . co  m
 *
 * @param url       The URL where to connect to.
 * @param file      The File to be sent.
 * @param contentType The content-type to advert in the PUT.
 * @return          The HTTP response as a String if the HTTP response code was 200 (OK).
 * @throws MalformedURLException
 * @return the HTTP response or <TT>null</TT> on errors.
 */
public String put(String url, File file, String contentType) {
    return put(url, new FileRequestEntity(file, contentType));
}

From source file:cdr.forms.SwordDepositHandler.java

public DepositResult deposit(Deposit deposit) {

    // Prepare the submission package

    Submission submission = Submission.create(deposit, this);

    File zipFile = makeZipFile(submission.getMetsDocumentRoot(), submission.getFiles());

    // Obtain the path for the collection in which we'll attempt to make the deposit

    Form form = deposit.getForm();/*from  www .j  ava 2 s . c o m*/

    String containerId = form.getDepositContainerId();

    if (containerId == null || "".equals(containerId.trim()))
        containerId = this.getDefaultContainer();

    String depositPath = getServiceUrl() + "collection/" + containerId;

    // Make the SWORD request

    String pid = "uuid:" + UUID.randomUUID().toString();

    HttpClient client = new HttpClient();

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(this.getUsername(), this.getPassword());
    client.getState().setCredentials(getAuthenticationScope(depositPath), creds);
    client.getParams().setAuthenticationPreemptive(true);

    PostMethod post = new PostMethod(depositPath);

    RequestEntity fileRequestEntity = new FileRequestEntity(zipFile, "application/zip");

    Header contentDispositionHeader = new Header("Content-Disposition", "attachment; filename=package.zip");
    post.addRequestHeader(contentDispositionHeader);

    Header packagingHeader = new Header("Packaging", "http://cdr.unc.edu/METS/profiles/Simple");
    post.addRequestHeader(packagingHeader);

    Header slugHeader = new Header("Slug", pid);
    post.addRequestHeader(slugHeader);

    post.setRequestEntity(fileRequestEntity);

    // Interpret the response from the SWORD endpoint

    DepositResult result = new DepositResult();

    try {

        // Set the result's status based on the HTTP response code

        int responseCode = client.executeMethod(post);

        if (responseCode >= 300) {
            LOG.error(String.valueOf(responseCode));
            LOG.error(post.getResponseBodyAsString());
            result.setStatus(Status.FAILED);
        } else {
            result.setStatus(Status.COMPLETE);
        }

        // Save the response body

        result.setResponseBody(post.getResponseBodyAsString());

        // Assign additional attributes based on the response body.

        try {

            Namespace atom = Namespace.getNamespace("http://www.w3.org/2005/Atom");

            SAXBuilder sx = new SAXBuilder();
            org.jdom.Document d = sx.build(post.getResponseBodyAsStream());

            // Set accessURL to the href of the first <link rel="alternate"> inside an Atom entry

            if (result.getStatus() == Status.COMPLETE) {

                if (d.getRootElement().getNamespace().equals(atom)
                        && d.getRootElement().getName().equals("entry")) {
                    @SuppressWarnings("unchecked")
                    List<Element> links = d.getRootElement().getChildren("link", atom);

                    for (Element link : links) {
                        if ("alternate".equals(link.getAttributeValue("rel"))) {
                            result.setAccessURL(link.getAttributeValue("href"));
                            break;
                        }
                    }
                }

            }

        } catch (JDOMException e) {
            LOG.error("There was a problem parsing the SWORD response.", e);
        }

        LOG.debug("response was: \n" + post.getResponseBodyAsString());

    } catch (HttpException e) {
        LOG.error("Exception during SWORD deposit", e);
        throw new Error(e);
    } catch (IOException e) {
        LOG.error("Exception during SWORD deposit", e);
        throw new Error(e);
    }

    return result;

}

From source file:com.redhat.demo.CrmTest.java

/**
 * HTTP POST http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
 * the add_customer.xml file to add a new customer to the system.
 * <p/>/*from  ww  w.j  av a2s .c  om*/
 * On the server side, it matches the CustomerService's addCustomer() method
 *
 * @throws Exception
 */
@Test
public void postCustomerTest() throws IOException {
    LOG.info("Sent HTTP POST request to add customer");
    String inputFile = this.getClass().getResource("/add_customer.xml").getFile();
    File input = new File(inputFile);
    PostMethod post = new PostMethod(CUSTOMER_SERVICE_URL);
    post.addRequestHeader("Accept", "application/xml");
    RequestEntity entity = new FileRequestEntity(input, "application/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    String res = "";

    try {
        int result = httpclient.executeMethod(post);
        LOG.info("Response status code: " + result);
        LOG.info("Response body: ");
        res = post.getResponseBodyAsString();
        LOG.info(res);
    } catch (IOException e) {
        LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL);
        LOG.error(
                "You should build the 'rest' quick start and deploy it to a local Fabric8 before running this test");
        LOG.error("Please read the README.md file in 'rest' quick start root");
        Assert.fail("Connection error");
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
    Assert.assertTrue(res.contains("Jack"));

}

From source file:com.comcast.cats.jenkins.service.AbstractService.java

/**
 * Create Project Via GET// w  w w .  j av  a2 s.c  o m
 * 
 * @param requestUrl
 *            Relative request URL
 * @param mapperClass
 *            Class to which the response should cast to.
 * @return JAXB deserialized response
 */
protected Object createProject(final String requestUrl, Class<?> mapperClass, File config) {
    Object domainObject = null;
    HttpClient client = new HttpClient();
    try {
        PostMethod request = new PostMethod(getAbsoluteUrl(requestUrl));
        request.addRequestHeader(CONTENT_TYPE, APPLICATION_XML);
        RequestEntity entity = new FileRequestEntity(config, "text/xml; charset=UTF-8");
        request.setRequestEntity(entity);
        String apiToken = jenkinsClientProperties.getJenkinsApiToken();
        if (!apiToken.isEmpty()) {
            request.setDoAuthentication(true);
        }

        domainObject = sendRequestToJenkins(mapperClass, domainObject, client, request, apiToken);

    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }

    return domainObject;
}