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

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

Introduction

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

Prototype

public HeadMethod(String paramString) 

Source Link

Usage

From source file:com.google.enterprise.connector.sharepoint.client.SiteDataHelper.java

/**
 * Makes a call to Site Data web service to retrieve site meta data and create
 * a SPDocuemnt and it returns a single SPDcoument.This method returns null if
 * and only if any one of SiteData stub or webState is null.
 *
 * @param webState The web from which we need to construct SPDcoument for it's
 *          landing page./*from w w  w.  j  a  va2  s .c  o m*/
 * @return a single SPDocument for the given web.
 */
public SPDocument getSiteData(final WebState webState) {
    if (webState == null) {
        LOGGER.warning("Unable to get the list collection because webstate is null");
        // in case if the web state is null and is not existing in SharePoint
        // server.
        return null;
    }

    final _sWebMetadataHolder sWebMetadata = getWebMetadata();
    if (sWebMetadata == null) {
        LOGGER.warning("Unable to get site data. The call to getSiteData returned null.");
        return null;
    }

    final SPDocument siteDataDocument = new SPDocument(
            webState.getPrimaryKey() + SPConstants.DEFAULT_SITE_LANDING_PAGE + SPConstants.DOC_TOKEN
                    + sWebMetadata.value.getWebID(),
            webState.getWebUrl() + SPConstants.DEFAULT_SITE_LANDING_PAGE, sWebMetadata.value.getLastModified(),
            sWebMetadata.value.getAuthor(), SPConstants.SITE, webState.getTitle(),
            sharepointClientContext.getFeedType(), webState.getSharePointType());
    String strUrl = Util.encodeURL(siteDataDocument.getUrl());
    HttpMethodBase method = new HeadMethod(strUrl);
    try {
        int responseCode = sharepointClientContext.checkConnectivity(strUrl, method);
        if (responseCode != 200) {
            LOGGER.log(Level.INFO,
                    "Possible Publishing website. Marking Url [ " + strUrl + " ] with Document Type as ACL");
            siteDataDocument.setDocumentType(DocumentType.ACL);
        }
    } catch (final Exception e) {
        LOGGER.log(Level.WARNING, "Unable to connect [ " + strUrl + " ] marking site home page as ACL document",
                e);
        siteDataDocument.setDocumentType(DocumentType.ACL);
    } finally {
        method.releaseConnection();
    }

    return siteDataDocument;
}

From source file:fedora.client.FedoraClient.java

public Date getLastModifiedDate(String locator) throws IOException {
    if (locator.startsWith(FEDORA_URI_PREFIX)) {
        String query = "select $date " + "from <#ri> " + "where <" + locator + "> <"
                + VIEW.LAST_MODIFIED_DATE.uri + "> $date";
        Map<String, String> map = new HashMap<String, String>();
        map.put("lang", "itql");
        map.put("query", query);
        TupleIterator tuples = getTuples(map);
        try {/* w ww  . ja v a 2  s .c o m*/
            if (tuples.hasNext()) {
                Map<String, Node> row = tuples.next();
                Literal dateLiteral = (Literal) row.get("date");
                if (dateLiteral == null) {
                    throw new IOException("A row was returned, but it did not contain a 'date' binding");
                }
                return DateUtility.parseDateAsUTC(dateLiteral.getLexicalForm());
            } else {
                throw new IOException("No rows were returned");
            }
        } catch (TrippiException e) {
            throw new IOException(e.getMessage());
        } finally {
            try {
                tuples.close();
            } catch (Exception e) {
            }
        }
    } else {
        HttpClient client = getHttpClient();

        HeadMethod head = new HeadMethod(locator);
        head.setDoAuthentication(true);
        head.setFollowRedirects(FOLLOW_REDIRECTS);

        try {
            int statusCode = client.executeMethod(head);
            if (statusCode != HttpStatus.SC_OK) {
                throw new IOException("Method failed: " + head.getStatusLine());
            }
            //Header[] headers = head.getResponseHeaders();

            // Retrieve just the last modified header value.
            Header header = head.getResponseHeader("last-modified");
            if (header != null) {
                String lastModified = header.getValue();
                return DateUtility.convertStringToDate(lastModified);
            } else {
                // return current date time
                return new Date();
            }
        } finally {
            head.releaseConnection();
        }
    }
}

From source file:com.google.enterprise.connector.sharepoint.wsclient.soap.SPSiteDataWS.java

