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

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

Introduction

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

Prototype

public PutMethod(String paramString) 

Source Link

Usage

From source file:com.vmware.aurora.vc.VcFileManager.java

static private void uploadFileWork(String url, boolean isPost, File file, String contentType, String cookie,
        ProgressListener listener) throws Exception {
    EntityEnclosingMethod method;//from w w w.  j a v  a2s . c o  m
    final RequestEntity entity = new ProgressListenerRequestEntity(file, contentType, listener);
    if (isPost) {
        method = new PostMethod(url);
        method.setContentChunked(true);
    } else {
        method = new PutMethod(url);
        method.addRequestHeader("Cookie", cookie);
        method.setContentChunked(false);
        HttpMethodParams params = new HttpMethodParams();
        params.setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        method.setParams(params);
    }
    method.setRequestEntity(entity);

    logger.info("upload " + file + " to " + url);
    long t1 = System.currentTimeMillis();
    boolean ok = false;
    try {
        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(method);
        String response = method.getResponseBodyAsString(100);
        logger.debug("status: " + statusCode + " response: " + response);
        if (statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_OK) {
            throw new Exception("Http post failed");
        }
        method.releaseConnection();
        ok = true;
    } finally {
        if (!ok) {
            method.abort();
        }
    }
    long t2 = System.currentTimeMillis();
    logger.info("upload " + file + " done in " + (t2 - t1) + " ms");
}

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

/**
 * sends a PUT or POST call to a URL using authentication and including a
 * file upload//from w  w w .  j  av  a2s.  c  o m
 *
 * @param type         one of UploadSpatialResource.PUT for a PUT call or
 *                     UploadSpatialResource.POST for a POST call
 * @param url          URL for PUT/POST call
 * @param username     account username for authentication
 * @param password     account password for authentication
 * @param resourcepath local path to file to upload, null for no file to
 *                     upload
 * @param contenttype  file MIME content type
 * @return server response status code as String or empty String if
 * unsuccessful
 */
public static String httpCall(int type, String url, String username, String password, String resourcepath,
        String contenttype) {
    String output = "";

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(10000);
    client.setTimeout(60000);
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    RequestEntity entity = null;
    if (resourcepath != null) {
        File input = new File(resourcepath);
        entity = new FileRequestEntity(input, contenttype);
    }

    HttpMethod call = null;
    ;
    if (type == PUT) {
        PutMethod put = new PutMethod(url);
        put.setDoAuthentication(true);
        if (entity != null) {
            put.setRequestEntity(entity);
        }
        call = put;
    } else if (type == POST) {
        PostMethod post = new PostMethod(url);
        if (entity != null) {
            post.setRequestEntity(entity);
        }
        call = post;
    } else {
        //SpatialLogger.log("UploadSpatialResource", "invalid type: " + type);
        return output;
    }

    // Execute the request 
    try {
        int result = client.executeMethod(call);

        output = result + ": " + call.getResponseBodyAsString();
    } catch (Exception e) {
        //SpatialLogger.log("UploadSpatialResource", "failed upload to: " + url);
        output = "0: " + e.getMessage();
        e.printStackTrace(System.out);
    } finally {
        // Release current connection to the connection pool once you are done 
        call.releaseConnection();
    }

    return output;
}

From source file:com.gisgraphy.rest.RestClient.java

private HttpMethod createPutMethod(String url, Map<String, Object> map) throws RestClientException {
    PutMethod httpMethod = new PutMethod(url);
    StringBuilder responseBody = new StringBuilder();
    if (map != null) {
        for (String key : map.keySet()) {
            if (map.get(key) != null) {
                responseBody.append(format("%s=%s\n", key, map.get(key).toString()));
            }/*  ww  w. j  a  va  2s. c o  m*/
        }
    }
    String responseBodyAsString = responseBody.toString();

    httpMethod.setRequestEntity(
            new StringRequestEntity(responseBodyAsString.substring(0, responseBody.length())));
    httpMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    return httpMethod;
}

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

/**
 * Performs a PUT to the given URL.//  www . j a v a2  s  .  c o m
 *
 * @param url       The URL where to connect to.
 * @param requestEntity The request to be sent.
 * @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, RequestEntity requestEntity) {
    return send(new PutMethod(url), url, requestEntity);
}

From source file:com.cordys.coe.ac.httpconnector.impl.StandardRequestHandler.java

/**
 * @see IRequestHandler#process(int, IServerConnection, HttpClient)
 *//*from   ww  w  .  j  av  a 2  s .  c o  m*/
