forked from eklipse2k8/CocoaRestClient
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCocoaRestClientAppDelegate.m
More file actions
850 lines (698 loc) · 24.9 KB
/
Copy pathCocoaRestClientAppDelegate.m
File metadata and controls
850 lines (698 loc) · 24.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
//
// CocoaRestClientAppDelegate.m
// CocoaRestClient
//
// Created by mmattozzi on 1/5/10.
//
#import "CocoaRestClientAppDelegate.h"
#import "CRCMultipartRequest.h"
#import "CRCFormEncodedRequest.h"
#import "CRCRawRequest.h"
#import "CRCFileRequest.h"
#import "CRCRequest.h"
#import <Foundation/Foundation.h>
#import "JSONKit.h"
#define MAIN_WINDOW_MENU_TAG 150
enum {
CRCContentTypeMultipart,
CRCContentTypeFormEncoded,
CRCContentTypeJson,
CRCContentTypeXml,
CRCContentTypeImage,
CRCContentTypeUnknown
};
typedef NSInteger CRCContentType;
static CRCContentType requestContentType;
@interface CocoaRestClientAppDelegate(Private)
- (void)determineRequestContentType;
- (void)loadSavedDictionary:(NSDictionary *)request;
- (void)loadSavedCRCRequest:(CRCRequest *)request;
@end
@implementation CocoaRestClientAppDelegate {
@private
NSMutableData *receivedData;
NSString *contentType;
NSMutableArray *headersTable;
NSMutableArray *filesTable;
NSMutableArray *paramsTable;
NSMutableArray *savedRequestsArray;
NSInteger timeout;
BOOL allowSelfSignedCerts;
BOOL followRedirects;
BOOL rawRequestInput;
NSDate *startDate;
CRCRequest *lastRequest;
}
@synthesize window;
@synthesize submitButton;
@synthesize urlBox;
@synthesize responseText;
@synthesize responseTextHeaders;
@synthesize requestText;
@synthesize methodButton;
@synthesize headersTable, filesTable, paramsTable;
@synthesize headersTableView, filesTableView, paramsTableView;
@synthesize username;
@synthesize password;
@synthesize savedOutlineView;
@synthesize saveRequestSheet;
@synthesize saveRequestTextField;
@synthesize savedRequestsDrawer;
@synthesize headersTab;
@synthesize timeoutSheet;
@synthesize timeoutField;
@synthesize plusParam, minusParam;
@synthesize rawRequestInput;
@synthesize tabView;
@synthesize reqHeadersTab;
@synthesize status;
- (id) init {
self = [super init];
if (self == nil)
return nil;
timeout = 20;
allowSelfSignedCerts = YES;
followRedirects = YES;
headersTable = [[NSMutableArray alloc] init];
filesTable = [[NSMutableArray alloc] init];
paramsTable = [[NSMutableArray alloc] init];
NSMutableDictionary *row = [[NSMutableDictionary alloc] init];
[row setObject:@"Content-Type" forKey:@"key"];
[row setObject:@"application/x-www-form-urlencoded" forKey:@"value"];
[headersTable addObject:row];
[self loadDataFromDisk];
return self;
}
- (void) setRawRequestInput:(BOOL)value{
rawRequestInput = value;
if(value){
[[requestText enclosingScrollView] setHidden:NO];
[[paramsTableView enclosingScrollView] setHidden:YES];
[plusParam setHidden:YES];
[minusParam setHidden:YES];
}
else {
[[requestText enclosingScrollView] setHidden:YES];
[[paramsTableView enclosingScrollView] setHidden:NO];
[plusParam setHidden:NO];
[minusParam setHidden:NO];
}
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
[methodButton removeAllItems];
[methodButton addItemWithTitle:@"GET"];
[methodButton addItemWithTitle:@"POST"];
[methodButton addItemWithTitle:@"PUT"];
[methodButton addItemWithTitle:@"DELETE"];
[methodButton addItemWithTitle:@"HEAD"];
[responseText setFont:[NSFont fontWithName:@"Courier New" size:12]];
[responseTextHeaders setFont:[NSFont fontWithName:@"Courier New" size:12]];
[requestText setFont:[NSFont fontWithName:@"Courier New" size:12]];
[urlBox setNumberOfVisibleItems:10];
[savedRequestsDrawer open];
}
- (void) determineRequestContentType{
for(NSDictionary * row in headersTable)
{
if([[[row objectForKey:@"key"] lowercaseString] isEqualToString:@"content-type"])
{
NSString * value = [[row objectForKey:@"value"] lowercaseString];
NSRange range;
if([value isEqualToString:@"application/x-www-form-urlencoded"]){
requestContentType = CRCContentTypeFormEncoded;
break;
}
if([value isEqualToString:@"multipart/form-data"]){
requestContentType = CRCContentTypeMultipart;
break;
}
range = [value rangeOfString:@"json"];
if(range.length > 0){
requestContentType = CRCContentTypeJson;
break;
}
range = [value rangeOfString:@"xml"];
if(range.length > 0){
requestContentType = CRCContentTypeXml;
break;
}
range = [value rangeOfString:@"image"];
if(range.length > 0){
requestContentType = CRCContentTypeImage;
break;
}
}
}
}
- (IBAction) runSubmit:(id)sender {
[self determineRequestContentType];
NSLog(@"Got submit press");
// Append http if it's not there
NSString *urlStr = [urlBox stringValue];
if (! [urlStr hasPrefix:@"http"] && ! [urlStr hasPrefix:@"https"]) {
urlStr = [[NSString alloc] initWithFormat:@"http://%@", urlStr];
[urlBox setStringValue:urlStr];
}
[responseText setString:[NSString stringWithFormat:@"Loading %@", urlStr]];
[status setStringValue:@"Opening URL..."];
[responseTextHeaders setString:@""];
[headersTab setLabel:@"Response Headers"];
[urlBox insertItemWithObjectValue: [urlBox stringValue] atIndex:0];
if (! receivedData) {
receivedData = [[NSMutableData alloc] init];
}
[receivedData setLength:0];
contentType = NULL;
NSURL *url = [NSURL URLWithString:urlStr];
NSString *method = [NSString stringWithString:[methodButton titleOfSelectedItem]];
NSMutableURLRequest * request = nil;
// headers first
NSMutableDictionary *headersDictionary = [[NSMutableDictionary alloc] init];
for(NSDictionary * row in headersTable)
{
[headersDictionary setObject:[row objectForKey:@"value"]
forKey:[row objectForKey:@"key"]];
NSLog(@"%@ = %@", [row objectForKey:@"key"], [row objectForKey:@"value"]);
}
// initialize request
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:method];
[request setAllHTTPHeaderFields:headersDictionary];
[request setTimeoutInterval:timeout];
NSLog(@"Building req");
if(self.rawRequestInput)
{
if ([method isEqualToString:@"PUT"] || [method isEqualToString:@"POST"]) {
if([filesTable count] > 0 && [[requestText string] isEqualToString:@""])
{
[CRCFileRequest createRequest:request];
}
else
{
[CRCRawRequest createRequest:request];
}
}
}
else
{
if ([method isEqualToString:@"PUT"] || [method isEqualToString:@"POST"]) {
switch(requestContentType)
{
case CRCContentTypeFormEncoded:
[CRCFormEncodedRequest createRequest:request];
break;
case CRCContentTypeMultipart:
[CRCMultipartRequest createRequest:request];
break;
}
}
}
NSLog(@"Sending method %@", method);
lastRequest = [CRCRequest requestWithApplication:self];
startDate = [NSDate date];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
if (! connection) {
NSLog(@"Could not open connection to resource");
}
}
#pragma mark -
#pragma mark Url Connection Delegate methods
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}
-(NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse {
return nil;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"Did receive response");
[status setStringValue:@"Receiving Data..."];
NSMutableString *headers = [[NSMutableString alloc] init];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
[headers appendFormat:@"HTTP %ld %@\n\n", (long)[httpResponse statusCode], [[NSHTTPURLResponse localizedStringForStatusCode:[httpResponse statusCode]] capitalizedString]];
[headersTab setLabel:[NSString stringWithFormat:@"Response Headers (%ld)", (long)[httpResponse statusCode]]];
NSDictionary *headerDict = [httpResponse allHeaderFields];
for (NSString *key in headerDict) {
[headers appendFormat:@"%@: %@\n", key, [headerDict objectForKey:key]];
if ([key isEqualToString:@"Content-Type"]) {
NSString *contentTypeLine = [headerDict objectForKey:key];
NSArray *parts = [contentTypeLine componentsSeparatedByString:@";"];
contentType = [[NSString alloc] initWithString:[parts objectAtIndex:0]];
NSLog(@"Got content type = %@", contentType);
}
}
[responseTextHeaders setString:headers];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Did fail");
[headersTab setLabel:@"Response Headers (Failed)"];
[responseText setString:[NSString stringWithFormat:@"Connection to %@ failed.", [urlBox stringValue]]];
[status setStringValue:@"Failed"];
}
// This controls if HTTP redirects are followed
- (NSURLRequest *)connection: (NSURLConnection *)inConnection
willSendRequest: (NSURLRequest *)inRequest
redirectResponse: (NSURLResponse *)inRedirectResponse;
{
if (inRedirectResponse) {
if (! followRedirects) {
return nil;
} else {
NSMutableURLRequest *r = [inRequest mutableCopy]; // original request
[r setURL: [inRequest URL]];
return r;
}
} else {
return inRequest;
}
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
if ([protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
return NO;
} else if ([protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
return allowSelfSignedCerts;
} else {
return YES;
}
}
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
} else {
if ([challenge previousFailureCount] == 0) {
NSURLCredential *newCredential;
newCredential = [NSURLCredential credentialWithUser:[username stringValue]
password:[password stringValue]
persistence:NSURLCredentialPersistenceNone];
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
[responseText setString:@"Authentication Failed"];
}
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSTimeInterval elapsed = [startDate timeIntervalSinceNow];
[status setStringValue:[NSString stringWithFormat:@"Finished in %f seconds", -1*elapsed]];
BOOL needToPrintPlain = YES;
if (contentType != NULL) {
if ([contentType isEqualToString:@"application/atom+xml"] ||
[contentType isEqualToString:@"application/rss+xml"] ||
[contentType isEqualToString:@"application/xml"]) {
NSLog(@"Formatting XML");
NSError *error;
NSXMLDocument *responseXML = [[NSXMLDocument alloc] initWithData:receivedData options:NSXMLDocumentTidyXML error:&error];
if (!responseXML) {
NSLog(@"Error reading response: %@", error);
}
[responseText setString:[responseXML XMLStringWithOptions:NSXMLNodePrettyPrint]];
needToPrintPlain = NO;
} else if ([contentType isEqualToString:@"application/json"]) {
NSLog(@"Formatting JSON");
NSString *jsonStringFromData = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
id jsonObj = [jsonStringFromData objectFromJSONString];
NSError *error = nil;
NSString *jsonFormattedString = [jsonObj JSONStringWithOptions:JKSerializeOptionPretty error:&error];
[responseText setString:jsonFormattedString];
needToPrintPlain = NO;
}
}
// Bail out, just print the text
if (needToPrintPlain) {
[responseText setString:[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]];
}
}
#pragma mark -
#pragma mark Params
- (IBAction) plusParamsRow:(id)sender {
NSMutableDictionary *row = [[NSMutableDictionary alloc] init];
[row setObject:@"Key" forKey:@"key"];
[row setObject:@"Value" forKey:@"value"];
[paramsTable addObject:row];
[paramsTableView reloadData];
[paramsTableView selectRow:([paramsTable count] - 1) byExtendingSelection:NO];
[paramsTableView editColumn:0 row:([paramsTable count] - 1) withEvent:nil select:YES];
}
- (IBAction) minusParamsRow:(id)sender {
[paramsTable removeObjectAtIndex:[paramsTableView selectedRow]];
[paramsTableView reloadData];
}
#pragma mark -
#pragma mark Files
- (IBAction) plusFileRow:(id)sender {
NSOpenPanel* picker = [NSOpenPanel openPanel];
[picker setCanChooseFiles:YES];
[picker setCanChooseDirectories:NO];
[picker setAllowsMultipleSelection:NO];
[picker beginSheetModalForWindow:window completionHandler:^(NSInteger actionStatus) {
if(actionStatus == NSOKButton)
{
for(NSURL* url in [picker URLs])
{
NSMutableDictionary *row = [[NSMutableDictionary alloc] init];
[row setObject:@"" forKey:@"key"];
[row setObject:[url relativePath] forKey:@"value"];
[row setObject:url forKey:@"url"];
[filesTable addObject:row];
[filesTableView reloadData];
[filesTableView selectRow:([filesTable count] - 1) byExtendingSelection:NO];
[filesTableView editColumn:0 row:([filesTable count] - 1) withEvent:nil select:YES];
}
}
}];
}
- (IBAction) minusFileRow:(id)sender {
[filesTable removeObjectAtIndex:[filesTableView selectedRow]];
[filesTableView reloadData];
}
#pragma mark Menu methods
- (IBAction) contentTypeMenuItemSelected:(id)sender
{
BOOL inserted = FALSE;
if([headersTable count] > 0)
{
for(NSMutableDictionary * row in headersTable)
{
if([[[row objectForKey:@"key"] lowercaseString] isEqualToString:@"content-type"])
{
[row setObject:[sender title] forKey:@"value"];
[headersTableView reloadData];
inserted = TRUE;
break;
}
}
}
if (! inserted) {
NSMutableDictionary *row = [[NSMutableDictionary alloc] init];
[row setObject:@"Content-Type" forKey:@"key"];
[row setObject:[sender title] forKey:@"value"];
[headersTable addObject:row];
[headersTableView reloadData];
}
[tabView selectTabViewItem:reqHeadersTab];
}
- (IBAction) allowSelfSignedCerts:(id)sender {
if ([sender state] == NSOnState) {
allowSelfSignedCerts = NO;
[sender setState:NSOffState];
} else {
allowSelfSignedCerts = YES;
[sender setState:NSOnState];
}
}
- (IBAction) followRedirects:(id)sender {
if ([sender state] == NSOnState) {
followRedirects = NO;
[sender setState:NSOffState];
} else {
followRedirects = YES;
[sender setState:NSOnState];
}
}
#pragma mark Table view methods
- (NSInteger) numberOfRowsInTableView:(NSTableView *) tableView {
NSLog(@"Calling number rows");
NSInteger count = 0;
if(tableView == headersTableView)
count = [headersTable count];
if(tableView == filesTableView)
count = [filesTable count];
if(tableView == paramsTableView)
count = [paramsTable count];
return count;
}
- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
id object;
NSLog(@"Calling objectValueForTableColumn %ld %@", (long)row, [tableColumn identifier]);
if(tableView == headersTableView)
object = [[headersTable objectAtIndex:row] objectForKey:[tableColumn identifier]];
if(tableView == filesTableView)
object = [[filesTable objectAtIndex:row] objectForKey:[tableColumn identifier]];
if(tableView == paramsTableView)
object = [[paramsTable objectAtIndex:row] objectForKey:[tableColumn identifier]];
return object;
}
- (void)tableView:(NSTableView *)aTableView setObjectValue:(id)anObject
forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex {
NSMutableDictionary *row;
if(aTableView == headersTableView){
row = [headersTable objectAtIndex:rowIndex];
if (row == NULL) {
row = [[NSMutableDictionary alloc] init];
}
[row setObject:anObject forKey:[aTableColumn identifier]];
[headersTable replaceObjectAtIndex:rowIndex withObject:row];
}
if(aTableView == filesTableView){
row = [filesTable objectAtIndex:rowIndex];
if (row == NULL) {
row = [[NSMutableDictionary alloc] init];
}
[row setObject:anObject forKey:[aTableColumn identifier]];
[filesTable replaceObjectAtIndex:rowIndex withObject:row];
}
if(aTableView == paramsTableView){
row = [paramsTable objectAtIndex:rowIndex];
if (row == NULL) {
row = [[NSMutableDictionary alloc] init];
}
[row setObject:anObject forKey:[aTableColumn identifier]];
[paramsTable replaceObjectAtIndex:rowIndex withObject:row];
}
}
- (IBAction) plusHeaderRow:(id)sender {
NSMutableDictionary *row = [[NSMutableDictionary alloc] init];
[headersTable addObject:row];
[headersTableView reloadData];
[headersTableView selectRow:([headersTable count] - 1) byExtendingSelection:NO];
[headersTableView editColumn:0 row:([headersTable count] - 1) withEvent:nil select:YES];
}
- (IBAction) minusHeaderRow:(id)sender {
[headersTable removeObjectAtIndex:[headersTableView selectedRow]];
[headersTableView reloadData];
}
- (IBAction) clearAuth:(id)sender {
[username setStringValue:@""];
[password setStringValue:@""];
}
#pragma mark OutlineViewDataSource methods
- (NSInteger) outlineView: (NSOutlineView *)outlineView numberOfChildrenOfItem: (id)item {
if (item == nil) {
return [savedRequestsArray count];
}
if (item == savedRequestsArray) {
return [item count];
}
return 0;
}
- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item {
return NO;
}
- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item {
if (item == nil) {
item = savedRequestsArray;
}
if (item == savedRequestsArray) {
return [item objectAtIndex:index];
}
return nil;
}
- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item {
if ([item isKindOfClass:[CRCRequest class]])
{
CRCRequest * req = (CRCRequest *)item;
return req.name;
}
else if([item isKindOfClass:[NSDictionary class]] )
{
return [item objectForKey:@"name"];
}
else if (item == savedRequestsArray) {
return savedRequestsArray;
}
return nil;
}
// Respond to click on a row of the saved requests outline view
- (IBAction) outlineClick:(id)sender {
/*
NSAlert *alert = [NSAlert new];
[alert setMessageText:[NSString stringWithFormat:@"Selected %@", [savedOutlineView itemAtRow:[savedOutlineView selectedRow]]]];
[alert runModal];
*/
[self loadSavedRequest:[savedOutlineView itemAtRow:[savedOutlineView selectedRow]]];
}
- (IBAction) deleteSavedRequest:(id) sender {
int row = [savedOutlineView selectedRow];
[savedRequestsArray removeObjectAtIndex:row];
[savedOutlineView reloadItem:nil reloadChildren:YES];
}
// Save an HTTP request into the request drawer
- (IBAction) saveRequest:(id) sender {
[NSApp beginSheet:saveRequestSheet modalForWindow:window
modalDelegate:self didEndSelector:NULL contextInfo:nil];
}
// Dispose of save request sheet
- (IBAction) doneSaveRequest:(id) sender {
if ([sender isKindOfClass:[NSTextField class]] || ! [[sender title] isEqualToString:@"Cancel"]) {
CRCRequest * request = [CRCRequest requestWithApplication:self];
[savedRequestsArray addObject:request];
[savedOutlineView reloadItem:nil reloadChildren:YES];
}
[saveRequestSheet orderOut:nil];
[NSApp endSheet:saveRequestSheet];
}
- (IBAction) openTimeoutDialog:(id) sender {
[timeoutField setIntValue:timeout];
[NSApp beginSheet:timeoutSheet modalForWindow:window modalDelegate:self didEndSelector:NULL contextInfo:nil];
}
- (IBAction) closeTimoutDialog:(id) sender {
if ([sender isKindOfClass:[NSTextField class]] || ! [[sender title] isEqualToString:@"Cancel"]) {
timeout = [timeoutField intValue];
}
[timeoutSheet orderOut:nil];
[NSApp endSheet:timeoutSheet];
}
- (void)loadSavedRequest:(id)request {
if([request isKindOfClass:[NSDictionary class]])
{
[self loadSavedDictionary:(NSDictionary *)request];
}
else if([request isKindOfClass:[CRCRequest class]])
{
[self loadSavedCRCRequest:(CRCRequest *)request];
}
}
// if it's a dictionary it's the old format, files, params, rawRequestInput will not be present
- (void)loadSavedDictionary:(NSDictionary *)request
{
[urlBox setStringValue:[request objectForKey:@"url"]];
[methodButton selectItemWithTitle:[request objectForKey:@"method"]];
[username setStringValue:[request objectForKey:@"username"]];
[password setStringValue:[request objectForKey:@"password"]];
self.rawRequestInput = YES;
if ([request objectForKey:@"body"])
{
[requestText setString:[request objectForKey:@"body"]];
}
else
{
[requestText setString:@""];
}
NSArray *headers = [request objectForKey:@"headers"];
NSMutableArray *headersTranslated = [[NSMutableArray alloc] init];
for(NSDictionary *header in headers) {
if ([header objectForKey:@"header-name"]) {
NSMutableDictionary *headerTranslated = [[NSMutableDictionary alloc] init];
[headerTranslated setObject:[header objectForKey:@"header-name"] forKey:@"key"];
[headerTranslated setObject:[header objectForKey:@"header-value"] forKey:@"value"];
[headersTranslated addObject:headerTranslated];
} else {
[headersTranslated addObject:header];
}
}
[headersTable removeAllObjects];
[paramsTable removeAllObjects];
[filesTable removeAllObjects];
if (headers)
[headersTable addObjectsFromArray:headersTranslated];
[headersTableView reloadData];
[filesTableView reloadData];
[paramsTableView reloadData];
}
- (void)loadSavedCRCRequest:(CRCRequest *)request
{
[urlBox setStringValue:request.url];
[methodButton selectItemWithTitle:request.method];
[username setStringValue:request.username];
[password setStringValue:request.password];
self.rawRequestInput = request.rawRequestInput;
if(request.rawRequestInput)
{
[requestText setString:request.requestText];
}
else
{
[requestText setString:@""];
}
NSArray *headers = [[NSArray alloc] initWithArray:request.headers copyItems:YES];
NSArray *params = [[NSArray alloc] initWithArray:request.params copyItems:YES];
NSArray *files = [[NSArray alloc] initWithArray:request.files copyItems:YES];
[headersTable removeAllObjects];
[paramsTable removeAllObjects];
[filesTable removeAllObjects];
// Make headers, params, and files mutable dictionaries when they get loaded so that
// they can still be updated after being loaded.
if (headers) {
for(NSDictionary *header in headers) {
NSMutableDictionary *headerTranslated = [[NSMutableDictionary alloc] initWithDictionary:header];
[headersTable addObject:headerTranslated];
}
}
if (params) {
for(NSDictionary *param in params) {
NSMutableDictionary *paramTranslated = [[NSMutableDictionary alloc] initWithDictionary:param];
[paramsTable addObject:paramTranslated];
}
}
if (files) {
for(NSDictionary *file in files) {
NSMutableDictionary *fileTranslated = [[NSMutableDictionary alloc] initWithDictionary:file];
[filesTable addObject:fileTranslated];
}
}
[headersTableView reloadData];
[filesTableView reloadData];
[paramsTableView reloadData];
}
- (NSString *) pathForDataFile {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *folder = @"~/Library/Application Support/CocoaRestClient/";
folder = [folder stringByExpandingTildeInPath];
if ([fileManager fileExistsAtPath: folder] == NO) {
NSError *error = nil;
[fileManager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:&error];
}
NSString *fileName = @"CocoaRestClient.savedRequests";
return [folder stringByAppendingPathComponent:fileName];
}
- (void) saveDataToDisk {
NSString *path = [self pathForDataFile];
[NSKeyedArchiver archiveRootObject:savedRequestsArray toFile:path];
}
- (void) loadDataFromDisk {
NSString *path = [self pathForDataFile];
savedRequestsArray = [[NSMutableArray alloc] initWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:path]];
}
- (IBAction) handleOpenWindow:(id)sender {
[window makeKeyAndOrderFront:self];
}
// Including this to disable Open Window menu item when window is already open
- (BOOL)validateMenuItem:(NSMenuItem *)item
{
//check to see if the Main Menu NSMenuItem is
//being validcated
if([item tag] == MAIN_WINDOW_MENU_TAG)
{
return ![window isVisible];
}
return TRUE;
}
- (void) applicationWillTerminate: (NSNotification *)note {
[self saveDataToDisk];
}
- (IBAction) helpInfo:(id)sender {
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://code.google.com/p/cocoa-rest-client/"]];
}
- (IBAction) licenseInfo:(id)sender {
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://cocoa-rest-client.googlecode.com/svn/trunk/LICENSE.txt"]];
}
- (IBAction) reloadLastRequest:(id)sender {
if (lastRequest != nil) {
[self loadSavedCRCRequest:(CRCRequest *)lastRequest];
[self runSubmit: self];
}
}
@end