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.apache.jackrabbit.webdav.server.BindTest.java

public void testBindCollections() throws Exception {
    String testcol = this.root + "testBindCollections/";
    String a1 = testcol + "a1/";
    String b1 = a1 + "b1/";
    String c1 = b1 + "c1/";
    String x1 = c1 + "x1";
    String a2 = testcol + "a2/";
    String b2 = a2 + "b2/";
    String c2 = b2 + "c2/";
    String x2 = c2 + "x2";
    int status;/*  w ww . j a v  a  2 s  .  c o  m*/
    try {
        MkColMethod mkcol = new MkColMethod(testcol);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);
        mkcol = new MkColMethod(a1);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);
        mkcol = new MkColMethod(a2);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);

        //create collection resource C
        mkcol = new MkColMethod(b1);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);
        mkcol = new MkColMethod(c1);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);

        //create plain resource R
        PutMethod put = new PutMethod(x1);
        put.setRequestEntity(new StringRequestEntity("foo", "text/plain", "UTF-8"));
        status = this.client.executeMethod(put);
        assertEquals(201, status);

        //create new binding of C with path a2/b2
        DavMethodBase bind = new BindMethod(a2, new BindInfo(b1, "b2"));
        status = this.client.executeMethod(bind);
        assertEquals(201, status);
        //check if both bindings report the same DAV:resource-id
        assertEquals(this.getResourceId(b1), this.getResourceId(b2));

        mkcol = new MkColMethod(c2);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);

        //create new binding of R with path a2/b2/c2/r2
        bind = new BindMethod(c2, new BindInfo(x1, "x2"));
        status = this.client.executeMethod(bind);
        assertEquals(201, status);
        //check if both bindings report the same DAV:resource-id
        assertEquals(this.getResourceId(x1), this.getResourceId(x2));

        //verify different path alternatives
        URI rid = this.getResourceId(x1);
        assertEquals(rid, this.getResourceId(x2));
        assertEquals(rid, this.getResourceId(testcol + "a2/b2/c1/x1"));
        assertEquals(rid, this.getResourceId(testcol + "a1/b1/c2/x2"));
        Object ps = this.getParentSet(x1).getValue();
        assertTrue(ps instanceof List);
        assertEquals(2, ((List) ps).size());
        ps = this.getParentSet(x2).getValue();
        assertTrue(ps instanceof List);
        assertEquals(2, ((List) ps).size());
    } finally {
        DeleteMethod delete = new DeleteMethod(testcol);
        status = this.client.executeMethod(delete);
        assertTrue("status: " + status, status == 200 || status == 204);
    }
}

From source file:org.apache.jackrabbit.webdav.server.BindTest.java

public void testUnbind() throws Exception {
    String testcol = this.root + "testUnbind/";
    String subcol1 = testcol + "bindtest1/";
    String testres1 = subcol1 + "res1";
    String subcol2 = testcol + "bindtest2/";
    String testres2 = subcol2 + "res2";
    int status;//w  w  w .  j av  a 2s. c o  m
    try {
        MkColMethod mkcol = new MkColMethod(testcol);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);
        mkcol = new MkColMethod(subcol1);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);
        mkcol = new MkColMethod(subcol2);
        status = this.client.executeMethod(mkcol);
        assertEquals(201, status);

        //create new resource R with path testSimpleBind/bindtest1/res1
        PutMethod put = new PutMethod(testres1);
        put.setRequestEntity(new StringRequestEntity("foo", "text/plain", "UTF-8"));
        status = this.client.executeMethod(put);
        assertEquals(201, status);

        //create new binding of R with path testSimpleBind/bindtest2/res2
        DavMethodBase bind = new BindMethod(subcol2, new BindInfo(testres1, "res2"));
        status = this.client.executeMethod(bind);
        assertEquals(201, status);
        //check if both bindings report the same DAV:resource-id
        assertEquals(this.getResourceId(testres1), this.getResourceId(testres2));

        //remove new path
        UnbindMethod unbind = new UnbindMethod(subcol2, new UnbindInfo("res2"));
        status = this.client.executeMethod(unbind);
        assertTrue("status: " + status, status == 200 || status == 204);

        //verify that the new binding is gone
        HeadMethod head = new HeadMethod(testres2);
        status = this.client.executeMethod(head);
        assertEquals(404, status);

        //verify that the initial binding is still there
        head = new HeadMethod(testres1);
        status = this.client.executeMethod(head);
        assertEquals(200, status);
    } finally {
        DeleteMethod delete = new DeleteMethod(testcol);
        status = this.client.executeMethod(delete);
        assertTrue("status: " + status, status == 200 || status == 204);
    }
}

