Example usage for org.apache.commons.httpclient HttpStatus SC_NOT_MODIFIED

List of usage examples for org.apache.commons.httpclient HttpStatus SC_NOT_MODIFIED

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_NOT_MODIFIED.

Prototype

int SC_NOT_MODIFIED

To view the source code for org.apache.commons.httpclient HttpStatus SC_NOT_MODIFIED.

Click Source Link

Document

<tt>304 Not Modified</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void updateLearningObjectInstance(LearningObjectInstance instance, int instanceId, int learningObjectId)
        throws Exception {
    String uri = String.format(_baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s",
            learningObjectId, instanceId);
    PutMethod method = (PutMethod) getInitializedHttpMethod(_httpClient, uri, HttpMethodType.PUT);
    String loiAsXml = serializeLearningObjectInstanceToXML(instance);
    InputStream is = new ByteArrayInputStream(loiAsXml.getBytes("UTF-8"));
    method.setRequestEntity(new InputStreamRequestEntity(is));
    try {// ww w.j  a va 2s .  c o  m
        int statusCode = _httpClient.executeMethod(method);
        // Put methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void updateLearningObjectiveUserAssessments(int learningObjectId, int instanceId, int[] userIds,
        List<LearningObjectiveAssessment> assessments) throws Exception {
    String uri = String.format(_baseUri
            + "/LearningObjectService.svc/learningObjects/%s/instances/%s/LearningObjectiveUserAssessments",
            learningObjectId, instanceId);
    QueryStringBuilder query = new QueryStringBuilder(uri, false);
    if (userIds != null && userIds.length > 0) {
        query.AddParameter("userIds", intArrayToCsvString(userIds));
    }//from   w  w  w . j  ava  2 s  .  c o m
    PutMethod method = (PutMethod) getInitializedHttpMethod(_httpClient, query.getQueryString(),
            HttpMethodType.PUT);

    String assessmentsAsXml = serializeLearningObjectiveAssessmentsToXml(assessments);
    InputStream is = new ByteArrayInputStream(assessmentsAsXml.getBytes("UTF-8"));
    method.setRequestEntity(new InputStreamRequestEntity(is));
    try {
        int statusCode = _httpClient.executeMethod(method);
        // Put methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }
    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void updateLearningObjectiveCollaborationAssessments(int learningObjectId, int instanceId,
        int collaborationId, List<LearningObjectiveAssessment> assessments) throws Exception {
    String uri = String.format(_baseUri
            + "/LearningObjectService.svc/learningObjects/%s/instances/%s/LearningObjectiveCollaborationAssessments/%s",
            learningObjectId, instanceId, collaborationId);
    PutMethod method = (PutMethod) getInitializedHttpMethod(_httpClient, uri, HttpMethodType.PUT);

    String assessmentsAsXml = serializeLearningObjectiveAssessmentsToXml(assessments);
    InputStream is = new ByteArrayInputStream(assessmentsAsXml.getBytes("UTF-8"));
    method.setRequestEntity(new InputStreamRequestEntity(is));
    try {/*from   w  w w .j  a v a 2s.  c o  m*/
        int statusCode = _httpClient.executeMethod(method);
        // Put methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }
    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.alfresco.services.solr.GetTextContentResponse.java

private void setStatus() {
    int status = response.getStatus();
    if (status == HttpStatus.SC_NOT_MODIFIED) {
        this.status = SolrApiContentStatus.NOT_MODIFIED;
    } else if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
        this.status = SolrApiContentStatus.GENERAL_FAILURE;
    } else if (status == HttpStatus.SC_OK) {
        this.status = SolrApiContentStatus.OK;
    } else if (status == HttpStatus.SC_NO_CONTENT) {
        if (transformStatusStr == null) {
            this.status = SolrApiContentStatus.UNKNOWN;
        } else {/*from  ww w . j  av  a  2 s. co m*/
            if (transformStatusStr.equals("noTransform")) {
                this.status = SolrApiContentStatus.NO_TRANSFORM;
            } else if (transformStatusStr.equals("transformFailed")) {
                this.status = SolrApiContentStatus.TRANSFORM_FAILED;
            } else {
                this.status = SolrApiContentStatus.UNKNOWN;
            }
        }
    }
}

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

public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException {
    StringBuilder url = new StringBuilder(getRepository().getUrl());
    if (!url.toString().endsWith("/")) {
        url.append('/');
    }//  w  w  w  .  j  a  va  2s  .com
    url.append(resourceName);
    HeadMethod headMethod = new HeadMethod(url.toString());

    int statusCode;
    try {
        statusCode = execute(headMethod);
    } catch (IOException e) {
        throw new TransferFailedException(e.getMessage(), e);
    }
    try {
        switch (statusCode) {
        case HttpStatus.SC_OK:
            return true;

        case HttpStatus.SC_NOT_MODIFIED:
            return true;

        case SC_NULL:
            throw new TransferFailedException("Failed to transfer file: " + url);

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

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException("Not authorized.");

        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            throw new AuthorizationException("Not authorized by proxy.");

        case HttpStatus.SC_NOT_FOUND:
            return false;

        //add more entries here
        default:
            throw new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
        }
    } finally {
        headMethod.releaseConnection();
    }
}

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

public void fillInputData(InputData inputData)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    Resource resource = inputData.getResource();

    StringBuilder url = new StringBuilder(getRepository().getUrl());
    if (!url.toString().endsWith("/")) {
        url.append('/');
    }//from ww w  . j a  v a2s . co m
    url.append(resource.getName());

    getMethod = new GetMethod(url.toString());

    long timestamp = resource.getLastModified();
    if (timestamp > 0) {
        SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd-MMM-yy HH:mm:ss zzz", Locale.US);
        fmt.setTimeZone(GMT_TIME_ZONE);
        Header hdr = new Header("If-Modified-Since", fmt.format(new Date(timestamp)));
        fireTransferDebug("sending ==> " + hdr + "(" + timestamp + ")");
        getMethod.addRequestHeader(hdr);
    }

    int statusCode;
    try {
        statusCode = execute(getMethod);
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

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

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

    // TODO [BP]: according to httpclient docs, really should swallow the output on error. verify if that is
    // required
    switch (statusCode) {
    case HttpStatus.SC_OK:
        break;

    case HttpStatus.SC_NOT_MODIFIED:
        // return, leaving last modified set to original value so getIfNewer should return unmodified
        return;

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

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

    case HttpStatus.SC_UNAUTHORIZED:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Not authorized.");

    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Not authorized by proxy.");

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

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

    InputStream is = null;

    Header contentLengthHeader = getMethod.getResponseHeader("Content-Length");

    if (contentLengthHeader != null) {
        try {
            long contentLength = Integer.valueOf(contentLengthHeader.getValue()).intValue();

            resource.setContentLength(contentLength);
        } catch (NumberFormatException e) {
            fireTransferDebug(
                    "error parsing content length header '" + contentLengthHeader.getValue() + "' " + e);
        }
    }

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

    long lastModified = 0;

    if (lastModifiedHeader != null) {
        try {
            lastModified = DateUtil.parseDate(lastModifiedHeader.getValue()).getTime();

            resource.setLastModified(lastModified);
        } catch (DateParseException e) {
            fireTransferDebug("Unable to parse last modified header");
        }

        fireTransferDebug("last-modified = " + lastModifiedHeader.getValue() + " (" + lastModified + ")");
    }

    Header contentEncoding = getMethod.getResponseHeader("Content-Encoding");
    boolean isGZipped = contentEncoding != null && "gzip".equalsIgnoreCase(contentEncoding.getValue());

    try {
        is = getMethod.getResponseBodyAsStream();
        if (isGZipped) {
            is = new GZIPInputStream(is);
        }
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        String msg = "Error occurred while retrieving from remote repository:" + getRepository() + ": "
                + e.getMessage();

        throw new TransferFailedException(msg, e);
    }

    inputData.setInputStream(is);
}

From source file:org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.java

public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException {
    String url = getRepository().getUrl() + "/" + resourceName;
    HeadMethod headMethod = new HeadMethod(url);
    int statusCode;
    try {//from w w w. j  av a 2  s  .co  m
        statusCode = execute(headMethod);
    } catch (IOException e) {
        throw new TransferFailedException(e.getMessage(), e);
    }
    try {
        switch (statusCode) {
        case HttpStatus.SC_OK:
            return true;

        case HttpStatus.SC_NOT_MODIFIED:
            return true;

        case SC_NULL:
            throw new TransferFailedException("Failed to transfer file: " + url);

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

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException("Not authorized.");

        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            throw new AuthorizationException("Not authorized by proxy.");

        case HttpStatus.SC_NOT_FOUND:
            return false;

        //add more entries here
        default:
            throw new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
        }
    } finally {
        headMethod.releaseConnection();
    }
}

From source file:org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.java

public void fillInputData(InputData inputData)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    Resource resource = inputData.getResource();

    String url = getRepository().getUrl() + "/" + resource.getName();
    getMethod = new GetMethod(url);
    long timestamp = resource.getLastModified();
    if (timestamp > 0) {
        SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd-MMM-yy HH:mm:ss zzz", Locale.US);
        fmt.setTimeZone(GMT_TIME_ZONE);//from  w w w.j a  va  2s . co  m
        Header hdr = new Header("If-Modified-Since", fmt.format(new Date(timestamp)));
        fireTransferDebug("sending ==> " + hdr + "(" + timestamp + ")");
        getMethod.addRequestHeader(hdr);
    }

    int statusCode;
    try {
        statusCode = execute(getMethod);
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

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

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

    // TODO [BP]: according to httpclient docs, really should swallow the output on error. verify if that is
    // required
    switch (statusCode) {
    case HttpStatus.SC_OK:
        break;

    case HttpStatus.SC_NOT_MODIFIED:
        // return, leaving last modified set to original value so getIfNewer should return unmodified
        return;

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

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

    case HttpStatus.SC_UNAUTHORIZED:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Not authorized.");

    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Not authorized by proxy.");

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

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

    InputStream is = null;

    Header contentLengthHeader = getMethod.getResponseHeader("Content-Length");

    if (contentLengthHeader != null) {
        try {
            long contentLength = Integer.valueOf(contentLengthHeader.getValue()).intValue();

            resource.setContentLength(contentLength);
        } catch (NumberFormatException e) {
            fireTransferDebug(
                    "error parsing content length header '" + contentLengthHeader.getValue() + "' " + e);
        }
    }

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

    long lastModified = 0;

    if (lastModifiedHeader != null) {
        try {
            lastModified = DateUtil.parseDate(lastModifiedHeader.getValue()).getTime();

            resource.setLastModified(lastModified);
        } catch (DateParseException e) {
            fireTransferDebug("Unable to parse last modified header");
        }

        fireTransferDebug("last-modified = " + lastModifiedHeader.getValue() + " (" + lastModified + ")");
    }

    Header contentEncoding = getMethod.getResponseHeader("Content-Encoding");
    boolean isGZipped = contentEncoding == null ? false : "gzip".equalsIgnoreCase(contentEncoding.getValue());

    try {
        is = getMethod.getResponseBodyAsStream();
        if (isGZipped) {
            is = new GZIPInputStream(is);
        }
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        String msg = "Error occurred while retrieving from remote repository:" + getRepository() + ": "
                + e.getMessage();

        throw new TransferFailedException(msg, e);
    }

    inputData.setInputStream(is);
}

From source file:org.archive.crawler.admin.StatisticsTracker.java

public void crawledURISuccessful(CrawlURI curi) {
    handleSeed(curi, SEED_DISPOSITION_SUCCESS);
    // save crawled bytes tally
    crawledBytes.accumulate(curi);//ww w  .  jav  a  2  s . c  om

    // save crawled docs tally
    if (curi.getFetchStatus() == HttpStatus.SC_NOT_MODIFIED) {
        notModifiedUriCount++;
    } else if (IdenticalDigestDecideRule.hasIdenticalDigest(curi)) {
        dupByHashUriCount++;
    } else {
        novelUriCount++;
    }

    // Save status codes
    incrementMapCount(statusCodeDistribution, Integer.toString(curi.getFetchStatus()));

    // Save mime types
    String mime = MimetypeUtils.truncate(curi.getContentType());
    incrementMapCount(mimeTypeDistribution, mime);
    incrementMapCount(mimeTypeBytes, mime, curi.getContentSize());

    // Save hosts stats.
    saveHostStats(curi.getFetchStatus() == FetchStatusCodes.S_DNS_SUCCESS ? "dns:"
            : this.controller.getServerCache().getHostFor(curi).getHostName(), curi.getContentSize());

    if (curi.containsKey(CrawlURI.A_SOURCE_TAG)) {
        saveSourceStats(curi.getString(CrawlURI.A_SOURCE_TAG),
                this.controller.getServerCache().getHostFor(curi).getHostName());
    }
}

From source file:org.archive.crawler.datamodel.CrawlSubstats.java

/**
 * Examing the CrawlURI and based on its status and internal values,
 * update tallies. /* w ww .  j  a va  2  s  .  co m*/
 * 
 * @param curi
 */
public synchronized void tally(CrawlURI curi, Stage stage) {
    switch (stage) {
    case SCHEDULED:
        totalScheduled++;
        break;
    case RETRIED:
        if (curi.getFetchStatus() <= 0) {
            fetchNonResponses++;
        }
        break;
    case SUCCEEDED:
        fetchSuccesses++;
        fetchResponses++;
        totalBytes += curi.getContentSize();
        successBytes += curi.getContentSize();

        if (curi.getFetchStatus() == HttpStatus.SC_NOT_MODIFIED) {
            notModifiedBytes += curi.getContentSize();
            notModifiedUrls++;
        } else if (IdenticalDigestDecideRule.hasIdenticalDigest(curi)) {
            dupByHashBytes += curi.getContentSize();
            dupByHashUrls++;
        } else {
            novelBytes += curi.getContentSize();
            novelUrls++;
        }

        break;
    case DISREGARDED:
        fetchDisregards++;
        if (curi.getFetchStatus() == S_ROBOTS_PRECLUDED) {
            robotsDenials++;
        }
        break;
    case FAILED:
        if (curi.getFetchStatus() <= 0) {
            fetchNonResponses++;
        } else {
            fetchResponses++;
            totalBytes += curi.getContentSize();
            if (curi.getFetchStatus() == HttpStatus.SC_NOT_MODIFIED) {
                notModifiedBytes += curi.getContentSize();
                notModifiedUrls++;
            } else if (IdenticalDigestDecideRule.hasIdenticalDigest(curi)) {
                dupByHashBytes += curi.getContentSize();
                dupByHashUrls++;
            } else {
                novelBytes += curi.getContentSize();
                novelUrls++;
            }
        }
        fetchFailures++;
        break;
    }
}