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.example.CrmTest.java

/**
 * HTTP PUT http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
 * the update_customer.xml file to update the customer information for customer 123.
 * <p/>/*  w w  w  .  j  a v a2s  .c o  m*/
 * On the server side, it matches the CustomerService's updateCustomer() method
 *
 * @throws Exception
 */
@Test
public void putCustomerTest() throws IOException {

    LOG.info("Sent HTTP PUT request to update customer info");

    String inputFile = this.getClass().getResource("/update_customer.xml").getFile();
    File input = new File(inputFile);
    PutMethod put = new PutMethod(CUSTOMER_SERVICE_URL);
    RequestEntity entity = new FileRequestEntity(input, "application/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    int result = 0;
    try {
        result = httpclient.executeMethod(put);
        LOG.info("Response status code: " + result);
        LOG.info("Response body: ");
        LOG.info(put.getResponseBodyAsString());
    } 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
        put.releaseConnection();
    }

    Assert.assertEquals(result, 200);
}

From source file:$.CrmTest.java

/**
     * HTTP PUT http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
     * the update_customer.xml file to update the customer information for customer 123.
     * <p/>//from  ww  w  .j a  va 2  s.c  om
     * On the server side, it matches the CustomerService's updateCustomer() method
     *
     * @throws Exception
     */
    @Test
    public void putCustomerTest() throws IOException {

        LOG.info("Sent HTTP PUT request to update customer info");

        String inputFile = this.getClass().getResource("/update_customer.xml").getFile();
        File input = new File(inputFile);
        PutMethod put = new PutMethod(CUSTOMER_SERVICE_URL);
        RequestEntity entity = new FileRequestEntity(input, "application/xml; charset=ISO-8859-1");
        put.setRequestEntity(entity);
        HttpClient httpclient = new HttpClient();
        int result = 0;
        try {
            result = httpclient.executeMethod(put);
            LOG.info("Response status code: " + result);
            LOG.info("Response body: ");
            LOG.info(put.getResponseBodyAsString());
        } 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
            put.releaseConnection();
        }

        Assert.assertEquals(result, 200);
    }

From source file:example.crm.CrmIT.java

/**
 * HTTP PUT http://localhost:9003/customers is used to upload the contents of
 * the update_customer.xml file to update the customer information for customer 123.
 * <p/>/*  ww w  .j  a  va  2  s .  co m*/
 * On the server side, it matches the CustomerService's updateCustomer() method
 *
 * @throws Exception
 */
@Test
public void putCustomerTest() throws IOException {

    LOG.info("Sent HTTP PUT request to update customer info");

    String inputFile = this.getClass().getResource("/update_customer.xml").getFile();
    File input = new File(inputFile);
    PutMethod put = new PutMethod(CUSTOMER_SERVICE_URL);
    RequestEntity entity = new FileRequestEntity(input, "application/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    int result = 0;
    try {
        result = httpclient.executeMethod(put);
        LOG.info("Response status code: " + result);
        LOG.info("Response body: ");
        LOG.info(put.getResponseBodyAsString());
    } 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
        put.releaseConnection();
    }

    Assert.assertEquals(result, 200);
}

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

/**
 * POSTs a File to the given URL.//  w  ww .  j  a  va2s  .  c o  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 POST.
 * @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 post(String url, File file, String contentType) {
    return post(url, new FileRequestEntity(file, contentType));
}

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

/**
 * HTTP PUT http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
 * the update_customer.xml file to update the customer information for customer 123.
 * <p/>//from  w  ww . j ava  2s  .c o m
 * On the server side, it matches the CustomerService's updateCustomer() method
 *
 * @throws Exception
 */
@Test
@Ignore
public void putCustomerTest() throws IOException {

    LOG.info("Sent HTTP PUT request to update customer info");

    String inputFile = this.getClass().getResource("/update_customer.xml").getFile();
    File input = new File(inputFile);
    PutMethod put = new PutMethod(CUSTOMER_SERVICE_URL);
    RequestEntity entity = new FileRequestEntity(input, "application/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    int result = 0;
    try {
        result = httpclient.executeMethod(put);
        LOG.info("Response status code: " + result);
        LOG.info("Response body: ");
        LOG.info(put.getResponseBodyAsString());
    } 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
        put.releaseConnection();
    }

    Assert.assertEquals(result, 200);
}

