-
Notifications
You must be signed in to change notification settings - Fork 29
/
D3VController.rb
executable file
·2513 lines (2171 loc) · 83.6 KB
/
D3VController.rb
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
# Copyright (c) 2020, Phil Rymek
# All rights reserved.
#
# date: 5.21.2012
# description: Contains all interaction with salesforce
# that d3v requires as well as some utility functions.
require 'rubygems'
require 'soap/soap'
require 'rforce'
require './salesforce_meta.rb'
require './defaultDriver.rb'
require './client_auth_header_handler.rb'
require 'json'
require 'pg'
class D3VController
attr_accessor :sfPartner, :sfMeta, :sfApex, :successfulLogin, :lrJSON, :defaultVersion, :userId
BACKSLASH = "\\"
APEX_CLASS = "ApexClass"
APEX_PAGE = "ApexPage"
APEX_COMPONENT = "ApexComponent"
APEX_TRIGGER = "ApexTrigger"
STATIC_RESOURCE = "StaticResource"
CUSTOM_OBJECT = "CustomObject"
APEX_CLASS_SUFFIX = ".cls"
APEX_PAGE_SUFFIX = ".page"
APEX_COMPONENT_SUFFIX = ".component"
APEX_TRIGGER_SUFFIX = ".trigger"
STATIC_RESOURCE_SUFFIX = ".resource"
CUSTOM_OBJECT_SUFFIX = "__c.object"
OPEN_FILE = "Open "
# initialize d3vController, called by every sinatra route in web.rb
# call this method one of two ways
# 1: username - username to authenticate as
# password - users password
# securityToken - users security token
# endpoint - test|prod
#
# 2: sessionId - users session id
# endpoint - partner api endpoint associated with session
# metaEndpoint - metadata api endpoint associated with session
# apexEndpoint - apex api endpoint associated with session
# anything - only used to differentiate between call 1 and 2
def initialize(*args)
@defaultVersion = getVersionNumber
case args.size
when 4
endpoint = args.pop
securityToken = args.pop
password = args.pop
username = args.pop
if endpoint == 'test'
endpoint = 'https://test.salesforce.com'
else
endpoint = 'https://login.salesforce.com'
end
@sfPartner = RForce::Binding.new endpoint + '/services/Soap/u/' + @defaultVersion
return login(username, password, securityToken)
when 5
@userId = args.pop
apexEndpoint = args.pop
metaEndpoint = args.pop
endpoint = args.pop
sessionId = args.pop
sessionId = sessionId == '{ success : false }' ? '' : sessionId
@sfPartner = RForce::Binding.new(endpoint, sessionId)
@sfPartner.create_server(URI.parse(endpoint))
continueLogin(sessionId, metaEndpoint, apexEndpoint)
end
end
def logClientError(msg, file, line, stackTrace)
#if file == nil || file == ''
# return
#end
#psql = "dbname=" + ENV['DBN'] +
# " host=" + ENV['DBH'] +
# " user=" + ENV['DBU'] +
# " password=" + ENV['DBP'] +
# " port=" + ENV['DBPO'] +
# " sslmode=require"
#conn = PGconn.connect(psql)
#timestamp = Time.now
#day = timestamp.month.to_s + "/" + timestamp.day.to_s + "/" + timestamp.year.to_s
#time = timestamp.hour.to_s + ":" + timestamp.min.to_s + ":" + timestamp.sec.to_s
#conn.prepare('statement1', 'INSERT INTO ClientError (day, epoch, time, msg, file, line, stack_trace) VALUES ($1, $2, $3, $4, $5, $6, $7);')
#conn.exec_prepared('statement1', [day, timestamp.to_i, time, msg[0..255], file[0..127], line[0..4], stackTrace[0..1023]])
#conn.flush
#conn.finish
end
# inserts a row into the auth fault table
# ip - ip address of user who hit error
# param - the 'state' parameter associated with the login
# error - the error encountered
# errorDesc - detail about the error
def logAuthFault(ip, state, error, errorDesc)
#psql = "dbname=" + ENV['DBN'] +
# " host=" + ENV['DBH'] +
# " user=" + ENV['DBU'] +
# " password=" + ENV['DBP'] +
# " port=" + ENV['DBPO'] +
# " sslmode=require"
#conn = PGconn.connect(psql)
#timestamp = Time.now
#day = timestamp.month.to_s + "/" + timestamp.day.to_s + "/" + timestamp.year.to_s
#time = timestamp.hour.to_s + ":" + timestamp.min.to_s + ":" + timestamp.sec.to_s
#conn.prepare('statement1', 'INSERT INTO AuthFault (ip_addr, day, epoch, time, state, key, err, err_desc) VALUES ($1, $2, $3, $4, $5, $6, $7, $8);')
#conn.exec_prepared('statement1', [ip, day, timestamp.to_i, time, state, '', error[0..126], errorDesc[0..254]])
#conn.flush
#conn.finish
end
# inserts a row into the successful login table
# ip - ip address of user who successful logged in
#def logSuccessfulAuth(ip)
# psql = "dbname=" + ENV['DBN'] +
# " host=" + ENV['DBH'] +
# " user=" + ENV['DBU'] +
# " password=" + ENV['DBP'] +
# " port=" + ENV['DBPO'] +
# " sslmode=require"
#
# conn = PGconn.connect(psql)
# timestamp = Time.now
# day = timestamp.month.to_s + "/" + timestamp.day.to_s + "/" + timestamp.year.to_s
# time = timestamp.hour.to_s + ":" + timestamp.min.to_s + ":" + timestamp.sec.to_s
#
# conn.prepare('statement1', 'INSERT INTO AuthenticatedLogin (ip_addr, day, epoch, time) VALUES ($1, $2, $3, $4);')
# conn.exec_prepared('statement1', [ip, day, timestamp.to_i, time])
#
# conn.flush
# conn.finish
#end
# inserts a row indicating a hit to the /login or /frontdoor pages
# ip - ip address of user who hit site
# source - login|frontdoor
#def logHit(ip, source)
# psql = "dbname=" + ENV['DBN'] +
# " host=" + ENV['DBH'] +
# " user=" + ENV['DBU'] +
# " password=" + ENV['DBP'] +
# " port=" + ENV['DBPO'] +
# " sslmode=require"
#
# conn = PGconn.connect(psql)
# timestamp = Time.now
# day = timestamp.month.to_s + "/" + timestamp.day.to_s + "/" + timestamp.year.to_s
# time = timestamp.hour.to_s + ":" + timestamp.min.to_s + ":" + timestamp.sec.to_s
#
# conn.prepare('statement1', 'INSERT INTO UnauthenticatedHit (ip_addr, day, epoch, time, location) VALUES ($1, $2, $3, $4, $5);')
# conn.exec_prepared('statement1', [ip, day, timestamp.to_i, time, source])
#
# conn.flush
# conn.finish
#end
# inserts a row indicating an unrecoverable error occured
# ip - ip address of user who encountered the error
# source - endpoint that caused the error
def logFailedRecovery(ip, source)
#psql = "dbname=" + ENV['DBN'] +
# " host=" + ENV['DBH'] +
# " user=" + ENV['DBU'] +
# " password=" + ENV['DBP'] +
# " port=" + ENV['DBPO'] +
# " sslmode=require"
#conn = PGconn.connect(psql)
#timestamp = Time.now
#day = timestamp.month.to_s + "/" + timestamp.day.to_s + "/" + timestamp.year.to_s
#time = timestamp.hour.to_s + ":" + timestamp.min.to_s + ":" + timestamp.sec.to_s
#conn.prepare('statement1', 'INSERT INTO FatalError (ip_addr, day, epoch, time, method) VALUES ($1, $2, $3, $4, $5);')
#conn.exec_prepared('statement1', [ip, day, timestamp.to_i, time, source[0..127]])
#conn.flush
#conn.finish
end
# inserts a row indicating a serverside error
# method - method error occured in
# error - what went wrong
# stackTrace - the stack trace from the error
def logException(method, error, stackTrace)
#psql = "dbname=" + ENV['DBN'] +
# " host=" + ENV['DBH'] +
# " user=" + ENV['DBU'] +
# " password=" + ENV['DBP'] +
# " port=" + ENV['DBPO'] +
# " sslmode=require"
#
#conn = PGconn.connect(psql)
#timestamp = Time.now
#day = timestamp.month.to_s + "/" + timestamp.day.to_s + "/" + timestamp.year.to_s
#time = timestamp.hour.to_s + ":" + timestamp.min.to_s + ":" + timestamp.sec.to_s
#stackTrace = stackTrace.kind_of?(Array) ? stackTrace.join(';') : stackTrace
#endpoint1 = @sfApex.endpoint_url == nil ? '' : @sfApex.endpoint_url
#endpoint2 = @sfPartner.url.host == nil ? '' : @sfPartner.url.host
#conn.prepare('statement1', 'INSERT INTO ServerError (day, epoch, time, method, message, trace) VALUES ($1, $2, $3, $4, $5, $6);')
#conn.exec_prepared('statement1', [day, timestamp.to_i, time, method[0..63], error[0..511], endpoint1 + ';' + endpoint2 + ';' + stackTrace[0..900]])
#conn.flush
#conn.finish
end
# used by initialize, instantiates various force.com apis
# sid - session id
# metaEnd - metadata api endpoint associated with session
# apexEnd - apex api endpoint associated with session
def continueLogin(sid, metaEnd, apexEnd)
begin
#this line is interesting to me, why do I need it?
#large posts fail without it
Rack::Utils.key_space_limit = 123456789
@sfMeta = SalesforceMeta.new(sid, metaEnd)
header = ClientAuthHeaderHandler.new
header.sessionid = sid
@sfApex = ApexPortType.new(apexEnd)
@sfApex.headerhandler << header
@successfulLogin = true
rescue
@successfulLogin = false
end
end
# login to force, called by initialize
# un - username
# pw - password
# st - security token
def login(un, pw, st)
begin
lr = @sfPartner.login un, pw + st
sid = lr.loginResponse.result.sessionId
metaUrl = lr.loginResponse.result.metadataServerUrl
@sfMeta = SalesforceMeta.new(sid, metaUrl)
altEP = metaUrl.split('.com/')[0] + '.com/services/Soap/s/'
apexUrl = altEP + @defaultVersion
header = ClientAuthHeaderHandler.new
header.sessionid = sid
@sfApex = ApexPortType.new(apexUrl)
@sfApex.headerhandler << header
@userId = lr.loginResponse.result.userInfo.userId
@lrJSON = '{sid:"' + sid + '",' +
'mep:"' + metaUrl + '",' +
'pep:"' + lr.loginResponse.result.serverUrl + '",' +
'uid:"' + @userId + '",' +
'aep:"' + apexUrl + '"}'
@successfulLogin = true
rescue
@lrJSON = 'false'
end
end
# parses the namespace out of a filename
# i.e. NAMESPACE.Filename returns NAMESPACE
# filename - filename to parse
# returns the namespace
def getNamespacePrefix(filename)
if filename.index('.') != nil
fnSplit = filename.split('.')
return fnSplit[0]
end
return ''
end
# parses the file out of a filename that has the namespace prefixed onto it
# i.e. NAMESPACE.Filename returns Filename
# filename - filename to parse
# returns the filename without the namespace
def getFilename(filename)
if filename.index('.') != nil
fnSplit = filename.split('.')
return fnSplit[1]
end
return filename
end
# builds out a portion of a where clause to match the appropriate namespace prefix
# namespacePrefix - the current files namespace prefix
# returns a portion of a query's where clause targeting the specified namespacePrefix
def getNamespacePrefixWhere(namespacePrefix)
if namespacePrefix != ''
return " NamespacePrefix = '" + namespacePrefix + "'"
end
return " NamespacePrefix = null"
end
# builds out a namespace prefix which can be prepended to metadata
# namespacePrefix - the current files namespace prefix
# returns a portion of a query's where clause targeting the specified namespacePrefix
def getNamespaceMetadataPrefix(namespace)
if namespace != ''
return namespace + '__'
end
return ''
end
# Saves apex.
# apexBody - the body of the apex.
# apexType - Class|Trigger
# filename - name of file to update
# key - last save key
# version - -1 to keep current version, else use specified version.
# pushCode - code generated client side
# recordId - id of record to update
# parsedFilename - filename parsed out of the code
# isRename - true when this is a file rename
# retryAllowed - will enable the fail - refresh token - retry flow
# returns compiliation errors
def saveApex(apexBody, apexType, filename, key, version, pushCode, recordId, parsedFilename, isRename, retryAllowed)
begin
saveValidated = filename == 'A!NEW!FILE';
toReturn = '['
if !saveValidated
if apexType == 'Class'
toReturn += validateClassKey(recordId, key) + ','
elsif apexType == 'Trigger'
toReturn += validateTriggerKey(recordId, key) + ','
end
toReturn = toReturn[0, toReturn.length-1] + ']'
saveValidated = JSON.parse(toReturn)[0]['success']
end
if filename == 'A!NEW!FILE' && parsedFilename.size > 0
validationResult = query("SELECT Id FROM Apex" + apexType + " WHERE Name = '" + parsedFilename + "' LIMIT 1")
if validationResult.length > 0
saveValidated = false
toReturn += '{ "success" : false, "name" : "NAME_ALREADY_TAKEN", "problem" : ' +
'"A file with this name already exists." }]'
end
end
if saveValidated
scripts = Array.new
tempClasses = []
if filename != 'A!NEW!FILE'
apexQuery = "SELECT Id, ApiVersion, Body FROM Apex" + apexType + " WHERE Id = '" + recordId + "'"
tempClasses = query(apexQuery)
if tempClasses.length && tempClasses.length > 0
tempClasses = tempClasses[0]
end
end
versionNumber = nil
if tempClasses == []
versionNumber = @defaultVersion
scripts << apexBody
elsif version.to_i == -1
versionNumber = tempClasses.ApiVersion
scripts << apexBody
else
scripts << tempClasses.Body
versionNumber = version + '.0'
end
oldEndpoint = @sfApex.endpoint_url
@sfApex.endpoint_url = oldEndpoint[0,oldEndpoint.length-4] + versionNumber
if apexType == 'Class'
compileResult = compileClasses(scripts)
elsif apexType == 'Trigger'
compileResult = compileTriggers(scripts)
end
@sfApex.endpoint_url = oldEndpoint
classBasedRows = ''
if compileResult.result['success'] == 'true'
if isRename && tempClasses.Id
delete([tempClasses.Id])
end
tempClasses = query("SELECT Id, LastModifiedById, LastModifiedDate, Name, NamespacePrefix, ApiVersion FROM Apex" + apexType +
" WHERE Id = '" + compileResult.result['id'] + "'")
if tempClasses.length && tempClasses.length > 0
tempClasses = tempClasses[0]
end
classBasedRows = '"LastModifiedById" : "' + tempClasses.LastModifiedById.to_s + '",' +
'"LastModifiedDate" : "' + tempClasses.LastModifiedDate.to_s + '",' +
'"NamespacePrefix" : "' + tempClasses.NamespacePrefix.to_s + '",' +
'"ApiVersion" : "' + tempClasses.ApiVersion.to_s + '",'
end
return '{ "bodyCrc" : "' + (compileResult.result['bodyCrc'] ? compileResult.result['bodyCrc'] : '') + '",' +
'"column" : "' + (compileResult.result['column'] ? compileResult.result['column'] : '') + '",' +
'"Id" : "' + (compileResult.result['id'] ? compileResult.result['id'] : '') + '",' +
'"line" : "' + (compileResult.result['line'] ? compileResult.result['line'] : '') + '",' +
'"Name" : "' + (compileResult.result['name'] ? compileResult.result['name'] : '') + '",' +
'"problem" : "' + (compileResult.result['problem'] ? compileResult.result['problem'] : '') + '",' +
'"success" : "' + (compileResult.result['success'] ? compileResult.result['success'] : '') + '",' +
classBasedRows +
'"warnings" : "' + (compileResult.result['warnings'] ? compileResult.result['warnings'] : '') + '"}'
end
return toReturn
rescue Exception => exception
if exception.message.index("Apex compilation must run tests on this production org") != nil
return '{ "bodyCrc" : "",' +
'"column" : "",' +
'"Id" : "",' +
'"line" : "",' +
'"Name" : "' + filename + '",' +
'"problem" : "Cannot save Apex code against this production org. Write this code in a sandbox first, then deploy it to this production org.",' +
'"success" : "false",' +
'"warnings" : ""}'
elsif exception.message.index("UNABLE_TO_LOCK_ROW") != nil
return '{ "bodyCrc" : "",' +
'"column" : "",' +
'"Id" : "",' +
'"line" : "",' +
'"Name" : "' + filename + '",' +
'"problem" : "' + exception.message + '",' +
'"success" : "false",' +
'"warnings" : ""}'
elsif exception.message.index("UNKNOWN_EXCEPTION") != nil
return '{ "bodyCrc" : "",' +
'"column" : "",' +
'"Id" : "",' +
'"line" : "",' +
'"Name" : "' + filename + '",' +
'"problem" : "' + exception.message + '",' +
'"success" : "false",' +
'"warnings" : ""}'
elsif retryAllowed && exception.message.index("Incorrect user name / password [faultcodesf:INVALID_LOGINfaultstringINVALID_LOGIN:") != nil
return 'retry'
else
logException('saveApex(' + apexType + ', ' + filename + ')', exception.message, exception.backtrace)
raise
end
end
end
# validates that the user saving the file has the most recent version of the file
# queryStr - get newest version of file to build key from
# key - key to validate against file queried for
# lastModifiedById - id of user who last modified this file
# lastModifiedName - name of user who last modified this file
# returns json with success and error info
def validateKeyFull(queryStr, key, lastModifiedById, lastModifiedName)
if lastModifiedById != nil && lastModifiedName != nil
classes = queryTooling(queryStr)
else
classes = query(queryStr)
end
if classes.length
classes = classes[0]
else
return generateKeyCheckResult(true, nil, nil, nil, nil, nil)
end
if classes.length == 0
return generateKeyCheckResult(true, nil, nil, nil, nil, nil)
else
if lastModifiedById != nil && lastModifiedById != '' && lastModifiedName != nil && lastModifiedName != ''
return generateKeyCheckResult(false, classes['Id'], lastModifiedById, lastModifiedName, classes['LastModifiedDate'], key)
end
return generateKeyCheckResult(false, classes.Id, classes.LastModifiedById, classes.LastModifiedBy.Name, classes.LastModifiedDate, key)
end
end
# validates that the user saving the file has the most recent version of the file
# queryStr - get newest version of file to build key from
# key - key to validate against file queried for
# returns json with success and error info
def validateKey(queryStr, key)
validateKeyFull(queryStr, key, nil, nil)
end
# validates a save key for an ApexClass
# fileId - id of file to validate key of
# key - key to validate
def validateObjectKey(fileId, key)
query = "SELECT Id, LastModifiedDate FROM CustomObject WHERE Id = '" + fileId + "'"
validateKeyFull(query, key, 'undefined', 'someone else')
end
# validates a save key for an ApexClass, checking for save to server conflicts
# recordId - id of record to validate
# key - key to validate
def validateClassKey(recordId, key)
query = "SELECT Id, LastModifiedById, LastModifiedDate, LastModifiedBy.Name FROM ApexClass WHERE Id = '" + recordId + "'"
validateKey(query, key)
end
# validates a save key for an ApexTrigger, checking for save to server conflicts
# recordId - id of record to validate
# key - key to validate
def validateTriggerKey(recordId, key)
query = "SELECT Id, LastModifiedById, LastModifiedDate, LastModifiedBy.Name FROM ApexTrigger WHERE Id = '" + recordId + "'"
validateKey(query, key)
end
# queries salesforce for the data necessary for the coverage report
# filter - the filter to use
def generateCoverageReport(filter)
baseSOQL = 'SELECT ApexClassOrTrigger.Name, NumLinesCovered, NumLinesUncovered, Coverage FROM ApexCodeCoverageAggregate '
filteredRes = queryTooling(baseSOQL + filter)
if filter == ''
fullRes = filteredRes
else
fullRes = queryTooling(baseSOQL)
end
coverageResults = Array.new
coverageResults[0] = filteredRes
coverageResults[1] = fullRes
return coverageResults
end
# generates json to return on key validation
# fnfe - true|false file queries for fnfe
# fileId - first part of key to compare against users key
# lmbId - second part of key to compare against users key
# lmbName - name of user who last modified the file
# epochTime - third part of key to compare against users key
# key - key to validate
def generateKeyCheckResult(fnfe, fileId, lmbId, lmbName, epochTime, key)
if fnfe
return '{ "success" : false, "name" : "FNFE", "problem" : "File not found!" }'
elsif key == (fileId + '-' + lmbId + '-' + epochTime)
return '{ "success" : true, "name" : "", "problem" : "" }'
end
shortFid = fileId[0..14]
shortLmb = lmbId[0..14]
if key == (shortFid + '-' + lmbId + '-' + epochTime)
return '{ "success" : true, "name" : "", "problem" : "" }'
elsif key == (shortFid + '-' + shortLmb + '-' + epochTime)
return '{ "success" : true, "name" : "", "problem" : "" }'
elsif key == (fileId + '-' + shortLmb + '-' + epochTime)
return '{ "success" : true, "name" : "", "problem" : "" }'
end
return '{ "success" : false, "name" : "CONFLICT_DURING_SAVE", ' +
'"problem" : "Please reopen this file and merge in your changes, ' + lmbName + ' contributed a more recent version." }'
end
# in order to sosl successfully
# token with reserved characters that need to be escaped
# token - what to escape
# returns the escaped token
def tokenEscape(token)
reservedCharacters = {
'?' => "\\?",
'&' => "\\&",
'|' => "\\|",
'!' => "\\!",
'{' => "\\{",
'}' => "\\}",
'[' => "\\[",
']' => "\\]",
'(' => "\\(",
')' => "\\)",
'^' => "\\^",
'~' => "\\~",
'*' => "\\*",
':' => "\\:",
'\\' => '\\\\',
'"' => '\"',
"'" => "\\'",
'+' => "\\+",
'-' => "\\-",
'%' => "\\%"
}
return token.gsub(/(\?|\&|\||\!|\{|\}|\[|\]|\(|\)|\^|\~|\*|\:|\\|\"|\'|\+|\-|\%)/) { reservedCharacters[$1] }
end
# find in files
# token - what to find
# returns what it found
def findInFiles(token)
begin
names = Array.new
token = tokenEscape(token)
result = sosl('FIND {"' + token + '" OR "' + token + '*"} IN ALL FIELDS RETURNING ApexClass(Name, Body, NamespacePrefix, LastModifiedDate order by Name), ApexPage(Name, NamespacePrefix, LastModifiedDate, Markup order by Name), ApexTrigger(Name, NamespacePrefix, LastModifiedDate, Body order by Name), ApexComponent(Name, NamespacePrefix, LastModifiedDate, Markup order by Name) limit 100')
if result != nil &&
result.searchResponse != nil &&
result.searchResponse.result != nil &&
result.searchResponse.result.searchRecords != nil
puts result
searchRecords = JSON.parse(result.searchResponse.result.searchRecords.to_json)
if result.searchResponse.result.searchRecords.length == 1
names << searchRecords['record']
elsif result.searchResponse.result.searchRecords.length > 1
searchRecords.each {
|item|
names << item['record']
}
end
end
return names
rescue Exception => exception
logException('findInFiles(' + token + ')', exception.message, exception.backtrace)
raise
end
end
# Saves a code update notice to the database
# filename - name of updated file
# type - Page/Component/Trigger/Class
# pushKey - unique key to identify this push
def registerCodeUpdate(filename, type, pushKey)
if @successfulLogin
begin
original = filename
namespace = getNamespacePrefix(filename)
filename = original + '.' + type
mdNamespace = getNamespaceMetadataPrefix(namespace)
results = query("SELECT Id FROM " + mdNamespace + "ASIDE_Code_Update__c WHERE " + mdNamespace + "Filename__c = '" + filename + "'")
if results.length > 0
delete(getIds(results))
end
codeUpdate = [
'type', mdNamespace + 'ASIDE_Code_Update__c',
mdNamespace + 'Filename__c', filename,
mdNamespace + 'Type__c', type,
mdNamespace + 'Push_Code__c', pushKey
]
@sfPartner.create :sObject => codeUpdate
rescue Exception => exception
logException('registerCodeUpdate(' + type + ',' + original + ')', exception.message, exception.backtrace)
raise
end
end
end
# given a list of records, returns a list of ids
# list - records to get ids from
# returns list of ids
def getIds(list)
ids = Array.new
list.each {
|item|
ids << item.Id
}
return ids
end
#logout of d3v
#sessionId - session id to revoke
def logout(sessionId)
if @successfulLogin
begin
@sfPartner.logout
rescue Exception => exception
end
end
end
# executes a soql query via rest
# queryStr - the soql query
# returns query results
def query(queryStr)
querySoap(queryStr)
end
# executes a soql query via rest
# queryStr - the soql query
# returns query results
def queryRest(queryStr)
HTTPClient.new.get_content(
'https://' + @sfPartner.url.host + '/services/data/v' + @defaultVersion + '/query?q=' + URI::escape(queryStr),
'',
{'Authorization' => 'OAuth ' + @sfPartner.session_id})
end
# executes a tooling api query
# queryStr - the soql query
# returns query results
def queryTooling(queryStr)
begin
result = HTTPClient.new.get_content(
'https://' + @sfPartner.url.host + '/services/data/v' + @defaultVersion + '/tooling/query?q=' + URI::escape(queryStr),
'',
{'Authorization' => 'OAuth ' + @sfPartner.session_id})
result = JSON.parse(result)
if result['records']
return result['records']
end
return Array.new
rescue Exception => ex
return nil
end
end
# executes a soql query via soap
# queryStr - the soql query
# returns query results
def querySoap(queryStr)
if @successfulLogin
qr = @sfPartner.query :queryString => queryStr
if qr.Fault
return qr.Fault
elsif qr.queryResponse.result.records
return qr.queryResponse.result.records
else
return Array.new
end
end
end
# executes a soql query via soap. uses queryMore to retrieve all records of a given type.
# queryStr - the soql query
# locator - query locator for when queryMore needs to be used
# results - the list of results so far, pass an empty array initial call
# returns query results
def queryAll(queryStr, locator, results)
if @successfulLogin
queryMore = false
if queryStr == nil
qr = @sfPartner.queryMore :queryLocator => locator
queryMore = true
else
qr = @sfPartner.query :queryString => queryStr
end
if qr.Fault
return qr.Fault
else
if queryMore && qr.queryMoreResponse
response = qr.queryMoreResponse
elsif !queryMore && qr.queryResponse
response = qr.queryResponse
end
if response.result.records
results = results + response.result.records
if response.result.done || response.result.queryLocator == nil
return results
else
queryAll(nil, response.result.queryLocator, results)
end
else
return results
end
end
end
end
# executes a sosl query
# soslStatement - the sosl query
# returns search results
def sosl(soslStatement)
if @successfulLogin
@sfPartner.search :searchString => soslStatement
end
end
# insert data
# objs - json string of what to insert
# objType - object type of data being inserted
def insert(objs, objType)
if @successfulLogin
begin
inserts = JSON.parse(objs)
result = @sfPartner.create inserts.collect{|toInsert| [:sObject, {:type => objType}.merge(toInsert)]}.flatten
return result.to_json
rescue Exception => exception
logException('insert(' + objType + ')', exception.message, exception.backtrace)
raise
end
end
end
# update data
# objs - json string of what to insert
# objType - object type of data being updated
def update(objs, objType)
if @successfulLogin
begin
updates = JSON.parse(objs)
result = @sfPartner.update updates.collect{|toUpdate| [:sObject, {:type => objType}.merge(toUpdate)]}.flatten
return result.to_json
rescue Exception => exception
logException('update(' + objType + ')', exception.message, exception.backtrace)
raise
end
end
end
# parses the page tag in the content passed in, to determine if automatic file generation needs to occur
# content - to parse
# matchResults - hash containing info about which automatic generation tags have been used
# returns content with auto file generation hash tag removed so the file can first be compiled
def parsePageTag(content, matchResults)
startIndex = content.index('<apex:')
endIndex = content.index('>', startIndex)
pageTag = content[startIndex..endIndex]
controllerMatch = pageTag.match(/\scontroller="#([A-Za-z0-9\_]*)"/i)
standardCtrlMatch = pageTag.match(/\sstandardcontroller="([A-Za-z0-9\_]*)"/i)
toReturn = content
if controllerMatch == nil
extensionsMatch = pageTag.match(/(\sextensions=")(?:[A-Za-z0-9\_]+[,\s]+)*(#([A-Za-z0-9\_]*)\s*\,?)[A-Za-z0-9\_,\s]*"/i)
if standardCtrlMatch != nil && extensionsMatch != nil
if extensionsMatch[2].index(',') == nil
toReturn = content.sub(extensionsMatch[0], '')
else
toReturn = content.sub(extensionsMatch[0], extensionsMatch[0].sub(extensionsMatch[2], ''))
end
end
elsif standardCtrlMatch == nil
toReturn = content.sub(controllerMatch[0], '')
end
matchResults[:ctrl] = controllerMatch
matchResults[:stdCtrl] = standardCtrlMatch
matchResults[:ext] = extensionsMatch
return toReturn
end
# auto generates a controller and test class
# name - name of vf page to generate controller for
# content - content of vf page
# modified - savable version of content
# pushCode - to validate save
# result - result of saving new vf page
# controllerMatch - match result from parsePageTag()
# type - ApexPage | ApexComponent
def autoGenerateControllerAndTest(name, content, modified, pushCode, result, controllerMatch, type)
apexClassName = name + controllerMatch[1]
apexClass = "public with sharing class " + apexClassName + " {\n\n" +
"\tpublic " + apexClassName + "() {\n\n\t}\n\n}"
saveApex(apexClass, 'Class', 'A!NEW!FILE', '', '', pushCode, nil, '', false, false)
testClass = "@isTest\nprivate class " + apexClassName + "Test {\n\n" +
"\tprivate static testMethod void testConstructor() {\n" +
"\t\t" + apexClassName + " ctrl = new " + apexClassName + "();\n" +
"\t\tSystem.assertNotEquals(null, ctrl);\n\t}\n\n}"
saveApex(testClass, 'Class', 'A!NEW!FILE', '', '', pushCode, nil, '', false, false)
content.sub!(controllerMatch[0], ' controller="' + apexClassName + '"')
updateVisualforce(content, type, result.createResponse.result[:id], pushCode)
end
# auto generates an extension and test class
# name - name of vf page to generate controller for
# content - content of vf page
# modified - savable version of content
# pushCode - to validate save
# result - result of saving new vf page
# standardCtrlMatch - match result from parsePageTag()
# extensionsMatch - match result from parsePageTag()
def autoGenerateExtensionAndTest(name, content, modified, pushCode, result, standardCtrlMatch, extensionsMatch)
apexClassName = name + extensionsMatch[3]
standardCtrl = standardCtrlMatch[1]
ctrlVar = standardCtrl.length > 3 ? standardCtrl[0..2].downcase : standardCtrl.downcase
apexClass = "public with sharing class " + apexClassName + " {\n\n" +
"\tpublic " + standardCtrl + " " + ctrlVar + " {get; set;}\n\n" +
"\tpublic " + apexClassName + "(ApexPages.StandardController ctrl) {\n" +
"\t\t" + ctrlVar + " = (" + standardCtrl + ") ctrl.getRecord();\n\t}\n\n}"
saveApex(apexClass, 'Class', 'A!NEW!FILE', '', '', pushCode, nil, '', false, false)
testClass = "@isTest\nprivate class " + apexClassName + "Test {\n\n" +
"\tprivate static testMethod void testConstructor() {\n" +
"\t\tApexPages.StandardController stdCtrl =\n" +
"\t\t\tnew ApexPages.StandardController(new " + standardCtrl + "());\n\n" +
"\t\t" + apexClassName + " ctrl = new " + apexClassName + "(stdCtrl);\n\n" +
"\t\tSystem.assertNotEquals(null, ctrl);\n\t}\n\n}"
saveApex(testClass, 'Class', 'A!NEW!FILE', '', '', pushCode, nil, '', false, false)
content.sub!(/(\sextensions="[A-Za-z0-9\_,\s]*)#[A-Za-z0-9\_]*([A-Za-z0-9\_,\s]*")/i, '\1' + apexClassName + '\2')
updateVisualforce(content, 'ApexPage', result.createResponse.result[:id], pushCode)
end
# if an auto generation hash tag has been used, generates the appropriate code
# name - name of vf page to generate controller for
# content - content of vf page
# modified - savable version of content
# pushCode - to validate save
# result - result of saving new vf page
# controllerMatch - match result from parsePageTag()
# standardCtrlMatch - match result from parsePageTag()
# extensionsMatch - match result from parsePageTag()
# type - ApexPage | ApexComponent
def autoGenerateCode(name, content, modified, pushCode, result, controllerMatch, standardCtrlMatch, extensionsMatch, type)
if controllerMatch != nil
autoGenerateControllerAndTest(name, content, modified, pushCode, result, controllerMatch, type)
elsif standardCtrlMatch != nil && extensionsMatch != nil
autoGenerateExtensionAndTest(name, content, modified, pushCode, result, standardCtrlMatch, extensionsMatch)
end
end
# creates a new visualforce file
# content - markup of new file
# type - ApexPage|ApexComponent
# name - name of new vf file
# pushCode - code generated client side
def createVisualforce(content, type, name, pushCode)
if @successfulLogin
begin
matchResults = {}
modified = parsePageTag(content, matchResults)
name = getFilename(name)
namespacePrefix = getNamespacePrefix(name)
prefixWhere = getNamespacePrefixWhere(namespacePrefix)
result = @sfPartner.create :sObject => [
:type, type,
:Markup, modified,
:Name, name,
:MasterLabel, name
]
tempVF = Array.new
if result.createResponse.result.success
autoGenerateCode(name, content, modified, pushCode, result, matchResults[:ctrl], matchResults[:stdCtrl], matchResults[:ext], type)
tempVF = query("SELECT Id, Name, LastModifiedById, LastModifiedDate, NamespacePrefix, ApiVersion FROM " + type + " WHERE Id = '" + result.createResponse.result[:id] + "'")
if tempVF.length && tempVF.length > 0
tempVF = tempVF[0]
end
end
vfSaveResult = Array.new
vfSaveResult[0] = result
vfSaveResult[1] = tempVF
return vfSaveResult
rescue Exception => exception
if exception.message.index("UNABLE_TO_LOCK_ROW") != nil
return '{ "bodyCrc" : "",' +
'"column" : "",' +
'"Id" : "",' +
'"line" : "",' +
'"Name" : "' + filename + '",' +
'"problem" : "' + exception.message + '",' +
'"success" : "false",' +
'"warnings" : ""}'
elsif exception.message.index("UNKNOWN_EXCEPTION") != nil
return '{ "bodyCrc" : "",' +
'"column" : "",' +
'"Id" : "",' +
'"line" : "",' +