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:org.cipango.kaleo.sipunit.WatcherInfoTest.java

/**
 * <pre>/* w  ww. java 2s  .co m*/
    Alice               Kaleo              SipUnit
  |                   |(1) PUBLISH          |
  |                   |<--------------------|
  |                   |(2) 200 OK           |
  |                   |-------------------->|
  |(3) SUBSCRIBE      |                     |
  |Event:presence     |                     |
  |------------------>|                     |
  |(4) 200 OK         |                     |
  |<------------------|                     |
  |(5) NOTIFY         |                     |
  |<------------------|                     |
  |(6) 200 OK         |                     |
  |------------------>|                     |
  |                   |(7) SUBSCRIBE        |
  |                   |Event:presence.winfo |
  |                   |<--------------------|
  |                   |(8) 200 OK           |
  |                   |-------------------->|
  |                   |(9) NOTIFY           |
  |                   |-------------------->|
  |                   |(10) 200 OK          |
  |                   |<--------------------|
  |                   |(11) HTTP PUT        | Change subscription state from 
  |                   |<--------------------| allow to polite-block
  |                   |(12) 200 OK          |
  |                   |-------------------->|
  |(13) NOTIFY        |                     | Send NOTIFY with neutral state
  |<------------------|                     |
  |(14) 200 OK        |                     |
  |------------------>|                     |
  |                   |(15) NOTIFY          |
  |                   |-------------------->| 
  |                   |(16) 200 OK          |
  |                   |<--------------------|
  |                   |(17) SUBSCRIBE       |
  |                   |Expires = 0          |
  |                   |<--------------------|
  |                   |(18) 200 OK          |
  |                   |-------------------->|
  |                   |(19) NOTIFY          |
  |                   |-------------------->|
  |                   |(20) 200 OK          |
  |                   |<--------------------|
  |(21) SUBSCRIBE     |                     |
  |Expires: 0         |                     |
  |------------------>|                     |
  |(22) 200 OK        |                     |
  |<------------------|                     |
  |(23) NOTIFY        |                     |
  |<------------------|                     |
  |(24) 200 OK        |                     |
  |------------------>|                     |
  |                   |(25) PUBLISH         |
  |                   |Expires = 0          |
  |                   |<--------------------|
  |                   |(26) 200 OK          |
  |                   |-------------------->|
  * </pre>
 */