/**
 * Makes a call to Site Data web service to retrieve site meta data and create
 * a SPDocuemnt and it returns a single SPDcoument.This method returns null if
 * and only if any one of SiteData stub or webState is null.
 *
 * @param webState The web from which we need to construct SPDcoument for it's
 *          landing page.//from   ww w  .j  a va  2  s. c  o m
 * @return a single SPDocument for the given web.
 * @throws SharepointException
 */
public SPDocument getSiteData(final WebState webState) throws SharepointException {
    final UnsignedIntHolder getWebResult = new UnsignedIntHolder();
    final _sWebMetadataHolder sWebMetadata = new _sWebMetadataHolder();
    final ArrayOf_sWebWithTimeHolder vWebs = new ArrayOf_sWebWithTimeHolder();
    final ArrayOf_sListWithTimeHolder vLists = new ArrayOf_sListWithTimeHolder();
    final ArrayOf_sFPUrlHolder vFPUrls = new ArrayOf_sFPUrlHolder();
    final StringHolder strRoles = new StringHolder();
    final ArrayOfStringHolder vRolesUsers = new ArrayOfStringHolder();
    final ArrayOfStringHolder vRolesGroups = new ArrayOfStringHolder();

    if (stub == null) {
        LOGGER.warning("Unable to get the list collection because stub is null");
        // in case if SiteData web service end point is not created properly.
        return null;
    }

    if (webState == null) {
        LOGGER.warning("Unable to get the list collection because webstate is null");
        // in case if the web state is null and is not existing in SharePoint
        // server.
        return null;
    }
    try {
        stub.getWeb(getWebResult, sWebMetadata, vWebs, vLists, vFPUrls, strRoles, vRolesUsers, vRolesGroups);
    } catch (final AxisFault af) {
        // Handling of username formats for
        // different authentication models.
        if ((SPConstants.UNAUTHORIZED.indexOf(af.getFaultString()) != -1)
                && (sharepointClientContext.getDomain() != null)) {
            final String username = Util.switchUserNameFormat(stub.getUsername());
            LOGGER.log(Level.CONFIG, "Web Service call failed for username [ " + stub.getUsername()
                    + " ]. Trying with " + username);
            stub.setUsername(username);
            try {
                stub.getWeb(getWebResult, sWebMetadata, vWebs, vLists, vFPUrls, strRoles, vRolesUsers,
                        vRolesGroups);
            } catch (final Exception e) {
                LOGGER.log(Level.WARNING,
                        "Unable to get site data for web because call to the WS failed. endpoint [ " + endpoint
                                + " ]",
                        e);
            }
        } else {
            LOGGER.log(Level.WARNING,
                    "Unable to get site data for web because call to the WS failed. endpoint [ " + endpoint
                            + " ]",
                    af);
        }
    } catch (final Throwable e) {
        LOGGER.log(Level.WARNING,
                "Unable to get the data for web because call to the WS failed. endpoint [ " + endpoint + " ]",
                e);
    }

    final SPDocument siteDataDocument = new SPDocument(
            webState.getPrimaryKey() + SPConstants.DEFAULT_SITE_LANDING_PAGE + SPConstants.DOC_TOKEN
                    + sWebMetadata.value.getWebID(),
            webState.getWebUrl() + SPConstants.DEFAULT_SITE_LANDING_PAGE,
            sWebMetadata.value.getLastModified().getInstance(), sWebMetadata.value.getAuthor(),
            SPConstants.SITE, webState.getTitle(), sharepointClientContext.getFeedType(),
            webState.getSharePointType());
    HttpMethodBase method = null;
    String strUrl = Util.encodeURL(siteDataDocument.getUrl());
    try {
        method = new HeadMethod(strUrl);
        int responseCode = sharepointClientContext.checkConnectivity(strUrl, method);
        if (responseCode != 200) {
            LOGGER.log(Level.INFO,
                    "Possible Publishing website.Marking Url [" + strUrl + " ] with Document Type as ACL");
            siteDataDocument.setDocumentType(DocumentType.ACL);
        }
    } catch (final Exception e) {
        LOGGER.log(Level.WARNING, "Unable to connect [ " + strUrl + " ] marking site home page as ACL document",
                e);
        siteDataDocument.setDocumentType(DocumentType.ACL);
    }

    return siteDataDocument;
}

From source file:JiraWebClient.java