From source file:au.edu.usq.fascinator.harvester.fedora.restclient.FedoraRestClient.java

public void ingest(String pid, Properties options, File content) throws IOException {
    StringBuilder uri = new StringBuilder(getBaseUrl());
    uri.append("/objects/");
    uri.append(pid);/*w  ww  .j  a v a  2s .c o m*/
    addParam(uri, options, "label");
    addParam(uri, options, "format");
    addParam(uri, options, "encoding");
    addParam(uri, options, "namespace");
    addParam(uri, options, "ownerId");
    addParam(uri, options, "logMessage");
    PostMethod method = new PostMethod(uri.toString());
    RequestEntity request = null;
    if (content == null) {
        request = new StringRequestEntity("", "text/xml", "UTF-8");
    } else {
        String mimeType = options.getProperty("mimeType", getMimeType(content));
        request = new FileRequestEntity(content, mimeType);
    }
    method.setRequestEntity(request);
    executeMethod(method);
    method.releaseConnection();
}

From source file:au.edu.usq.fascinator.harvester.fedora.restclient.FedoraRestClient.java

public void addDatastream(String pid, String dsId, String dsLabel, String contentType, File content)
        throws IOException {
    Properties options = new Properties();
    options.setProperty("dsLabel", dsLabel);
    options.setProperty("controlGroup", "M");
    RequestEntity request = new FileRequestEntity(content, contentType);
    addDatastream(pid, dsId, options, contentType, request);
}

From source file:edu.mit.lib.tools.Modernize.java

private void uploadPackage(Path pkg, String targetUri) throws IOException {
    // using older Apache http client library to make compatible with more systems
    PostMethod post = new PostMethod(targetUri);
    HttpClient client = new HttpClient();
    RequestEntity entity = new FileRequestEntity(pkg.toFile(), "application/zip");
    post.setRequestEntity(entity);//ww  w .j  ava  2s .c o  m
    try {
        int result = client.executeMethod(post);
    } finally {
        post.releaseConnection();
    }
}

From source file:cz.vsb.gis.ruz76.gt.Examples.java

public String testREST_PUT() {
    String strURL = "http://localhost:8080/geoserver/rest/workspaces/acme/datastores/reky/file.shp";
    PutMethod put = new PutMethod(strURL);

    put.setRequestHeader("Content-type", "application/zip");
    put.setRequestEntity(new FileRequestEntity(new File("reky.zip"), "application/zip"));
    put.setDoAuthentication(true);//from  w  w w  . j  ava  2  s  .c  om

    HttpClient httpclient = new HttpClient();

    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "geoserver");
    httpclient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds);

    try {

        int response = httpclient.executeMethod(put);

        System.out.println("Response: ");
        BufferedReader br = new BufferedReader(new InputStreamReader(put.getResponseBodyAsStream()));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        //System.out.println(post.getResponseBodyAsStream());

    } catch (IOException ex) {
        Logger.getLogger(Examples.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        put.releaseConnection();
    }

    return "TestREST2";
}

From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java