public void testSubscription3() throws Exception {
    PublishSession publishSession = new PublishSession(getBobPhone());
    Request publish = publishSession.newPublish(getClass().getResourceAsStream("publish1.xml"), 60); // 1
    publishSession.sendRequest(publish, SipResponse.OK); // 2

    SubscribeSession presenceSession = new SubscribeSession(getAlicePhone(), "presence");
    Request subscribe = presenceSession.newInitialSubscribe(100, getBobUri()); // 3
    presenceSession.sendRequest(subscribe, Response.OK); // 4

    ServerTransaction tx = presenceSession.waitForNotify(); // 5
    //System.out.println("3:\n" + tx.getRequest());
    presenceSession.sendResponse(Response.OK, tx); // 6
    Presence presence = getPresence(tx.getRequest());
    assertEquals(Basic.OPEN, presence.getTupleArray()[0].getStatus().getBasic());

    SubscribeSession winfoSession = new SubscribeSession(getBobPhone(), "presence.winfo"); // 7
    subscribe = winfoSession.newInitialSubscribe(60, getBobUri());
    winfoSession.sendRequest(subscribe, Response.OK); // 8

    tx = winfoSession.waitForNotify(); // 9
    Request notify = tx.getRequest();
    //System.out.println(notify);
    winfoSession.sendResponse(Response.OK, tx); // 10 
    SubscriptionStateHeader subState = (SubscriptionStateHeader) notify.getHeader(SubscriptionStateHeader.NAME);
    assertEquals(SubscriptionStateHeader.ACTIVE.toLowerCase(), subState.getState().toLowerCase());
    assertEquals(WatcherInfoEventPackage.NAME,
            ((EventHeader) notify.getHeader(EventHeader.NAME)).getEventType());
    Watcherinfo watcherinfo = getWatcherinfo(notify);
    assertEquals(0, watcherinfo.getVersion().intValue());
    assertEquals(Watcherinfo.State.FULL, watcherinfo.getState());
    assertEquals(1, watcherinfo.getWatcherListArray().length);
    WatcherList watcherList = watcherinfo.getWatcherListArray(0);
    assertEquals(getBobUri(), watcherList.getResource());
    assertEquals(PresenceEventPackage.NAME, watcherList.getPackage());
    assertEquals(1, watcherList.getWatcherArray().length);
    Watcher watcher = watcherList.getWatcherArray(0);
    assertEquals(Event.SUBSCRIBE, watcher.getEvent());
    assertEquals(getAliceUri(), watcher.getStringValue());
    assertEquals(Status.ACTIVE, watcher.getStatus());

    HttpClient httpClient = new HttpClient();
    PutMethod put = new PutMethod(getHttpXcapUri() + BOB_PRES_RULES_URI); // 11

    InputStream is = WatcherInfoTest.class
            .getResourceAsStream("/xcap-root/pres-rules/users/put/elementPoliteBlock.xml");
    RequestEntity entity = new InputStreamRequestEntity(is, "application/xcap-el+xml");
    put.setRequestEntity(entity);

    int result = httpClient.executeMethod(put);
    assertEquals(200, result); // 12
    put.releaseConnection();

    tx = presenceSession.waitForNotify(); // 13
    //System.out.println("11:\n" + tx.getRequest());
    presenceSession.sendResponse(Response.OK, tx); // 14
    presence = getPresence(tx.getRequest());
    assertEquals(Basic.CLOSED, presence.getTupleArray()[0].getStatus().getBasic());

    tx = winfoSession.waitForNotify(); // 15
    notify = tx.getRequest();
    winfoSession.sendResponse(Response.OK, tx); // 16
    System.out.println(notify);
    subState = (SubscriptionStateHeader) notify.getHeader(SubscriptionStateHeader.NAME);
    assertEquals(SubscriptionStateHeader.ACTIVE.toLowerCase(), subState.getState().toLowerCase());
    assertEquals(WatcherInfoEventPackage.NAME,
            ((EventHeader) notify.getHeader(EventHeader.NAME)).getEventType());
    watcherinfo = getWatcherinfo(notify);
    assertEquals(1, watcherinfo.getVersion().intValue());
    assertEquals(Watcherinfo.State.FULL, watcherinfo.getState());
    assertEquals(1, watcherinfo.getWatcherListArray().length);
    watcherList = watcherinfo.getWatcherListArray(0);
    assertEquals(getBobUri(), watcherList.getResource());
    assertEquals(PresenceEventPackage.NAME, watcherList.getPackage());
    assertEquals(1, watcherList.getWatcherArray().length);
    watcher = watcherList.getWatcherArray(0);
    assertEquals(Event.SUBSCRIBE, watcher.getEvent());
    assertEquals(getAliceUri(), watcher.getStringValue());
    assertEquals(Status.ACTIVE, watcher.getStatus());

    subscribe = winfoSession.newSubsequentSubscribe(0); // 17
    winfoSession.sendRequest(subscribe, Response.OK); // 18

    tx = winfoSession.waitForNotify(); // 19
    winfoSession.sendResponse(Response.OK, tx); // 20

    subscribe = presenceSession.newSubsequentSubscribe(0); // 21
    presenceSession.sendRequest(subscribe, Response.OK); // 22

    tx = presenceSession.waitForNotify(); // 23
    presenceSession.sendResponse(Response.OK, tx); // 24

    publish = publishSession.newUnpublish(); // 25
    publishSession.sendRequest(publish, Response.OK); // 26
}

From source file:org.cipango.kaleo.sipunit.WatcherInfoTest.java

