Java Code Examples for java.net.HttpURLConnection#HTTP_PRECON_FAILED

The following examples show how to use java.net.HttpURLConnection#HTTP_PRECON_FAILED . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: okdownload   File: DownloadStrategy.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable public ResumeFailedCause getPreconditionFailedCause(int responseCode,
                                                              boolean isAlreadyProceed,
                                                              @NonNull BreakpointInfo info,
                                                              @Nullable String responseEtag) {
    final String localEtag = info.getEtag();
    if (responseCode == HttpURLConnection.HTTP_PRECON_FAILED) {
        return RESPONSE_PRECONDITION_FAILED;
    }

    if (!Util.isEmpty(localEtag) && !Util.isEmpty(responseEtag) && !responseEtag
            .equals(localEtag)) {
        // etag changed.
        // also etag changed is relate to HTTP_PRECON_FAILED
        return RESPONSE_ETAG_CHANGED;
    }

    if (responseCode == HttpURLConnection.HTTP_CREATED && isAlreadyProceed) {
        // The request has been fulfilled and has resulted in one or more new resources
        // being created.
        // mark this case is precondition failed for
        // 1. checkout whether accept partial
        // 2. 201 means new resources so range must be from beginning otherwise it can't
        // match local range.
        return RESPONSE_CREATED_RANGE_NOT_FROM_0;
    }

    if (responseCode == HttpURLConnection.HTTP_RESET && isAlreadyProceed) {
        return RESPONSE_RESET_RANGE_NOT_FROM_0;
    }

    return null;
}
 
Example 2
Source Project: hono   File: CrudHttpClient.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private static ServiceInvocationException newUnexpectedResponseStatusException(final int statusCode) {
    if (statusCode >= 400 && statusCode < 500) {
        return new ClientErrorException(statusCode);
    } else if (statusCode >= 500 && statusCode < 600) {
        return new ServerErrorException(statusCode);
    } else {
        return new ClientErrorException(HttpURLConnection.HTTP_PRECON_FAILED,
                "Unexpected response status " + statusCode);
    }
}
 
Example 3
/**
 * Dispatches a read operation of N bytes.
 * 
 * @param readLength
 *            An <code>int</code> which represents the number of bytes to read.
 * 
 * @throws IOException
 *             If an I/O error occurs.
 */
@DoesServiceRequest
private synchronized void dispatchRead(final int readLength) throws IOException {
    try {
        final byte[] byteBuffer = new byte[readLength];

        this.parentFileRef.downloadRangeInternal(this.currentAbsoluteReadPosition, (long) readLength, byteBuffer,
                0, null /* this.accessCondition */, this.options, this.opContext);

        // Check Etag manually for now -- use access condition once conditional headers supported.
        if (this.accessCondition != null) {
            if (!this.accessCondition.getIfMatch().equals(this.parentFileRef.getProperties().getEtag())) {
                throw new StorageException(StorageErrorCode.CONDITION_FAILED.toString(),
                        SR.INVALID_CONDITIONAL_HEADERS, HttpURLConnection.HTTP_PRECON_FAILED, null, null);
            }
        }

        this.currentBuffer = new ByteArrayInputStream(byteBuffer);
        this.bufferSize = readLength;
        this.bufferStartOffset = this.currentAbsoluteReadPosition;
    }
    catch (final StorageException e) {
        this.streamFaulted = true;
        this.lastError = Utility.initIOException(e);
        throw this.lastError;
    }
}
 
Example 4
public PreconditionFailedException(String message) {
    super(message, HttpURLConnection.HTTP_PRECON_FAILED);
}
 
Example 5
/**
 * Translates the specified HTTP status code into a storage exception.
 * 
 * @param statusCode
 *            The HTTP status code returned by the operation.
 * @param statusDescription
 *            A <code>String</code> that represents the status description.
 * @param inner
 *            An <code>Exception</code> object that represents a reference to the initial exception, if one exists.
 * 
 * @return A <code>StorageException</code> object that represents translated exception.
 **/
