Merge branch 'experimental-overrideable-http-operation-validation' into experimental-1.0RC1

This commit is contained in:
Mattt Thompson 2012-03-09 16:05:29 -08:00
commit d5d44f681e
6 changed files with 148 additions and 140 deletions

View file

@ -23,13 +23,16 @@
#import <Foundation/Foundation.h>
#import "AFURLConnectionOperation.h"
/**
Returns a set of MIME types detected in an HTTP `Accept` or `Content-Type` header.
*/
extern NSSet * AFContentTypesFromHTTPHeader(NSString *string);
/**
`AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
*/
@interface AFHTTPRequestOperation : AFURLConnectionOperation {
@private
NSIndexSet *_acceptableStatusCodes;
NSSet *_acceptableContentTypes;
NSError *_HTTPError;
dispatch_queue_t _successCallbackQueue;
dispatch_queue_t _failureCallbackQueue;
@ -44,30 +47,15 @@
*/
@property (readonly, nonatomic, retain) NSHTTPURLResponse *response;
///----------------------------------------------------------
/// @name Managing And Checking For Acceptable HTTP Responses
///----------------------------------------------------------
/**
Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
By default, this is the range 200 to 299, inclusive.
*/
@property (nonatomic, retain) NSIndexSet *acceptableStatusCodes;
/**
A Boolean value that corresponds to whether the status code of the response is within the specified set of acceptable status codes. Returns `YES` if `acceptableStatusCodes` is `nil`.
*/
@property (readonly) BOOL hasAcceptableStatusCode;
/**
Returns an `NSSet` object containing the acceptable MIME types. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
By default, this is `nil`.
*/
@property (nonatomic, retain) NSSet *acceptableContentTypes;
/**
A Boolean value that corresponds to whether the MIME type of the response is among the specified set of acceptable content types. Returns `YES` if `acceptableContentTypes` is `nil`.
*/
@ -83,6 +71,42 @@
*/
@property (nonatomic) dispatch_queue_t failureCallbackQueue;
///-------------------------------------------------------------
/// @name Managing Accceptable HTTP Status Codes & Content Types
///-------------------------------------------------------------
/**
Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
By default, this is the range 200 to 299, inclusive.
*/
+ (NSIndexSet *)acceptableStatusCodes;
/**
Adds status codes to the set of acceptable HTTP status codes returned by `+acceptableStatusCodes` in subsequent calls by this class and its descendents.
@param statusCodes The status codes to be added to the set of acceptable HTTP status codes
*/
+ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes;
/**
Returns an `NSSet` object containing the acceptable MIME types. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
By default, this is `nil`.
*/
+ (NSSet *)acceptableContentTypes;
/**
Adds content types to the set of acceptable MIME types returned by `+acceptableContentTypes` in subsequent calls by this class and its descendents.
@param contentTypes The content types to be added to the set of acceptable MIME types
*/
+ (void)addAcceptableContentTypes:(NSSet *)contentTypes;
///-----------------------------------------------------
/// @name Determining Whether A Request Can Be Processed
///-----------------------------------------------------
/**
A Boolean value determining whether or not the class can process the specified request. For example, `AFJSONRequestOperation` may check to make sure the content type was `application/json` or the URL path extension was `.json`.

View file

@ -22,6 +22,44 @@
#import "AFHTTPRequestOperation.h"
#import <objc/runtime.h>
NSSet * AFContentTypesFromHTTPHeader(NSString *string) {
static NSCharacterSet *_skippedCharacterSet = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_skippedCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@" ,"];
});
if (!string) {
return nil;
}
NSScanner *scanner = [NSScanner scannerWithString:string];
scanner.charactersToBeSkipped = _skippedCharacterSet;
NSMutableSet *mutableContentTypes = [NSMutableSet set];
while (![scanner isAtEnd]) {
NSString *contentType = nil;
if ([scanner scanUpToString:@";" intoString:&contentType]) {
[scanner scanUpToString:@"," intoString:nil];
}
if (contentType) {
[mutableContentTypes addObject:contentType];
}
}
return [NSSet setWithSet:mutableContentTypes];
}
static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL selector, void *block) {
Method originalMethod = class_getClassMethod(klass, selector);
IMP implementation = imp_implementationWithBlock(block);
class_replaceMethod(objc_getMetaClass([NSStringFromClass(klass) cStringUsingEncoding:NSUTF8StringEncoding]), selector, implementation, method_getTypeEncoding(originalMethod));
}
static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) {
NSMutableString *string = [NSMutableString string];
@ -59,27 +97,11 @@ static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) {
@end
@implementation AFHTTPRequestOperation
@synthesize acceptableStatusCodes = _acceptableStatusCodes;
@synthesize acceptableContentTypes = _acceptableContentTypes;
@synthesize HTTPError = _HTTPError;
@synthesize successCallbackQueue = _successCallbackQueue;
@synthesize failureCallbackQueue = _failureCallbackQueue;
- (id)initWithRequest:(NSURLRequest *)request {
self = [super initWithRequest:request];
if (!self) {
return nil;
}
self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
return self;
}
- (void)dealloc {
[_acceptableStatusCodes release];
[_acceptableContentTypes release];
[_HTTPError release];
if (_successCallbackQueue) {
@ -103,13 +125,13 @@ static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) {
if (self.response && !self.HTTPError) {
if (![self hasAcceptableStatusCode]) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
[userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected status code in (%@), got %d", nil), AFStringFromIndexSet(self.acceptableStatusCodes), [self.response statusCode]] forKey:NSLocalizedDescriptionKey];
[userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected status code in (%@), got %d", nil), AFStringFromIndexSet([[self class] acceptableStatusCodes]), [self.response statusCode]] forKey:NSLocalizedDescriptionKey];
[userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
self.HTTPError = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo] autorelease];
} else if ([self.responseData length] > 0 && ![self hasAcceptableContentType]) { // Don't invalidate content type if there is no content
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
[userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected content type %@, got %@", nil), self.acceptableContentTypes, [self.response MIMEType]] forKey:NSLocalizedDescriptionKey];
[userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected content type %@, got %@", nil), [[self class] acceptableContentTypes], [self.response MIMEType]] forKey:NSLocalizedDescriptionKey];
[userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
self.HTTPError = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo] autorelease];
@ -124,11 +146,11 @@ static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) {
}
- (BOOL)hasAcceptableStatusCode {
return !self.acceptableStatusCodes || [self.acceptableStatusCodes containsIndex:[self.response statusCode]];
return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:[self.response statusCode]];
}
- (BOOL)hasAcceptableContentType {
return !self.acceptableContentTypes || [self.acceptableContentTypes containsObject:[self.response MIMEType]];
return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:[self.response MIMEType]];
}
- (void)setSuccessCallbackQueue:(dispatch_queue_t)successCallbackQueue {
@ -183,8 +205,36 @@ static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) {
#pragma mark - AFHTTPClientOperation
+ (NSIndexSet *)acceptableStatusCodes {
return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
}
+ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes {
NSMutableIndexSet *mutableStatusCodes = [[[NSMutableIndexSet alloc] initWithIndexSet:[self acceptableStatusCodes]] autorelease];
[mutableStatusCodes addIndexes:statusCodes];
AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableStatusCodes), ^(id _self) {
return mutableStatusCodes;
});
}
+ (NSSet *)acceptableContentTypes {
return nil;
}
+ (void)addAcceptableContentTypes:(NSSet *)contentTypes {
NSMutableSet *mutableContentTypes = [[[NSMutableSet alloc] initWithSet:[self acceptableContentTypes] copyItems:YES] autorelease];
[mutableContentTypes unionSet:contentTypes];
AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableContentTypes), ^(id _self) {
return mutableContentTypes;
});
}
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return YES;
if (![[self class] isEqual:[AFHTTPRequestOperation class]]) {
return YES;
}
return [[self acceptableContentTypes] intersectsSet:AFContentTypesFromHTTPHeader([request valueForHTTPHeaderField:@"Accept"])];
}
@end

View file

@ -37,9 +37,6 @@ static dispatch_queue_t image_request_operation_processing_queue() {
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
@property (readwrite, nonatomic, retain) NSImage *responseImage;
#endif
+ (NSSet *)defaultAcceptableContentTypes;
+ (NSSet *)defaultAcceptablePathExtensions;
@end
@implementation AFImageRequestOperation
@ -126,22 +123,12 @@ static dispatch_queue_t image_request_operation_processing_queue() {
}
#endif
+ (NSSet *)defaultAcceptableContentTypes {
return [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
}
+ (NSSet *)defaultAcceptablePathExtensions {
return [NSSet setWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil];
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes];
#if __IPHONE_OS_VERSION_MIN_REQUIRED
self.imageScale = [[UIScreen mainScreen] scale];
#endif
@ -192,33 +179,19 @@ static dispatch_queue_t image_request_operation_processing_queue() {
#pragma mark - AFHTTPClientOperation
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]];
+ (NSSet *)acceptableContentTypes {
return [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
}
#if __IPHONE_OS_VERSION_MIN_REQUIRED
+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id object))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{
return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) {
success(image);
} failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) {
failure(response, error);
}];
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
static NSSet * _acceptablePathExtension = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_acceptablePathExtension = [[NSSet alloc] initWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil];
});
return [_acceptablePathExtension containsObject:[[request URL] pathExtension]] || [super canProcessRequest:request];
}
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id object))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{
return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) {
success(image);
} failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) {
failure(response, error);
}];
}
#endif
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

View file

@ -35,9 +35,6 @@ static dispatch_queue_t json_request_operation_processing_queue() {
@interface AFJSONRequestOperation ()
@property (readwrite, nonatomic, retain) id responseJSON;
@property (readwrite, nonatomic, retain) NSError *JSONError;
+ (NSSet *)defaultAcceptableContentTypes;
+ (NSSet *)defaultAcceptablePathExtensions;
@end
@implementation AFJSONRequestOperation
@ -62,29 +59,6 @@ static dispatch_queue_t json_request_operation_processing_queue() {
return requestOperation;
}
+ (NSSet *)defaultAcceptableContentTypes {
return [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
}
+ (NSSet *)defaultAcceptablePathExtensions {
return [NSSet setWithObjects:@"json", nil];
}
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]];
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes];
return self;
}
- (void)dealloc {
[_responseJSON release];
[_JSONError release];
@ -115,6 +89,16 @@ static dispatch_queue_t json_request_operation_processing_queue() {
}
}
#pragma mark - AFHTTPRequestOperation
+ (NSSet *)acceptableContentTypes {
return [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
}
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[[request URL] pathExtension] isEqualToString:@"json"] || [super canProcessRequest:request];
}
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{

View file

@ -35,9 +35,6 @@ static dispatch_queue_t property_list_request_operation_processing_queue() {
@property (readwrite, nonatomic, retain) id responsePropertyList;
@property (readwrite, nonatomic, assign) NSPropertyListFormat propertyListFormat;
@property (readwrite, nonatomic, retain) NSError *propertyListError;
+ (NSSet *)defaultAcceptableContentTypes;
+ (NSSet *)defaultAcceptablePathExtensions;
@end
@implementation AFPropertyListRequestOperation
@ -64,22 +61,12 @@ static dispatch_queue_t property_list_request_operation_processing_queue() {
return requestOperation;
}
+ (NSSet *)defaultAcceptableContentTypes {
return [NSSet setWithObjects:@"application/x-plist", nil];
}
+ (NSSet *)defaultAcceptablePathExtensions {
return [NSSet setWithObjects:@"plist", nil];
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes];
self.propertyListReadOptions = NSPropertyListImmutable;
return self;
@ -111,8 +98,14 @@ static dispatch_queue_t property_list_request_operation_processing_queue() {
}
}
#pragma mark - AFHTTPRequestOperation
+ (NSSet *)acceptableContentTypes {
return [NSSet setWithObjects:@"application/x-plist", nil];
}
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]];
return [[[request URL] pathExtension] isEqualToString:@"plist"] || [super canProcessRequest:request];
}
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

View file

@ -39,9 +39,6 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
@property (readwrite, nonatomic, retain) NSXMLDocument *responseXMLDocument;
#endif
@property (readwrite, nonatomic, retain) NSError *XMLError;
+ (NSSet *)defaultAcceptableContentTypes;
+ (NSSet *)defaultAcceptablePathExtensions;
@end
@implementation AFXMLRequestOperation
@ -91,25 +88,6 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
}
#endif
+ (NSSet *)defaultAcceptableContentTypes {
return [NSSet setWithObjects:@"application/xml", @"text/xml", nil];
}
+ (NSSet *)defaultAcceptablePathExtensions {
return [NSSet setWithObjects:@"xml", nil];
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes];
return self;
}
- (void)dealloc {
[_responseXMLParser release];
@ -158,8 +136,14 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
self.responseXMLParser.delegate = nil;
}
#pragma mark - AFHTTPRequestOperation
+ (NSSet *)acceptableContentTypes {
return [NSSet setWithObjects:@"application/xml", @"text/xml", nil];
}
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]];
return [[[request URL] pathExtension] isEqualToString:@"xml"] || [super canProcessRequest:request];
}
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success