/**
 * <pre>//from w w  w  . j  a v a  2 s  .com
Bob                Kaleo                 Alice
  |                   |(1) PUBLISH          |
  |                   |<--------------------|
  |                   |(2) 200 OK           |
  |                   |-------------------->|
  |(3) SUBSCRIBE      |                     |
  |Event:presence     |                     |
  |Expires: 0         |                     |
  |------------------>|                     |
  |(4) 200 OK         |                     |
  |<------------------|                     |
  |(5) NOTIFY         |                     | In pending state, so basic status is closed
  |<------------------|                     |
  |(6) 200 OK         |                     |
  |------------------>|                     |
  |                   |(7) SUBSCRIBE        |
  |                   |Event:presence.winfo |
  |                   |<--------------------|
  |                   |(8) 200 OK           |
  |                   |-------------------->|
  |                   |(9) NOTIFY           |
  |                   |-------------------->|
  |                   |(10) 200 OK          |
  |                   |<--------------------|
  |                   |(11) HTTP PUT        | Change subscription state from 
  |                   |<--------------------| allow to polite-block
  |                   |(12) 200 OK          |
  |                   |-------------------->|
  |(13) SUBSCRIBE     |                     |
  |Event:presence     |                     |
  |Expires: 0         |                     |
  |------------------>|                     |
  |(14) 200 OK        |                     |
  |<------------------|                     |
  |(15) NOTIFY        |                     |
  |<------------------|                     |
  |(16) 200 OK        |                     |
  |------------------>|                     |
  |                   |(17) PUBLISH         |
  |                   |Expires = 0          |
  |                   |<--------------------|
  |                   |(18) 200 OK          |
  |                   |-------------------->|
  * </pre>
  * Note: Alice and Bob are inverted in this test.
 */
public void testWaitingState() throws Exception {
    PublishSession publishSession = new PublishSession(getAlicePhone());
    Request publish = publishSession.newPublish(getClass().getResourceAsStream("publish1.xml"), 60); // 1
    publishSession.sendRequest(publish, SipResponse.OK); // 2

    SubscribeSession presenceSession = new SubscribeSession(getBobPhone(), "presence");
    Request subscribe = presenceSession.newInitialSubscribe(0, getAliceUri()); // 3
    presenceSession.sendRequest(subscribe, Response.OK); // 4

    ServerTransaction tx = presenceSession.waitForNotify(); // 5
    System.out.println("5:\n" + tx.getRequest());
    presenceSession.sendResponse(Response.OK, tx); // 6
    Presence presence = getPresence(tx.getRequest());
    assertEquals(Basic.CLOSED, presence.getTupleArray()[0].getStatus().getBasic());

    SubscribeSession winfoSession = new SubscribeSession(getAlicePhone(), "presence.winfo"); // 7
    subscribe = winfoSession.newInitialSubscribe(60, getAliceUri());
    winfoSession.sendRequest(subscribe, Response.OK); // 8

    tx = winfoSession.waitForNotify(); // 9
    Request notify = tx.getRequest();
    System.out.println("9:\n" + notify);
    winfoSession.sendResponse(Response.OK, tx); // 10 
    SubscriptionStateHeader subState = (SubscriptionStateHeader) notify.getHeader(SubscriptionStateHeader.NAME);
    assertEquals(SubscriptionStateHeader.ACTIVE.toLowerCase(), subState.getState().toLowerCase());
    assertEquals(WatcherInfoEventPackage.NAME,
            ((EventHeader) notify.getHeader(EventHeader.NAME)).getEventType());
    Watcherinfo watcherinfo = getWatcherinfo(notify);
    assertEquals(0, watcherinfo.getVersion().intValue());
    assertEquals(Watcherinfo.State.FULL, watcherinfo.getState());
    assertEquals(1, watcherinfo.getWatcherListArray().length);
    WatcherList watcherList = watcherinfo.getWatcherListArray(0);
    assertEquals(getAliceUri(), watcherList.getResource());
    assertEquals(PresenceEventPackage.NAME, watcherList.getPackage());
    assertEquals(1, watcherList.getWatcherArray().length);
    Watcher watcher = watcherList.getWatcherArray(0);
    assertEquals(Event.TIMEOUT, watcher.getEvent());
    assertEquals(getBobUri(), watcher.getStringValue());
    assertEquals(Status.WAITING, watcher.getStatus());

    HttpClient httpClient = new HttpClient();
    PutMethod put = new PutMethod(getHttpXcapUri() + ALICE_PRES_RULES_URI); // 11

    InputStream is = WatcherInfoTest.class
            .getResourceAsStream("/xcap-root/pres-rules/users/put/elementCondAliceBob.xml");
    RequestEntity entity = new InputStreamRequestEntity(is, "application/xcap-el+xml");
    put.setRequestEntity(entity);

    int result = httpClient.executeMethod(put);
    assertEquals(200, result); // 12
    put.releaseConnection();

    presenceSession = new SubscribeSession(getBobPhone(), "presence");
    subscribe = presenceSession.newInitialSubscribe(0, getAliceUri()); // 13
    presenceSession.sendRequest(subscribe, Response.OK); // 14

    tx = presenceSession.waitForNotify(); // 15
    System.out.println("15:\n" + tx.getRequest());
    presenceSession.sendResponse(Response.OK, tx); // 16
    presence = getPresence(tx.getRequest());
    assertEquals(Basic.OPEN, presence.getTupleArray()[0].getStatus().getBasic());

    publish = publishSession.newUnpublish(); // 25
    publishSession.sendRequest(publish, Response.OK); // 26
}