From source file:org.apache.jackrabbit.webdav.server.RFC4918DestinationHeaderTest.java

public void testMove() throws HttpException, IOException, DavException, URISyntaxException {

    String testuri = this.root + "movetest";
    String destinationuri = testuri + "2";
    String destinationpath = new URI(destinationuri).getRawPath();
    // make sure the scheme is removed
    assertFalse(destinationpath.contains(":"));

    int status;/* w  w w .j  a v a  2 s .c om*/
    try {
        PutMethod put = new PutMethod(testuri);
        status = this.client.executeMethod(put);
        assertTrue("status: " + status, status == 200 || status == 201 || status == 204);

        // try to move outside the servlet's name space
        MoveMethod move = new MoveMethod(testuri, "/foobar", true);
        status = this.client.executeMethod(move);
        assertTrue("status: " + status, status == 403);

        // try a relative path
        move = new MoveMethod(testuri, "foobar", true);
        status = this.client.executeMethod(move);
        assertTrue("status: " + status, status == 400);

        move = new MoveMethod(testuri, destinationpath, true);
        status = this.client.executeMethod(move);
        assertTrue("status: " + status, status == 200 || status == 201 || status == 204);

        HeadMethod head = new HeadMethod(destinationuri);
        status = this.client.executeMethod(head);
        assertTrue("status: " + status, status == 200);

        head = new HeadMethod(testuri);
        status = this.client.executeMethod(head);
        assertTrue("status: " + status, status == 404);

    } finally {
        DeleteMethod delete = new DeleteMethod(testuri);
        status = this.client.executeMethod(delete);
        assertTrue("status: " + status, status == 200 || status == 204 || status == 404);
        delete = new DeleteMethod(destinationuri);
        status = this.client.executeMethod(delete);
        assertTrue("status: " + status, status == 200 || status == 204 || status == 404);
    }
}

From source file:org.apache.jackrabbit.webdav.server.RFC4918IfHeaderTest.java

public void testPutIfEtag() throws HttpException, IOException, DavException, URISyntaxException {

    String testuri = this.root + "iftest";

    int status;//  w w w .ja v a  2 s .c o  m
    try {
        PutMethod put = new PutMethod(testuri);
        String condition = "<" + testuri + "> ([" + "\"an-etag-this-testcase-invented\"" + "])";
        put.setRequestEntity(new StringRequestEntity("1"));
        put.setRequestHeader("If", condition);
        status = this.client.executeMethod(put);
        assertEquals("status: " + status, 412, status);
    } finally {
        DeleteMethod delete = new DeleteMethod(testuri);
        status = this.client.executeMethod(delete);
        assertTrue("status: " + status, status == 200 || status == 204 || status == 404);
    }
}

From source file:org.apache.jackrabbit.webdav.server.RFC4918IfHeaderTest.java

