Example usage for org.apache.commons.httpclient.methods HeadMethod releaseConnection

List of usage examples for org.apache.commons.httpclient.methods HeadMethod releaseConnection

Introduction

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

Prototype

@Override
public void releaseConnection() 

Source Link

Document

Releases the connection being used by this HTTP method.

Usage

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java

private int performHead(String uri) throws HttpException, IOException {
    HeadMethod head = new HeadMethod(uri);
    try {//from   w w w  .  j  ava 2s  . co  m
        return getHttpClient().executeMethod(head);
    } finally {
        head.releaseConnection();
    }
}

From source file:org.apache.wink.itest.contextresolver.DepartmentTest.java

/**
 * This will drive several different requests that interact with the
 * Departments resource class./*from w  w  w .j a v a 2s .  c o m*/
 */
public void testDepartmentsResourceJAXB() throws Exception {
    PostMethod postMethod = null;
    GetMethod getAllMethod = null;
    GetMethod getOneMethod = null;
    HeadMethod headMethod = null;
    DeleteMethod deleteMethod = null;
    try {

        // make sure everything is clear before testing
        DepartmentDatabase.clearEntries();

        // create a new Department
        Department newDepartment = new Department();
        newDepartment.setDepartmentId("1");
        newDepartment.setDepartmentName("Marketing");
        JAXBContext context = JAXBContext
                .newInstance(new Class<?>[] { Department.class, DepartmentListWrapper.class });
        Marshaller marshaller = context.createMarshaller();
        StringWriter sw = new StringWriter();
        marshaller.marshal(newDepartment, sw);
        HttpClient client = new HttpClient();
        postMethod = new PostMethod(getBaseURI());
        RequestEntity reqEntity = new ByteArrayRequestEntity(sw.toString().getBytes(), "text/xml");
        postMethod.setRequestEntity(reqEntity);
        client.executeMethod(postMethod);

        newDepartment = new Department();
        newDepartment.setDepartmentId("2");
        newDepartment.setDepartmentName("Sales");
        sw = new StringWriter();
        marshaller.marshal(newDepartment, sw);
        client = new HttpClient();
        postMethod = new PostMethod(getBaseURI());
        reqEntity = new ByteArrayRequestEntity(sw.toString().getBytes(), "text/xml");
        postMethod.setRequestEntity(reqEntity);
        client.executeMethod(postMethod);

        // now let's get the list of Departments that we just created
        // (should be 2)
        client = new HttpClient();
        getAllMethod = new GetMethod(getBaseURI());
        client.executeMethod(getAllMethod);
        byte[] bytes = getAllMethod.getResponseBody();
        assertNotNull(bytes);
        InputStream bais = new ByteArrayInputStream(bytes);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Object obj = unmarshaller.unmarshal(bais);
        assertTrue(obj instanceof DepartmentListWrapper);
        DepartmentListWrapper wrapper = (DepartmentListWrapper) obj;
        List<Department> dptList = wrapper.getDepartmentList();
        assertNotNull(dptList);
        assertEquals(2, dptList.size());

        // now get a specific Department that was created
        client = new HttpClient();
        getOneMethod = new GetMethod(getBaseURI() + "/1");
        client.executeMethod(getOneMethod);
        bytes = getOneMethod.getResponseBody();
        assertNotNull(bytes);
        bais = new ByteArrayInputStream(bytes);
        obj = unmarshaller.unmarshal(bais);
        assertTrue(obj instanceof Department);
        Department dept = (Department) obj;
        assertEquals("1", dept.getDepartmentId());
        assertEquals("Marketing", dept.getDepartmentName());

        // let's send a Head request for both an existent and non-existent
        // resource
        // we are testing to see if header values being set in the resource
        // implementation
        // are sent back appropriately
        client = new HttpClient();
        headMethod = new HeadMethod(getBaseURI() + "/3");
        client.executeMethod(headMethod);
        assertNotNull(headMethod.getResponseHeaders());
        Header header = headMethod.getResponseHeader("unresolved-id");
        assertNotNull(header);
        assertEquals("3", header.getValue());
        headMethod.releaseConnection();

        // now the resource that should exist
        headMethod = new HeadMethod(getBaseURI() + "/1");
        client.executeMethod(headMethod);
        assertNotNull(headMethod.getResponseHeaders());
        header = headMethod.getResponseHeader("resolved-id");
        assertNotNull(header);
        assertEquals("1", header.getValue());

        deleteMethod = new DeleteMethod(getBaseURI() + "/1");
        client.executeMethod(deleteMethod);
        assertEquals(204, deleteMethod.getStatusCode());

        deleteMethod = new DeleteMethod(getBaseURI() + "/2");
        client.executeMethod(deleteMethod);
        assertEquals(204, deleteMethod.getStatusCode());
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
        if (getAllMethod != null) {
            getAllMethod.releaseConnection();
        }
        if (getOneMethod != null) {
            getOneMethod.releaseConnection();
        }
        if (headMethod != null) {
            headMethod.releaseConnection();
        }
        if (deleteMethod != null) {
            deleteMethod.releaseConnection();
        }
    }
}