From source file:org.codehaus.httpcache4j.client.HTTPClientResponseResolver.java

/**
 * Determines the HttpClient's request method from the HTTPMethod enum.
 *
 * @param method     the HTTPCache enum that determines
 * @param requestURI the request URI.//www. ja  va 2 s.com
 * @return a new HttpMethod subclass.
 */
protected HttpMethod getMethod(HTTPMethod method, URI requestURI) {
    if (CONNECT.equals(method)) {
        HostConfiguration config = new HostConfiguration();
        config.setHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme());
        return new ConnectMethod(config);
    } else if (DELETE.equals(method)) {
        return new DeleteMethod(requestURI.toString());
    } else if (GET.equals(method)) {
        return new GetMethod(requestURI.toString());
    } else if (HEAD.equals(method)) {
        return new HeadMethod(requestURI.toString());
    } else if (OPTIONS.equals(method)) {
        return new OptionsMethod(requestURI.toString());
    } else if (POST.equals(method)) {
        return new PostMethod(requestURI.toString());
    } else if (PUT.equals(method)) {
        return new PutMethod(requestURI.toString());
    } else if (TRACE.equals(method)) {
        return new TraceMethod(requestURI.toString());
    } else {
        throw new IllegalArgumentException("Cannot handle method: " + method);
    }
}

From source file:org.collectionspace.chain.csp.persistence.services.connection.ServicesConnection.java

private HttpMethod createMethod(RequestMethod method, String uri, InputStream data) throws ConnectionException {
    uri = prepend_base(uri);//  w  w w .  j  av a2s.co m
    if (uri == null)
        throw new ConnectionException("URI must not be null");
    // Extract QP's
    int qp_start = uri.indexOf('?');
    String qps = null;
    if (qp_start != -1) {
        qps = uri.substring(qp_start + 1);
        uri = uri.substring(0, qp_start);
    }
    HttpMethod out = null;
    switch (method) {
    case POST: {
        out = new PostMethod(uri);
        if (data != null)
            ((PostMethod) out).setRequestEntity(new InputStreamRequestEntity(data));
        break;
    }
    case PUT: {
        out = new PutMethod(uri);
        if (data != null)
            ((PutMethod) out).setRequestEntity(new InputStreamRequestEntity(data));
        break;
    }
    case GET:
        out = new GetMethod(uri);
        break;
    case DELETE:
        out = new DeleteMethod(uri);
        break;
    default:
        throw new ConnectionException("Unsupported method " + method, 0, uri);
    }
    if (qps != null)
        out.setQueryString(qps);
    out.setDoAuthentication(true);
    return out;
}