public void testPutIfLockToken() throws HttpException, IOException, DavException, URISyntaxException {

    String testuri = this.root + "iflocktest";
    String locktoken = null;/*from   w ww  .  j a v a 2  s. com*/

    int status;
    try {
        PutMethod put = new PutMethod(testuri);
        put.setRequestEntity(new StringRequestEntity("1"));
        status = this.client.executeMethod(put);
        assertTrue("status: " + status, status == 200 || status == 201 || status == 204);

        LockMethod lock = new LockMethod(testuri,
                new LockInfo(Scope.EXCLUSIVE, Type.WRITE, "testcase", 10000, true));
        status = this.client.executeMethod(lock);
        assertEquals("status", 200, status);
        locktoken = lock.getLockToken();
        assertNotNull(locktoken);

        // try to overwrite without lock token
        put = new PutMethod(testuri);
        put.setRequestEntity(new StringRequestEntity("2"));
        status = this.client.executeMethod(put);
        assertEquals("status: " + status, 423, status);

        // try to overwrite using bad lock token
        put = new PutMethod(testuri);
        put.setRequestEntity(new StringRequestEntity("2"));
        put.setRequestHeader("If", "(<" + "DAV:foobar" + ">)");
        status = this.client.executeMethod(put);
        assertEquals("status: " + status, 412, status);

        // try to overwrite using correct lock token, using  No-Tag-list format
        put = new PutMethod(testuri);
        put.setRequestEntity(new StringRequestEntity("2"));
        put.setRequestHeader("If", "(<" + locktoken + ">)");
        status = this.client.executeMethod(put);
        assertTrue("status: " + status, status == 200 || status == 204);

        // try to overwrite using correct lock token, using Tagged-list format
        // and full URI
        put = new PutMethod(testuri);
        put.setRequestEntity(new StringRequestEntity("3"));
        put.setRequestHeader("If", "<" + testuri + ">" + "(<" + locktoken + ">)");
        status = this.client.executeMethod(put);
        assertTrue("status: " + status, status == 200 || status == 204);

        // try to overwrite using correct lock token, using Tagged-list format
        // and absolute path only
        put = new PutMethod(testuri);
        put.setRequestEntity(new StringRequestEntity("4"));
        put.setRequestHeader("If", "<" + new URI(testuri).getRawPath() + ">" + "(<" + locktoken + ">)");
        status = this.client.executeMethod(put);
        assertTrue("status: " + status, status == 200 || status == 204);

        // try to overwrite using correct lock token, using Tagged-list format
        // and bad path
        put = new PutMethod(testuri);
        put.setRequestEntity(new StringRequestEntity("5"));
        put.setRequestHeader("If", "</foobar>" + "(<" + locktoken + ">)");
        status = this.client.executeMethod(put);
        assertTrue("status: " + status, status == 404 || status == 412);
    } finally {
        DeleteMethod delete = new DeleteMethod(testuri);
        if (locktoken != null) {
            delete.setRequestHeader("If", "(<" + locktoken + ">)");
        }
        status = this.client.executeMethod(delete);
        assertTrue("status: " + status, status == 200 || status == 204 || status == 404);
    }
}

From source file:org.apache.jackrabbit.webdav.server.RFC4918PropfindTest.java

