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

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

Introduction

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

Prototype

@Override
public Header getResponseHeader(String headerName) 

Source Link

Document

Gets the response header associated with the given name.

Usage

From source file:opendap.gateway.BesGatewayApi.java

@Override
public boolean getCatalog(String dataSourceUrl, Document response)
        throws PPTException, BadConfigurationException, IOException, JDOMException {

    // Go get the HEAD for the catalog:
    HttpClient httpClient = new HttpClient();
    HeadMethod headReq = new HeadMethod(dataSourceUrl);

    try {//from   w ww.  ja v a  2s  .c  o m
        int statusCode = httpClient.executeMethod(headReq);

        if (statusCode != HttpStatus.SC_OK) {
            log.error("Unable to HEAD s3 object: " + dataSourceUrl);
            Dap4Error error = new Dap4Error();
            error.setMessage("OLFS: Unable to access requested resource.");
            error.setContext(dataSourceUrl);
            error.setHttpCode(statusCode);

            return false;
        }

        Header lastModifiedHeader = headReq.getResponseHeader("Last-Modified");
        if (lastModifiedHeader == null) {
            return false;
        }
        String lmtString = lastModifiedHeader.getValue();
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
        Date lastModified = format.parse(lmtString);

        int size = -1;
        Header contentLengthHeader = headReq.getResponseHeader("Content-Length");

        if (contentLengthHeader != null) {
            String sizeStr = contentLengthHeader.getValue();
            try {
                size = Integer.parseInt(sizeStr);
            } catch (NumberFormatException nfe) {
                log.warn("Received invalid content length from datasource: {}: ", dataSourceUrl);
            }
        }

        Element catalogElement = getShowCatalogResponseDocForDatasetUrl(dataSourceUrl, size, lastModified);

        response.detachRootElement();
        response.setRootElement(catalogElement);

        return true;

    } catch (Exception e) {
        log.error("Unable to HEAD the s3 resource: {} Error Msg: {}", dataSourceUrl, e.getMessage());
    }

    return false;

}

From source file:opendap.noaa_s3.S3BesApi.java

/**
 * Returns the last modified time of the remote resource identified by the passed remote resource URL.
 *
 * @param remoteResourceUrl The remote resource URL to check.
 * @return The last-modified time OR -1 if the last modified was not available for any reason (including a
 * not found - 404)/*from   ww  w. j  av a 2 s.  c  om*/
 */
private long getLastModified(String remoteResourceUrl) {

    // @TODO Cache this! We do this for every response  - we should just read it from the index files
    // (cause it's already there) and then we can focus on caching/updating/refreshing just the catalog index.

    log.debug("getLastModified() - remoteResourceUrl: " + remoteResourceUrl);

    // Try to get it from the request cache.
    String lmt_cache_key = remoteResourceUrl + "_last-modified";
    Long lmt = (Long) RequestCache.get(lmt_cache_key);
    if (lmt != null) {
        log.debug("getLastModified() - using cached lmt: {}", lmt);
        return lmt;
    }

    // It's not in the cache so hop to it!

    long lastModifiedTime;

    try {
        // Go get the HEAD for the catalog:
        HttpClient httpClient = new HttpClient();
        HeadMethod headReq = new HeadMethod(remoteResourceUrl);

        try {
            int statusCode = httpClient.executeMethod(headReq);

            if (statusCode != HttpStatus.SC_OK) {
                log.error("getLastModified() - Unable to HEAD s3 object: " + remoteResourceUrl);
                lastModifiedTime = -1;
            } else {
                log.debug("getLastModified(): Executed HTTP HEAD for " + remoteResourceUrl);

                Header lastModifiedHeader = headReq.getResponseHeader("Last-Modified");

                if (lastModifiedHeader == null) {
                    lastModifiedTime = -1;
                } else {
                    String lmtString = lastModifiedHeader.getValue();
                    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
                    Date d = format.parse(lmtString);
                    lastModifiedTime = d.getTime();
                }
            }

        } catch (Exception e) {
            log.error("Unable to HEAD the s3 resource: {} Error Msg: {}", remoteResourceUrl, e.getMessage());
            lastModifiedTime = -1;
        }

    } catch (Exception e) {
        log.debug("getLastModified(): Returning: -1");
        lastModifiedTime = -1;
    }

    RequestCache.put(lmt_cache_key, lastModifiedTime);

    return lastModifiedTime;

}

From source file:org.apache.jackrabbit.spi2davex.ValueLoader.java