From source file:org.collectionspace.services.client.test.BaseServiceTest.java

/**
 * Submits an HTTP request to a specified URL, with the submitted
 * entity body, and returns the status code of the response.
 * Currently accepts POST and PUT requests.
 *
 * @param  method  An HTTP method.//  w w w.  j a va 2s.co  m
 *
 * @param  url     A String representation of a URL.
 *
 * @param  mediaType  The media type of the entity body to be submitted.
 *
 * @param  entityStr     The contents of the entity body to be submitted.
 *
 * @return The status code received in the HTTP response.
 */
protected int submitRequest(String method, String url, String mediaType, String entityStr) {
    int statusCode = 0;
    EntityEnclosingMethod httpMethod = null;
    try {
        TestServiceClient client = new TestServiceClient();
        if (method.equals(javax.ws.rs.HttpMethod.POST)) {
            httpMethod = new PostMethod(url);
        } else if (method.equals(javax.ws.rs.HttpMethod.PUT)) {
            httpMethod = new PutMethod(url);
        }
        if (httpMethod != null) {
            StringRequestEntity entityBody = new StringRequestEntity(mediaType, entityStr, NULL_CHARSET);
            httpMethod.setRequestEntity(entityBody);
            statusCode = client.getHttpClient().executeMethod(httpMethod);
        }
    } catch (Exception e) {
        logger.error("Exception during HTTP " + method + " request to " + url + ":", e);
    } finally {
        if (httpMethod != null)
            httpMethod.releaseConnection();
    }
    return statusCode;
}

From source file:org.cryptomator.frontend.webdav.WebDavServerTest.java

@Test
public void testPut() throws HttpException, IOException {
    final HttpClient client = new HttpClient();

    // create file:
    final byte[] testContent = "hello world".getBytes();
    final EntityEnclosingMethod putMethod = new PutMethod(servletRoot + "/foo.txt");
    putMethod.setRequestEntity(new ByteArrayRequestEntity(testContent));
    final int putResponse = client.executeMethod(putMethod);
    Assert.assertEquals(201, putResponse);
    Assert.assertTrue(fs.file("foo.txt").exists());

    // check file contents:
    ByteBuffer buf = ByteBuffer.allocate(testContent.length);
    try (ReadableFile r = fs.file("foo.txt").openReadable()) {
        r.read(buf);/*w  w  w .  j av  a2s. co  m*/
    }
    Assert.assertArrayEquals(testContent, buf.array());

    putMethod.releaseConnection();
}

From source file:org.demo.workflow.integration.Helper.java

@SuppressWarnings("deprecation")
public String putTaskProperties(String task_instance_id, String body) throws HttpException, IOException {
    String connectionUrl = replaceTokensInURL(ALF_URL_SERV_WORK_ASSIGN[1], "host", host);
    connectionUrl = replaceTokensInURL(connectionUrl, "task_instance_id", task_instance_id);

    PutMethod method = new PutMethod(connectionUrl);
    method.setDoAuthentication(true);/*from w w w.ja v a2s  . com*/
    method.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
    method.setRequestBody(body);

    client.executeMethod(method);

    String rt = method.getResponseBodyAsString();

    return rt;
}

From source file:org.eclipse.ecf.remoteservice.rest.client.RestClientService.java

protected HttpMethod preparePutMethod(String uri, IRemoteCall call, IRemoteCallable callable)
        throws NotSerializableException {
    PutMethod result = new PutMethod(uri);
    HttpPutRequestType putRequestType = (HttpPutRequestType) callable.getRequestType();

    IRemoteCallParameter[] defaultParameters = callable.getDefaultParameters();
    Object[] parameters = call.getParameters();

    if (putRequestType.useRequestEntity()) {
        if (defaultParameters != null && defaultParameters.length > 0 && parameters != null
                && parameters.length > 0) {
            RequestEntity requestEntity = putRequestType.generateRequestEntity(uri, call, callable,
                    defaultParameters[0], parameters[0]);
            result.setRequestEntity(requestEntity);
        }// ww w  . j  a v a  2s. c om
    } else {
        NameValuePair[] params = toNameValuePairs(uri, call, callable);
        if (params != null)
            result.setQueryString(params);
    }
    return result;
}