public byte[] getData(Context context) throws IOException, EngineException {
    HttpMethod method = null;/*from  w  w  w .  j av a  2  s  .  c o  m*/

    try {
        // Fire event for plugins
        long t0 = System.currentTimeMillis();
        Engine.theApp.pluginsManager.fireHttpConnectorGetDataStart(context);

        // Retrieving httpState
        getHttpState(context);

        Engine.logBeans.trace("(HttpConnector) Retrieving data as a bytes array...");
        Engine.logBeans.debug("(HttpConnector) Connecting to: " + sUrl);

        // Setting the referer
        referer = sUrl;

        URL url = null;
        url = new URL(sUrl);

        // Proxy configuration
        Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url);

        Engine.logBeans.debug("(HttpConnector) Https: " + https);

        String host = "";
        int port = -1;
        if (sUrl.toLowerCase().startsWith("https:")) {
            if (!https) {
                Engine.logBeans.debug("(HttpConnector) Setting up SSL properties");
                certificateManager.collectStoreInformation(context);
            }

            url = new URL(sUrl);
            host = url.getHost();
            port = url.getPort();
            if (port == -1)
                port = 443;

            Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port);

            Engine.logBeans
                    .debug("(HttpConnector) CertificateManager has changed: " + certificateManager.hasChanged);
            if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost()))
                    || (hostConfiguration.getPort() != port)) {
                Engine.logBeans.debug("(HttpConnector) Using MySSLSocketFactory for creating the SSL socket");
                Protocol myhttps = new Protocol("https",
                        MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore,
                                certificateManager.keyStorePassword, certificateManager.trustStore,
                                certificateManager.trustStorePassword, this.trustAllServerCertificates),
                        port);

                hostConfiguration.setHost(host, port, myhttps);
            }

            sUrl = url.getFile();
            Engine.logBeans.debug("(HttpConnector) Updated URL for SSL purposes: " + sUrl);
        } else {
            url = new URL(sUrl);
            host = url.getHost();
            port = url.getPort();

            Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port);
            hostConfiguration.setHost(host, port);
        }
        AbstractHttpTransaction httpTransaction = (AbstractHttpTransaction) context.transaction;

        // Retrieve HTTP method
        HttpMethodType httpVerb = httpTransaction.getHttpVerb();
        String sHttpVerb = httpVerb.name();
        final String sCustomHttpVerb = httpTransaction.getCustomHttpVerb();

        if (sCustomHttpVerb.length() > 0) {
            Engine.logBeans.debug(
                    "(HttpConnector) HTTP verb: " + sHttpVerb + " overridden to '" + sCustomHttpVerb + "'");

            switch (httpVerb) {
            case GET:
                method = new GetMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case POST:
                method = new PostMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case PUT:
                method = new PutMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case DELETE:
                method = new DeleteMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case HEAD:
                method = new HeadMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case OPTIONS:
                method = new OptionsMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case TRACE:
                method = new TraceMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            }
        } else {
            Engine.logBeans.debug("(HttpConnector) HTTP verb: " + sHttpVerb);

            switch (httpVerb) {
            case GET:
                method = new GetMethod(sUrl);
                break;
            case POST:
                method = new PostMethod(sUrl);
                break;
            case PUT:
                method = new PutMethod(sUrl);
                break;
            case DELETE:
                method = new DeleteMethod(sUrl);
                break;
            case HEAD:
                method = new HeadMethod(sUrl);
                break;
            case OPTIONS:
                method = new OptionsMethod(sUrl);
                break;
            case TRACE:
                method = new TraceMethod(sUrl);
                break;
            }
        }

        // Setting HTTP parameters
        boolean hasUserAgent = false;

        for (List<String> httpParameter : httpParameters) {
            String key = httpParameter.get(0);
            String value = httpParameter.get(1);
            if (key.equalsIgnoreCase("host") && !value.equals(host)) {
                value = host;
            }

            if (!key.startsWith(DYNAMIC_HEADER_PREFIX)) {
                method.setRequestHeader(key, value);
            }
            if (HeaderName.UserAgent.is(key)) {
                hasUserAgent = true;
            }
        }

        // set user-agent header if not found
        if (!hasUserAgent) {
            HeaderName.UserAgent.setRequestHeader(method, getUserAgent(context));
        }

        // Setting POST or PUT parameters if any
        Engine.logBeans.debug("(HttpConnector) Setting " + httpVerb + " data");
        if (method instanceof EntityEnclosingMethod) {
            EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) method;
            AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject;

            if (doMultipartFormData) {
                RequestableHttpVariable body = (RequestableHttpVariable) httpTransaction
                        .getVariable(Parameter.HttpBody.getName());
                if (body != null && body.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) {
                    String stringValue = httpTransaction.getParameterStringValue(Parameter.HttpBody.getName());
                    String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue,
                            getProject().getName());
                    File file = new File(filepath);
                    if (file.exists()) {
                        HeaderName.ContentType.setRequestHeader(method, contentType);
                        entityEnclosingMethod.setRequestEntity(new FileRequestEntity(file, contentType));
                    } else {
                        throw new FileNotFoundException(file.getAbsolutePath());
                    }
                } else {
                    List<Part> parts = new LinkedList<Part>();

                    for (RequestableVariable variable : transaction.getVariablesList()) {
                        if (variable instanceof RequestableHttpVariable) {
                            RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable;

                            if ("POST".equals(httpVariable.getHttpMethod())) {
                                Object httpObjectVariableValue = transaction
                                        .getVariableValue(httpVariable.getName());

                                if (httpVariable.isMultiValued()) {
                                    if (httpObjectVariableValue instanceof Collection<?>) {
                                        for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) {
                                            addFormDataPart(parts, httpVariable, httpVariableValue);
                                        }
                                    }
                                } else {
                                    addFormDataPart(parts, httpVariable, httpObjectVariableValue);
                                }
                            }
                        }
                    }
                    MultipartRequestEntity mre = new MultipartRequestEntity(
                            parts.toArray(new Part[parts.size()]), entityEnclosingMethod.getParams());
                    HeaderName.ContentType.setRequestHeader(method, mre.getContentType());
                    entityEnclosingMethod.setRequestEntity(mre);
                }
            } else if (MimeType.TextXml.is(contentType)) {
                final MimeMultipart[] mp = { null };

                for (RequestableVariable variable : transaction.getVariablesList()) {
                    if (variable instanceof RequestableHttpVariable) {
                        RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable;

                        if (httpVariable.getDoFileUploadMode() == DoFileUploadMode.MTOM) {
                            Engine.logBeans.trace(
                                    "(HttpConnector) Variable " + httpVariable.getName() + " detected as MTOM");

                            MimeMultipart mimeMultipart = mp[0];
                            try {
                                if (mimeMultipart == null) {
                                    Engine.logBeans.debug("(HttpConnector) Preparing the MTOM request");

                                    mimeMultipart = new MimeMultipart("related; type=\"application/xop+xml\"");
                                    MimeBodyPart bp = new MimeBodyPart();
                                    bp.setText(postQuery, "UTF-8");
                                    bp.setHeader(HeaderName.ContentType.value(), contentType);
                                    mimeMultipart.addBodyPart(bp);
                                }

                                Object httpObjectVariableValue = transaction
                                        .getVariableValue(httpVariable.getName());

                                if (httpVariable.isMultiValued()) {
                                    if (httpObjectVariableValue instanceof Collection<?>) {
                                        for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) {
                                            addMtomPart(mimeMultipart, httpVariable, httpVariableValue);
                                        }
                                    }
                                } else {
                                    addMtomPart(mimeMultipart, httpVariable, httpObjectVariableValue);
                                }
                                mp[0] = mimeMultipart;
                            } catch (Exception e) {
                                Engine.logBeans.warn(
                                        "(HttpConnector) Failed to add MTOM part for " + httpVariable.getName(),
                                        e);
                            }
                        }
                    }
                }

                if (mp[0] == null) {
                    entityEnclosingMethod.setRequestEntity(
                            new StringRequestEntity(postQuery, MimeType.TextXml.value(), "UTF-8"));
                } else {
                    Engine.logBeans.debug("(HttpConnector) Commit the MTOM request with the ContentType: "
                            + mp[0].getContentType());

                    HeaderName.ContentType.setRequestHeader(method, mp[0].getContentType());
                    entityEnclosingMethod.setRequestEntity(new RequestEntity() {

                        @Override
                        public void writeRequest(OutputStream outputStream) throws IOException {
                            try {
                                mp[0].writeTo(outputStream);
                            } catch (MessagingException e) {
                                new IOException(e);
                            }
                        }

                        @Override
                        public boolean isRepeatable() {
                            return true;
                        }

                        @Override
                        public String getContentType() {
                            return mp[0].getContentType();
                        }

                        @Override
                        public long getContentLength() {
                            return -1;
                        }
                    });
                }
            } else {
                String charset = httpTransaction.getComputedUrlEncodingCharset();
                HeaderName.ContentType.setRequestHeader(method, contentType);
                entityEnclosingMethod
                        .setRequestEntity(new StringRequestEntity(postQuery, contentType, charset));
            }
        }

        // Getting the result
        Engine.logBeans.debug("(HttpConnector) HttpClient: getting response body");
        byte[] result = executeMethod(method, context);
        Engine.logBeans.debug("(HttpConnector) Total read bytes: " + ((result != null) ? result.length : 0));

        // Fire event for plugins
        long t1 = System.currentTimeMillis();
        Engine.theApp.pluginsManager.fireHttpConnectorGetDataEnd(context, t0, t1);

        fireDataChanged(new ConnectorEvent(this, result));

        return result;
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}