public Map<String, String> loadHeaders(String uri, String[] headerNames)
        throws IOException, RepositoryException {
    HeadMethod method = new HeadMethod(uri);
    try {//w w w.  jav  a2 s  . c  o m
        int statusCode = client.executeMethod(method);
        if (statusCode == DavServletResponse.SC_OK) {
            Map<String, String> headers = new HashMap<String, String>();
            for (String name : headerNames) {
                Header hdr = method.getResponseHeader(name);
                if (hdr != null) {
                    headers.put(name, hdr.getValue());
                }
            }
            return headers;
        } else {
            throw ExceptionConverter.generate(new DavException(statusCode, ("Unable to load headers at " + uri
                    + " - Status line = " + method.getStatusLine().toString())));
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:org.apache.maven.proxy.config.HttpRepoConfiguration.java

/**
 * @param method//from  w ww  . j  ava 2s  . co  m
 * @return
 */
private long getContentLength(HeadMethod method) {
    Header contentLengthHeader = method.getResponseHeader("Content-Length");
    if (contentLengthHeader == null) {
        return -1L;
    }
    String lastModifiedString = contentLengthHeader.getValue();
    return Long.parseLong(lastModifiedString);
}

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  ww.ja  v  a2  s.  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 annotated with a custom
 * HEAD annotation.//from   w  w w  .  j  a v a2 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.dataconservancy.dcs.access.http.DatastreamServletTest.java

public void testHead() throws Exception {
    // ServletTester has internal errors processing head requests so use http client

    String baseurl = servletContainer.createSocketConnector(true);

    HttpClient client = new HttpClient();

    HeadMethod head = new HeadMethod(baseurl + "/access/datastream/" + ds_entity.getId());
    int status = client.executeMethod(head);

    assertEquals(200, status);/*w  w w.  j a va2  s .c  o m*/

    assertEquals(ds_entity.getSizeBytes(), head.getResponseContentLength());
    assertNotNull(head.getResponseHeader("ETag"));
    assertNotNull(head.getResponseHeader("Content-Type"));
    assertEquals("application/xbox", head.getResponseHeader("Content-Type").getValue());

    head = new HeadMethod(baseurl + "/access/datastream/doesnotexist");
    status = client.executeMethod(head);
    assertEquals(404, status);
}

From source file:org.dataconservancy.dcs.access.http.EntityServletTest.java

public void testHead() throws Exception {
    HttpClient client = new HttpClient();

    for (DcsEntity entity : entities) {
        HeadMethod head = new HeadMethod(entity.getId());

        int status = client.executeMethod(head);
        assertEquals(200, status);//  ww  w.jav a2s. co m

        assertEquals("application/xml", head.getResponseHeader("Content-Type").getValue());
        assertTrue(head.getResponseContentLength() > 0);
        assertNotNull(head.getResponseHeader("ETag"));
    }

    HeadMethod head = new HeadMethod(entities.get(0).getId() + "blah");
    int status = client.executeMethod(head);
    assertEquals(404, status);
}

From source file:org.dataconservancy.dcs.access.http.GQMQueryServletTest.java

public void testHEAD() throws Exception {
    String baseurl = servletContainer.createSocketConnector(true);

    HttpClient client = new HttpClient();
    HeadMethod head = new HeadMethod(
            baseurl + "/qf/query/" + ServletUtil.encodeURLPath("intersects([line 'EPSG:4326' 4 -1, 4 1])"));
    int status = client.executeMethod(head);
    Assert.assertEquals(200, status);/*from   w  w w .  j a  v a 2  s  .  com*/

    Assert.assertEquals("application/xml", head.getResponseHeader("Content-Type").getValue());
    Assert.assertEquals("" + gqms.getGQMs().size(), head.getResponseHeader("X-TOTAL-MATCHES").getValue());

    head = new HeadMethod(baseurl + "/qf/query/badfield:");
    status = client.executeMethod(head);
    Assert.assertEquals(404, status);
}

From source file:org.dataconservancy.dcs.access.http.QueryServletTest.java

public void testHEAD() throws Exception {
    Collection<DcsFile> files = dcp.getFiles();

    // ServletTester has internal errors processing head requests so use http client
    // request.setMethod("GET");
    String baseurl = servletContainer.createSocketConnector(true);

    HttpClient client = new HttpClient();

    HeadMethod head = new HeadMethod(baseurl + "/access/query/" + ServletUtil.encodeURLPath("entityType:File"));
    int status = client.executeMethod(head);
    assertEquals(200, status);//from w w  w . jav  a  2 s  . co m

    assertEquals("application/xml", head.getResponseHeader("Content-Type").getValue());
    assertEquals("" + files.size(), head.getResponseHeader("X-TOTAL-MATCHES").getValue());

    head = new HeadMethod(baseurl + "/access/query/badfield:");
    status = client.executeMethod(head);
    assertEquals(404, status);
}