4 * Created by Colin Barrett on 12/23/05.
6 * This class is explicitly released under the BSD license with the following modification:
7 * It may be used without reproduction of its copyright notice within The Adium Project.
9 * This class was created for use in the Adium project, which is released under the GPL.
10 * The release of this specific class (AIXMLAppender) under BSD in no way changes the licensing of any other portion
11 * of the Adium project.
14 Copyright (c) 2005, 2006 Colin Barrett
17 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
19 Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
20 Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
21 in the documentation and/or other materials provided with the distribution.
22 Neither the name of Adium nor the names of its contributors may be used to endorse or promote products
23 derived from this software without specific prior written permission.
25 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
26 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 - Possible support for "healing" a damaged XML file?
35 - Possibly refactor the initializeDocument... and addElement... methods to return a BOOL and/or RBR an error code of some kind to indicate success or failure.
36 - Instead of just testing for ' ' in -rootElementNameForFileAtPath:, use NSCharacterSet and be more general.
40 #import "AIXMLAppender.h"
41 #import <AIUtilities/AIFileManagerAdditions.h>
42 #import <AIUtilities/AIStringAdditions.h>
46 #define XML_APPENDER_BLOCK_SIZE 4096
48 #define XML_MARKER @"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
51 failedUtf8BomLength = 6
54 @interface AIXMLAppender(PRIVATE)
55 - (NSString *)createElementWithName:(NSString *)name content:(NSString *)content attributeKeys:(NSArray *)keys attributeValues:(NSArray *)values;
56 - (NSString *)rootElementNameForFileAtPath:(NSString *)path;
57 - (void)prepareFileHandle;
61 * @class AIXMLAppender
62 * @brief Provides multiple-write access to an XML document while maintaining wellformedness.
64 * Just a couple of general comments here;
65 * - Despite the hackish nature of seeking backwards and overwriting, sometimes you need to cheat a little or things
66 * get a bit insane. That's what was happening, so a Grand Compromise was reached, and this is what we're doing.
69 @implementation AIXMLAppender
72 * @brief Create a new, autoreleased document.
74 * @param path Path to the file where XML document will be stored
76 + (id)documentWithPath:(NSString *)path
78 return [[[self alloc] initWithPath:path] autorelease];
82 * @brief Create a new document at the path \a path
86 - (id)initWithPath:(NSString *)path
88 if ((self = [super init])) {
89 //Set up our instance variables
90 rootElementName = nil;
91 filePath = [path copy];
93 fullSyncAfterEachAppend = YES;
95 [self prepareFileHandle];
107 [file release]; //This will also close the fd, since we set the closeOnDealloc flag to YES
108 [rootElementName release];
115 * @brief If the document is initialized.
117 * @return YES if the document is initialized. NO otherwise.
119 * This should be called before adding any elements to the document. If the document is uninitialized, any element
120 * adding methods will fail. If the document is initialized, any initializing methods will fail.
122 - (BOOL)isInitialized
128 * @brief The path to the file.
130 * @return The path to the file the XML document is being written to.
138 * @brief Name of the root element of this document
140 * @return The name of the root element of this document, nil if not initialized.
142 - (NSString *)rootElement
144 return rootElementName;
148 * @brief Set if a full sync to disk should be performed after each write
150 * A full sync is relatively costly but ensures that the data is immediately written.
151 * If appending a single item, the default value of YES is appropriate.
153 * If many append operations will occur, such as in a loop, set this to NO, then call
154 * -[AIXMLAppender performFullSync] when complete to perform the sync.
156 * Not calling performFullSync at all is only a problem in case of a power failure; the system will
157 * at some undetermined point in the future write data to disk in any case.
159 - (void)setFullSyncAfterEachAppend:(BOOL)shouldFullSync
161 fullSyncAfterEachAppend = shouldFullSync;
165 * @brief Should a full sync be performed whenever an addElement call is made?
167 * See setFullSyncAfterEachAppend: for information
169 - (BOOL)fullSyncAfterEachAppend
171 return fullSyncAfterEachAppend;
175 * @brief Perform a full sync immediately
177 * This is only useful if fullSyncAfterEachAppend is NO.
178 * fullSyncAfterEachAppend is YES by default.
180 - (void)performFullSync
182 if (initialized && file)
183 fcntl([file fileDescriptor], F_FULLFSYNC, /*arg*/ 0);
188 - (void)prepareFileHandle
190 NSFileManager *manager = [NSFileManager defaultManager];
192 //Check if the file already exists
193 if ([manager fileExistsAtPath:filePath]) {
194 //Get the root element name and set initialized
195 rootElementName = [[self rootElementNameForFileAtPath:filePath] retain];
196 initialized = (rootElementName != nil);
197 //We may need to create the directory structure, so call this just in case
199 [manager createDirectoriesForPath:[filePath stringByDeletingLastPathComponent]];
203 //Open our file handle and seek if necessary
204 const char *pathCString = [filePath fileSystemRepresentation];
205 int fd = open(pathCString, O_CREAT | O_WRONLY, 0644);
207 AILog(@"Couldn't open log file %@ (%s - length %u) for writing!",
208 filePath, pathCString, (pathCString ? strlen(pathCString) : 0));
210 file = [[NSFileHandle alloc] initWithFileDescriptor:fd closeOnDealloc:YES];
214 int closingTagLength = [rootElementName length] + 4; //</rootElementName>
215 [file seekToFileOffset:sb.st_size - closingTagLength];
220 - (BOOL)writeData:(NSData *)data seekBackLength:(int)seekBackLength
225 [file writeData:data];
227 } @catch (NSException *writingException) {
228 /* NSFileHandle raises an exception if:
229 * * the file descriptor is closed or is not valid - we should reopen the file and try again
230 * * if the receiver represents an unconnected pipe or socket endpoint - this should never happen
231 * * if no free space is left on the file system - this should be handled gracefully if possible.. but the user is probably in trouble.
232 * * if any other writing error occurs - as with lack of free space.
235 [[writingException name] isEqualToString:NSFileHandleOperationException] &&
236 [[writingException reason] rangeOfString:@"Bad file descriptor"].location != NSNotFound) {
238 [file release]; file = nil;
239 } @catch (NSException *releaseException) {
240 //Don't need to do anything... but if we failed to write, we may fail to deallocate, too.
244 [self prepareFileHandle];
246 [file writeData:data];
249 } @catch (NSException *secondWritingException) {
250 NSLog(@"Exception while writing %@ log file %@: %@ (%@)",
251 (initialized ? @"initialized" : @"uninitialized"), filePath, [secondWritingException name], [secondWritingException reason]);
256 NSLog(@"Exception while writing %@ log file %@: %@ (%@)",
257 (initialized ? @"initialized" : @"uninitialized"), filePath, [writingException name], [writingException reason]);
263 if (fullSyncAfterEachAppend)
264 fcntl([file fileDescriptor], F_FULLFSYNC, /*arg*/ 0);
267 [file seekToFileOffset:([file offsetInFile] - seekBackLength)];
269 } @catch (NSException *seekException) {
270 /* -[NSFileHandler seekToFileOffset:] raises an exception if
271 * * the message is sent to an NSFileHandle object representing a pipe or socket
272 * * if the file descriptor is closed
273 * * if any other error occurs in seeking.
275 NSLog(@"Exception while seeking in %@ log file %@: %@ (%@)",
276 (initialized ? @"initialized" : @"uninitialized"), filePath, [seekException name], [seekException reason]);
285 * @brief Sets up the document.
287 * @param name The name of the root element for this document.
288 * @param keys An array of the attribute keys the element has.
289 * @param values An array of the attribute values the element has.
291 - (BOOL)initializeDocumentWithRootElementName:(NSString *)name attributeKeys:(NSArray *)keys attributeValues:(NSArray *)values
293 //Don't initialize twice
296 if (!initialized && file) {
297 //Keep track of this for later
298 rootElementName = [name retain];
301 int closingTagLength = [rootElementName length] + 4; //</rootElementName>
302 NSString *rootElement = [self createElementWithName:rootElementName content:@"" attributeKeys:keys attributeValues:values];
303 NSString *initialDocument = [NSString stringWithFormat:@"%@\n%@", XML_MARKER, rootElement];
305 //Write the data, and then seek backwards
306 success = [self writeData:[initialDocument dataUsingEncoding:NSUTF8StringEncoding] seekBackLength:closingTagLength];
315 * @brief Adds a node to the document.
317 * @param name The name of the root element for this document.
318 * @param content The stuff between the open and close tags. If nil, then the tag will be self closing.
319 * @param keys An array of the attribute keys the element has.
320 * @param values An array of the attribute values the element has.
323 - (BOOL)addElementWithName:(NSString *)name content:(NSString *)content attributeKeys:(NSArray *)keys attributeValues:(NSArray *)values
325 return [self addElementWithName:name
326 escapedContent:(content ? [content stringByEscapingForXMLWithEntities:nil] : nil)
328 attributeValues:values];
332 * @brief Adds a node to the document, performing no escaping on the content.
334 * @param name The name of the root element for this document.
335 * @param content The stuff between the open and close tags. If nil, then the tag will be self closing. No escaping will be performed on the content.
336 * @param keys An array of the attribute keys the element has.
337 * @param values An array of the attribute values the element has.
340 - (BOOL)addElementWithName:(NSString *)name escapedContent:(NSString *)content attributeKeys:(NSArray *)keys attributeValues:(NSArray *)values
344 //Don't add if not initialized, or if we couldn't open the file
345 if (initialized && file) {
347 NSString *element = [self createElementWithName:name content:content attributeKeys:keys attributeValues:values];
348 NSString *closingTag = [NSString stringWithFormat:@"</%@>\n", rootElementName];
350 if (element != nil) {
351 //Write the data, and then seek backwards
352 success = [self writeData:[[element stringByAppendingString:closingTag] dataUsingEncoding:NSUTF8StringEncoding]
353 seekBackLength:[closingTag length]];
360 #pragma mark Private Methods
363 * @brief Creates an element node.
365 * @param name The name of the element.
366 * @param content The stuff between the open and close tags. If nil, then the tag will be self closing. No escaping will be performed on the content.
367 * @param keys An array of the attribute keys the element has.
368 * @param values An array of the attribute values the element has.
369 * @return An XML element, suitable for insertion into a document.
371 * The two attribute arrays must be of the same size, or the method will return nil.
374 - (NSString *)createElementWithName:(NSString *)name content:(NSString *)content attributeKeys:(NSArray *)keys attributeValues:(NSArray *)values
376 //Check our precondition
377 if ([keys count] != [values count]) {
378 NSLog(@"Attribute key (%@) and value (%@) arrays for element %@ are of differing lengths, %u and %u, respectively", keys, values, name, [keys count], [values count]);
382 //Collapse the attributes
383 NSMutableString *attributeString = [NSMutableString string];
384 NSEnumerator *attributeKeyEnumerator = [keys objectEnumerator];
385 NSEnumerator *attributeValueEnumerator = [values objectEnumerator];
386 NSString *key = nil, *value = nil;
387 while ((key = [attributeKeyEnumerator nextObject]) && (value = [attributeValueEnumerator nextObject])) {
388 [attributeString appendFormat:@" %@=\"%@\"",
389 [key stringByEscapingForXMLWithEntities:nil],
390 [value stringByEscapingForXMLWithEntities:nil]];
394 NSString *escapedName = [name stringByEscapingForXMLWithEntities:nil];
396 return [NSString stringWithFormat:@"<%@%@>%@</%@>\n", escapedName, attributeString, content, escapedName];
398 return [NSString stringWithFormat:@"<%@%@/>\n", escapedName, attributeString];
402 * @brief Get the root element name for file
404 * @return The root element name, or nil if there isn't one (possibly because the file is not valid XML)
406 - (NSString *)rootElementNameForFileAtPath:(NSString *)path
408 //Create a temporary file handle for validation, and read the marker
409 NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
411 if(!handle) return nil;
413 NSScanner *scanner = nil;
415 //Read a block of arbitrary size
416 NSString *block = [[[NSString alloc] initWithData:[handle readDataOfLength:XML_APPENDER_BLOCK_SIZE]
417 encoding:NSUTF8StringEncoding] autorelease];
418 //If we read 0 characters, then we have reached the end of the file, so return
419 if ([block length] == 0) {
424 scanner = [NSScanner scannerWithString:block];
425 [scanner scanUpToString:@"<" intoString:nil];
426 } while([scanner isAtEnd]); //If the scanner is at the end, not found in this block
428 //Scn past the '<' we know is there
429 [scanner scanString:@"<" intoString:nil];
431 NSString *accumulated = [NSString string];
432 NSMutableString *accumulator = [NSMutableString string];
435 [scanner scanUpToString:@" " intoString:&accumulated]; //very naive
436 [accumulator appendString:accumulated];
438 //If the scanner is at the end, not found in this block
439 found = ![scanner isAtEnd];
441 //If we've found the end of the element name, break
445 NSString *block = [[[NSString alloc] initWithData:[handle readDataOfLength:XML_APPENDER_BLOCK_SIZE]
446 encoding:NSUTF8StringEncoding] autorelease];
447 //Again, if we've reached the end of the file, we aren't initialized, so return nil
448 if ([block length] == 0) {
453 scanner = [NSScanner scannerWithString:block];
458 //We've obviously found the root element name, so return a nonmutable copy.
459 return [NSString stringWithString:accumulator];