Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Initial Commit

  • Loading branch information...
commit 2bdd6fa025c96b805ef60c363ce99894f2db6308 0 parents
@patcoll authored Pat Collins committed
30 .gitignore
@@ -0,0 +1,30 @@
+# xcode noise
+build/*
+*.pbxuser
+*.xcuserstate
+*.mode1v3
+
+# old skool
+.svn
+
+# osx noise
+.DS_Store
+profile
+
+build/
+
+*.mode1
+*.mode1v3
+*.mode2v3
+*.perspective
+*.perspectivev3
+*.pbxuser
+*.xcworkspace
+xcuserdata
+
+.svn
+CVS
+
+.DS_Store
+*~.nib
+*.swp
65 JSON.h
@@ -0,0 +1,65 @@
+/*
+ Copyright (C) 2009-2010 Stig Brautaset. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name of the author nor the names of its contributors may be used
+ to endorse or promote products derived from this software without specific
+ prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ @mainpage A strict JSON parser and generator for Objective-C
+
+ JSON (JavaScript Object Notation) is a lightweight data-interchange
+ format. This framework provides two apis for parsing and generating
+ JSON. One standard object-based and a higher level api consisting of
+ categories added to existing Objective-C classes.
+
+ This framework does its best to be as strict as possible, both in what it accepts and what it generates. For example, it does not support trailing commas in arrays or objects. Nor does it support embedded comments, or anything else not in the JSON specification. This is considered a feature.
+
+ @section Links
+
+ @li <a href="http://stig.github.com/json-framework">Project home page</a>.
+ @li Online version of the <a href="http://stig.github.com/json-framework/api">API documentation</a>.
+
+*/
+
+
+// This setting of 1 is best if you copy the source into your project.
+// The build transforms the 1 to a 0 when building the framework and static lib.
+
+#if 1
+
+#import "SBJsonParser.h"
+#import "SBJsonWriter.h"
+#import "NSObject+SBJSON.h"
+#import "NSString+SBJSON.h"
+
+#else
+
+#import <JSON/SBJsonParser.h>
+#import <JSON/SBJsonWriter.h>
+#import <JSON/NSObject+SBJSON.h>
+#import <JSON/NSString+SBJSON.h>
+
+#endif
53 NSObject+SBJSON.h
@@ -0,0 +1,53 @@
+/*
+ Copyright (C) 2009 Stig Brautaset. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name of the author nor the names of its contributors may be used
+ to endorse or promote products derived from this software without specific
+ prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import <Foundation/Foundation.h>
+
+
+/**
+ @brief Adds JSON generation to Foundation classes
+
+ This is a category on NSObject that adds methods for returning JSON representations
+ of standard objects to the objects themselves. This means you can call the
+ -JSONRepresentation method on an NSArray object and it'll do what you want.
+ */
+@interface NSObject (NSObject_SBJSON)
+
+/**
+ @brief Returns a string containing the receiver encoded in JSON.
+
+ This method is added as a category on NSObject but is only actually
+ supported for the following objects:
+ @li NSDictionary
+ @li NSArray
+ */
+- (NSString *)JSONRepresentation;
+
+@end
+
44 NSObject+SBJSON.m
@@ -0,0 +1,44 @@
+/*
+ Copyright (C) 2009 Stig Brautaset. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name of the author nor the names of its contributors may be used
+ to endorse or promote products derived from this software without specific
+ prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import "NSObject+SBJSON.h"
+#import "SBJsonWriter.h"
+
+@implementation NSObject (NSObject_SBJSON)
+
+- (NSString *)JSONRepresentation {
+ SBJsonWriter *jsonWriter = [SBJsonWriter new];
+ NSString *json = [jsonWriter stringWithObject:self];
+ if (!json)
+ NSLog(@"-JSONRepresentation failed. Error trace is: %@", [jsonWriter errorTrace]);
+ [jsonWriter release];
+ return json;
+}
+
+@end
48 NSString+SBJSON.h
@@ -0,0 +1,48 @@
+/*
+ Copyright (C) 2009 Stig Brautaset. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name of the author nor the names of its contributors may be used
+ to endorse or promote products derived from this software without specific
+ prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import <Foundation/Foundation.h>
+
+/**
+ @brief Adds JSON parsing methods to NSString
+
+This is a category on NSString that adds methods for parsing the target string.
+*/
+@interface NSString (NSString_SBJSON)
+
+/**
+ @brief Returns the NSDictionary or NSArray represented by the current string's JSON representation.
+
+ Returns the dictionary or array represented in the receiver, or nil on error.
+
+ Returns the NSDictionary or NSArray represented by the current string's JSON representation.
+ */
+- (id)JSONValue;
+
+@end
45 NSString+SBJSON.m
@@ -0,0 +1,45 @@
+/*
+ Copyright (C) 2007-2009 Stig Brautaset. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name of the author nor the names of its contributors may be used
+ to endorse or promote products derived from this software without specific
+ prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import "NSString+SBJSON.h"
+#import "SBJsonParser.h"
+
+@implementation NSString (NSString_SBJSON)
+
+- (id)JSONValue
+{
+ SBJsonParser *jsonParser = [SBJsonParser new];
+ id repr = [jsonParser objectWithString:self];
+ if (!repr)
+ NSLog(@"-JSONValue failed. Error trace is: %@", [jsonParser errorTrace]);
+ [jsonParser release];
+ return repr;
+}
+
+@end
27 PLInvocationHandler.h
@@ -0,0 +1,27 @@
+//
+// PLInvocationHandler.h
+// fcgi_objc
+//
+// Created by ampatspell on 8/30/08.
+// Copyright 2008 ampatspell. All rights reserved.
+//
+
+#import <Cocoa/Cocoa.h>
+#include <fcgiapp.h>
+
+@interface PLInvocationHandler : NSObject {
+ @private
+ int invocationNumber;
+}
+@property(readwrite) int invocationNumber;
+
+- (PLInvocationHandler *)init;
+
+- (void)handleInputStream:(FCGX_Stream *)inputStream
+ outputStream:(FCGX_Stream *)outputStream
+ errorStream:(FCGX_Stream *)errorStream
+ paramArray:(FCGX_ParamArray)params;
+
+- (int)incrementInvocationNumber;
+
+@end
59 PLInvocationHandler.m
@@ -0,0 +1,59 @@
+//
+// PLInvocationHandler.m
+// fcgi_objc
+//
+// Created by ampatspell on 8/30/08.
+// Copyright 2008 ampatspell. All rights reserved.
+//
+
+#import "PLInvocationHandler.h"
+
+
+@implementation PLInvocationHandler
+@synthesize invocationNumber;
+
+- (PLInvocationHandler *)init
+{
+ if(self == [super init]) {
+ [self setInvocationNumber:0];
+ }
+ return self;
+}
+
+#pragma mark -
+
+- (void)handleInputStream:(FCGX_Stream *)inputStream
+ outputStream:(FCGX_Stream *)outputStream
+ errorStream:(FCGX_Stream *)errorStream
+ paramArray:(FCGX_ParamArray)params;
+{
+ FCGX_FPrintF(outputStream, "Content-type: text/html\r\n\r\n");
+ FCGX_FPrintF(outputStream, "Hello from %i with #%i", getpid(), [self incrementInvocationNumber]);
+ FCGX_FPrintF(outputStream, "<br>");
+
+// NSDictionary *dict = [[NSProcessInfo processInfo] environment];
+// for (NSString *key in dict) {
+// NSString *val = [dict objectForKey:key];
+// FCGX_FPrintF(outputStream, "%s: %s<br>", [key UTF8String], [val UTF8String]);
+// }
+
+ FCGX_FPrintF(outputStream, "sizeof FCGX_ParamArray: %d<br>", sizeof(FCGX_ParamArray));
+
+ for (int i=0; i<sizeof(params); i++) {
+ FCGX_FPrintF(outputStream, "%s<br>", params[i]);
+ }
+}
+
+- (int)incrementInvocationNumber
+{
+ return invocationNumber++;
+}
+
+#pragma mark -
+
+- (void)dealloc
+{
+ [super dealloc];
+}
+
+@end
86 SBJsonBase.h
@@ -0,0 +1,86 @@
+/*
+ Copyright (C) 2009 Stig Brautaset. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name of the author nor the names of its contributors may be used
+ to endorse or promote products derived from this software without specific
+ prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import <Foundation/Foundation.h>
+
+extern NSString * SBJSONErrorDomain;
+
+
+enum {
+ EUNSUPPORTED = 1,
+ EPARSENUM,
+ EPARSE,
+ EFRAGMENT,
+ ECTRL,
+ EUNICODE,
+ EDEPTH,
+ EESCAPE,
+ ETRAILCOMMA,
+ ETRAILGARBAGE,
+ EEOF,
+ EINPUT
+};
+
+/**
+ @brief Common base class for parsing & writing.
+
+ This class contains the common error-handling code and option between the parser/writer.
+ */
+@interface SBJsonBase : NSObject {
+ NSMutableArray *errorTrace;
+
+@protected
+ NSUInteger depth, maxDepth;
+}
+
+/**
+ @brief The maximum recursing depth.
+
+ Defaults to 512. If the input is nested deeper than this the input will be deemed to be
+ malicious and the parser returns nil, signalling an error. ("Nested too deep".) You can
+ turn off this security feature by setting the maxDepth value to 0.
+ */
+@property NSUInteger maxDepth;
+
+/**
+ @brief Return an error trace, or nil if there was no errors.
+
+ Note that this method returns the trace of the last method that failed.
+ You need to check the return value of the call you're making to figure out
+ if the call actually failed, before you know call this method.
+ */
+ @property(copy,readonly) NSArray* errorTrace;
+
+/// @internal for use in subclasses to add errors to the stack trace
+- (void)addErrorWithCode:(NSUInteger)code description:(NSString*)str;
+
+/// @internal for use in subclasess to clear the error before a new parsing attempt
+- (void)clearErrorTrace;
+
+@end
78 SBJsonBase.m
@@ -0,0 +1,78 @@
+/*
+ Copyright (C) 2009 Stig Brautaset. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name of the author nor the names of its contributors may be used
+ to endorse or promote products derived from this software without specific
+ prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import "SBJsonBase.h"
+NSString * SBJSONErrorDomain = @"org.brautaset.JSON.ErrorDomain";
+
+
+@implementation SBJsonBase
+
+@synthesize errorTrace;
+@synthesize maxDepth;
+
+- (id)init {
+ self = [super init];
+ if (self)
+ self.maxDepth = 512;
+ return self;
+}
+
+- (void)dealloc {
+ [errorTrace release];
+ [super dealloc];
+}
+
+- (void)addErrorWithCode:(NSUInteger)code description:(NSString*)str {
+ NSDictionary *userInfo;
+ if (!errorTrace) {
+ errorTrace = [NSMutableArray new];
+ userInfo = [NSDictionary dictionaryWithObject:str forKey:NSLocalizedDescriptionKey];
+
+ } else {
+ userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
+ str, NSLocalizedDescriptionKey,
+ [errorTrace lastObject], NSUnderlyingErrorKey,
+ nil];
+ }
+
+ NSError *error = [NSError errorWithDomain:SBJSONErrorDomain code:code userInfo:userInfo];
+
+ [self willChangeValueForKey:@"errorTrace"];
+ [errorTrace addObject:error];
+ [self didChangeValueForKey:@"errorTrace"];
+}
+
+- (void)clearErrorTrace {
+ [self willChangeValueForKey:@"errorTrace"];
+ [errorTrace release];
+ errorTrace = nil;
+ [self didChangeValueForKey:@"errorTrace"];
+}
+
+@end
86 SBJsonParser.h
@@ -0,0 +1,86 @@
+/*
+ Copyright (C) 2009 Stig Brautaset. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name of the author nor the names of its contributors may be used
+ to endorse or promote products derived from this software without specific
+ prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import <Foundation/Foundation.h>
+#import "SBJsonBase.h"
+
+/**
+ @brief The JSON parser class.
+
+ JSON is mapped to Objective-C types in the following way:
+
+ @li Null -> NSNull
+ @li String -> NSMutableString
+ @li Array -> NSMutableArray
+ @li Object -> NSMutableDictionary
+ @li Boolean -> NSNumber (initialised with -initWithBool:)
+ @li Number -> (NSNumber | NSDecimalNumber)
+
+ Since Objective-C doesn't have a dedicated class for boolean values, these turns into NSNumber
+ instances. These are initialised with the -initWithBool: method, and
+ round-trip back to JSON properly. (They won't silently suddenly become 0 or 1; they'll be
+ represented as 'true' and 'false' again.)
+
+ As an optimisation short JSON integers turn into NSNumber instances, while complex ones turn into NSDecimalNumber instances.
+ We can thus avoid any loss of precision as JSON allows ridiculously large numbers.
+
+ */
+@interface SBJsonParser : SBJsonBase {
+
+@private
+ const char *c;
+}
+
+/**
+ @brief Return the object represented by the given string
+
+ Returns the object represented by the passed-in string or nil on error. The returned object can be
+ a string, number, boolean, null, array or dictionary.
+
+ @param repr the json string to parse
+ */
+- (id)objectWithString:(NSString *)repr;
+
+/**
+ @brief Return the object represented by the given string
+
+ Returns the object represented by the passed-in string or nil on error. The returned object can be
+ a string, number, boolean, null, array or dictionary.
+
+ @param jsonText the json string to parse
+ @param error pointer to an NSError object to populate on error
+ */
+
+- (id)objectWithString:(NSString*)jsonText
+ error:(NSError**)error;
+
+
+@end
+
+
516 SBJsonParser.m
@@ -0,0 +1,516 @@
+/*
+ Copyright (C) 2009,2010 Stig Brautaset. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name of the author nor the names of its contributors may be used
+ to endorse or promote products derived from this software without specific
+ prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import "SBJsonParser.h"
+
+@interface SBJsonParser ()
+
+- (BOOL)scanValue:(NSObject **)o;
+
+- (BOOL)scanRestOfArray:(NSMutableArray **)o;
+- (BOOL)scanRestOfDictionary:(NSMutableDictionary **)o;
+- (BOOL)scanRestOfNull:(NSNull **)o;
+- (BOOL)scanRestOfFalse:(NSNumber **)o;
+- (BOOL)scanRestOfTrue:(NSNumber **)o;
+- (BOOL)scanRestOfString:(NSMutableString **)o;
+
+// Cannot manage without looking at the first digit
+- (BOOL)scanNumber:(NSNumber **)o;
+
+- (BOOL)scanHexQuad:(unichar *)x;
+- (BOOL)scanUnicodeChar:(unichar *)x;
+
+- (BOOL)scanIsAtEnd;
+
+@end
+
+#define skipWhitespace(c) while (isspace(*c)) c++
+#define skipDigits(c) while (isdigit(*c)) c++
+
+
+@implementation SBJsonParser
+
+static char ctrl[0x22];
+
+
++ (void)initialize {
+ ctrl[0] = '\"';
+ ctrl[1] = '\\';
+ for (int i = 1; i < 0x20; i++)
+ ctrl[i+1] = i;
+ ctrl[0x21] = 0;
+}
+
+- (id)objectWithString:(NSString *)repr {
+ [self clearErrorTrace];
+
+ if (!repr) {
+ [self addErrorWithCode:EINPUT description:@"Input was 'nil'"];
+ return nil;
+ }
+
+ depth = 0;
+ c = [repr UTF8String];
+
+ id o;
+ if (![self scanValue:&o]) {
+ return nil;
+ }
+
+ // We found some valid JSON. But did it also contain something else?
+ if (![self scanIsAtEnd]) {
+ [self addErrorWithCode:ETRAILGARBAGE description:@"Garbage after JSON"];
+ return nil;
+ }
+
+ NSAssert1(o, @"Should have a valid object from %@", repr);
+
+ // Check that the object we've found is a valid JSON container.
+ if (![o isKindOfClass:[NSDictionary class]] && ![o isKindOfClass:[NSArray class]]) {
+ [self addErrorWithCode:EFRAGMENT description:@"Valid fragment, but not JSON"];
+ return nil;
+ }
+
+ return o;
+}
+
+- (id)objectWithString:(NSString*)repr error:(NSError**)error {
+ id tmp = [self objectWithString:repr];
+ if (tmp)
+ return tmp;
+
+ if (error)
+ *error = [self.errorTrace lastObject];
+ return nil;
+}
+
+
+/*
+ In contrast to the public methods, it is an error to omit the error parameter here.
+ */
+- (BOOL)scanValue:(NSObject **)o
+{
+ skipWhitespace(c);
+
+ switch (*c++) {
+ case '{':
+ return [self scanRestOfDictionary:(NSMutableDictionary **)o];
+ break;
+ case '[':
+ return [self scanRestOfArray:(NSMutableArray **)o];
+ break;
+ case '"':
+ return [self scanRestOfString:(NSMutableString **)o];
+ break;
+ case 'f':
+ return [self scanRestOfFalse:(NSNumber **)o];
+ break;
+ case 't':
+ return [self scanRestOfTrue:(NSNumber **)o];
+ break;
+ case 'n':
+ return [self scanRestOfNull:(NSNull **)o];
+ break;
+ case '-':
+ case '0'...'9':
+ c--; // cannot verify number correctly without the first character
+ return [self scanNumber:(NSNumber **)o];
+ break;
+ case '+':
+ [self addErrorWithCode:EPARSENUM description: @"Leading + disallowed in number"];
+ return NO;
+ break;
+ case 0x0:
+ [self addErrorWithCode:EEOF description:@"Unexpected end of string"];
+ return NO;
+ break;
+ default:
+ [self addErrorWithCode:EPARSE description: @"Unrecognised leading character"];
+ return NO;
+ break;
+ }
+
+ NSAssert(0, @"Should never get here");
+ return NO;
+}
+
+- (BOOL)scanRestOfTrue:(NSNumber **)o
+{
+ if (!strncmp(c, "rue", 3)) {
+ c += 3;
+ *o = [NSNumber numberWithBool:YES];
+ return YES;
+ }
+ [self addErrorWithCode:EPARSE description:@"Expected 'true'"];
+ return NO;
+}
+
+- (BOOL)scanRestOfFalse:(NSNumber **)o
+{
+ if (!strncmp(c, "alse", 4)) {
+ c += 4;
+ *o = [NSNumber numberWithBool:NO];
+ return YES;
+ }
+ [self addErrorWithCode:EPARSE description: @"Expected 'false'"];
+ return NO;
+}
+
+- (BOOL)scanRestOfNull:(NSNull **)o {
+ if (!strncmp(c, "ull", 3)) {
+ c += 3;
+ *o = [NSNull null];
+ return YES;
+ }
+ [self addErrorWithCode:EPARSE description: @"Expected 'null'"];
+ return NO;
+}
+
+- (BOOL)scanRestOfArray:(NSMutableArray **)o {
+ if (maxDepth && ++depth > maxDepth) {
+ [self addErrorWithCode:EDEPTH description: @"Nested too deep"];
+ return NO;
+ }
+
+ *o = [NSMutableArray arrayWithCapacity:8];
+
+ for (; *c ;) {
+ id v;
+
+ skipWhitespace(c);
+ if (*c == ']' && c++) {
+ depth--;
+ return YES;
+ }
+
+ if (![self scanValue:&v]) {
+ [self addErrorWithCode:EPARSE description:@"Expected value while parsing array"];
+ return NO;
+ }
+
+ [*o addObject:v];
+
+ skipWhitespace(c);
+ if (*c == ',' && c++) {
+ skipWhitespace(c);
+ if (*c == ']') {
+ [self addErrorWithCode:ETRAILCOMMA description: @"Trailing comma disallowed in array"];
+ return NO;
+ }
+ }
+ }
+
+ [self addErrorWithCode:EEOF description: @"End of input while parsing array"];
+ return NO;
+}
+
+- (BOOL)scanRestOfDictionary:(NSMutableDictionary **)o
+{
+ if (maxDepth && ++depth > maxDepth) {
+ [self addErrorWithCode:EDEPTH description: @"Nested too deep"];
+ return NO;
+ }
+
+ *o = [NSMutableDictionary dictionaryWithCapacity:7];
+
+ for (; *c ;) {
+ id k, v;
+
+ skipWhitespace(c);
+ if (*c == '}' && c++) {
+ depth--;
+ return YES;
+ }
+
+ if (!(*c == '\"' && c++ && [self scanRestOfString:&k])) {
+ [self addErrorWithCode:EPARSE description: @"Object key string expected"];
+ return NO;
+ }
+
+ skipWhitespace(c);
+ if (*c != ':') {
+ [self addErrorWithCode:EPARSE description: @"Expected ':' separating key and value"];
+ return NO;
+ }
+
+ c++;
+ if (![self scanValue:&v]) {
+ NSString *string = [NSString stringWithFormat:@"Object value expected for key: %@", k];
+ [self addErrorWithCode:EPARSE description: string];
+ return NO;
+ }
+
+ [*o setObject:v forKey:k];
+
+ skipWhitespace(c);
+ if (*c == ',' && c++) {
+ skipWhitespace(c);
+ if (*c == '}') {
+ [self addErrorWithCode:ETRAILCOMMA description: @"Trailing comma disallowed in object"];
+ return NO;
+ }
+ }
+ }
+
+ [self addErrorWithCode:EEOF description: @"End of input while parsing object"];
+ return NO;
+}
+
+- (BOOL)scanRestOfString:(NSMutableString **)o
+{
+ // if the string has no control characters in it, return it in one go, without any temporary allocations.
+ size_t len = strcspn(c, ctrl);
+ if (len && *(c + len) == '\"')
+ {
+ *o = [[[NSMutableString alloc] initWithBytes:(char*)c length:len encoding:NSUTF8StringEncoding] autorelease];
+ c += len + 1;
+ return YES;
+ }
+
+ *o = [NSMutableString stringWithCapacity:16];
+ do {
+ // First see if there's a portion we can grab in one go.
+ // Doing this caused a massive speedup on the long string.
+ len = strcspn(c, ctrl);
+ if (len) {
+ // check for
+ id t = [[NSString alloc] initWithBytesNoCopy:(char*)c
+ length:len
+ encoding:NSUTF8StringEncoding
+ freeWhenDone:NO];
+ if (t) {
+ [*o appendString:t];
+ [t release];
+ c += len;
+ }
+ }
+
+ if (*c == '"') {
+ c++;
+ return YES;
+
+ } else if (*c == '\\') {
+ unichar uc = *++c;
+ switch (uc) {
+ case '\\':
+ case '/':
+ case '"':
+ break;
+
+ case 'b': uc = '\b'; break;
+ case 'n': uc = '\n'; break;
+ case 'r': uc = '\r'; break;
+ case 't': uc = '\t'; break;
+ case 'f': uc = '\f'; break;
+
+ case 'u':
+ c++;
+ if (![self scanUnicodeChar:&uc]) {
+ [self addErrorWithCode:EUNICODE description: @"Broken unicode character"];
+ return NO;
+ }
+ c--; // hack.
+ break;
+ default:
+ [self addErrorWithCode:EESCAPE description: [NSString stringWithFormat:@"Illegal escape sequence '0x%x'", uc]];
+ return NO;
+ break;
+ }
+ CFStringAppendCharacters((CFMutableStringRef)*o, &uc, 1);
+ c++;
+
+ } else if (*c < 0x20) {
+ [self addErrorWithCode:ECTRL description: [NSString stringWithFormat:@"Unescaped control character '0x%x'", *c]];
+ return NO;
+
+ } else {
+ NSLog(@"should not be able to get here");
+ }
+ } while (*c);
+
+ [self addErrorWithCode:EEOF description:@"Unexpected EOF while parsing string"];
+ return NO;
+}
+
+- (BOOL)scanUnicodeChar:(unichar *)x
+{
+ unichar hi, lo;
+
+ if (![self scanHexQuad:&hi]) {
+ [self addErrorWithCode:EUNICODE description: @"Missing hex quad"];
+ return NO;
+ }
+
+ if (hi >= 0xd800) { // high surrogate char?
+ if (hi < 0xdc00) { // yes - expect a low char
+
+ if (!(*c == '\\' && ++c && *c == 'u' && ++c && [self scanHexQuad:&lo])) {
+ [self addErrorWithCode:EUNICODE description: @"Missing low character in surrogate pair"];
+ return NO;
+ }
+
+ if (lo < 0xdc00 || lo >= 0xdfff) {
+ [self addErrorWithCode:EUNICODE description:@"Invalid low surrogate char"];
+ return NO;
+ }
+
+ hi = (hi - 0xd800) * 0x400 + (lo - 0xdc00) + 0x10000;
+
+ } else if (hi < 0xe000) {
+ [self addErrorWithCode:EUNICODE description:@"Invalid high character in surrogate pair"];
+ return NO;
+ }
+ }
+
+ *x = hi;
+ return YES;
+}
+
+- (BOOL)scanHexQuad:(unichar *)x
+{
+ *x = 0;
+ for (int i = 0; i < 4; i++) {
+ unichar uc = *c;
+ c++;
+ int d = (uc >= '0' && uc <= '9')
+ ? uc - '0' : (uc >= 'a' && uc <= 'f')
+ ? (uc - 'a' + 10) : (uc >= 'A' && uc <= 'F')
+ ? (uc - 'A' + 10) : -1;
+ if (d == -1) {
+ [self addErrorWithCode:EUNICODE description:@"Missing hex digit in quad"];
+ return NO;
+ }
+ *x *= 16;
+ *x += d;
+ }
+ return YES;
+}
+
+- (BOOL)scanNumber:(NSNumber **)o
+{
+ BOOL simple = YES;
+
+ const char *ns = c;
+
+ // The logic to test for validity of the number formatting is relicensed
+ // from JSON::XS with permission from its author Marc Lehmann.
+ // (Available at the CPAN: http://search.cpan.org/dist/JSON-XS/ .)
+
+ if ('-' == *c)
+ c++;
+
+ if ('0' == *c && c++) {
+ if (isdigit(*c)) {
+ [self addErrorWithCode:EPARSENUM description: @"Leading 0 disallowed in number"];
+ return NO;
+ }
+
+ } else if (!isdigit(*c) && c != ns) {
+ [self addErrorWithCode:EPARSENUM description: @"No digits after initial minus"];
+ return NO;
+
+ } else {
+ skipDigits(c);
+ }
+
+ // Fractional part
+ if ('.' == *c && c++) {
+ simple = NO;
+ if (!isdigit(*c)) {
+ [self addErrorWithCode:EPARSENUM description: @"No digits after decimal point"];
+ return NO;
+ }
+ skipDigits(c);
+ }
+
+ // Exponential part
+ if ('e' == *c || 'E' == *c) {
+ simple = NO;
+ c++;
+
+ if ('-' == *c || '+' == *c)
+ c++;
+
+ if (!isdigit(*c)) {
+ [self addErrorWithCode:EPARSENUM description: @"No digits after exponent"];
+ return NO;
+ }
+ skipDigits(c);
+ }
+
+ // If we are only reading integers, don't go through the expense of creating an NSDecimal.
+ // This ends up being a very large perf win.
+ if (simple) {
+ BOOL negate = NO;
+ long long val = 0;
+ const char *d = ns;
+
+ if (*d == '-') {
+ negate = YES;
+ d++;
+ }
+
+ while (isdigit(*d)) {
+ val *= 10;
+ if (val < 0)
+ goto longlong_overflow;
+ val += *d - '0';
+ if (val < 0)
+ goto longlong_overflow;
+ d++;
+ }
+
+ *o = [NSNumber numberWithLongLong:negate ? -val : val];
+ return YES;
+
+ } else {
+ // jumped to by simple branch, if an overflow occured
+ longlong_overflow:;
+
+ id str = [[NSString alloc] initWithBytesNoCopy:(char*)ns
+ length:c - ns
+ encoding:NSUTF8StringEncoding
+ freeWhenDone:NO];
+ [str autorelease];
+ if (str && (*o = [NSDecimalNumber decimalNumberWithString:str]))
+ return YES;
+
+ [self addErrorWithCode:EPARSENUM description: @"Failed creating decimal instance"];
+ return NO;
+ }
+}
+
+- (BOOL)scanIsAtEnd
+{
+ skipWhitespace(c);
+ return !*c;
+}
+
+
+@end
127 SBJsonWriter.h
@@ -0,0 +1,127 @@
+/*
+ Copyright (C) 2009 Stig Brautaset. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name of the author nor the names of its contributors may be used
+ to endorse or promote products derived from this software without specific
+ prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import <Foundation/Foundation.h>
+#import "SBJsonBase.h"
+
+/**
+ @brief The JSON writer class.
+
+ Objective-C types are mapped to JSON types in the following way:
+
+ @li NSNull -> Null
+ @li NSString -> String
+ @li NSArray -> Array
+ @li NSDictionary -> Object
+ @li NSNumber (-initWithBool:) -> Boolean
+ @li NSNumber -> Number
+
+ In JSON the keys of an object must be strings. NSDictionary keys need
+ not be, but attempting to convert an NSDictionary with non-string keys
+ into JSON will throw an exception.
+
+ NSNumber instances created with the +initWithBool: method are
+ converted into the JSON boolean "true" and "false" values, and vice
+ versa. Any other NSNumber instances are converted to a JSON number the
+ way you would expect.
+
+ */
+@interface SBJsonWriter : SBJsonBase {
+
+@private
+ BOOL sortKeys, humanReadable;
+}
+
+/**
+ @brief Whether we are generating human-readable (multiline) JSON.
+
+ Set whether or not to generate human-readable JSON. The default is NO, which produces
+ JSON without any whitespace. (Except inside strings.) If set to YES, generates human-readable
+ JSON with linebreaks after each array value and dictionary key/value pair, indented two
+ spaces per nesting level.
+ */
+@property BOOL humanReadable;
+
+/**
+ @brief Whether or not to sort the dictionary keys in the output.
+
+ If this is set to YES, the dictionary keys in the JSON output will be in sorted order.
+ (This is useful if you need to compare two structures, for example.) The default is NO.
+ */
+@property BOOL sortKeys;
+
+/**
+ @brief Return JSON representation (or fragment) for the given object.
+
+ Returns a string containing JSON representation of the passed in value, or nil on error.
+ If nil is returned and @p error is not NULL, @p *error can be interrogated to find the cause of the error.
+
+ @param value any instance that can be represented as a JSON fragment
+
+ */
+- (NSString*)stringWithObject:(id)value;
+
+/**
+ @brief Return JSON representation (or fragment) for the given object.
+
+ Returns a string containing JSON representation of the passed in value, or nil on error.
+ If nil is returned and @p error is not NULL, @p *error can be interrogated to find the cause of the error.
+
+ @param value any instance that can be represented as a JSON fragment
+ @param error pointer to object to be populated with NSError on failure
+
+ */- (NSString*)stringWithObject:(id)value
+ error:(NSError**)error;
+
+
+@end
+
+/**
+ @brief Allows generation of JSON for otherwise unsupported classes.
+
+ If you have a custom class that you want to create a JSON representation for you can implement
+ this method in your class. It should return a representation of your object defined
+ in terms of objects that can be translated into JSON. For example, a Person
+ object might implement it like this:
+
+ @code
+ - (id)proxyForJson {
+ return [NSDictionary dictionaryWithObjectsAndKeys:
+ name, @"name",
+ phone, @"phone",
+ email, @"email",
+ nil];
+ }
+ @endcode
+
+ */
+@interface NSObject (SBProxyForJson)
+- (id)proxyForJson;
+@end
+
239 SBJsonWriter.m
@@ -0,0 +1,239 @@
+/*
+ Copyright (C) 2009 Stig Brautaset. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name of the author nor the names of its contributors may be used
+ to endorse or promote products derived from this software without specific
+ prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import "SBJsonWriter.h"
+
+@interface SBJsonWriter ()
+
+- (BOOL)appendValue:(id)fragment into:(NSMutableString*)json;
+- (BOOL)appendArray:(NSArray*)fragment into:(NSMutableString*)json;
+- (BOOL)appendDictionary:(NSDictionary*)fragment into:(NSMutableString*)json;
+- (BOOL)appendString:(NSString*)fragment into:(NSMutableString*)json;
+
+- (NSString*)indent;
+
+@end
+
+@implementation SBJsonWriter
+
+@synthesize sortKeys;
+@synthesize humanReadable;
+
+static NSMutableCharacterSet *kEscapeChars;
+
++ (void)initialize {
+ kEscapeChars = [[NSMutableCharacterSet characterSetWithRange: NSMakeRange(0,32)] retain];
+ [kEscapeChars addCharactersInString: @"\"\\"];
+}
+
+- (NSString*)stringWithObject:(id)value {
+ [self clearErrorTrace];
+
+ if ([value isKindOfClass:[NSDictionary class]] || [value isKindOfClass:[NSArray class]]) {
+ depth = 0;
+ NSMutableString *json = [NSMutableString stringWithCapacity:128];
+ if ([self appendValue:value into:json])
+ return json;
+ }
+
+ if ([value respondsToSelector:@selector(proxyForJson)]) {
+ NSString *tmp = [self stringWithObject:[value proxyForJson]];
+ if (tmp)
+ return tmp;
+ }
+
+ [self addErrorWithCode:EFRAGMENT description:@"Not valid type for JSON"];
+ return nil;
+}
+
+- (NSString*)stringWithObject:(id)value error:(NSError**)error {
+ NSString *tmp = [self stringWithObject:value];
+ if (tmp)
+ return tmp;
+
+ if (error)
+ *error = [self.errorTrace lastObject];
+ return nil;
+}
+
+- (NSString*)indent {
+ return [@"\n" stringByPaddingToLength:1 + 2 * depth withString:@" " startingAtIndex:0];
+}
+
+- (BOOL)appendValue:(id)fragment into:(NSMutableString*)json {
+ if ([fragment isKindOfClass:[NSDictionary class]]) {
+ if (![self appendDictionary:fragment into:json])
+ return NO;
+
+ } else if ([fragment isKindOfClass:[NSArray class]]) {
+ if (![self appendArray:fragment into:json])
+ return NO;
+
+ } else if ([fragment isKindOfClass:[NSString class]]) {
+ if (![self appendString:fragment into:json])
+ return NO;
+
+ } else if ([fragment isKindOfClass:[NSNumber class]]) {
+ if ('c' == *[fragment objCType]) {
+ [json appendString:[fragment boolValue] ? @"true" : @"false"];
+ } else if ([fragment isEqualToNumber:(NSNumber*)kCFNumberNaN]) {
+ [self addErrorWithCode:EUNSUPPORTED description:@"NaN is not a valid number in JSON"];
+ return NO;
+
+ } else if (isinf([fragment doubleValue])) {
+ [self addErrorWithCode:EUNSUPPORTED description:@"Infinity is not a valid number in JSON"];
+ return NO;
+
+ } else {
+ [json appendString:[fragment stringValue]];
+ }
+ } else if ([fragment isKindOfClass:[NSNull class]]) {
+ [json appendString:@"null"];
+ } else if ([fragment respondsToSelector:@selector(proxyForJson)]) {
+ [self appendValue:[fragment proxyForJson] into:json];
+
+ } else {
+ [self addErrorWithCode:EUNSUPPORTED description:[NSString stringWithFormat:@"JSON serialisation not supported for %@", [fragment class]]];
+ return NO;
+ }
+ return YES;
+}
+
+- (BOOL)appendArray:(NSArray*)fragment into:(NSMutableString*)json {
+ if (maxDepth && ++depth > maxDepth) {
+ [self addErrorWithCode:EDEPTH description: @"Nested too deep"];
+ return NO;
+ }
+ [json appendString:@"["];
+
+ BOOL addComma = NO;
+ for (id value in fragment) {
+ if (addComma)
+ [json appendString:@","];
+ else
+ addComma = YES;
+
+ if ([self humanReadable])
+ [json appendString:[self indent]];
+
+ if (![self appendValue:value into:json]) {
+ return NO;
+ }
+ }
+
+ depth--;
+ if ([self humanReadable] && [fragment count])
+ [json appendString:[self indent]];
+ [json appendString:@"]"];
+ return YES;
+}
+
+- (BOOL)appendDictionary:(NSDictionary*)fragment into:(NSMutableString*)json {
+ if (maxDepth && ++depth > maxDepth) {
+ [self addErrorWithCode:EDEPTH description: @"Nested too deep"];
+ return NO;
+ }
+ [json appendString:@"{"];
+
+ NSString *colon = [self humanReadable] ? @" : " : @":";
+ BOOL addComma = NO;
+ NSArray *keys = [fragment allKeys];
+ if (self.sortKeys)
+ keys = [keys sortedArrayUsingSelector:@selector(compare:)];
+
+ for (id value in keys) {
+ if (addComma)
+ [json appendString:@","];
+ else
+ addComma = YES;
+
+ if ([self humanReadable])
+ [json appendString:[self indent]];
+
+ if (![value isKindOfClass:[NSString class]]) {
+ [self addErrorWithCode:EUNSUPPORTED description: @"JSON object key must be string"];
+ return NO;
+ }
+
+ if (![self appendString:value into:json])
+ return NO;
+
+ [json appendString:colon];
+ if (![self appendValue:[fragment objectForKey:value] into:json]) {
+ [self addErrorWithCode:EUNSUPPORTED description:[NSString stringWithFormat:@"Unsupported value for key %@ in object", value]];
+ return NO;
+ }
+ }
+
+ depth--;
+ if ([self humanReadable] && [fragment count])
+ [json appendString:[self indent]];
+ [json appendString:@"}"];
+ return YES;
+}
+
+- (BOOL)appendString:(NSString*)fragment into:(NSMutableString*)json {
+
+ [json appendString:@"\""];
+
+ NSRange esc = [fragment rangeOfCharacterFromSet:kEscapeChars];
+ if ( !esc.length ) {
+ // No special chars -- can just add the raw string:
+ [json appendString:fragment];
+
+ } else {
+ NSUInteger length = [fragment length];
+ for (NSUInteger i = 0; i < length; i++) {
+ unichar uc = [fragment characterAtIndex:i];
+ switch (uc) {
+ case '"': [json appendString:@"\\\""]; break;
+ case '\\': [json appendString:@"\\\\"]; break;
+ case '\t': [json appendString:@"\\t"]; break;
+ case '\n': [json appendString:@"\\n"]; break;
+ case '\r': [json appendString:@"\\r"]; break;
+ case '\b': [json appendString:@"\\b"]; break;
+ case '\f': [json appendString:@"\\f"]; break;
+ default:
+ if (uc < 0x20) {
+ [json appendFormat:@"\\u%04x", uc];
+ } else {
+ CFStringAppendCharacters((CFMutableStringRef)json, &uc, 1);
+ }
+ break;
+
+ }
+ }
+ }
+
+ [json appendString:@"\""];
+ return YES;
+}
+
+
+@end
419 Web.xcodeproj/project.pbxproj
@@ -0,0 +1,419 @@
+// !$*UTF8*$!
+{
+ archiveVersion = 1;
+ classes = {
+ };
+ objectVersion = 46;
+ objects = {
+
+/* Begin PBXBuildFile section */
+ 7906CA49133A32FF0007C9D0 /* PLInvocationHandler.m in Sources */ = {isa = PBXBuildFile; fileRef = 7906CA48133A32FF0007C9D0 /* PLInvocationHandler.m */; };
+ 7906CA4D133A372A0007C9D0 /* libfcgi.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 7906CA4C133A372A0007C9D0 /* libfcgi.dylib */; };
+ 7906CA9D133BAC180007C9D0 /* NSObject+SBJSON.m in Sources */ = {isa = PBXBuildFile; fileRef = 7906CA94133BAC180007C9D0 /* NSObject+SBJSON.m */; };
+ 7906CA9E133BAC180007C9D0 /* NSString+SBJSON.m in Sources */ = {isa = PBXBuildFile; fileRef = 7906CA96133BAC180007C9D0 /* NSString+SBJSON.m */; };
+ 7906CA9F133BAC180007C9D0 /* SBJsonBase.m in Sources */ = {isa = PBXBuildFile; fileRef = 7906CA98133BAC180007C9D0 /* SBJsonBase.m */; };
+ 7906CAA0133BAC180007C9D0 /* SBJsonParser.m in Sources */ = {isa = PBXBuildFile; fileRef = 7906CA9A133BAC180007C9D0 /* SBJsonParser.m */; };
+ 7906CAA1133BAC180007C9D0 /* SBJsonWriter.m in Sources */ = {isa = PBXBuildFile; fileRef = 7906CA9C133BAC180007C9D0 /* SBJsonWriter.m */; };
+ 7906CAA5133BBB480007C9D0 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 79441AE6133A10F000980FE8 /* main.m */; };
+ 7906CAA6133BBB480007C9D0 /* PLInvocationHandler.m in Sources */ = {isa = PBXBuildFile; fileRef = 7906CA48133A32FF0007C9D0 /* PLInvocationHandler.m */; };
+ 7906CAA7133BBB480007C9D0 /* NSObject+SBJSON.m in Sources */ = {isa = PBXBuildFile; fileRef = 7906CA94133BAC180007C9D0 /* NSObject+SBJSON.m */; };
+ 7906CAA8133BBB480007C9D0 /* NSString+SBJSON.m in Sources */ = {isa = PBXBuildFile; fileRef = 7906CA96133BAC180007C9D0 /* NSString+SBJSON.m */; };
+ 7906CAA9133BBB480007C9D0 /* SBJsonBase.m in Sources */ = {isa = PBXBuildFile; fileRef = 7906CA98133BAC180007C9D0 /* SBJsonBase.m */; };
+ 7906CAAA133BBB480007C9D0 /* SBJsonParser.m in Sources */ = {isa = PBXBuildFile; fileRef = 7906CA9A133BAC180007C9D0 /* SBJsonParser.m */; };
+ 7906CAAB133BBB480007C9D0 /* SBJsonWriter.m in Sources */ = {isa = PBXBuildFile; fileRef = 7906CA9C133BAC180007C9D0 /* SBJsonWriter.m */; };
+ 7906CAAD133BBB480007C9D0 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79441AE3133A10F000980FE8 /* Foundation.framework */; };
+ 7906CAAE133BBB480007C9D0 /* libfcgi.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 7906CA4C133A372A0007C9D0 /* libfcgi.dylib */; };
+ 7906CABF133BC6EA0007C9D0 /* Web in CopyFiles */ = {isa = PBXBuildFile; fileRef = 7906CABD133BC6AD0007C9D0 /* Web */; };
+ 7906CAC8133BCA7F0007C9D0 /* WebFastCGI-bin in CopyFiles */ = {isa = PBXBuildFile; fileRef = 7906CAC4133BC9300007C9D0 /* WebFastCGI-bin */; };
+ 79441AE4133A10F000980FE8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79441AE3133A10F000980FE8 /* Foundation.framework */; };
+ 79441AE7133A10F000980FE8 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 79441AE6133A10F000980FE8 /* main.m */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXCopyFilesBuildPhase section */
+ 7906CAAF133BBB480007C9D0 /* CopyFiles */ = {
+ isa = PBXCopyFilesBuildPhase;
+ buildActionMask = 12;
+ dstPath = /Users/patcollins/bin;
+ dstSubfolderSpec = 0;
+ files = (
+ 7906CAC8133BCA7F0007C9D0 /* WebFastCGI-bin in CopyFiles */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 79441ADD133A10F000980FE8 /* CopyFiles */ = {
+ isa = PBXCopyFilesBuildPhase;
+ buildActionMask = 12;
+ dstPath = /Users/patcollins/bin;
+ dstSubfolderSpec = 0;
+ files = (
+ 7906CABF133BC6EA0007C9D0 /* Web in CopyFiles */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXCopyFilesBuildPhase section */
+
+/* Begin PBXFileReference section */
+ 7906CA47133A32FF0007C9D0 /* PLInvocationHandler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PLInvocationHandler.h; sourceTree = "<group>"; };
+ 7906CA48133A32FF0007C9D0 /* PLInvocationHandler.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PLInvocationHandler.m; sourceTree = "<group>"; };
+ 7906CA4C133A372A0007C9D0 /* libfcgi.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libfcgi.dylib; path = usr/lib/libfcgi.dylib; sourceTree = SDKROOT; };
+ 7906CA91133BAAFC0007C9D0 /* JSON.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSON.h; sourceTree = "<group>"; };
+ 7906CA93133BAC180007C9D0 /* NSObject+SBJSON.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSObject+SBJSON.h"; sourceTree = "<group>"; };
+ 7906CA94133BAC180007C9D0 /* NSObject+SBJSON.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSObject+SBJSON.m"; sourceTree = "<group>"; };
+ 7906CA95133BAC180007C9D0 /* NSString+SBJSON.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSString+SBJSON.h"; sourceTree = "<group>"; };
+ 7906CA96133BAC180007C9D0 /* NSString+SBJSON.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSString+SBJSON.m"; sourceTree = "<group>"; };
+ 7906CA97133BAC180007C9D0 /* SBJsonBase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SBJsonBase.h; sourceTree = "<group>"; };
+ 7906CA98133BAC180007C9D0 /* SBJsonBase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SBJsonBase.m; sourceTree = "<group>"; };
+ 7906CA99133BAC180007C9D0 /* SBJsonParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SBJsonParser.h; sourceTree = "<group>"; };
+ 7906CA9A133BAC180007C9D0 /* SBJsonParser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SBJsonParser.m; sourceTree = "<group>"; };
+ 7906CA9B133BAC180007C9D0 /* SBJsonWriter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SBJsonWriter.h; sourceTree = "<group>"; };
+ 7906CA9C133BAC180007C9D0 /* SBJsonWriter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SBJsonWriter.m; sourceTree = "<group>"; };
+ 7906CAB4133BBB480007C9D0 /* WebFastCGI-bin */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; name = "WebFastCGI-bin"; path = "/Users/patcollins/git/Web/Web/build/Release/WebFastCGI-bin"; sourceTree = "<absolute>"; };
+ 7906CABD133BC6AD0007C9D0 /* Web */ = {isa = PBXFileReference; lastKnownFileType = text; path = Web; sourceTree = BUILT_PRODUCTS_DIR; };
+ 7906CAC2133BC7E80007C9D0 /* .htaccess */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = .htaccess; sourceTree = "<group>"; };
+ 7906CAC3133BC7E80007C9D0 /* index.php */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.script.php; path = index.php; sourceTree = "<group>"; };
+ 7906CAC4133BC9300007C9D0 /* WebFastCGI-bin */ = {isa = PBXFileReference; lastKnownFileType = text; path = "WebFastCGI-bin"; sourceTree = BUILT_PRODUCTS_DIR; };
+ 79441ADF133A10F000980FE8 /* Web */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; name = Web; path = /Users/patcollins/git/Web/Web/build/Release/Web; sourceTree = "<absolute>"; };
+ 79441AE3133A10F000980FE8 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
+ 79441AE6133A10F000980FE8 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
+ 79441AE9133A10F000980FE8 /* Web-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Web-Prefix.pch"; sourceTree = "<group>"; };
+ 79441AEA133A10F000980FE8 /* Web.1 */ = {isa = PBXFileReference; lastKnownFileType = text.man; path = Web.1; sourceTree = "<group>"; };
+/* End PBXFileReference section */
+
+/* Begin PBXFrameworksBuildPhase section */
+ 7906CAAC133BBB480007C9D0 /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 7906CAAD133BBB480007C9D0 /* Foundation.framework in Frameworks */,
+ 7906CAAE133BBB480007C9D0 /* libfcgi.dylib in Frameworks */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 79441ADC133A10F000980FE8 /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 79441AE4133A10F000980FE8 /* Foundation.framework in Frameworks */,
+ 7906CA4D133A372A0007C9D0 /* libfcgi.dylib in Frameworks */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXFrameworksBuildPhase section */
+
+/* Begin PBXGroup section */
+ 7906CA92133BAB000007C9D0 /* JSON */ = {
+ isa = PBXGroup;
+ children = (
+ 7906CA91133BAAFC0007C9D0 /* JSON.h */,
+ 7906CA93133BAC180007C9D0 /* NSObject+SBJSON.h */,
+ 7906CA94133BAC180007C9D0 /* NSObject+SBJSON.m */,
+ 7906CA95133BAC180007C9D0 /* NSString+SBJSON.h */,
+ 7906CA96133BAC180007C9D0 /* NSString+SBJSON.m */,
+ 7906CA97133BAC180007C9D0 /* SBJsonBase.h */,
+ 7906CA98133BAC180007C9D0 /* SBJsonBase.m */,
+ 7906CA99133BAC180007C9D0 /* SBJsonParser.h */,
+ 7906CA9A133BAC180007C9D0 /* SBJsonParser.m */,
+ 7906CA9B133BAC180007C9D0 /* SBJsonWriter.h */,
+ 7906CA9C133BAC180007C9D0 /* SBJsonWriter.m */,
+ );
+ name = JSON;
+ sourceTree = "<group>";
+ };
+ 7906CAA2133BBAC20007C9D0 /* Dependencies */ = {
+ isa = PBXGroup;
+ children = (
+ 7906CA92133BAB000007C9D0 /* JSON */,
+ 7906CA4C133A372A0007C9D0 /* libfcgi.dylib */,
+ 7906CA47133A32FF0007C9D0 /* PLInvocationHandler.h */,
+ 7906CA48133A32FF0007C9D0 /* PLInvocationHandler.m */,
+ );
+ name = Dependencies;
+ sourceTree = "<group>";
+ };
+ 7906CAC0133BC7700007C9D0 /* Products */ = {
+ isa = PBXGroup;
+ children = (
+ 7906CABD133BC6AD0007C9D0 /* Web */,
+ );
+ name = Products;
+ sourceTree = "<group>";
+ };
+ 7906CAC1133BC7E80007C9D0 /* public */ = {
+ isa = PBXGroup;
+ children = (
+ 7906CAC2133BC7E80007C9D0 /* .htaccess */,
+ 7906CAC3133BC7E80007C9D0 /* index.php */,
+ );
+ path = public;
+ sourceTree = "<group>";
+ };
+ 79441AD4133A10F000980FE8 = {
+ isa = PBXGroup;
+ children = (
+ 7906CAC1133BC7E80007C9D0 /* public */,
+ 7906CAA2133BBAC20007C9D0 /* Dependencies */,
+ 79441AE5133A10F000980FE8 /* Web */,
+ 79441AE2133A10F000980FE8 /* Frameworks */,
+ 7906CAC0133BC7700007C9D0 /* Products */,
+ 7906CAC4133BC9300007C9D0 /* WebFastCGI-bin */,
+ );
+ sourceTree = "<group>";
+ };
+ 79441AE2133A10F000980FE8 /* Frameworks */ = {
+ isa = PBXGroup;
+ children = (
+ 79441AE3133A10F000980FE8 /* Foundation.framework */,
+ );
+ name = Frameworks;
+ sourceTree = "<group>";
+ };
+ 79441AE5133A10F000980FE8 /* Web */ = {
+ isa = PBXGroup;
+ children = (
+ 79441AE6133A10F000980FE8 /* main.m */,
+ 79441AEA133A10F000980FE8 /* Web.1 */,
+ 79441AE8133A10F000980FE8 /* Supporting Files */,
+ );
+ path = Web;
+ sourceTree = "<group>";
+ };
+ 79441AE8133A10F000980FE8 /* Supporting Files */ = {
+ isa = PBXGroup;
+ children = (
+ 79441AE9133A10F000980FE8 /* Web-Prefix.pch */,
+ );
+ name = "Supporting Files";
+ sourceTree = "<group>";
+ };
+/* End PBXGroup section */
+
+/* Begin PBXNativeTarget section */
+ 7906CAA3133BBB480007C9D0 /* WebFastCGI-bin */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = 7906CAB1133BBB480007C9D0 /* Build configuration list for PBXNativeTarget "WebFastCGI-bin" */;
+ buildPhases = (
+ 7906CAA4133BBB480007C9D0 /* Sources */,
+ 7906CAAC133BBB480007C9D0 /* Frameworks */,
+ 7906CAAF133BBB480007C9D0 /* CopyFiles */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ );
+ name = "WebFastCGI-bin";
+ productName = Web;
+ productReference = 7906CAB4133BBB480007C9D0 /* WebFastCGI-bin */;
+ productType = "com.apple.product-type.tool";
+ };
+ 79441ADE133A10F000980FE8 /* Web */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = 79441AED133A10F000980FE8 /* Build configuration list for PBXNativeTarget "Web" */;
+ buildPhases = (
+ 79441ADB133A10F000980FE8 /* Sources */,
+ 79441ADC133A10F000980FE8 /* Frameworks */,
+ 79441ADD133A10F000980FE8 /* CopyFiles */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ );
+ name = Web;
+ productName = Web;
+ productReference = 79441ADF133A10F000980FE8 /* Web */;
+ productType = "com.apple.product-type.tool";
+ };
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+ 79441AD6133A10F000980FE8 /* Project object */ = {
+ isa = PBXProject;
+ attributes = {
+ ORGANIZATIONNAME = ShowClix;
+ };
+ buildConfigurationList = 79441AD9133A10F000980FE8 /* Build configuration list for PBXProject "Web" */;
+ compatibilityVersion = "Xcode 3.2";
+ developmentRegion = English;
+ hasScannedForEncodings = 0;
+ knownRegions = (
+ en,
+ );
+ mainGroup = 79441AD4133A10F000980FE8;
+ productRefGroup = 79441AD4133A10F000980FE8;
+ projectDirPath = "";
+ projectRoot = "";
+ targets = (
+ 79441ADE133A10F000980FE8 /* Web */,
+ 7906CAA3133BBB480007C9D0 /* WebFastCGI-bin */,
+ );
+ };
+/* End PBXProject section */
+
+/* Begin PBXSourcesBuildPhase section */
+ 7906CAA4133BBB480007C9D0 /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 7906CAA5133BBB480007C9D0 /* main.m in Sources */,
+ 7906CAA6133BBB480007C9D0 /* PLInvocationHandler.m in Sources */,
+ 7906CAA7133BBB480007C9D0 /* NSObject+SBJSON.m in Sources */,
+ 7906CAA8133BBB480007C9D0 /* NSString+SBJSON.m in Sources */,
+ 7906CAA9133BBB480007C9D0 /* SBJsonBase.m in Sources */,
+ 7906CAAA133BBB480007C9D0 /* SBJsonParser.m in Sources */,
+ 7906CAAB133BBB480007C9D0 /* SBJsonWriter.m in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+ 79441ADB133A10F000980FE8 /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 79441AE7133A10F000980FE8 /* main.m in Sources */,
+ 7906CA49133A32FF0007C9D0 /* PLInvocationHandler.m in Sources */,
+ 7906CA9D133BAC180007C9D0 /* NSObject+SBJSON.m in Sources */,
+ 7906CA9E133BAC180007C9D0 /* NSString+SBJSON.m in Sources */,
+ 7906CA9F133BAC180007C9D0 /* SBJsonBase.m in Sources */,
+ 7906CAA0133BAC180007C9D0 /* SBJsonParser.m in Sources */,
+ 7906CAA1133BAC180007C9D0 /* SBJsonWriter.m in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXSourcesBuildPhase section */
+
+/* Begin XCBuildConfiguration section */
+ 7906CAB2133BBB480007C9D0 /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
+ COPY_PHASE_STRIP = NO;
+ GCC_DYNAMIC_NO_PIC = NO;
+ GCC_ENABLE_OBJC_EXCEPTIONS = YES;
+ GCC_PRECOMPILE_PREFIX_HEADER = YES;
+ GCC_PREFIX_HEADER = "Web/Web-Prefix.pch";
+ GCC_PREPROCESSOR_DEFINITIONS = (
+ DEBUG,
+ FASTCGI,
+ );
+ HEADER_SEARCH_PATHS = "";
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ };
+ name = Debug;
+ };
+ 7906CAB3133BBB480007C9D0 /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
+ COPY_PHASE_STRIP = YES;
+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+ GCC_ENABLE_OBJC_EXCEPTIONS = YES;
+ GCC_PRECOMPILE_PREFIX_HEADER = YES;
+ GCC_PREFIX_HEADER = "Web/Web-Prefix.pch";
+ GCC_PREPROCESSOR_DEFINITIONS = FASTCGI;
+ HEADER_SEARCH_PATHS = "";
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ };
+ name = Release;
+ };
+ 79441AEB133A10F000980FE8 /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
+ GCC_C_LANGUAGE_STANDARD = gnu99;
+ GCC_OPTIMIZATION_LEVEL = 0;
+ GCC_PREPROCESSOR_DEFINITIONS = DEBUG;
+ GCC_SYMBOLS_PRIVATE_EXTERN = NO;
+ GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ HEADER_SEARCH_PATHS = "/usr/local/include/**";
+ LIBRARY_SEARCH_PATHS = "/usr/local/lib/**";
+ MACOSX_DEPLOYMENT_TARGET = 10.6;
+ ONLY_ACTIVE_ARCH = YES;
+ SDKROOT = macosx;
+ USER_HEADER_SEARCH_PATHS = "";
+ };
+ name = Debug;
+ };
+ 79441AEC133A10F000980FE8 /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
+ GCC_C_LANGUAGE_STANDARD = gnu99;
+ GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ HEADER_SEARCH_PATHS = "/usr/local/include/**";
+ LIBRARY_SEARCH_PATHS = "/usr/local/lib/**";
+ MACOSX_DEPLOYMENT_TARGET = 10.6;
+ SDKROOT = macosx;
+ USER_HEADER_SEARCH_PATHS = "";
+ };
+ name = Release;
+ };
+ 79441AEE133A10F000980FE8 /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
+ COPY_PHASE_STRIP = NO;
+ GCC_DYNAMIC_NO_PIC = NO;
+ GCC_ENABLE_OBJC_EXCEPTIONS = YES;
+ GCC_PRECOMPILE_PREFIX_HEADER = YES;
+ GCC_PREFIX_HEADER = "Web/Web-Prefix.pch";
+ HEADER_SEARCH_PATHS = "";
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ };
+ name = Debug;
+ };
+ 79441AEF133A10F000980FE8 /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
+ COPY_PHASE_STRIP = YES;
+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+ GCC_ENABLE_OBJC_EXCEPTIONS = YES;
+ GCC_PRECOMPILE_PREFIX_HEADER = YES;
+ GCC_PREFIX_HEADER = "Web/Web-Prefix.pch";
+ HEADER_SEARCH_PATHS = "";
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ };
+ name = Release;
+ };
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+ 7906CAB1133BBB480007C9D0 /* Build configuration list for PBXNativeTarget "WebFastCGI-bin" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 7906CAB2133BBB480007C9D0 /* Debug */,
+ 7906CAB3133BBB480007C9D0 /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+ 79441AD9133A10F000980FE8 /* Build configuration list for PBXProject "Web" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 79441AEB133A10F000980FE8 /* Debug */,
+ 79441AEC133A10F000980FE8 /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+ 79441AED133A10F000980FE8 /* Build configuration list for PBXNativeTarget "Web" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 79441AEE133A10F000980FE8 /* Debug */,
+ 79441AEF133A10F000980FE8 /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+/* End XCConfigurationList section */
+ };
+ rootObject = 79441AD6133A10F000980FE8 /* Project object */;
+}
7 Web/Web-Prefix.pch
@@ -0,0 +1,7 @@
+//
+// Prefix header for all source files of the 'Web' target in the 'Web' project
+//
+
+#ifdef __OBJC__
+ #import <Foundation/Foundation.h>
+#endif
79 Web/Web.1
@@ -0,0 +1,79 @@
+.\"Modified from man(1) of FreeBSD, the NetBSD mdoc.template, and mdoc.samples.
+.\"See Also:
+.\"man mdoc.samples for a complete listing of options
+.\"man mdoc for the short list of editing options
+.\"/usr/share/misc/mdoc.template
+.Dd 3/23/11 \" DATE
+.Dt Web 1 \" Program name and manual section number
+.Os Darwin
+.Sh NAME \" Section Header - required - don't modify
+.Nm Web,
+.\" The following lines are read in generating the apropos(man -k) database. Use only key
+.\" words here as the database is built based on the words here and in the .ND line.
+.Nm Other_name_for_same_program(),
+.Nm Yet another name for the same program.
+.\" Use .Nm macro to designate other names for the documented program.
+.Nd This line parsed for whatis database.
+.Sh SYNOPSIS \" Section Header - required - don't modify
+.Nm
+.Op Fl abcd \" [-abcd]
+.Op Fl a Ar path \" [-a path]
+.Op Ar file \" [file]
+.Op Ar \" [file ...]
+.Ar arg0 \" Underlined argument - use .Ar anywhere to underline
+arg2 ... \" Arguments
+.Sh DESCRIPTION \" Section Header - required - don't modify
+Use the .Nm macro to refer to your program throughout the man page like such:
+.Nm
+Underlining is accomplished with the .Ar macro like this:
+.Ar underlined text .
+.Pp \" Inserts a space
+A list of items with descriptions:
+.Bl -tag -width -indent \" Begins a tagged list
+.It item a \" Each item preceded by .It macro
+Description of item a
+.It item b
+Description of item b
+.El \" Ends the list
+.Pp
+A list of flags and their descriptions:
+.Bl -tag -width -indent \" Differs from above in tag removed
+.It Fl a \"-a flag as a list item
+Description of -a flag
+.It Fl b
+Description of -b flag
+.El \" Ends the list
+.Pp
+.\" .Sh ENVIRONMENT \" May not be needed
+.\" .Bl -tag -width "ENV_VAR_1" -indent \" ENV_VAR_1 is width of the string ENV_VAR_1
+.\" .It Ev ENV_VAR_1
+.\" Description of ENV_VAR_1
+.\" .It Ev ENV_VAR_2
+.\" Description of ENV_VAR_2
+.\" .El
+.Sh FILES \" File used or created by the topic of the man page
+.Bl -tag -width "/Users/joeuser/Library/really_long_file_name" -compact
+.It Pa /usr/share/file_name
+FILE_1 description
+.It Pa /Users/joeuser/Library/really_long_file_name
+FILE_2 description
+.El \" Ends the list
+.\" .Sh DIAGNOSTICS \" May not be needed
+.\" .Bl -diag
+.\" .It Diagnostic Tag
+.\" Diagnostic informtion here.
+.\" .It Diagnostic Tag
+.\" Diagnostic informtion here.
+.\" .El
+.Sh SEE ALSO
+.\" List links in ascending order by section, alphabetically within a section.
+.\" Please do not reference files that do not exist without filing a bug report
+.Xr a 1 ,
+.Xr b 1 ,
+.Xr c 1 ,
+.Xr a 2 ,
+.Xr b 2 ,
+.Xr a 3 ,
+.Xr b 3
+.\" .Sh BUGS \" Document known, unremedied bugs
+.\" .Sh HISTORY \" Document history if command behaves in a unique manner
54 Web/main.m
@@ -0,0 +1,54 @@
+//
+// main.m
+// Web
+//
+// Created by Pat Collins on 3/23/11.
+// Copyright 2011 ShowClix. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+#import "JSON.h"
+#if FASTCGI
+#import <fcgiapp.h>
+#import "PLInvocationHandler.h"
+#endif
+
+int main (int argc, const char * argv[])
+{
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+// NSLog(@"stuff");
+// printf("%s<br>", [@"test22" UTF8String]);
+
+ NSDictionary *dict = [[NSProcessInfo processInfo] environment];
+ NSLog(@"environment: %@", dict);
+
+ if (getenv("WEB_ENV") != NULL) {
+ NSDictionary *webdict = [[NSString stringWithCString:getenv("WEB_ENV") encoding:NSUTF8StringEncoding] JSONValue];
+ NSLog(@"web environment: %@", webdict);
+
+ for (NSString *key in webdict) {
+ NSString *val = [webdict objectForKey:key];
+ printf("%s: %s<br>", [key UTF8String], [[NSString stringWithFormat:@"%@", val] UTF8String]);
+ }
+ }
+
+
+#if FASTCGI
+ FCGX_Stream *in, *out, *err;
+ FCGX_ParamArray envp;
+
+ PLInvocationHandler *handler = [[PLInvocationHandler alloc] init];
+
+ // insert code here...
+ while (FCGX_Accept(&in, &out, &err, &envp) >= 0) {
+ [handler handleInputStream:in outputStream:out errorStream:err paramArray:envp];
+ }
+
+ [handler release];
+#endif
+
+ [pool drain];
+ return 0;
+}
+
19 public/.htaccess
@@ -0,0 +1,19 @@
+Options +FollowSymLinks
+<IfModule mod_rewrite.c>
+ RewriteEngine On
+
+ RewriteCond %{DOCUMENT_ROOT}/maintenance.html -f
+ RewriteCond %{SCRIPT_FILENAME} !maintenance.html
+ RewriteRule ^(.*)$ maintenance.html [L]
+
+ RewriteCond %{REQUEST_FILENAME} -d
+ RewriteCond %{REQUEST_FILENAME}index.php -f
+ RewriteRule ^(.*)$ %{REQUEST_URI}index.php [QSA,L]
+
+ RewriteCond %{REQUEST_FILENAME} -d
+ RewriteCond %{REQUEST_FILENAME}index.html -f
+ RewriteRule ^(.*)$ %{REQUEST_URI}index.html [L]
+
+ RewriteCond %{REQUEST_FILENAME} !-f
+ RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
+</IfModule>
32 public/index.php
@@ -0,0 +1,32 @@
+<?php
+$descriptorspec = array(
+ 0 => array("pipe", "r"), // stdin is a pipe that the child will read from
+ 1 => array("pipe", "w"), // stdout is a pipe that the child will write to
+ 2 => array("file", "/tmp/Web-error-output.txt", "a") // stderr is a file to write to
+);
+
+$script = "/Users/patcollins/bin/Web";
+$pipes = array();
+$cwd = '/tmp';
+$env = array('WEB_ENV' => json_encode($_SERVER));
+// $env = $_SERVER;
+// var_dump($env);
+
+$process = proc_open($script, $descriptorspec, $pipes, $cwd, $env);
+
+// http://php.net/manual/en/function.proc-open.php
+if (is_resource($process)) {
+ // $pipes now looks like this:
+ // 0 => writeable handle connected to child stdin
+ // 1 => readable handle connected to child stdout
+ // Any error output will be appended to /tmp/error-output.txt
+
+ echo stream_get_contents($pipes[1]);
+ fclose($pipes[1]);
+
+ // It is important that you close any pipes before calling
+ // proc_close in order to avoid a deadlock
+ $return_value = proc_close($process);
+
+ // echo "$return_value\n";
+}
Please sign in to comment.
Something went wrong with that request. Please try again.