private void watchUnwatchIssue(final JiraIssue issue, final boolean watch, IProgressMonitor monitor)
        throws JiraException {
    doInSession(monitor, new JiraWebSessionCallback() {
        @Override/*from   www  .j  a va  2  s . c o m*/
        public void run(JiraClient server, String baseUrl, IProgressMonitor monitor) throws JiraException {
            StringBuilder urlBuffer = new StringBuilder(baseUrl);
            String version = client.getCache().getServerInfo(monitor).getVersion();
            if (new JiraVersion(version).compareTo(JiraVersion.JIRA_4_1) >= 0) {
                urlBuffer.append("/secure/VoteOrWatchIssue.jspa"); //$NON-NLS-1$
                urlBuffer.append("?id=").append(issue.getId()); //$NON-NLS-1$
                urlBuffer.append("&watch=").append(watch ? "watch" : "unwatch"); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
            } else {
                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());

            if (new JiraVersion(version).compareTo(JiraVersion.JIRA_4_1) >= 0) {
                prepareSecurityToken(head);
            }

            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:com.google.enterprise.connector.sharepoint.client.SharepointClientContext.java

/**
 * Check the connectivity to a given URL by making HTTP head request.
 *
 * @param strURL The URL to be checked/*w  w w  . j  av a2s  .  c  om*/
 * @return the HTTP response code
 */
public int checkConnectivity(final String strURL, HttpMethodBase method) throws IOException {
    LOGGER.log(Level.CONFIG, "Connecting [ " + strURL + " ] ....");
    String username = this.username;
    final String host = Util.getHost(strURL);
    Credentials credentials = null;
    boolean kerberos = false;
    boolean ntlm = true; // We first try to use ntlm

    if (kdcServer != null && !kdcServer.equalsIgnoreCase(SPConstants.BLANK_STRING)) {
        credentials = new NTCredentials(username, password, host, domain);
        kerberos = true;
    } else if (!kerberos && null != domain && !domain.equals("")) {
        credentials = new NTCredentials(username, password, host, domain);
    } else {
        credentials = new UsernamePasswordCredentials(username, password);
        ntlm = false;
    }

    boolean isInputMethodNull = (null == method);
    if (isInputMethodNull) {
        method = new HeadMethod(strURL);
    }

    try {
        int responseCode = clientFactory.checkConnectivity(method, credentials);
        if (responseCode == 401 && ntlm && !kerberos) {
            LOGGER.log(Level.FINE, "Trying with HTTP Basic.");
            username = Util.getUserNameWithDomain(this.username, domain);
            credentials = new UsernamePasswordCredentials(username, password);
            responseCode = clientFactory.checkConnectivity(method, credentials);
        }
        if (responseCode != 200) {
            LOGGER.log(Level.WARNING, "responseCode: " + responseCode);
        }
        return responseCode;
    } finally {
        if (isInputMethodNull) {
            // Since method variable was local to this method
            // releasing connection here.
            method.releaseConnection();
        }
    }
}

From source file:com.google.enterprise.connector.sharepoint.client.SharepointClientContext.java

/**
 * Detect SharePoint type from the URL/*from w ww.j  ava 2s .c om*/
 *
 * @param strURL
 * @return the SharePoint Type of the siteURL being passed
 */
public SPConstants.SPType checkSharePointType(String strURL) {
    LOGGER.log(Level.CONFIG, "Checking [ " + strURL + " ] for the SharePoint version.");

    strURL = Util.encodeURL(strURL);
    HttpMethodBase method = null;
    String version;
    try {
        method = new HeadMethod(strURL);
        checkConnectivity(strURL, method);
        version = clientFactory.getResponseHeader(method, "MicrosoftSharePointTeamServices");
        LOGGER.info("SharePoint Version: " + version);
    } catch (final Exception e) {
        LOGGER.log(Level.WARNING, "Unable to connect " + strURL, e);
        return null;
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    if (version == null) {
        LOGGER.warning("Sharepoint version not found for the site [ " + strURL + " ]");
        return null;
    }

    /* Fix Details: ------------ SharePoint connector requires to know the
     * version of the SharePoint repository<br/> for following a)
     * MySite\Personal Site handling which is different in SP2003 & SP2007 Note:
     * current mysite handling fails for SP2010.<br/> However mysite URLs can be
     * discovered using the custom site discovery WS. b) Content Feed\Bulk
     * AuthZ: This is achieved through custom web services which is supported on
     * SP2007 Note: Checked that same web services work for SP2010 as well
     */

    if (version.trim().startsWith("6") || version.trim().startsWith("11")) {
        return SPType.SP2003;
    } else {
        // Return type as SP2007 for all SharePoint Versions starting
        // from MOSS 2007 and WSS 3.
        return SPType.SP2007;
    }
}

From source file:JiraWebClient.java

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

        @Override//from w ww .  java  2s .  c  o  m
        public void run(JiraClient server, String baseUrl, IProgressMonitor monitor) throws JiraException {
            StringBuilder urlBuffer = new StringBuilder(baseUrl);
            String version = client.getCache().getServerInfo(monitor).getVersion();
            if (new JiraVersion(version).compareTo(JiraVersion.JIRA_4_1) >= 0) {
                urlBuffer.append("/secure/VoteOrWatchIssue.jspa"); //$NON-NLS-1$
                urlBuffer.append("?id=").append(issue.getId()); //$NON-NLS-1$
                urlBuffer.append("&vote=").append(vote ? "vote" : "unvote"); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
            } else {
                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());
            if (new JiraVersion(version).compareTo(JiraVersion.JIRA_4_1) >= 0) {
                prepareSecurityToken(head);
            }

            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:JiraWebClient.java

public void deleteIssue(final JiraIssue issue, IProgressMonitor monitor) throws JiraException {
    doInSession(monitor, new JiraWebSessionCallback() {

        @Override//from  w  w  w.j av  a 2 s.  c  om
        public void run(JiraClient server, String baseUrl, IProgressMonitor monitor) throws JiraException {
            StringBuilder urlBuffer = new StringBuilder(baseUrl);
            urlBuffer.append("/secure/DeleteIssue.jspa"); //$NON-NLS-1$
            urlBuffer.append("?id=").append(issue.getId()); //$NON-NLS-1$
            urlBuffer.append("&confirm=true"); //$NON-NLS-1$

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

    });
}

From source file:com.eucalyptus.imaging.backend.ImagingTaskStateManager.java

private boolean doesManifestExist(final String manifestUrl) throws Exception {
    // validate urls per EUCA-9144
    final UrlValidator urlValidator = new UrlValidator();
    if (!urlValidator.isEucalyptusUrl(manifestUrl))
        throw new RuntimeException("Manifest's URL is not in the Eucalyptus format: " + manifestUrl);
    final HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 10000);
    client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, 30000);
    GetMethod method = new GetMethod(manifestUrl);
    String manifest = null;//from ww  w  .  j  a  va  2s. c  om
    try {
        // avoid TCP's CLOSE_WAIT  
        method.setRequestHeader("Connection", "close");
        client.executeMethod(method);
        manifest = method.getResponseBodyAsString(ImageConfiguration.getInstance().getMaxManifestSizeBytes());
        if (manifest == null) {
            return false;
        } else if (manifest.contains("<Code>NoSuchKey</Code>")
                || manifest.contains("The specified key does not exist")) {
            return false;
        }
    } catch (final Exception ex) {
        return false;
    } finally {
        method.releaseConnection();
    }
    final List<String> partsUrls = getPartsHeadUrl(manifest);
    for (final String url : partsUrls) {
        if (!urlValidator.isEucalyptusUrl(url))
            throw new RuntimeException("Manifest's URL is not in the Eucalyptus format: " + url);
        HeadMethod partCheck = new HeadMethod(url);
        int res = client.executeMethod(partCheck);
        if (res != HttpStatus.SC_OK) {
            return false;
        }
    }
    return true;
}

From source file:de.mpg.escidoc.services.common.util.Util.java

public static Node getSize(String url) {
    DocumentBuilder documentBuilder;

    HttpClient httpClient = new HttpClient();
    HeadMethod headMethod = new HeadMethod(url);

    try {//from  w w w . j  a v  a  2s.c  o m
        logger.info("Getting size of " + url);
        ProxyHelper.executeMethod(httpClient, headMethod);

        if (headMethod.getStatusCode() != 200) {
            logger.warn("Wrong status code " + headMethod.getStatusCode() + " at " + url);
        }

        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element element = document.createElement("size");
        document.appendChild(element);
        Header header = headMethod.getResponseHeader("Content-Length");
        if (header != null) {
            element.setTextContent(header.getValue());
            return document;
        } else {
            element.setTextContent("0");
            return document;
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}