From source file:org.apache.wink.itest.methodannotations.HttpMethodTest.java

/**
 * Tests that a HEAD request can be sent to resource containing only a GET
 * method.//from   w ww.  ja va2s .c  om
 */
public void testHEADRequest() {
    try {
        HeadMethod httpMethod = new HeadMethod();
        httpMethod.setURI(new URI(BASE_URI, false));
        httpclient = new HttpClient();

        try {
            int result = httpclient.executeMethod(httpMethod);
            System.out.println("Response status code: " + result);
            System.out.println("Response body: ");
            String responseBody = httpMethod.getResponseBodyAsString();
            System.out.println(responseBody);
            assertEquals(200, result);
            assertEquals(null, responseBody);
            Header[] headers = httpMethod.getResponseHeaders();
            assertNotNull(headers);
            assertTrue("Response for HEAD request contained no headers", headers.length > 0);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            fail(ioe.getMessage());
        } finally {
            httpMethod.releaseConnection();
        }
    } catch (URIException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:org.apache.wink.itest.methodannotations.HttpMethodTest.java

/**
 * Tests that a HEAD request can be sent to resource annotated with a custom
 * HEAD annotation./*from  ww w.j av  a  2  s.  c  o m*/
 */
public void testCustomHEADRequest() {
    try {
        HeadMethod httpMethod = new HeadMethod();
        httpMethod.setURI(new URI(ALT_URI, false));
        httpclient = new HttpClient();

        try {
            int result = httpclient.executeMethod(httpMethod);
            System.out.println("Response status code: " + result);
            System.out.println("Response body: ");
            String responseBody = httpMethod.getResponseBodyAsString();
            System.out.println(responseBody);
            assertEquals(200, result);
            assertEquals(null, responseBody);
            Header header = httpMethod.getResponseHeader("HEAD");
            assertNotNull(header);
            assertEquals("TRUE", header.getValue());
        } catch (IOException ioe) {
            ioe.printStackTrace();
            fail(ioe.getMessage());
        } finally {
            httpMethod.releaseConnection();
        }
    } catch (URIException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

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

@Test
public void headSupported() {
    if (logger.isDebugEnabled()) {
        logger.debug(BaseServiceTest.testBanner("headSupported", CLASS_NAME));
    }//from  w w w  .  j a v a  2  s .com
    String url = serviceClient.getBaseURL() + "intakes";
    HeadMethod method = new HeadMethod(url);
    try {
        int statusCode = httpClient.executeMethod(method);
        Assert.assertEquals(method.getResponseBody(), null, "expected null");
        if (logger.isDebugEnabled()) {
            logger.debug("headSupported url=" + url + " status=" + statusCode);
            for (Header h : method.getResponseHeaders()) {
                logger.debug("headSupported header name=" + h.getName() + " value=" + h.getValue());
            }
        }
        Assert.assertEquals(statusCode, HttpStatus.SC_OK, "expected " + HttpStatus.SC_OK);
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: ", e);
    } catch (IOException e) {
        logger.error("Fatal transport error", e);
    } catch (Exception e) {
        logger.error("unknown exception ", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:org.deri.pipes.utils.HttpResponseCache.java

/**
 * @param client/*  ww  w . j  a va 2  s.  c om*/
 * @param location
 * @param location2
 * @return
 */
public static HttpResponseData getResponseData(HttpClient client, String location,
        Map<String, String> requestHeaders) throws Exception {
    synchronized (client) {
        if (MINIMUM_CACHE_TIME_MILLIS <= 0) {
            logger.debug("caching disabled.");
            return getDataFromRequest(client, location, requestHeaders);
        }
        String cacheKey = makeCacheKey(location, requestHeaders);
        if (requestHeaders == null) {
            requestHeaders = new HashMap<String, String>();
        }
        if (requestHeaders.get(HEADER_USER_AGENT) == null) {
            requestHeaders.put(HEADER_USER_AGENT, getDefaultUserAgent());
        }
        JCS jcs = null;
        try {
            jcs = JCS.getInstance("httpResponseCache");
        } catch (Exception e) {
            logger.warn("Problem getting JCS cache" + e, e);
        }
        if (jcs != null) {
            try {
                HttpResponseData data = (HttpResponseData) jcs.get(cacheKey);
                if (data != null) {
                    if (data.getExpires() > System.currentTimeMillis()) {
                        logger.info("Retrieved from cache (not timed out):" + location);
                        return data;
                    }
                    if (location.length() < 2000) {
                        HeadMethod headMethod = new HeadMethod(location);
                        headMethod.setFollowRedirects(true);
                        addRequestHeaders(headMethod, requestHeaders);

                        try {
                            int response = client.executeMethod(headMethod);
                            Header lastModifiedHeader = headMethod.getResponseHeader(HEADER_LAST_MODIFIED);
                            if (response == data.getResponse()) {
                                if (lastModifiedHeader == null) {
                                    logger.debug("Not using cache (No last modified header available) for "
                                            + location);
                                } else if (lastModifiedHeader != null
                                        && data.getLastModified().equals(lastModifiedHeader.getValue())) {
                                    setExpires(data, headMethod);
                                    jcs.put(cacheKey, data);
                                    logger.info("Retrieved from cache (used HTTP HEAD request to check "
                                            + HEADER_LAST_MODIFIED + ") :" + location);
                                    return data;
                                } else {
                                    logger.debug("Not using cache (last modified changed) for " + location);
                                }
                            }
                        } finally {
                            headMethod.releaseConnection();
                        }
                    }

                }
            } catch (Exception e) {
                logger.warn("Problem retrieving from cache for " + location, e);
            }
        }
        HttpResponseData data = getDataFromRequest(client, location, requestHeaders);
        if (jcs != null) {
            try {
                jcs.put(cacheKey, data);
                logger.debug("cached " + location);
            } catch (Exception e) {
                logger.warn("Could not store response for " + location + " in cache", e);
            }
        }

        return data;
    }
}

From source file:org.eclipse.mylyn.internal.discovery.core.util.HttpClientTransportService.java

/**
 * Verify availability of resources at the given web locations. Normally this would be done using an HTTP HEAD.
 * /* w  w  w  . j a va2s. c o  m*/
 * @param locations
 *            the locations of the resource to verify
 * @param one
 *            indicate if only one of the resources must exist
 * @param monitor
 *            the monitor
 * @return true if the resource exists
 */
public long getLastModified(java.net.URI uri, IProgressMonitor monitor) throws CoreException, IOException {
    WebLocation location = new WebLocation(uri.toString());
    monitor = Policy.monitorFor(monitor);
    monitor.beginTask(NLS.bind(Messages.WebUtil_task_retrievingUrl, location.getUrl()),
            IProgressMonitor.UNKNOWN);
    try {
        HttpClient client = new HttpClient();
        org.eclipse.mylyn.commons.net.WebUtil.configureHttpClient(client, ""); //$NON-NLS-1$

        HeadMethod method = new HeadMethod(location.getUrl());
        try {
            HostConfiguration hostConfiguration = org.eclipse.mylyn.commons.net.WebUtil
                    .createHostConfiguration(client, location, monitor);
            int result = org.eclipse.mylyn.commons.net.WebUtil.execute(client, hostConfiguration, method,
                    monitor);
            if (result == HttpStatus.SC_OK) {
                Header lastModified = method.getResponseHeader("Last-Modified"); //$NON-NLS-1$
                if (lastModified != null) {
                    try {
                        return DateUtil.parseDate(lastModified.getValue()).getTime();
                    } catch (DateParseException e) {
                        // fall through
                    }
                }
                return 0;
            } else if (result == HttpStatus.SC_NOT_FOUND) {
                throw new FileNotFoundException(
                        NLS.bind(Messages.WebUtil_cannotDownload, location.getUrl(), result));
            } else {
                throw new IOException(NLS.bind(Messages.WebUtil_cannotDownload, location.getUrl(), result));
            }
        } finally {
            method.releaseConnection();
        }
    } finally {
        monitor.done();
    }
}

From source file:org.eclipse.mylyn.internal.jira.core.service.web.JiraWebClient.java

private void watchUnwatchIssue(final JiraIssue issue, final boolean watch, IProgressMonitor monitor)
        throws JiraException {
    doInSession(monitor, new JiraWebSessionCallback() {
        @Override/*from  w ww . ja v  a  2  s  .  c  o  m*/
        public void run(JiraClient server, String baseUrl, IProgressMonitor monitor) throws JiraException {
            StringBuilder urlBuffer = new StringBuilder(baseUrl);
            urlBuffer.append("/browse/").append(issue.getKey()); //$NON-NLS-1$
            urlBuffer.append("?watch=").append(Boolean.toString(watch)); //$NON-NLS-1$

            HeadMethod head = new HeadMethod(urlBuffer.toString());
            try {
                int result = execute(head);
                if (result != HttpStatus.SC_OK) {
                    throw new JiraException("Changing watch status failed. Return code: " + result); //$NON-NLS-1$
                }
            } finally {
                head.releaseConnection();
            }
        }

    });
}

From source file:org.eclipse.mylyn.internal.jira.core.service.web.JiraWebClient.java

private void voteUnvoteIssue(final JiraIssue issue, final boolean vote, IProgressMonitor monitor)
        throws JiraException {
    doInSession(monitor, new JiraWebSessionCallback() {

        @Override//from w  ww. j a  v  a  2s .c om
        public void run(JiraClient server, String baseUrl, IProgressMonitor monitor) throws JiraException {
            StringBuilder urlBuffer = new StringBuilder(baseUrl);
            urlBuffer.append("/browse/").append(issue.getKey()); //$NON-NLS-1$
            urlBuffer.append("?vote=").append(vote ? "vote" : "unvote"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

            HeadMethod head = new HeadMethod(urlBuffer.toString());
            try {
                int result = execute(head);
                if (result != HttpStatus.SC_OK) {
                    throw new JiraException("Changing vote failed. Return code: " + result); //$NON-NLS-1$
                }
            } finally {
                head.releaseConnection();
            }
        }

    });
}

From source file:org.exist.xquery.modules.httpclient.HEADFunction.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    Sequence response = null;//from w  w  w  .  jav a2s  . com

    // must be a URL
    if (args[0].isEmpty()) {
        return (Sequence.EMPTY_SEQUENCE);
    }

    //get the url
    String url = args[0].itemAt(0).getStringValue();

    //get the persist state
    boolean persistState = args[1].effectiveBooleanValue();

    //setup HEAD request
    HeadMethod head = new HeadMethod(url);

    //setup HEAD Request Headers
    if (!args[2].isEmpty()) {
        setHeaders(head, ((NodeValue) args[2].itemAt(0)).getNode());
    }

    try {

        //execute the request
        response = doRequest(context, head, persistState, null, null);
    } catch (IOException ioe) {
        throw (new XPathException(this, ioe.getMessage(), ioe));
    } finally {
        head.releaseConnection();
    }

    return (response);
}