-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAppController.m
2070 lines (1739 loc) · 59.2 KB
/
AppController.m
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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Project: DataBasin
Copyright (C) 2008-2024 Free Software Foundation
Author: Riccardo Mottola
Created: 2008-11-13 22:44:02 +0100 by multix
Application Controller
This application is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This application is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 31 Milk Street #960789 Boston, MA 02196 USA.
*/
#import "AppController.h"
#import <DataBasinKit/DBSoap.h>
#import <DataBasinKit/DBSoapCSV.h>
#import <DataBasinKit/DBFileWriter.h>
#import <DataBasinKit/DBCSVWriter.h>
#import <DataBasinKit/DBHTMLWriter.h>
#import <DataBasinKit/DBCSVReader.h>
#import "DBLogger.h"
#import "DBProgress.h"
#import "Preferences.h"
#define DB_ENVIRONMENT_PRODUCTION 0
#define DB_ENVIRONMENT_SANDBOX 1
#define MAX_STORED_LOGINS 10
#if defined(__APPLE__) && (MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4)
#define NSUTF16StringEncoding 999
#endif
@implementation AppController
- (id)init
{
if ((self = [super init]))
{
NSUserDefaults *defaults;
defaults = [NSUserDefaults standardUserDefaults];
logger = [[DBLogger alloc] init];
[self reloadDefaults];
loginDict = [defaults objectForKey: @"logins"];
if (loginDict == nil)
loginDict = [NSMutableDictionary dictionary];
else
loginDict = [NSMutableDictionary dictionaryWithDictionary:loginDict];
[loginDict retain];
}
return self;
}
- (void)dealloc
{
[preferences release];
[dbCsv release];
[db release];
[logger release];
[loginDict release];
[super dealloc];
}
- (void)awakeFromNib
{
NSString *lastUsername;
objInspector = [[DBObjectInspector alloc] init];
lastUsername = [[NSUserDefaults standardUserDefaults] stringForKey: @"lastUsername"];
if (lastUsername != nil)
{
[fieldUserName setStringValue: lastUsername];
[self usernameFieldAction:fieldUserName];
}
[fieldOrgName setDrawsBackground:NO];
[fieldServerUrl setDrawsBackground:NO];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotif
{
}
- (BOOL)applicationShouldTerminate:(id)sender
{
return YES;
}
- (void)applicationWillTerminate:(NSNotification *)aNotif
{
}
- (BOOL)application:(NSApplication *)application openFile:(NSString *)fileName
{
return NO;
}
- (void)reloadDefaults
{
NSUserDefaults *defaults;
id obj;
unsigned size;
defaults = [NSUserDefaults standardUserDefaults];
obj = [defaults objectForKey: @"LogLevel"];
/* if the log level is not set we set it to the standard level */
if (obj == nil)
{
obj = [NSNumber numberWithInt: LogStandard];
[defaults setObject:obj forKey: @"LogLevel"];
}
[logger setLogLevel: [obj intValue]];
obj = [defaults objectForKey: @"StringEncoding"];
if (obj == nil)
{
obj = [NSNumber numberWithInt: NSUTF8StringEncoding];
[defaults setObject:obj forKey: @"StringEncoding"];
}
size = [defaults integerForKey:@"UpBatchSize"];
if (size == 0)
{
size = 10;
[defaults setInteger:size forKey:@"UpBatchSize"];
}
[db setUpBatchSize:size];
size = [defaults integerForKey:@"DownBatchSize"];
if (size == 0)
{
size = 100;
[defaults setInteger:size forKey:@"DownBatchSize"];
}
[db setDownBatchSize:size];
size = [defaults integerForKey:@"MaxSOQLQueryLength"];
if (size == 0)
{
size = MAX_SOQL_LENGTH;
[defaults setInteger:size forKey:@"MaxSOQLQueryLength"];
}
[db setMaxSOQLLength:size];
[db setEnableFieldTypesDescribeForQuery:[[defaults objectForKey:@"DescribeFieldTypesInQueries"] boolValue]];
[defaults synchronize];
// FIXME here we should set the defaults of the CSV reader/writers
}
- (IBAction)showPrefPanel:(id)sender
{
if (!preferences)
{
preferences = [[Preferences alloc] init];
[preferences setAppController:self];
}
[preferences showPrefPanel:sender];
}
- (void)showException:(NSException *)e
{
NSLog(@"Exception: %@ - %@", e, [e reason]);
[faultTextView setString:[e reason]];
[faultPanel makeKeyAndOrderFront:self];
}
/* SESSION INSPECTOR */
- (IBAction)showSessionInspector:(id)sender
{
[winSessionInspector makeKeyAndOrderFront:self];
}
/* USER INSPECTOR */
- (IBAction)showUserInspector:(id)sender
{
[winUserInspector makeKeyAndOrderFront:self];
}
- (IBAction)setEnableSessionEditing:(id)sender
{
if ([buttonSessionEditEnable state] == NSOnState)
{
[fieldOrgId setEditable:YES];
[fieldOrgId setDrawsBackground:YES];
[fieldHost setEditable:YES];
[fieldHost setDrawsBackground:YES];
[fieldSessionId setEditable:YES];
[fieldSessionId setDrawsBackground:YES];
[buttonSetSessionData setEnabled:YES];
}
else
{
[fieldOrgId setEditable:NO];
[fieldOrgId setDrawsBackground:NO];
[fieldHost setEditable:NO];
[fieldHost setDrawsBackground:NO];
[fieldSessionId setEditable:NO];
[fieldSessionId setDrawsBackground:NO];
[buttonSetSessionData setEnabled:NO];
}
}
- (IBAction)setSessionData:(id)sender
{
NSString *session;
NSString *hostStr;
NSString *urlStr;
NSString *orgIdStr;
NSURL *URL;
NSUserDefaults *defaults;
session = [fieldSessionId stringValue];
hostStr = [fieldHost stringValue];
orgIdStr = [fieldOrgId stringValue];
if (nil == session || [session length] < 10)
{
NSRunAlertPanel(@"Attention", @"Invalid session string.", @"Ok", nil, nil);
return;
}
if (nil == orgIdStr || !([orgIdStr length] == 15 || [orgIdStr length] == 18))
{
NSRunAlertPanel(@"Attention", @"Invalid Org ID string.", @"Ok", nil, nil);
return;
}
if ([orgIdStr length] == 18)
{
orgIdStr = [orgIdStr substringToIndex:15];
}
if (nil == hostStr || [hostStr length] < 10)
{
NSRunAlertPanel(@"Attention", @"Invalid Host.", @"Ok", nil, nil);
return;
}
urlStr = [NSString stringWithFormat: @"https://%@/services/Soap/u/%@/%@", hostStr, [DBSoap apiVersion], orgIdStr];
URL = [[NSURL alloc] initWithString:urlStr];
// we show what we calculated
[fieldServerUrl setStringValue:[URL absoluteString]];
defaults = [NSUserDefaults standardUserDefaults];
NSLog(@"set URL to URL: %@", URL);
[db release];
[dbCsv release];
db = [[DBSoap alloc] init];
[db setLogger: logger];
[db setUpBatchSize:[[defaults objectForKey:@"UpBatchSize"] intValue]];
[db setDownBatchSize:[[defaults objectForKey:@"DownBatchSize"] intValue]];
[db setMaxSOQLLength:[[defaults objectForKey:@"MaxSOQLQueryLength"] intValue]];
[db setEnableFieldTypesDescribeForQuery:[[defaults objectForKey:@"DescribeFieldTypesInQueries"] boolValue]];
[db setSessionId:session];
[db setServerURL:URL];
[URL release];
dbCsv = [[DBSoapCSV alloc] init];
[dbCsv setDBSoap:db];
[logger log:LogStandard :@"[AppController doSetSessionData] setting Session Data directly.\n"];
/* set or update soap handlers */
[objInspector setSoapHandler:db];
}
/* LOGGER */
- (IBAction)showLog:(id)sender
{
[logger show:sender];
}
/* LOGIN */
- (IBAction)showLogin:(id)sender
{
[winLogin makeKeyAndOrderFront:self];
}
- (IBAction)usernameFieldAction:(id)sender
{
NSDictionary *loginSet;
NSString *userName;
NSString *token;
NSNumber *envNum;
userName = [fieldUserName stringValue];
loginSet = [loginDict objectForKey:userName];
if (loginSet == nil)
return;
[fieldPassword setStringValue:[loginSet objectForKey:@"password"]];
token = [loginSet objectForKey:@"token"];
if (token == nil)
token = @"";
[fieldToken setStringValue:token];
envNum = [loginSet objectForKey:@"environment"];
if (envNum)
[popupEnvironment selectItemAtIndex:[envNum intValue]];
}
- (IBAction)doLogin:(id)sender
{
NSString *userName;
NSString *password;
NSString *token;
NSURL *url;
NSDictionary *uInfo;
NSMutableDictionary *loginSet;
NSUserDefaults *defaults;
userName = [fieldUserName stringValue];
password = [fieldPassword stringValue];
token = [fieldToken stringValue];
defaults = [NSUserDefaults standardUserDefaults];
/* if present, we append the security token to the password */
if (token != nil)
password = [password stringByAppendingString:token];
db = [[DBSoap alloc] init];
[db setLogger: logger];
[db setUpBatchSize:[[defaults objectForKey:@"UpBatchSize"] intValue]];
[db setDownBatchSize:[[defaults objectForKey:@"DownBatchSize"] intValue]];
[db setMaxSOQLLength:[[defaults objectForKey:@"MaxSOQLQueryLength"] intValue]];
[db setEnableFieldTypesDescribeForQuery:[[defaults objectForKey:@"DescribeFieldTypesInQueries"] boolValue]];
dbCsv = [[DBSoapCSV alloc] init];
[dbCsv setDBSoap:db];
url = nil;
if ([popupEnvironment indexOfSelectedItem] == DB_ENVIRONMENT_PRODUCTION)
url = [DBSoap loginURLProduction];
else if ([popupEnvironment indexOfSelectedItem] == DB_ENVIRONMENT_SANDBOX)
url = [DBSoap loginURLTest];
[logger log:LogStandard :@"[AppController doLogin] Url: %@\n", [url absoluteString]];
NS_DURING
[db login :url :userName :password];
/* session inspector fields */
[fieldSessionId setStringValue:[db sessionId]];
[fieldServerUrl setStringValue:[[db serverURL] absoluteString]];
[fieldHost setStringValue:[[db serverURL] host]];
if ([db passwordExpired])
[fieldPwdExpired setStringValue: @"YES"];
else
[fieldPwdExpired setStringValue: @"NO"];
/* user inspector fields */
uInfo = [db userInfo];
[fieldOrgName setStringValue: [uInfo objectForKey:@"organizationName"]];
[fieldOrgId setStringValue: [uInfo objectForKey:@"organizationId"]];
[fieldUserNameInsp setStringValue: [uInfo objectForKey:@"userName"]];
[fieldUserFullName setStringValue: [uInfo objectForKey:@"userFullName"]];
[fieldUserEmail setStringValue: [uInfo objectForKey:@"userEmail"]];
[fieldUserId setStringValue: [uInfo objectForKey:@"userId"]];
[fieldProfileId setStringValue: [uInfo objectForKey:@"profileId"]];
[fieldRoleId setStringValue: [uInfo objectForKey:@"roleId"]];
NS_HANDLER
[logger log:LogStandard :@"Login failed\n"];
[loginStatus setImage:[NSImage imageNamed:@"butt_red_16.tif"]];
if ([[localException name] hasPrefix:@"DB"])
{
[self performSelectorOnMainThread:@selector(showException:) withObject:localException waitUntilDone:YES];
return;
}
else
{
NSLog(@"Unexpected exception: %@", [localException name]);
}
NS_ENDHANDLER
[logger log:LogStandard :@"[AppController doLogin] %@ logged in succesfully\n", userName];
[loginStatus setImage:[NSImage imageNamed:@"butt_green_16.tif"]];
loginSet = [NSMutableDictionary dictionaryWithCapacity:4];
[loginSet retain];
[loginSet setObject:userName forKey:@"username"];
[loginSet setObject:[fieldPassword stringValue] forKey:@"password"];
if (token != nil)
[loginSet setObject:token forKey:@"token"];
[loginSet setObject:[NSDate date] forKey:@"lastlogin"];
[loginSet setObject:[NSNumber numberWithInt:[popupEnvironment indexOfSelectedItem]] forKey:@"environment"];
[loginDict setObject:loginSet forKey:userName];
[loginSet release];
NSLog(@"login dictionary is: %@", loginDict);
if ([loginDict count] > MAX_STORED_LOGINS)
{
NSEnumerator *e;
id key;
id oldKey;
[logger log:LogInformative :@"[AppController doLogin] Maximum number of stored logins reached, removing oldest\n"];
e = [loginDict keyEnumerator];
oldKey = nil;
while ((key = [e nextObject]))
{
NSDictionary *currSet;
NSDictionary *oldSet;
if (oldKey == nil)
oldKey = key;
currSet = [loginDict objectForKey:key];
oldSet = [loginDict objectForKey:oldKey];
if ([(NSString *)[currSet objectForKey:@"lastlogin"] compare: [oldSet objectForKey:@"lastlogin"]] == NSOrderedAscending)
oldKey = key;
}
[logger log:LogInformative :@"[AppController doLogin] delete: %@\n", oldKey];
[loginDict removeObjectForKey:oldKey];
}
[[NSUserDefaults standardUserDefaults] setObject:loginDict forKey: @"logins"];
[[NSUserDefaults standardUserDefaults] setObject:userName forKey: @"lastUsername"];
/* set or update soap handlers */
[objInspector setSoapHandler:db];
}
/* UPDATE SOBJECT LIST */
- (IBAction)runDescribeGlobal:(id)sender
{
NS_DURING
[db updateObjects];
NS_HANDLER
if ([[localException name] hasPrefix:@"DB"])
{
[faultTextView setString:[localException reason]];
[faultPanel makeKeyAndOrderFront:nil];
}
NS_ENDHANDLER
}
/* SELECT */
- (IBAction)showSelect:(id)sender
{
[progIndSelect setDoubleValue:0];
[winSelect makeKeyAndOrderFront:self];
}
- (IBAction)browseFileSelect:(id)sender
{
NSSavePanel *savePanel;
NSArray *types;
types = [NSArray arrayWithObjects:@"csv", @"html", @"xls", nil];
savePanel = [NSSavePanel savePanel];
[savePanel setAllowedFileTypes:types];
if ([savePanel runModal] == NSOKButton)
{
NSString *fileName;
fileName = [savePanel filename];
[fieldFileSelect setStringValue:fileName];
}
}
- (void)resetSelectUI:(id)arg
{
[buttonSelectExec setEnabled:YES];
[buttonSelectStop setEnabled:NO];
}
- (void)performSelect:(id)arg
{
NSString *statement;
NSString *filePath;
NSFileHandle *fileHandle;
NSFileManager *fileManager;
DBFileWriter *fileWriter;
NSString *str;
NSUserDefaults *defaults;
NSAutoreleasePool *arp;
NSString *fileType;
arp = [NSAutoreleasePool new];
defaults = [NSUserDefaults standardUserDefaults];
statement = [fieldQuerySelect string];
filePath = [fieldFileSelect stringValue];
fileType = DBFileFormatCSV;
if ([[[filePath pathExtension] lowercaseString] isEqualToString:@"html"])
fileType = DBFileFormatHTML;
else if ([[[filePath pathExtension] lowercaseString] isEqualToString:@"xls"])
fileType = DBFileFormatXLS;
fileManager = [NSFileManager defaultManager];
if ([fileManager createFileAtPath:filePath contents:nil attributes:nil] == NO)
{
NSRunAlertPanel(@"Attention", @"Could not create File.", @"Ok", nil, nil);
[self performSelectorOnMainThread:@selector(resetSelectUI:) withObject:self waitUntilDone:NO];
return;
}
fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
if (fileHandle == nil)
{
NSRunAlertPanel(@"Attention", @"Cannot create File.", @"Ok", nil, nil);
[self performSelectorOnMainThread:@selector(resetSelectUI:) withObject:self waitUntilDone:NO];
return;
}
selectProgress = [[DBProgress alloc] init];
[selectProgress setProgressIndicator: progIndSelect];
[selectProgress setRemainingTimeField: fieldRTSelect];
[selectProgress setLogger:logger];
[selectProgress reset];
fileWriter = nil;
if (fileType == DBFileFormatCSV)
{
fileWriter = [[DBCSVWriter alloc] initWithHandle:fileHandle];
[(DBCSVWriter *)fileWriter setLineBreakHandling:[defaults integerForKey:CSVWriteLineBreakHandling]];
str = [defaults stringForKey:@"CSVWriteQualifier"];
if (str)
[(DBCSVWriter *)fileWriter setQualifier:str];
str = [defaults stringForKey:@"CSVWriteSeparator"];
if (str)
[(DBCSVWriter *)fileWriter setSeparator:str];
}
else if (fileType == DBFileFormatHTML || fileType == DBFileFormatXLS)
{
fileWriter = [[DBHTMLWriter alloc] initWithHandle:fileHandle];
if (fileType == DBFileFormatXLS)
[fileWriter setFileFormat:DBFileFormatXLS];
else
[fileWriter setFileFormat:DBFileFormatHTML];
}
[fileWriter setWriteFieldsOrdered:([orderedWritingSelect state] == NSOnState)];
[fileWriter setLogger:logger];
[fileWriter setStringEncoding: [defaults integerForKey: @"StringEncoding"]];
NSLog(@"fileType is: %@, writer: %@", fileType, fileWriter);
NS_DURING
[dbCsv query :statement queryAll:([queryAllSelect state] == NSOnState) toWriter:fileWriter progressMonitor:selectProgress];
NS_HANDLER
if ([[localException name] hasPrefix:@"DB"])
{
[self performSelectorOnMainThread:@selector(showException:) withObject:localException waitUntilDone:YES];
}
NS_ENDHANDLER
[fileWriter release];
[fileHandle closeFile];
[selectProgress release];
selectProgress = nil;
[self performSelectorOnMainThread:@selector(resetSelectUI:) withObject:self waitUntilDone:NO];
[arp release];
}
- (IBAction)executeSelect:(id)sender
{
[buttonSelectExec setEnabled:NO];
[buttonSelectStop setEnabled:YES];
[NSThread detachNewThreadSelector:@selector(performSelect:) toTarget:self withObject:nil];
}
- (IBAction)stopSelect:(id)sender
{
[selectProgress setShouldStop:YES];
}
/* INSERT */
- (void)resetInsertUI:(id)arg
{
[buttonInsertExec setEnabled:YES];
[buttonInsertStop setEnabled:NO];
}
- (IBAction)showInsert:(id)sender
{
NSArray *objectNames;
NSMutableArray *filteredObjectNames;
BOOL filterShare;
BOOL filterHistory;
BOOL filterChangeEvent;
BOOL filterFeed;
NSUInteger i;
NSUserDefaults *defaults;
defaults = [NSUserDefaults standardUserDefaults];
filterShare = [defaults boolForKey:@"FilterObjects_Share"];
filterHistory = [defaults boolForKey:@"FilterObjects_History"];
filterChangeEvent = [defaults boolForKey:@"FilterObjects_ChangeEvent"];
filterFeed= [defaults boolForKey:@"FilterObjects_Feed"];
[winInsert makeKeyAndOrderFront:self];
[progIndInsert setIndeterminate:YES];
objectNames = nil;
NS_DURING
objectNames = [db sObjectNames];
NS_HANDLER
if ([[localException name] hasPrefix:@"DB"])
{
[self performSelectorOnMainThread:@selector(showException:) withObject:localException waitUntilDone:YES];
}
NS_ENDHANDLER
filteredObjectNames = [[NSMutableArray alloc] initWithCapacity:1];
for (i = 0; i < [objectNames count]; i++)
{
NSString *name;
name = [objectNames objectAtIndex:i];
if (filterShare && [name hasSuffix: @"Share"])
name = nil;
if (filterHistory && [name hasSuffix: @"History"])
name = nil;
if (filterChangeEvent && [name hasSuffix: @"ChangeEvent"])
name = nil;
if (filterFeed && [name hasSuffix: @"Feed"])
name = nil;
if (name)
[filteredObjectNames addObject:name];
}
[comboObjectsInsert removeAllItems];
[comboObjectsInsert addItemsWithObjectValues: filteredObjectNames];
[progIndInsert setIndeterminate:NO];
[progIndInsert setDoubleValue:0];
[filteredObjectNames release];
}
- (IBAction)browseFileInsert:(id)sender
{
NSOpenPanel *openPanel;
openPanel = [NSOpenPanel openPanel];
// [openPanel setRequiredFileType:@"csv"];
if ([openPanel runModal] == NSOKButton)
{
NSString *fileName;
fileName = [openPanel filename];
[fieldFileInsert setStringValue:fileName];
}
}
- (void)performInsert:(id)arg
{
NSString *filePath;
NSString *resFilePath;
DBCSVReader *reader;
NSString *intoWhichObject;
NSMutableArray *results;
NSFileManager *fileManager;
NSFileHandle *resFH;
NSUserDefaults *defaults;
DBCSVWriter *resWriter;
NSString *str;
NSAutoreleasePool *arp;
arp = [NSAutoreleasePool new];
defaults = [NSUserDefaults standardUserDefaults];
filePath = [fieldFileInsert stringValue];
if (filePath == nil)
{
[logger log:LogInformative :@"[AppController performInsert] nil file paths\n"];
return;
}
resFilePath = [[filePath stringByDeletingLastPathComponent] stringByAppendingPathComponent: @"results.csv"];
NSLog(@"writing results to: %@", resFilePath);
intoWhichObject = [[comboObjectsInsert stringValue] retain];
[logger log:LogInformative :@"[AppController performInsert] object: %@\n", intoWhichObject];
insertProgress = [[DBProgress alloc] init];
[insertProgress setLogger:logger];
[insertProgress setProgressIndicator: progIndInsert];
[insertProgress setRemainingTimeField: fieldRTInsert];
[insertProgress reset];
results = nil;
reader = [[DBCSVReader alloc] initWithPath:filePath withLogger:logger];
str = [defaults stringForKey:@"CSVReadQualifier"];
if (str)
[reader setQualifier:str];
str = [defaults stringForKey:@"CSVReadSeparator"];
if (str)
[reader setSeparator:str];
[reader parseHeaders];
[dbCsv setRunAssignmentRules:[defaults boolForKey:@"RunAssignmentRules"]];
NS_DURING
results = [dbCsv create:intoWhichObject fromReader:reader progressMonitor:insertProgress];
[results retain];
NS_HANDLER
if ([[localException name] hasPrefix:@"DB"])
{
[self performSelectorOnMainThread:@selector(showException:) withObject:localException waitUntilDone:YES];
[self resetInsertUI:self];
}
NS_ENDHANDLER
fileManager = [NSFileManager defaultManager];
if (results && [fileManager createFileAtPath:resFilePath contents:nil attributes:nil] == NO)
{
NSRunAlertPanel(@"Attention", @"Could not create File.", @"Ok", nil, nil);
}
resFH = [NSFileHandle fileHandleForWritingAtPath:resFilePath];
if (resFH == nil)
{
NSRunAlertPanel(@"Attention", @"Cannot create File.", @"Ok", nil, nil);
}
else
{
if (results != nil && [results count] > 0)
{
resWriter = [[DBCSVWriter alloc] initWithHandle:resFH];
[resWriter setLogger:logger];
[resWriter setStringEncoding: [defaults integerForKey: @"StringEncoding"]];
str = [defaults stringForKey:@"CSVWriteQualifier"];
if (str)
[resWriter setQualifier:str];
str = [defaults stringForKey:@"CSVWriteSeparator"];
if (str)
[resWriter setSeparator:str];
[resWriter setFieldNames:[results objectAtIndex: 0] andWriteThem:YES];
[resWriter writeDataSet: results];
[resWriter release];
}
else
{
[logger log:LogStandard :@"[AppController executeInsert] No Results"];
}
}
[reader release];
[intoWhichObject release];
[insertProgress release];
insertProgress = nil;
[self performSelectorOnMainThread:@selector(resetInsertUI:) withObject:self waitUntilDone:NO];
[results release];
[arp release];
}
- (IBAction)executeInsert:(id)sender
{
[buttonInsertExec setEnabled:NO];
[buttonInsertStop setEnabled:YES];
[NSThread detachNewThreadSelector:@selector(performInsert:) toTarget:self withObject:nil];
}
- (IBAction)stopInsert:(id)sender
{
[insertProgress setShouldStop:YES];
}
/* UPDATE */
- (IBAction)showUpdate:(id)sender
{
NSArray *objectNames;
NSMutableArray *filteredObjectNames;
BOOL filterShare;
BOOL filterHistory;
NSUInteger i;
NSUserDefaults *defaults;
defaults = [NSUserDefaults standardUserDefaults];
filterShare = [defaults boolForKey:@"FilterObjects_Share"];
filterHistory = [defaults boolForKey:@"FilterObjects_History"];
[winUpdate makeKeyAndOrderFront:self];
[progIndUpdate setIndeterminate:YES];
objectNames = nil;
NS_DURING
objectNames = [db sObjectNames];
NS_HANDLER
if ([[localException name] hasPrefix:@"DB"])
{
[self performSelectorOnMainThread:@selector(showException:) withObject:localException waitUntilDone:YES];
}
NS_ENDHANDLER
filteredObjectNames = [[NSMutableArray alloc] initWithCapacity:1];
for (i = 0; i < [objectNames count]; i++)
{
NSString *name;
name = [objectNames objectAtIndex:i];
if (filterShare && [name hasSuffix: @"Share"])
name = nil;
if (filterHistory && [name hasSuffix: @"History"])
name = nil;
if (name)
[filteredObjectNames addObject:name];
}
[comboObjectsUpdate removeAllItems];
[comboObjectsUpdate addItemsWithObjectValues: filteredObjectNames];
[progIndUpdate setIndeterminate:NO];
[progIndUpdate setDoubleValue:0];
[filteredObjectNames release];
}
- (IBAction)browseFileUpdate:(id)sender
{
NSOpenPanel *openPanel;
openPanel = [NSOpenPanel openPanel];
// [openPanel setRequiredFileType:@"csv"];
if ([openPanel runModal] == NSOKButton)
{
NSString *fileName;
fileName = [openPanel filename];
[fieldFileUpdate setStringValue:fileName];
}
}
- (void)resetUpdateUI:(id)arg
{
[buttonUpdateExec setEnabled:YES];
[buttonUpdateStop setEnabled:NO];
}
- (void)performUpdate:(id)arg
{
NSString *filePath;
NSString *resFilePath;
DBCSVReader *reader;
NSString *whichObject;
NSMutableArray *results;
NSFileManager *fileManager;
NSFileHandle *resFH;
NSUserDefaults *defaults;
DBCSVWriter *resWriter;
NSString *str;
NSAutoreleasePool *arp;
arp = [NSAutoreleasePool new];
defaults = [NSUserDefaults standardUserDefaults];
filePath = [fieldFileUpdate stringValue];
resFilePath = [[filePath stringByDeletingLastPathComponent] stringByAppendingPathComponent: @"results.csv"];
[logger log:LogDebug: @"[AppController executeUpdate] writing results to: %@", resFilePath];
updateProgress = [[DBProgress alloc] init];
[updateProgress setLogger:logger];
[updateProgress setProgressIndicator: progIndUpdate];
[updateProgress setRemainingTimeField: fieldRTUpdate];
[updateProgress reset];
whichObject = [[comboObjectsUpdate stringValue] retain];
[logger log:LogInformative :@"[AppController executeUpdate] object: %@\n", whichObject];
results = nil;
reader = [[DBCSVReader alloc] initWithPath:filePath withLogger:logger];
str = [defaults stringForKey:@"CSVReadQualifier"];
if (str)
[reader setQualifier:str];
str = [defaults stringForKey:@"CSVReadSeparator"];
if (str)
[reader setSeparator:str];
[reader parseHeaders];
[dbCsv setRunAssignmentRules:[defaults boolForKey:@"RunAssignmentRules"]];
NS_DURING
results = [dbCsv update:whichObject fromReader:reader progressMonitor:updateProgress];
[results retain];
NS_HANDLER
if ([[localException name] hasPrefix:@"DB"])
{
[self performSelectorOnMainThread:@selector(showException:) withObject:localException waitUntilDone:YES];
}
else
{
[localException raise];
}
NS_ENDHANDLER
fileManager = [NSFileManager defaultManager];
if ([fileManager createFileAtPath:resFilePath contents:nil attributes:nil] == NO)
{
NSRunAlertPanel(@"Attention", @"Could not create File.", @"Ok", nil, nil);
}
resFH = [NSFileHandle fileHandleForWritingAtPath:resFilePath];
if (resFH == nil)
{
NSRunAlertPanel(@"Attention", @"Cannot create File.", @"Ok", nil, nil);
}
else
{
if (results != nil && [results count] > 0)
{
resWriter = [[DBCSVWriter alloc] initWithHandle:resFH];
[resWriter setLogger:logger];
[resWriter setStringEncoding: [defaults integerForKey: @"StringEncoding"]];
str = [defaults stringForKey:@"CSVWriteQualifier"];
if (str)
[resWriter setQualifier:str];
str = [defaults stringForKey:@"CSVWriteSeparator"];
if (str)
[resWriter setSeparator:str];
[resWriter setFieldNames:[results objectAtIndex: 0] andWriteThem:YES];
[resWriter writeDataSet: results];
[resWriter release];
}
else
{
[logger log:LogStandard :@"[AppController executeUpdate] No Results"];
}
}
[reader release];
[whichObject release];
[updateProgress release];
updateProgress = nil;
[results release];
[self performSelectorOnMainThread:@selector(resetUpdateUI:) withObject:self waitUntilDone:NO];
[arp release];
}
- (IBAction)executeUpdate:(id)sender
{
[buttonUpdateExec setEnabled:NO];
[buttonUpdateStop setEnabled:YES];
[NSThread detachNewThreadSelector:@selector(performUpdate:) toTarget:self withObject:nil];
}
- (IBAction)stopUpdate:(id)sender
{
[updateProgress setShouldStop:YES];
}
/* SELECT IDENTIFY */
- (IBAction)showSelectIdentify:(id)sender
{
[winSelectIdentify makeKeyAndOrderFront:self];
[progIndSelectIdent setIndeterminate:NO];
[progIndSelectIdent setDoubleValue:0];
}
- (IBAction)browseFileSelectIdentifyIn:(id)sender
{
NSOpenPanel *openPanel;
openPanel = [NSOpenPanel openPanel];
if ([openPanel runModal] == NSOKButton)
{
NSString *fileName;
fileName = [openPanel filename];
[fieldFileSelectIdentifyIn setStringValue:fileName];
}
}