From source file:org.eclipse.mylyn.internal.oslc.core.client.AbstractOslcClient.java

protected PutMethod createPutMethod(String requestPath) {
    PutMethod method = new PutMethod(getRequestPath(requestPath));
    method.setFollowRedirects(false);//from www .  j  a v a 2  s.c  o  m
    method.setDoAuthentication(true);
    return method;
}

From source file:org.eclipse.om2m.comm.http.RestHttpClient.java

/**
* Converts a protocol-independent {@link RequestIndication} object into a standard HTTP request and sends a standard HTTP request.
* Converts the received standard HTTP request into {@link ResponseConfirm} object and returns it back.
* @param requestIndication - protocol independent request.
* @return protocol independent response.
*//*w w  w . j a v  a2 s.  c o m*/
public ResponseConfirm sendRequest(RequestIndication requestIndication) {

    logServiceTracker = new ServiceTracker(FrameworkUtil.getBundle(RestHttpClient.class).getBundleContext(),
            org.osgi.service.log.LogService.class.getName(), null);
    logServiceTracker.open();
    logservice = (LogService) logServiceTracker.getService();
    LOGGER.debug("Http Client > " + requestIndication);
    logservice.log(LogService.LOG_ERROR, "Http Client > " + requestIndication);

    HttpClient httpclient = new HttpClient();

    ResponseConfirm responseConfirm = new ResponseConfirm();
    HttpMethod httpMethod = null;
    String url = requestIndication.getUrl();
    if (!url.startsWith(protocol + "://")) {
        url = protocol + "://" + url;
    }
    try {
        switch (requestIndication.getMethod()) {
        case "RETRIEVE":
            httpMethod = new GetMethod(url);
            break;
        case "CREATE":
            httpMethod = new PostMethod(url);

            ((PostMethod) httpMethod).setRequestEntity(
                    new StringRequestEntity(requestIndication.getRepresentation(), "application/xml", "UTF8"));
            break;
        case "UPDATE":
            httpMethod = new PutMethod(url);
            ((PutMethod) httpMethod).setRequestEntity(
                    new StringRequestEntity(requestIndication.getRepresentation(), "application/xml", "UTF8"));
            break;
        case "DELETE":
            httpMethod = new DeleteMethod(url);
            break;
        case "EXECUTE":
            httpMethod = new PostMethod(url);
            break;
        default:
            return new ResponseConfirm();
        }
        httpMethod.addRequestHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64(requestIndication.getRequestingEntity().getBytes())));
        httpMethod.setQueryString(getQueryFromParams(requestIndication.getParameters()));

        int statusCode = httpclient.executeMethod(httpMethod);
        responseConfirm.setStatusCode(getRestStatusCode(statusCode));

        if (statusCode != 204) {
            if (httpMethod.getResponseBody() != null) {
                responseConfirm.setRepresentation(new String(httpMethod.getResponseBody()));
            }
        }
        if (statusCode == 201) {
            if (httpMethod.getResponseHeader("Location").getValue() != null) {
                responseConfirm.setResourceURI(httpMethod.getResponseHeader("Location").getValue());
            }
        }
        //LOGGER.debug("Http Client > "+responseConfirm);
        LOGGER.debug("Http Client > " + responseConfirm);
        logservice.log(LogService.LOG_ERROR, "Http Client > " + responseConfirm);

    } catch (IOException e) {
        LOGGER.error(url + " Not Found" + responseConfirm, e);
        logservice.log(LogService.LOG_ERROR, url + " Not Found" + responseConfirm);

    } finally {
        httpMethod.releaseConnection();
    }

    return responseConfirm;
}