@Override
public HttpMethod process(int requestNode, IServerConnection connection, HttpClient httpClient)
        throws HandlerException {
    String uri = getRequestUri(requestNode, connection, httpClient);
    EntityEnclosingMethod httpMethod;

    if (LOG.isDebugEnabled()) {
        LOG.debug("HTTP method is: " + m_method.getHttpMethodType());
    }

    switch (m_method.getHttpMethodType()) {
    case GET:
        HttpMethod httpMethodGet = new GetMethod(uri); // Get method does not have a body. 
        setRequestHeaders(httpMethodGet);
        return httpMethodGet;

    case POST:
        httpMethod = new PostMethod(uri);
        break;

    case PUT:
        httpMethod = new PutMethod(uri);
        break;

    case DELETE:
        HttpMethod httpMethodDelete = new DeleteMethod(uri); // Delete method does not have a body.
        setRequestHeaders(httpMethodDelete);
        return httpMethodDelete;

    default:
        throw new HandlerException(HandlerExceptionMessages.UNKNOWN_HTTP_METHOD);
    }

    int reqNode = requestNode;

    try {
        reqNode = preProcessXml(reqNode, reqNode != requestNode);

        if (xsltNode != 0) {
            reqNode = executeXslt(reqNode, m_method, reqNode != requestNode);
        }

        if (m_requestRootXPath != null) {
            reqNode = handleRequestXPath(reqNode, m_method, reqNode != requestNode);
        }

        if ((m_removeNamespaceUriSet != null) || m_removeAllNamespaces) {
            XmlUtils.removeNamespacesRecursively(reqNode, m_removeNamespaceUriSet);
        }

        reqNode = postProcessXml(reqNode, reqNode != requestNode);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Final Request XML: " + Node.writeToString(reqNode, true));
        }

        // Get the data that should be posted.
        byte[] reqData = getPostData(reqNode, connection);
        String contentType = getContentType();

        httpMethod.setRequestEntity(new ByteArrayRequestEntity(reqData, contentType));

        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending data: " + new String(reqData));
        }

        httpMethod.setRequestHeader("Content-type", contentType);
        setRequestHeaders(httpMethod);
    } finally {
        if ((reqNode != 0) && (reqNode != requestNode)) {
            Node.delete(reqNode);
            reqNode = 0;
        }
    }

    return httpMethod;
}

From source file:io.fabric8.quickstarts.fabric.rest.secure.CrmSecureTest.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  w w.j  av  a 2s.  com
 * On the server side, it matches the CustomerService's updateCustomer() method
 *
 * @throws Exception
 */
@Test
public void putCustomerTest() throws IOException {

    LOG.info("============================================");
    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);
    put.getHostAuthState().setAuthScheme(scheme);
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);

    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:com.cellbots.local.EyesView.java

public void surfaceDestroyed(SurfaceHolder holder) {
    mCamera.stopPreview();/*from   w w  w  .  ja  va2  s .  c o m*/
    mCamera.release();
    mCamera = null;
    // If putUrl is null, it means that only personas overlay was requested.
    if (putUrl == null) {
        return;
    }
    if (isLocalUrl) {
        mParent.setRemoteEyesImage(new byte[0]);
        return;
    }
    try {
        PutMethod put = new PutMethod(putUrl);
        put.setRequestBody(new ByteArrayInputStream(new byte[0]));
        put.execute(mHttpState, mConnection);
    } catch (NoHttpResponseException e) {
        // Silently ignore this.
    } catch (IOException e) {
        e.printStackTrace();
        resetConnection();
    }
}

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

@Override
public void updateAccount(Account account) {
    String resource = String.format(baseUrl + ACCOUNT, account.getId());
    PutMethod method = new PutMethod(resource);
    try {/* ww w . ja v a  2s .  c  o  m*/
        String data = serialize(account);
        method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING));
        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return;
        }
        assertResponseCodeOK(method, statusCode);

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

From source file:de.mpg.mpdl.inge.pubman.web.multipleimport.processor.ZfNProcessor.java

/**
 * Uploads a file to the staging servlet and returns the corresponding URL.
 * /*ww w  . j av a2  s  .  c  o  m*/
 * @param InputStream to upload
 * @param mimetype The mimetype of the file
 * @param userHandle The userhandle to use for upload
 * @return The URL of the uploaded file.
 * @throws Exception If anything goes wrong...
 */
private URL uploadFile(InputStream in, String mimetype, String userHandle) throws Exception {
    // Prepare the HttpMethod.
    String fwUrl = PropertyReader.getFrameworkUrl();
    PutMethod method = new PutMethod(fwUrl + "/st/staging-file");
    method.setRequestEntity(new InputStreamRequestEntity(in, -1));
    method.setRequestHeader("Content-Type", mimetype);
    method.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
    // Execute the method with HttpClient.
    HttpClient client = new HttpClient();
    client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    XmlTransformingBean ctransforming = new XmlTransformingBean();
    return ctransforming.transformUploadResponseToFileURL(response);
}

From source file:de.mpg.escidoc.pubman.multipleimport.processor.ZfNProcessor.java

/**
 * Uploads a file to the staging servlet and returns the corresponding URL.
 * @param InputStream to upload//from   w w  w. j a v  a 2 s .  c om
 * @param mimetype The mimetype of the file
 * @param userHandle The userhandle to use for upload
 * @return The URL of the uploaded file.
 * @throws Exception If anything goes wrong...
 */
private URL uploadFile(InputStream in, String mimetype, String userHandle) throws Exception {
    // Prepare the HttpMethod.
    String fwUrl = de.mpg.escidoc.services.framework.ServiceLocator.getFrameworkUrl();
    PutMethod method = new PutMethod(fwUrl + "/st/staging-file");
    method.setRequestEntity(new InputStreamRequestEntity(in, -1));
    method.setRequestHeader("Content-Type", mimetype);
    method.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
    // Execute the method with HttpClient.
    HttpClient client = new HttpClient();
    client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    XmlTransformingBean ctransforming = new XmlTransformingBean();
    return ctransforming.transformUploadResponseToFileURL(response);
}