public void testPropfindInclude() throws HttpException, IOException, DavException, URISyntaxException {

    String testuri = this.root + "iftest";

    int status;//w  w  w  .j a  v a2  s.c  o m
    try {
        PutMethod put = new PutMethod(testuri);
        put.setRequestEntity(new StringRequestEntity("1"));
        status = this.client.executeMethod(put);
        assertEquals("status: " + status, 201, status);

        DavPropertyNameSet names = new DavPropertyNameSet();
        names.add(DeltaVConstants.COMMENT);
        PropFindMethod propfind = new PropFindMethod(testuri, DavConstants.PROPFIND_ALL_PROP_INCLUDE, names, 0);
        status = client.executeMethod(propfind);
        assertEquals(207, status);

        MultiStatus multistatus = propfind.getResponseBodyAsMultiStatus();
        MultiStatusResponse[] responses = multistatus.getResponses();
        assertEquals(1, responses.length);

        MultiStatusResponse response = responses[0];
        DavPropertySet found = response.getProperties(200);
        DavPropertySet notfound = response.getProperties(404);

        assertTrue(found.contains(DeltaVConstants.COMMENT) || notfound.contains(DeltaVConstants.COMMENT));
    } finally {
        DeleteMethod delete = new DeleteMethod(testuri);
        status = this.client.executeMethod(delete);
        assertTrue("status: " + status, status == 200 || status == 204 || status == 404);
    }
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

/**
 * Samples the URL passed in and stores the result in
 * <code>HTTPSampleResult</code>, following redirects and downloading
 * page resources as appropriate.//from w w  w . j  ava2  s  .  c o  m
 * <p>
 * When getting a redirect target, redirects are not followed and resources
 * are not downloaded. The caller will take care of this.
 *
 * @param url
 *            URL to sample
 * @param method
 *            HTTP method: GET, POST,...
 * @param areFollowingRedirect
 *            whether we're getting a redirect target
 * @param frameDepth
 *            Depth of this target in the frame structure. Used only to
 *            prevent infinite recursion.
 * @return results of the sampling
 */
@Override
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {

    String urlStr = url.toString();

    if (log.isDebugEnabled()) {
        log.debug("Start : sample " + urlStr);
        log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth);
    }

    HttpMethodBase httpMethod = null;

    HTTPSampleResult res = new HTTPSampleResult();
    res.setMonitor(isMonitor());

    res.setSampleLabel(urlStr); // May be replaced later
    res.setHTTPMethod(method);
    res.setURL(url);

    res.sampleStart(); // Count the retries as well in the time
    try {
        // May generate IllegalArgumentException
        if (method.equals(HTTPConstants.POST)) {
            httpMethod = new PostMethod(urlStr);
        } else if (method.equals(HTTPConstants.GET)) {
            httpMethod = new GetMethod(urlStr);
        } else if (method.equals(HTTPConstants.PUT)) {
            httpMethod = new PutMethod(urlStr);
        } else if (method.equals(HTTPConstants.HEAD)) {
            httpMethod = new HeadMethod(urlStr);
        } else if (method.equals(HTTPConstants.TRACE)) {
            httpMethod = new TraceMethod(urlStr);
        } else if (method.equals(HTTPConstants.OPTIONS)) {
            httpMethod = new OptionsMethod(urlStr);
        } else if (method.equals(HTTPConstants.DELETE)) {
            httpMethod = new EntityEnclosingMethod(urlStr) {
                @Override
                public String getName() { // HC3.1 does not have the method
                    return HTTPConstants.DELETE;
                }
            };
        } else if (method.equals(HTTPConstants.PATCH)) {
            httpMethod = new EntityEnclosingMethod(urlStr) {
                @Override
                public String getName() { // HC3.1 does not have the method
                    return HTTPConstants.PATCH;
                }
            };
        } else {
            throw new IllegalArgumentException("Unexpected method: '" + method + "'");
        }

        final CacheManager cacheManager = getCacheManager();
        if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) {
            if (cacheManager.inCache(url)) {
                return updateSampleResultForResourceInCache(res);
            }
        }

        // Set any default request headers
        setDefaultRequestHeaders(httpMethod);

        // Setup connection
        HttpClient client = setupConnection(url, httpMethod, res);
        savedClient = client;

        // Handle the various methods
        if (method.equals(HTTPConstants.POST)) {
            String postBody = sendPostData((PostMethod) httpMethod);
            res.setQueryString(postBody);
        } else if (method.equals(HTTPConstants.PUT) || method.equals(HTTPConstants.PATCH)
                || method.equals(HTTPConstants.DELETE)) {
            String putBody = sendEntityData((EntityEnclosingMethod) httpMethod);
            res.setQueryString(putBody);
        }

        int statusCode = client.executeMethod(httpMethod);

        // We've finished with the request, so we can add the LocalAddress to it for display
        final InetAddress localAddr = client.getHostConfiguration().getLocalAddress();
        if (localAddr != null) {
            httpMethod.addRequestHeader(HEADER_LOCAL_ADDRESS, localAddr.toString());
        }
        // Needs to be done after execute to pick up all the headers
        res.setRequestHeaders(getConnectionHeaders(httpMethod));

        // Request sent. Now get the response:
        InputStream instream = httpMethod.getResponseBodyAsStream();

        if (instream != null) {// will be null for HEAD
            instream = new CountingInputStream(instream);
            try {
                Header responseHeader = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
                if (responseHeader != null && HTTPConstants.ENCODING_GZIP.equals(responseHeader.getValue())) {
                    InputStream tmpInput = new GZIPInputStream(instream); // tmp inputstream needs to have a good counting
                    res.setResponseData(
                            readResponse(res, tmpInput, (int) httpMethod.getResponseContentLength()));
                } else {
                    res.setResponseData(
                            readResponse(res, instream, (int) httpMethod.getResponseContentLength()));
                }
            } finally {
                JOrphanUtils.closeQuietly(instream);
            }
        }

        res.sampleEnd();
        // Done with the sampling proper.

        // Now collect the results into the HTTPSampleResult:

        res.setSampleLabel(httpMethod.getURI().toString());
        // Pick up Actual path (after redirects)

        res.setResponseCode(Integer.toString(statusCode));
        res.setSuccessful(isSuccessCode(statusCode));

        res.setResponseMessage(httpMethod.getStatusText());

        String ct = null;
        Header h = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        if (h != null)// Can be missing, e.g. on redirect
        {
            ct = h.getValue();
            res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1
            res.setEncodingAndType(ct);
        }

        res.setResponseHeaders(getResponseHeaders(httpMethod));
        if (res.isRedirect()) {
            final Header headerLocation = httpMethod.getResponseHeader(HTTPConstants.HEADER_LOCATION);
            if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
                throw new IllegalArgumentException("Missing location header");
            }
            String redirectLocation = headerLocation.getValue();
            res.setRedirectLocation(redirectLocation); // in case sanitising fails
        }

        // record some sizes to allow HTTPSampleResult.getBytes() with different options
        if (instream != null) {
            res.setBodySize(((CountingInputStream) instream).getCount());
        }
        res.setHeadersSize(calculateHeadersSize(httpMethod));
        if (log.isDebugEnabled()) {
            log.debug("Response headersSize=" + res.getHeadersSize() + " bodySize=" + res.getBodySize()
                    + " Total=" + (res.getHeadersSize() + res.getBodySize()));
        }

        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            res.setURL(new URL(httpMethod.getURI().toString()));
        }

        // Store any cookies received in the cookie manager:
        saveConnectionCookies(httpMethod, res.getURL(), getCookieManager());

        // Save cache information
        if (cacheManager != null) {
            cacheManager.saveDetails(httpMethod, res);
        }

        // Follow redirects and download page resources if appropriate:
        res = resultProcessing(areFollowingRedirect, frameDepth, res);

        log.debug("End : sample");
        return res;
    } catch (IllegalArgumentException e) { // e.g. some kinds of invalid URL
        res.sampleEnd();
        // pick up headers if failed to execute the request
        // httpMethod can be null if method is unexpected
        if (httpMethod != null) {
            res.setRequestHeaders(getConnectionHeaders(httpMethod));
        }
        errorResult(e, res);
        return res;
    } catch (IOException e) {
        res.sampleEnd();
        // pick up headers if failed to execute the request
        // httpMethod cannot be null here, otherwise 
        // it would have been caught in the previous catch block
        res.setRequestHeaders(getConnectionHeaders(httpMethod));
        errorResult(e, res);
        return res;
    } finally {
        savedClient = null;
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:org.apache.jmeter.protocol.oauth.sampler.OAuthSampler.java

/**
 * Samples the URL passed in and stores the result in
 * <code>HTTPSampleResult</code>, following redirects and downloading
 * page resources as appropriate./*from  ww  w  .  j  a  v  a 2 s  .  c  om*/
 * <p>
 * When getting a redirect target, redirects are not followed and resources
 * are not downloaded. The caller will take care of this.
 * 
 * @param url
 *            URL to sample
 * @param method
 *            HTTP method: GET, POST,...
 * @param areFollowingRedirect
 *            whether we're getting a redirect target
 * @param frameDepth
 *            Depth of this target in the frame structure. Used only to
 *            prevent infinite recursion.
 * @return results of the sampling
 */
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {

    String urlStr = url.toExternalForm();

    // Check if this is an entity-enclosing method
    boolean isPost = method.equals(POST) || method.equals(PUT);

    HTTPSampleResult res = new HTTPSampleResult();
    res.setMonitor(isMonitor());

    // Handles OAuth signing
    try {
        message = getOAuthMessage(url, method);

        urlStr = message.URL;

        if (isPost) {
            urlStr = message.URL;
        } else {
            if (useAuthHeader)
                urlStr = OAuth.addParameters(message.URL, nonOAuthParams);
            else
                urlStr = OAuth.addParameters(message.URL, message.getParameters());
        }
    } catch (IOException e) {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$
        return err;
    } catch (OAuthException e) {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$
        return err;
    } catch (URISyntaxException e) {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$
        return err;
    }

    log.debug("Start : sample " + urlStr); //$NON-NLS-1$
    log.debug("method " + method); //$NON-NLS-1$

    HttpMethodBase httpMethod = null;
    res.setSampleLabel(urlStr); // May be replaced later
    res.setHTTPMethod(method);
    res.sampleStart(); // Count the retries as well in the time
    HttpClient client = null;
    InputStream instream = null;

    try {
        // May generate IllegalArgumentException
        if (method.equals(POST)) {
            httpMethod = new PostMethod(urlStr);
        } else if (method.equals(PUT)) {
            httpMethod = new PutMethod(urlStr);
        } else if (method.equals(HEAD)) {
            httpMethod = new HeadMethod(urlStr);
        } else if (method.equals(TRACE)) {
            httpMethod = new TraceMethod(urlStr);
        } else if (method.equals(OPTIONS)) {
            httpMethod = new OptionsMethod(urlStr);
        } else if (method.equals(DELETE)) {
            httpMethod = new DeleteMethod(urlStr);
        } else if (method.equals(GET)) {
            httpMethod = new GetMethod(urlStr);
        } else {
            log.error("Unexpected method (converted to GET): " + method); //$NON-NLS-1$
            httpMethod = new GetMethod(urlStr);
        }

        // Set any default request headers
        setDefaultRequestHeaders(httpMethod);
        // Setup connection
        client = setupConnection(new URL(urlStr), httpMethod, res);
        // Handle POST and PUT
        if (isPost) {
            String postBody = sendPostData(httpMethod);
            res.setQueryString(postBody);
        }

        res.setRequestHeaders(getConnectionHeaders(httpMethod));

        int statusCode = client.executeMethod(httpMethod);

        // Request sent. Now get the response:
        instream = httpMethod.getResponseBodyAsStream();

        if (instream != null) {// will be null for HEAD

            Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING);
            if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) {
                instream = new GZIPInputStream(instream);
            }
            res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength()));
        }

        res.sampleEnd();
        // Done with the sampling proper.

        // Now collect the results into the HTTPSampleResult:

        res.setSampleLabel(httpMethod.getURI().toString());
        // Pick up Actual path (after redirects)

        res.setResponseCode(Integer.toString(statusCode));
        res.setSuccessful(isSuccessCode(statusCode));

        res.setResponseMessage(httpMethod.getStatusText());

        String ct = null;
        org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE);
        if (h != null)// Can be missing, e.g. on redirect
        {
            ct = h.getValue();
            res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1
            res.setEncodingAndType(ct);
        }

        res.setResponseHeaders(getResponseHeaders(httpMethod));
        if (res.isRedirect()) {
            final Header headerLocation = httpMethod.getResponseHeader(HEADER_LOCATION);
            if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
                throw new IllegalArgumentException("Missing location header"); //$NON-NLS-1$
            }
            res.setRedirectLocation(headerLocation.getValue());
        }

        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            res.setURL(new URL(httpMethod.getURI().toString()));
        }

        // Store any cookies received in the cookie manager:
        saveConnectionCookies(httpMethod, res.getURL(), getCookieManager());

        // Save cache information
        final CacheManager cacheManager = getCacheManager();
        if (cacheManager != null) {
            cacheManager.saveDetails(httpMethod, res);
        }

        // Follow redirects and download page resources if appropriate:
        res = resultProcessing(areFollowingRedirect, frameDepth, res);

        log.debug("End : sample"); //$NON-NLS-1$
        httpMethod.releaseConnection();
        return res;
    } catch (IllegalArgumentException e)// e.g. some kinds of invalid URL
    {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$
        return err;
    } catch (IOException e) {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$
        return err;
    } finally {
        JOrphanUtils.closeQuietly(instream);
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:org.apache.manifoldcf.examples.ManifoldCFAPIConnect.java

/** Perform an API PUT operation.
*@param restPath is the URL path of the REST object, starting with "/".
*@param input is the input JSON.//  w  ww  . j a  va  2 s  . c  om
*@return the json response.
*/
public String performAPIRawPutOperation(String restPath, String input) throws IOException {
    HttpClient client = new HttpClient();
    PutMethod method = new PutMethod(formURL(restPath));
    method.setRequestHeader("Content-type", "text/plain; charset=UTF-8");
    method.setRequestBody(input);
    int response = client.executeMethod(method);
    byte[] responseData = method.getResponseBody();
    // We presume that the data is utf-8, since that's what the API
    // uses throughout.
    String responseString = new String(responseData, "utf-8");
    if (response != HttpStatus.SC_OK && response != HttpStatus.SC_CREATED)
        throw new IOException("API http error; expected " + HttpStatus.SC_OK + " or " + HttpStatus.SC_CREATED
                + ", saw " + Integer.toString(response) + ": " + responseString);
    return responseString;
}

From source file:org.apache.maven.wagon.providers.webdav.AbstractHttpClientWagon.java

private void put(Resource resource, File source, RequestEntityImplementation requestEntityImplementation,
        String url) throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException {

    // preemptive true for put
    client.getParams().setAuthenticationPreemptive(true);

    //Parent directories need to be created before posting
    try {// ww  w  .  j ava 2 s.c om
        mkdirs(PathUtils.dirname(resource.getName()));
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);
    }

    PutMethod putMethod = new PutMethod(url);

    firePutStarted(resource, source);

    try {
        putMethod.setRequestEntity(requestEntityImplementation);

        int statusCode;
        try {
            statusCode = execute(putMethod);

        } catch (IOException e) {
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);

            throw new TransferFailedException(e.getMessage(), e);
        }

        fireTransferDebug(url + " - Status code: " + statusCode);

        // Check that we didn't run out of retries.
        switch (statusCode) {
        // Success Codes
        case HttpStatus.SC_OK: // 200
        case HttpStatus.SC_CREATED: // 201
        case HttpStatus.SC_ACCEPTED: // 202
        case HttpStatus.SC_NO_CONTENT: // 204
            break;

        // handle all redirect even if http specs says " the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user"
        case HttpStatus.SC_MOVED_PERMANENTLY: // 301
        case HttpStatus.SC_MOVED_TEMPORARILY: // 302
        case HttpStatus.SC_SEE_OTHER: // 303
            String relocatedUrl = calculateRelocatedUrl(putMethod);
            fireTransferDebug("relocate to " + relocatedUrl);
            put(resource, source, requestEntityImplementation, relocatedUrl);
            return;

        case SC_NULL: {
            TransferFailedException e = new TransferFailedException("Failed to transfer file: " + url);
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);
            throw e;
        }

        case HttpStatus.SC_FORBIDDEN:
            fireSessionConnectionRefused();
            throw new AuthorizationException("Access denied to: " + url);

        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceDoesNotExistException("File: " + url + " does not exist");

            //add more entries here
        default: {
            TransferFailedException e = new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);
            throw e;
        }
        }

        firePutCompleted(resource, source);
    } finally {
        putMethod.releaseConnection();
    }
}