protected static StorageException translateFromHttpStatus(final int statusCode, final String statusDescription,
        final Exception inner) {
    String errorCode;
    switch (statusCode) {
    case HttpURLConnection.HTTP_FORBIDDEN:
        errorCode = StorageErrorCode.ACCESS_DENIED.toString();
        break;
    case HttpURLConnection.HTTP_GONE:
    case HttpURLConnection.HTTP_NOT_FOUND:
        errorCode = StorageErrorCode.RESOURCE_NOT_FOUND.toString();
        break;
    case 416:
    case HttpURLConnection.HTTP_BAD_REQUEST:
        // 416: RequestedRangeNotSatisfiable - No corresponding enum in HttpURLConnection
        errorCode = StorageErrorCode.BAD_REQUEST.toString();
        break;

    case HttpURLConnection.HTTP_PRECON_FAILED:
    case HttpURLConnection.HTTP_NOT_MODIFIED:
        errorCode = StorageErrorCode.CONDITION_FAILED.toString();
        break;

    case HttpURLConnection.HTTP_CONFLICT:
        errorCode = StorageErrorCode.RESOURCE_ALREADY_EXISTS.toString();
        break;

    case HttpURLConnection.HTTP_UNAVAILABLE:
        errorCode = StorageErrorCode.SERVER_BUSY.toString();
        break;

    case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
        errorCode = StorageErrorCode.SERVICE_TIMEOUT.toString();
        break;

    case HttpURLConnection.HTTP_INTERNAL_ERROR:
        errorCode = StorageErrorCode.SERVICE_INTERNAL_ERROR.toString();
        break;

    case HttpURLConnection.HTTP_NOT_IMPLEMENTED:
        errorCode = StorageErrorCode.NOT_IMPLEMENTED.toString();
        break;

    case HttpURLConnection.HTTP_BAD_GATEWAY:
        errorCode = StorageErrorCode.BAD_GATEWAY.toString();
        break;

    case HttpURLConnection.HTTP_VERSION:
        errorCode = StorageErrorCode.HTTP_VERSION_NOT_SUPPORTED.toString();
        break;
    default:
        errorCode = null;
    }

    if (errorCode == null) {
        return null;
    } else {
        return new StorageException(errorCode, statusDescription, statusCode, null, inner);
    }
}
 
Example 6
/**
 * Initializes a new instance of the BlobInputStream class.
 * 
 * @param parentBlob
 *            A {@link CloudBlob} object which represents the blob that this stream is associated with.
 * @param accessCondition
 *            An {@link AccessCondition} object which represents the access conditions for the blob.
 * @param options
 *            A {@link BlobRequestOptions} object which represents that specifies any additional options for the
 *            request.
 * @param opContext
 *            An {@link OperationContext} object which is used to track the execution of the operation.
 * 
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
@DoesServiceRequest
protected BlobInputStream(final CloudBlob parentBlob, final AccessCondition accessCondition,
        final BlobRequestOptions options, final OperationContext opContext) throws StorageException {
    this.parentBlobRef = parentBlob;
    this.parentBlobRef.assertCorrectBlobType();
    this.options = new BlobRequestOptions(options);
    this.opContext = opContext;
    this.streamFaulted = false;
    this.currentAbsoluteReadPosition = 0;
    this.readSize = parentBlob.getStreamMinimumReadSizeInBytes();

    if (options.getUseTransactionalContentMD5() && this.readSize > 4 * Constants.MB) {
        throw new IllegalArgumentException(SR.INVALID_RANGE_CONTENT_MD5_HEADER);
    }

    parentBlob.downloadAttributes(accessCondition, this.options, this.opContext);

    this.retrievedContentMD5Value = parentBlob.getProperties().getContentMD5();

    // Will validate it if it was returned
    this.validateBlobMd5 = !options.getDisableContentMD5Validation()
            && !Utility.isNullOrEmpty(this.retrievedContentMD5Value);

    // Validates the first option, and sets future requests to use if match
    // request option.

    // If there is an existing conditional validate it, as we intend to
    // replace if for future requests.
    String previousLeaseId = null;
    if (accessCondition != null) {
        previousLeaseId = accessCondition.getLeaseID();

        if (!accessCondition.verifyConditional(this.parentBlobRef.getProperties().getEtag(), this.parentBlobRef
                .getProperties().getLastModified())) {
            throw new StorageException(StorageErrorCode.CONDITION_FAILED.toString(),
                    SR.INVALID_CONDITIONAL_HEADERS, HttpURLConnection.HTTP_PRECON_FAILED, null, null);
        }
    }

    this.accessCondition = AccessCondition.generateIfMatchCondition(this.parentBlobRef.getProperties().getEtag());
    this.accessCondition.setLeaseID(previousLeaseId);

    this.streamLength = parentBlob.getProperties().getLength();

    if (this.validateBlobMd5) {
        try {
            this.md5Digest = MessageDigest.getInstance("MD5");
        }
        catch (final NoSuchAlgorithmException e) {
            // This wont happen, throw fatal.
            throw Utility.generateNewUnexpectedStorageException(e);
        }
    }

    this.reposition(0);
}
 
Example 7
Source Project: Sentry-Android   File: Sentry.java    License: MIT License 4 votes vote down vote up
/**
 * Map from HTTP status code to reason description.
 * Sentry HTTP breadcrumbs expect a text description of the HTTP status-code.
 * This function implements a look-up table with a default value for unknown status-codes.
 * @param statusCode an integer HTTP status code, expected to be in the range [200,505].
 * @return a non-empty string in all cases.
 */
private static String httpReason(int statusCode) {
    switch (statusCode) {
        // 2xx
        case HttpURLConnection.HTTP_OK: return "OK";
        case HttpURLConnection.HTTP_CREATED: return "Created";
        case HttpURLConnection.HTTP_ACCEPTED: return "Accepted";
        case HttpURLConnection.HTTP_NOT_AUTHORITATIVE: return "Non-Authoritative Information";
        case HttpURLConnection.HTTP_NO_CONTENT: return "No Content";
        case HttpURLConnection.HTTP_RESET: return "Reset Content";
        case HttpURLConnection.HTTP_PARTIAL: return "Partial Content";

        // 3xx
        case HttpURLConnection.HTTP_MULT_CHOICE: return "Multiple Choices";
        case HttpURLConnection.HTTP_MOVED_PERM: return "Moved Permanently";
        case HttpURLConnection.HTTP_MOVED_TEMP: return "Temporary Redirect";
        case HttpURLConnection.HTTP_SEE_OTHER: return "See Other";
        case HttpURLConnection.HTTP_NOT_MODIFIED: return "Not Modified";
        case HttpURLConnection.HTTP_USE_PROXY: return "Use Proxy";

        // 4xx
        case HttpURLConnection.HTTP_BAD_REQUEST: return "Bad Request";
        case HttpURLConnection.HTTP_UNAUTHORIZED: return "Unauthorized";
        case HttpURLConnection.HTTP_PAYMENT_REQUIRED: return "Payment Required";
        case HttpURLConnection.HTTP_FORBIDDEN: return "Forbidden";
        case HttpURLConnection.HTTP_NOT_FOUND: return "Not Found";
        case HttpURLConnection.HTTP_BAD_METHOD: return "Method Not Allowed";
        case HttpURLConnection.HTTP_NOT_ACCEPTABLE: return "Not Acceptable";
        case HttpURLConnection.HTTP_PROXY_AUTH: return "Proxy Authentication Required";
        case HttpURLConnection.HTTP_CLIENT_TIMEOUT: return "Request Time-Out";
        case HttpURLConnection.HTTP_CONFLICT: return "Conflict";
        case HttpURLConnection.HTTP_GONE: return "Gone";
        case HttpURLConnection.HTTP_LENGTH_REQUIRED: return "Length Required";
        case HttpURLConnection.HTTP_PRECON_FAILED: return "Precondition Failed";
        case HttpURLConnection.HTTP_ENTITY_TOO_LARGE: return "Request Entity Too Large";
        case HttpURLConnection.HTTP_REQ_TOO_LONG: return "Request-URI Too Large";
        case HttpURLConnection.HTTP_UNSUPPORTED_TYPE: return "Unsupported Media Type";

        // 5xx
        case HttpURLConnection.HTTP_INTERNAL_ERROR: return "Internal Server Error";
        case HttpURLConnection.HTTP_NOT_IMPLEMENTED: return "Not Implemented";
        case HttpURLConnection.HTTP_BAD_GATEWAY: return "Bad Gateway";
        case HttpURLConnection.HTTP_UNAVAILABLE: return "Service Unavailable";
        case HttpURLConnection.HTTP_GATEWAY_TIMEOUT: return "Gateway Timeout";
        case HttpURLConnection.HTTP_VERSION: return "Version Not Supported";

        default: return "unknown";
    }
}
 
Example 8
/**
 * Constructor.
 *
 * @param msg   human readable message
 * @param cause reason for this exception
 */
public GeniePreconditionException(final String msg, final Throwable cause) {
    super(HttpURLConnection.HTTP_PRECON_FAILED, msg, cause);
}
 
Example 9
/**
 * Constructor.
 *
 * @param msg human readable message
 */
public GeniePreconditionException(final String msg) {
    super(HttpURLConnection.HTTP_PRECON_FAILED, msg);
}