-
Notifications
You must be signed in to change notification settings - Fork 0
/
Create arcgis project tool.v1.pyt
3126 lines (2684 loc) · 162 KB
/
Create arcgis project tool.v1.pyt
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
import subprocess
import arcpy
from arcpy import env
import sqlite3
import xml.etree.ElementTree
import os
import json
import zipfile
from arcpy import mapping
import os
from xml.dom.minidom import parse
from datetime import datetime
import time
import copy
import shutil
import types
import ConfigParser
import copy
Config = ConfigParser.ConfigParser()
arcpy.env.overwriteOutput = True
#notes: urlKey in portals.self.json must be blank or it will try to authenticate at arcgis.com
#other gotchas
#For polygon styles, makes sure to use "style": "esriSFSSolid" and NOT "style": "esriSLSSolid" for the outline style
#import time
#env.workspace = "CURRENT"
#env.addOutputsToMap = False
#env.overwriteOutput = True
arcpy.env.overwriteOutput = True
toolkitPath = os.path.abspath(os.path.dirname(__file__)).replace("\\","/")
class Toolbox(object):
def __init__(self):
self.label = "Create ArcServices toolbox"
self.alias = "arcservices"
self.canRunInBackground = False
# List of tool classes associated with this toolbox
self.tools = [CreateNewProject]
class CreateNewProject(object):
def __init__(self):
self.label = "Convert map document to JSON"
self.alias="arcservices"
self.description = "Creates the JSON files for a standalone ArcGIS Online/Server node application. Note: you need to fill out the project information in the File->Map Document Properties before running."
def getParameterInfo(self):
Config.read(toolkitPath+"/settings.ini")
servername = arcpy.Parameter(
displayName="Enter server FQDN (example: www.esri.com)",
name="servername",
datatype="GPString",
parameterType="Required",
direction="Input",
multiValue=False)
try:
servername.value = Config.get("settings","server")
except Exception as e:
pass
if not servername.value:
servername.value = "gis.biz.tm"
username = arcpy.Parameter(
displayName="Enter your username",
name="username",
datatype="GPString",
parameterType="Optional",
direction="Input",
multiValue=False)
try:
username.value= Config.get("settings","username")
except Exception as e:
pass
if not username.value:
username.value="shale"
#projecttitle = arcpy.Parameter(
# displayName="Enter your project title",
# name="projectname",
# datatype="GPString",
# parameterType="Required",
# direction="Input",
# multiValue=False)
#projectname = arcpy.Parameter(
# displayName="Enter your project name (no spaces)",
# name="projectname",
# datatype="GPString",
# parameterType="Required",
# direction="Input",
# multiValue=False)
#tags = arcpy.Parameter(
# displayName="Enter tags",
# name="tags",
# datatype="GPString",
# parameterType="Optional",
# direction="Input",
# multiValue=False)
#
#summary = arcpy.Parameter(
# displayName="Enter project summary",
# name="summary",
# datatype="GPString",
# parameterType="Optional",
# direction="Input",
# multiValue=False)
#
#description = arcpy.Parameter(
# displayName="Enter project description",
# name="description",
# datatype="GPString",
# parameterType="Optional",
# direction="Input",
# multiValue=False)
outputfolder = arcpy.Parameter(
displayName="Enter output folder",
name="outputfolder",
datatype="DEFolder",
parameterType="Required",
direction="Input")
try:
outputfolder.value= Config.get("settings","destination")
except Exception as e:
pass
if not outputfolder.value:
outputfolder.value=os.getcwd().replace("\\","/")
sqlitedb = arcpy.Parameter()
sqlitedb.name = u'Output_Report_File'
sqlitedb.displayName = u'Output Sqlite database'
sqlitedb.parameterType = 'Optional'
sqlitedb.direction = 'Output'
sqlitedb.datatype = u'File'
try:
sqlitedb.value= Config.get("settings","sqlitedb")
except Exception as e:
pass
pg = arcpy.Parameter()
pg.name = u'Output_DB_String'
pg.displayName = u'Postgresql database connection string Example: PG:"host=localhost user=postgres dbname=gis"'
pg.parameterType = 'Optional'
pg.direction = 'Output'
pg.datatype = u'GPString'
try:
pg.value= Config.get("settings","pg")
except Exception as e:
pass
#param0.filter.type = "ValueList"
#param0.filter.list = ["Street","Aerial","Terrain","Topographic"]
parameters = [servername,username,outputfolder,sqlitedb,pg]
#username,projecttitle,projectname,tags,summary,description,
return parameters
def isLicensed(self): #optional
return True
def updateParameters(self, parameters): #optional
if parameters[2].altered:
try:
os.makedirs(parameters[2].valueAsText)
except Exception as e:
return
return
def updateMessages(self, parameters): #optional
return
def execute(self, parameters, messages):
serverName = parameters[0].valueAsText
username = parameters[1].valueAsText
baseDestinationPath = parameters[2].valueAsText
sqliteDb = parameters[3].valueAsText
pg = parameters[4].valueAsText
created_ts=int(time.time()*1000)
# suppose you want to add it to the current MXD (open MXD)
try:
if type(messages)==types.ListType:
vals = messages
#vals = messages.split("|")
if len(vals)>1:
serverName = vals[1]
if len(vals)>2:
username= vals[2]
if len(vals)>3:
baseDestinationPath=vals[3].replace("\\","/")
if len(vals)>4:
sqliteDb=vals[4]
if len(vals)>5:
pg=vals[5]
mxdName=vals[0].replace("\\","/")
mxd = arcpy.mapping.MapDocument(mxdName)
else:
mxd = arcpy.mapping.MapDocument("CURRENT")
except Exception as e:
printMessage("Still Unable to open map document. Make sure background processing is unchecked in the geoprocessing options")
return
if sqliteDb.find(".sqlite") == -1:
sqliteDb = sqliteDb + ".sqlite"
if os.path.exists(sqliteDb):
os.remove(sqliteDb)
#try:
# arcpy.gp.CreateSQLiteDatabase(sqliteDb, "SPATIALITE")
#except Exception as e:
# arcpy.AddMessage("Database already exists")
printMessage("Exporting dataframe: " + mxd.activeDataFrame.name)
serviceName = mxd.activeDataFrame.name.replace(" ","").lower()
if serviceName=='Layers':
printMessage("Rename the dataframe from Layers to service name. Must be valid service name (no spaces)")
return
#mxd.makeThumbnail ()
#toolkitPath = os.path.abspath(os.path.dirname(__file__)).replace("\\","/")
templatePath = toolkitPath + "/templates"
if not os.path.exists(templatePath):
printMessage("Template path not found: " + templatePath)
return
cfgfile = open(toolkitPath+"/settings.ini",'w')
try:
Config.add_section("settings")
except Exception as e:
pass
printMessage("Server name: " +serverName)
printMessage("User name: " + username)
printMessage("Destination path: " + baseDestinationPath)
printMessage("Sqlite path: " + sqliteDb)
printMessage("Postgresql connection: " + pg)
Config.set("settings","server",serverName)
Config.set("settings","username",username)
Config.set("settings","destination",baseDestinationPath)
Config.set("settings","sqlitedb",sqliteDb)
Config.set("settings","pg",pg)
Config.write(cfgfile)
cfgfile.close()
del cfgfile
if baseDestinationPath:
baseDestinationPath = unicode(baseDestinationPath).encode('unicode-escape')
baseDestinationPath=baseDestinationPath.replace("\\","/")+ os.sep +"catalogs"
else:
baseDestinationPath = toolkitPath+ os.sep +"catalogs"
#baseDestinationPath = baseDestinationPath + os.sep + serviceName
serviceDestinationPath = baseDestinationPath + os.sep + serviceName
#if the folder does not exist create it
if not os.path.exists(baseDestinationPath):
os.makedirs(serviceDestinationPath)
else:
#check to see if service already exists. If so, remove it so it can be overwritten
if os.path.exists(serviceDestinationPath):
try:
shutil.rmtree(serviceDestinationPath)
except Exception as e:
printMessage("Unable to remove destination path")
#return
try:
os.makedirs(serviceDestinationPath)
except Exception as e:
printMessage("Unable to create destination path")
servicesDestinationPath = serviceDestinationPath + "/services"
if not os.path.exists(servicesDestinationPath):
try:
os.makedirs(servicesDestinationPath)
except Exception as e:
pass
printMessage("Services path: " +servicesDestinationPath)
dataDestinationPath = serviceDestinationPath + "/shapefiles"
if not os.path.exists(dataDestinationPath):
try:
os.makedirs(dataDestinationPath)
except Exception as e:
pass
printMessage("Shapefile path: " +dataDestinationPath)
replicaDestinationPath = serviceDestinationPath + "/replicas"
if not os.path.exists(replicaDestinationPath):
try:
os.makedirs(replicaDestinationPath)
except Exception as e:
pass
printMessage("Replica path: " +replicaDestinationPath)
mapfileDestinationPath = serviceDestinationPath + "/mapfiles"
if not os.path.exists(mapfileDestinationPath):
os.makedirs(mapfileDestinationPath)
printMessage("Mapfile path: " +mapfileDestinationPath)
symbols = getSymbology(mxd)
dataFrames = arcpy.mapping.ListDataFrames(mxd, "*")
if os.path.exists(baseDestinationPath + "/config.json"):
config=openJSON(baseDestinationPath + "/config.json")
try:
config["services"][serviceName]={}
except:
printMessage("Service already exists: " + serviceName)
config["services"][serviceName]["layers"]={}
else:
config={}
config["services"]={}
config["services"][serviceName]={"layers":{}}
config["hostname"]=serverName
config["username"]=username
#config["services"][serviceName]["mxd"]=mxd.filePath
#config["services"][serviceName]["sqliteDb"]=sqliteDb
#config["services"][serviceName]["pg"]=pg
#config["services"][serviceName]["dataSource"]="sqlite"
#config["services"][serviceName]["rootPath"]=baseDestinationPath
config["mxd"]=mxd.filePath
config["sqliteDb"]=sqliteDb
config["pg"]=pg
config["dataSource"]="sqlite"
config["rootPath"]=baseDestinationPath
#config["services"][serviceName]["layers"]={}
fullname = mxd.author
if fullname=="":
printMessage("Author missing in File->Map Document Properties")
return
first_name = fullname.split(' ')[0]
last_name = fullname.split(' ')[1]
email_address = first_name + '.' + last_name + '@' + serverName
if not username:
username=fullname.lower().replace(" ","")
title = mxd.title
if title=="":
printMessage("Title missing in File->Map Document Properties")
return
tags = mxd.tags
if not tags:
tags=""
summary = mxd.summary
if not summary:
summary=""
description = mxd.description
if not description:
description=""
initializeSqlite(sqliteDb)
if not os.path.exists(baseDestinationPath + "/portals.self.json"):
portals_self_json=openJSON(templatePath + "/portals.self.json")
portals_self_json['portalHostname']=serverName
portals_self_json['defaultExtent']['xmin']=mxd.activeDataFrame.extent.XMin
portals_self_json['defaultExtent']['ymin']=mxd.activeDataFrame.extent.YMin
portals_self_json['defaultExtent']['xmax']=mxd.activeDataFrame.extent.XMax
portals_self_json['defaultExtent']['ymax']=mxd.activeDataFrame.extent.YMax
portals_self_json['user']['fullName']=fullname
portals_self_json['user']['firstName']=first_name
portals_self_json['user']['lastName']=last_name
portals_self_json['user']['email']=email_address
portals_self_json['user']['username']=username
file = saveJSON(baseDestinationPath + "/portals.self.json",portals_self_json)
LoadCatalog(sqliteDb,"portals", "self",file)
if not os.path.exists(baseDestinationPath + "/community.users.json"):
community_users_json=openJSON(templatePath + "/community.users.json")
community_users_json['fullName']=fullname
community_users_json['firstName']=first_name
community_users_json['lastName']=last_name
community_users_json['email']=email_address
community_users_json['username']=username
community_users_json['created']=created_ts
community_users_json['modified']=created_ts
community_users_json['lastLogin']=created_ts
#community_users_json['groups'][0]['userMembership']['username']=username
file = saveJSON(baseDestinationPath + "/community.users.json",community_users_json)
LoadCatalog(sqliteDb,"community", "users",file)
#User info
content_users_json=openJSON(templatePath + "/content.users.json")
content_users_json['username']=username
#content_users_json['items'][0]['created']=int(time.time()*1000)
file = saveJSON(baseDestinationPath + "/content.users.json",content_users_json)
LoadCatalog(sqliteDb,"content", "users",file)
#Search results
if not os.path.exists(baseDestinationPath + "/search.json"):
search_json=openJSON(templatePath + "/search.json")
#search_json['results'][0]=username
baseResult = search_json['results'][0]
search_json['results']=[]
else:
search_json=openJSON(baseDestinationPath + "/search.json")
baseResult = search_json['results'][0]
#see if result already exists and delete it
for idx, val in enumerate(search_json['results']):
if val["id"] == serviceName:
del search_json['results'][idx]
#search_json['results']
#add stuff for each dataframe below
#community groups
#community_groups_json=openJSON(templatePath + "/community.groups.json")
#saveJSON(destinationPath + "/community.groups.json",community_groups_json)
shutil.copy2(templatePath + "/community.groups.json", baseDestinationPath + "/community.groups.json")
#os.system("copy "+ templatePath + "/community.groups.json " + servicesDestinationPath + "/community.groups.json")
#result = 0
feature_services={"currentVersion":10.3,"folders":[],"services":[]}
#if not os.path.exists(servicesDestinationPath+"/FeatureServer.json"):
# saveJSON(servicesDestinationPath + "/FeatureServer.json",response)
#else:
# featureServer_json=openJSON(servicesDestinationPath + "/FeatureServer.json")
# if not serviceName in featureServer_json['folders']:
# featureServer_json['folders'].append(serviceName);
# saveJSON(servicesDestinationPath + "/FeatureServer.json",featureServer_json)
# #create base FeatureServer.json file with folders for each service
# #,"folders":["Canvas","Demographics","Elevation","Ocean","Polar","Reference","Specialty","Utilities"]
#for dataFrame in dataFrames:
if mxd.activeDataFrame:
dataFrame = mxd.activeDataFrame
serviceName = dataFrame.name.replace(" ","").lower()
#mxd.activeDataFrame.name
if serviceName=='Layers':
printMessage("Rename the dataframe from Layers to service name. Must be valid service name (no spaces)")
return
#else:
# dataFrame = dataFrame #mxd.activeDataFrame
operationalLayers = []
operationalTables = []
operationalTablesObj = []
allData=[]
layerIds={}
id=0
#for df in arcpy.mapping.ListDataFrames(mxd):
for lyr in arcpy.mapping.ListLayers(mxd, "", dataFrame):
# Exit if the current layer is not a service layer.
if lyr.isServiceLayer or lyr.supports("SERVICEPROPERTIES"): # or not lyr.visible
continue
#lyr.visible=True
#opLayer = {
# "id": lyr.name,
# "title": lyr.name,
# "url": lyr.serviceProperties["Resturl"]+ "/" + lyr.longName + "/" + lyr.serviceProperties["ServiceType"],
# "opacity": (100 - lyr.transparency) / 100,
# "visibility": lyr.visible
#}
printMessage("Exporting layer: " + lyr.name)
operationalLayers.append(lyr)
allData.append(lyr)
layerIds[lyr.name]=id
id = id+1
#arcpy.mapping.RemoveLayer(df, lyr)
if len(operationalLayers)==0:
printMessage("No Feature layers found in data frame!")
return
id=len(operationalLayers)
for tbl in arcpy.mapping.ListTableViews(mxd, "", dataFrame):
operationalTables.append(tbl)
allData.append(tbl)
operationalTablesObj.append({"name":tbl.name,"id":id})
layerIds[tbl.name]=id
id=id+1
#now add any attachment tables
for lyr in allData:
desc = arcpy.Describe(lyr)
if hasattr(desc, "layer"):
featureName=os.path.basename(desc.layer.catalogPath)
rootFGDB=desc.layer.catalogPath.replace("\\","/")
else:
featureName=os.path.basename(desc.catalogPath)
rootFGDB=os.path.dirname(desc.catalogPath).replace("\\","/")
#layerIds[tbl.name]=id
layerIds[featureName]=layerIds[lyr.name]
if arcpy.Exists(rootFGDB+"/"+featureName+"__ATTACH"):
layerIds[featureName+"__ATTACH"]=id
id=id+1
#lyrpath=os.getcwd().replace("\\","/")
#lyrpath = os.path.abspath(os.path.dirname(__file__)).replace("\\","/")
ext = operationalLayers[0].getExtent()
dataFrame.extent = ext
desc = arcpy.Describe(operationalLayers[0])
if hasattr(desc, "layer"):
ws=desc.layer.catalogPath.replace("\\","/")
else:
ws=os.path.dirname(desc.catalogPath).replace("\\","/")
for j,rel in enumerate(allData):
printMessage(str(j) + ": " + rel.name)
relationships = [c.name for c in arcpy.Describe(ws).children if c.datatype == "RelationshipClass"]
relArr=[]
desc = arcpy.Describe(lyr)
if not desc.relationshipClassNames:
return rel
if hasattr(desc, "layer"):
featureName=os.path.basename(desc.layer.catalogPath)
rootFGDB=desc.layer.catalogPath.replace("\\","/")
else:
featureName=os.path.basename(desc.catalogPath)
rootFGDB=os.path.dirname(desc.catalogPath).replace("\\","/")
config["fgdb"]=rootFGDB
relationshipList = {}
relationshipObj = {}
relations={}
#for index in xrange(0, field_info.count):
#[u'farm_tracts_inspections__ATTACHREL', u'farm_tractsInspectionRelClass', u'homesites_inspections__ATTACHREL', u'homesitesInspectionRelClass', u'grazing_inspections__ATTACHREL', u'grazing_permitteeRelClass', u'grazing_permitteesInspectionRelClass']
#for j,rel in enumerate(desc.relationshipClassNames):
id=0
destIds={}
printMessage("Find relationships")
for rc in relationships:
relDesc = arcpy.Describe(rootFGDB+"/"+rc)
if relDesc.isAttachmentRelationship:
continue
try:
originId=layerIds[relDesc.originClassNames[0]]
except:
printMessage("Skipping relation: " + relDesc.originClassNames[0])
continue
try:
destId=layerIds[relDesc.destinationClassNames[0]]
except:
printMessage("Skipping relation: " + relDesc.destinationClassNames[0])
continue
#if not layerIds.has_key(originId):
# printMessage("Skipping relation: " + relDesc.destinationClassNames[0])
# continue
printMessage("Relationship Name: " + rc)
printMessage("Origin Class Names")
printMessage(relDesc.originClassNames)
printMessage("Origin Class Keys")
printMessage(relDesc.originClassKeys)
printMessage("Destination Class Names")
printMessage(relDesc.destinationClassNames)
printMessage("Destination Class Keys")
printMessage(relDesc.destinationClassKeys)
printMessage("Key type: "+relDesc.keyType)
printMessage(relDesc.notification)
printMessage("backwardPathLabel: "+relDesc.backwardPathLabel)
printMessage("forwardPathLabel: "+relDesc.forwardPathLabel)
#originId=getDataIndex(allData,relDesc.originClassNames[0])
#destId=getDataIndex(allData,relDesc.destinationClassNames[0])
relatedTableId=0
role=""
key=""
relations[str(id)]={"oTable":relDesc.originClassNames[0],"dTable":relDesc.destinationClassNames[0],"oJoinKey":relDesc.originClassKeys[0][0],"dJoinKey":relDesc.originClassKeys[1][0],"oId":originId,"dId":destId}
relationshipList[originId]={"origin":originId,"dest":destId,"id":id,"name":relDesc.backwardPathLabel,"keyField":relDesc.originClassKeys[1][0]}
relObj = {"id":id,"name":relDesc.forwardPathLabel,"relatedTableId":destId,"cardinality":"esriRelCardinality"+relDesc.cardinality,"role":"esriRelRoleOrigin","keyField":relDesc.originClassKeys[0][0],"composite":relDesc.isComposite}
destIds[str(originId)]=id
id=id+1
try:
len(relationshipObj[relDesc.originClassNames[0]])
except:
relationshipObj[relDesc.originClassNames[0]]=[]
relationshipObj[relDesc.originClassNames[0]].append(relObj)
try:
len(relationshipObj[relDesc.destinationClassNames[0]])
except:
relationshipObj[relDesc.destinationClassNames[0]]=[]
#if relationship already exists, use its id instead
destId = id
#if destIds[originId]:
try:
destId = destIds[str(originId)]
except:
pass
relObj = {"id":destId,"name":relDesc.backwardPathLabel,"relatedTableId":originId,"cardinality":"esriRelCardinality"+relDesc.cardinality,"role":"esriRelRoleDestination","keyField":relDesc.originClassKeys[1][0],"composite":relDesc.isComposite}
relationshipObj[relDesc.destinationClassNames[0]].append(relObj)
#printMessage(json.dumps(relationshipObj, indent=4, sort_keys=True))
#print(destIds)
config["services"][serviceName]["relationships"]=relations
#return
#printMessage(relationships)
#for rc in relationships:
# rc_path = ws + "\\" + rc
# des_rc = arcpy.Describe(rc_path)
# printMessage(des_rc.originClassNames)
#rc_list = [c.name for c in arcpy.Describe(workspace).children if c.datatype == "RelationshipClass"]
#for rc in rc_list:
#rc_path = workspace + "\\" + rc
#des_rc = arcpy.Describe(rc_path)
#origin = des_rc.originClassNames
#destination = des_rc.destinationClassNames
#mxd.activeDataFrame=dataFrame
mxd.activeView = dataFrame.name
arcpy.RefreshActiveView()
#out_file_name = r"c:\thumbnails\{basename}.png".format(basename=os.path.basename(featureclass))
# Export "thumbnail" of data frame
#if the folder does not exist create it
if not os.path.exists(servicesDestinationPath+"/thumbnails/"):
os.makedirs(servicesDestinationPath+"/thumbnails/")
out_file_name = servicesDestinationPath + "/thumbnails/" + serviceName + ".png"
arcpy.mapping.ExportToPNG(mxd, out_file_name, dataFrame, 200, 133)
#dataFrame = arcpy.mapping.ListDataFrames(mxd, "*")[0]
#if dataFrame != mxd.activeDataFrame:
# printMessage("Active data frame is not the first data frame")
feature_services['folders'].append(serviceName)
#now set path to serviceName folder
#destinationPath = servicesDestinationPath + "/data" #+ serviceName
#print destinationPath
#printMessage("Spatial JSON destination path: " + servicesDestinationPath)
#if the folder does not exist create it
#if not os.path.exists(destinationPath):
# os.makedirs(destinationPath)
rootService_json={"folders": [], "services":[{"name":serviceName,"type":"FeatureServer","url":"http://"+serverName+"/rest/services/"+serviceName+"/FeatureServer"},{"name":serviceName,"type":"MapServer"}], "currentVersion": 10.3}
file = saveJSON(servicesDestinationPath + "/"+serviceName+".json",rootService_json)
LoadService(sqliteDb,serviceName,serviceName, -1,"",file)
#analysis = arcpy.mapping.AnalyzeForMSD(mxd)
#
#for key in ('messages', 'warnings', 'errors'):
# printMessage( "----" + key.upper() + "---")
# vars = analysis[key]
# for ((message, code), layerlist) in vars.iteritems():
# printMessage( " " + message + " (CODE %i)" % code)
# printMessage( " applies to:")
# for layer in layerlist:
# printMessage( layer.name)
# printMessage("")
# sddraft = templatePath + serviceName + '.sddraft'
# sd = templatePath + serviceName + '.sd'
# summary = 'Sample output'
# tags = 'county, counties, population, density, census'
#
# # create service definition draft
# analysis = arcpy.mapping.CreateMapSDDraft(mxd, sddraft, serviceName, 'ARCGIS_SERVER')
#
# for key in ('messages', 'warnings', 'errors'):
# printMessage("----" + key.upper() + "---")
# vars = analysis[key]
# for ((message, code), layerlist) in vars.iteritems():
# printMessage(" " + message + " (CODE %i)" % code)
# printMessage(" applies to:")
# for layer in layerlist:
# printMessage(layer.name)
# printMessage("")
#
# printMessage("")
# printMessage("")
# #arcpy.StageService_server(sddraft, sd)
#
# # stage and upload the service if the sddraft analysis did not contain errors
# if analysis['errors'] == {}:
# # Execute StageService
# arcpy.StageService_server(sddraft, sd)
# # Execute UploadServiceDefinition
# #arcpy.UploadServiceDefinition_server(sd, con)
# else:
# # if the sddraft analysis contained errors, display them
# #arcpy.StageService_server(sddraft, sd)
# printMessage(analysis['errors'])
# #print analysis['errors']
#arcpy.mapping.ConvertToMSD(mxd,toolkitPath+"/output.msd",dataFrame, "NORMAL", "NORMAL")
#mxde = MxdExtras(mxd)
#for lyr in mxde.itervalues():
# printMessage("Layer Name: " + lyr.name )
# printMessage("Layer Symbology Field Name: " + lyr.symbologyFieldName)
oldspatialref = dataFrame.spatialReference
coordinateSystem = 'GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.017453292519943295]]'
#set to wgs84
dataFrame.spatialReference = coordinateSystem
#get coors of extent center in new coordinate system
x = (dataFrame.extent.XMin + dataFrame.extent.XMax)/2
y = (dataFrame.extent.YMin + dataFrame.extent.YMax)/2
#printMessage(str(dataFrame.extent.XMin) + "," + str(dataFrame.extent.YMin) + "," + str(dataFrame.extent.XMax) + "," + str(dataFrame.extent.YMax))
xmin_geo=dataFrame.extent.XMin
xmax_geo=dataFrame.extent.XMax
ymin_geo=dataFrame.extent.YMin
ymax_geo=dataFrame.extent.YMax
# set dataframe spatial ref back
dataFrame.spatialReference = oldspatialref
output = {
"extent": {
"xmin": dataFrame.extent.XMin,
"ymin": dataFrame.extent.YMin,
"xmax": dataFrame.extent.XMax,
"ymax": dataFrame.extent.YMax
},
"scale": dataFrame.scale,
"rotation": dataFrame.rotation,
"spatialReference": {"wkid": dataFrame.spatialReference.PCSCode}
}
result=copy.deepcopy(baseResult) # deep copy
result['snippet']=summary
result['title']=dataFrame.description
result['id']=serviceName
#result['extent']=[0,0]
result['extent'][0]=[0,0]
result['extent'][1]=[0,0]
result['extent'][0][0]=xmin_geo
result['extent'][0][1]=ymin_geo
result['extent'][1][0]=xmax_geo
result['extent'][1][1]=ymax_geo
result['owner']=username
result['created']=created_ts
result['modified']=created_ts
if tags!="":
result['tags']=tags.split(",")
search_json['results'].append(result)
#result = result + 1
#only need to update the operationalLayers
content_items_json=openJSON(templatePath + "/content.items.data.json")
opLayers = content_items_json['operationalLayers']=getOperationalLayers(operationalLayers,serverName,serviceName,symbols)
opTables = content_items_json['tables']=getTables(operationalTables,serverName,serviceName,len(opLayers))
file = saveJSON(servicesDestinationPath + "/content.data.json",content_items_json)
LoadService(sqliteDb,serviceName,"content", -1,"data",file)
content_items_json=openJSON(templatePath + "/content.items.json")
content_items_json["id"]=title
content_items_json["owner"]=username
content_items_json["created"]=created_ts
content_items_json["modified"]=created_ts
content_items_json["title"]=title
content_items_json["snippet"]=summary
content_items_json["description"]=description
content_items_json['extent'][0][0]=xmin_geo
content_items_json['extent'][0][1]=ymin_geo
content_items_json['extent'][1][0]=xmax_geo
content_items_json['extent'][1][1]=ymax_geo
content_items_json["type"]="Feature Service"
content_items_json["url"]="http://"+serverName+"/rest/services/"+serviceName+"/FeatureServer"
file=saveJSON(servicesDestinationPath + "/content.items.json",content_items_json)
LoadService(sqliteDb,serviceName,"content", -1,"items",file)
#create JSON description of all services. Each dataframe is a service for this application.
featureserver_json={
"currentVersion":10.3,
"services": [{
"name":serviceName,
"type":"FeatureServer",
"url": "http://"+serverName + "/arcgis/rest/services/"+serviceName+"/FeatureServer"
}]
}
#file=saveJSON(servicesDestinationPath + "/FeatureServer.json",featureserver_json)
#LoadService(sqliteDb,serviceName,"FeatureServer", -1,"",file)
#create JSON description of all layers in the service.
featureserver_json=openJSON(templatePath + "/name.FeatureServer.json")
featureserver_json['initialExtent']['xmin']=dataFrame.extent.XMin
featureserver_json['initialExtent']['ymin']=dataFrame.extent.YMin
featureserver_json['initialExtent']['xmax']=dataFrame.extent.XMax
featureserver_json['initialExtent']['ymax']=dataFrame.extent.YMax
featureserver_json['fullExtent']['xmin']=dataFrame.extent.XMin
featureserver_json['fullExtent']['ymin']=dataFrame.extent.YMin
featureserver_json['fullExtent']['xmax']=dataFrame.extent.XMax
featureserver_json['fullExtent']['ymax']=dataFrame.extent.YMax
featureserver_json['layers'] = getLayers(operationalLayers)
featureserver_json['tables']=operationalTablesObj
file=saveJSON(servicesDestinationPath + "/FeatureServer.json",featureserver_json)
LoadService(sqliteDb,serviceName,"FeatureServer", -1,"",file)
maps_json=openJSON(templatePath + "/name.MapServer.json")
maps_json['initialExtent']['xmin']=dataFrame.extent.XMin
maps_json['initialExtent']['ymin']=dataFrame.extent.YMin
maps_json['initialExtent']['xmax']=dataFrame.extent.XMax
maps_json['initialExtent']['ymax']=dataFrame.extent.YMax
maps_json['fullExtent']['xmin']=dataFrame.extent.XMin
maps_json['fullExtent']['ymin']=dataFrame.extent.YMin
maps_json['fullExtent']['xmax']=dataFrame.extent.XMax
maps_json['fullExtent']['ymax']=dataFrame.extent.YMax
maps_json['layers'] = featureserver_json['layers']
maps_json['server']=serverName
maps_json['name']=serviceName
maps_json['mapName']=serviceName
maps_json['tables']=operationalTablesObj
file=saveJSON(servicesDestinationPath + "/MapServer.json",maps_json)
LoadService(sqliteDb,serviceName,"MapServer", -1,"",file)
minx=str(dataFrame.extent.XMin)
miny=str(dataFrame.extent.YMin)
maxx=str(dataFrame.extent.XMax)
maxy=str(dataFrame.extent.YMax)
serviceitems_json=openJSON(templatePath + "/GDB_ServiceItems.json")
serviceitems_json["name"]=title
serviceitems_json["serviceDescription"]=summary
serviceitems_json["description"]=description
serviceitems_json['initialExtent']['xmin']=dataFrame.extent.XMin
serviceitems_json['initialExtent']['ymin']=dataFrame.extent.YMin
serviceitems_json['initialExtent']['xmax']=dataFrame.extent.XMax
serviceitems_json['initialExtent']['ymax']=dataFrame.extent.YMax
serviceitems_json['fullExtent']['xmin']=dataFrame.extent.XMin
serviceitems_json['fullExtent']['ymin']=dataFrame.extent.YMin
serviceitems_json['fullExtent']['xmax']=dataFrame.extent.XMax
serviceitems_json['fullExtent']['ymax']=dataFrame.extent.YMax
createReplica(mxd,dataFrame,allData,replicaDestinationPath,toolkitPath,username,serviceName,serverName,minx,miny,maxx,maxy,relationshipList,layerIds,serviceitems_json)
#create a JSON service file for each feature layer -- broken ---
serviceRep=[]
id=0
for lyr in operationalLayers:
desc = arcpy.Describe(lyr)
if hasattr(desc, "layer"):
featureName=os.path.basename(desc.layer.catalogPath)
else:
featureName=os.path.basename(desc.catalogPath)
printMessage(lyr.name+": " + featureName)
feature_json=openJSON(templatePath + "/name.FeatureServer.id.json")
feature_json['defaultVisibility']=lyr.visible
feature_json['description'] = lyr.description
feature_json['fields']=getFields(lyr)
#type=esriFieldTypeOID
#for i in feature_json:
# printMessage(i + ": " + str(feature_json[i]))
#printMessage(feature_json['displayField'])
#if lyr.showLabels:
lbl=""
if lyr.supports("LABELCLASSES"):
for lblclass in lyr.labelClasses:
lblclass.showClassLabels = True
#feature_json.displayField
lbl=lblclass.expression.replace("[","").replace("]","")
#lblclass.expression = " [Label]"
if lbl!="":
feature_json['displayField']=lbl
else:
feature_json['displayField']=getDisplayField(feature_json['fields'])
if desc.shapeType:
if desc.shapeType=='Polygon':
feature_json['geometryType']='esriGeometryPolygon'
feature_json['templates'][0]['drawingTool']="esriFeatureEditToolPolygon"
elif desc.shapeType=='Polyline':
feature_json['geometryType']='esriGeometryPolyline'
feature_json['templates'][0]['drawingTool']="esriFeatureEditToolPolyline"
elif desc.shapeType=='Point':
feature_json['geometryType']='esriGeometryPoint'
elif desc.shapeType=='MultiPoint':
feature_json['geometryType']='esriGeometryMultiPoint'
feature_json['id']=layerIds[lyr.name] #id
feature_json['name']=lyr.name
if desc.hasOID:
feature_json['objectIdField']=desc.OIDFieldName
feature_json['objectIdFieldName']=desc.OIDFieldName
if desc.hasGlobalID:
feature_json['globalIdField'] = desc.globalIDFieldName
feature_json['globalIdFieldName']=desc.globalIDFieldName
else:
feature_json['globalIdField'] = ""
feature_json['indexes']=getIndexes(lyr)
feature_json['minScale']=lyr.minScale
feature_json['maxScale']=lyr.maxScale
#bad below, should be Feature Layer, not FeatureLayer
#feature_json['type']=desc.dataType #'Feature Layer'
feature_json['extent']['xmin']=desc.extent.XMin
feature_json['extent']['ymin']=desc.extent.YMin
feature_json['extent']['xmax']=desc.extent.XMax
feature_json['extent']['ymax']=desc.extent.YMax
#feature_json['indexes']=[]
feature_json['templates'][0]['name']=serviceName
attributes={}
for field in feature_json['fields']:
#printMessage(field['name'])
if field['editable']:
attributes[ field['name'] ]=None
feature_json['templates'][0]['prototype']['attributes']=attributes
#feature_json['drawingInfo']['renderer']['symbol']=getSymbol(lyr)
#feature_json['relationships']=getRelationships(lyr,id,len(operationalLayers),operationalTables,relationshipObj)
feature_json['relationships']=relationshipObj[featureName] #getRelationships(lyr,relationshipObj)
feature_json['drawingInfo']=getSymbol(lyr,symbols[featureName],lyr.name)
#set editor tracking fields
editorTracking={}
if desc.editorTrackingEnabled:
editorTracking['creationDateField']=desc.createdAtFieldName
editorTracking['creatorField']=desc.creatorFieldName
editorTracking['editDateField']=desc.editedAtFieldName
editorTracking['editorField']=desc.editorFieldName
feature_json['editFieldsInfo']=editorTracking
else:
del feature_json['editFieldsInfo']
feature_json['editingInfo']={"lastEditDate":created_ts}
if arcpy.Exists(rootFGDB+"/"+featureName+"__ATTACH"):
feature_json['hasAttachments']=True
feature_json['advancedQueryCapabilities']['supportsQueryAttachments']=True
feature_json['attachmentProperties']=[{"name":"name","isEnabled":True},{"name":"size","isEnabled":True},{"name":"contentType","isEnabled":True},{"name":"keywords","isEnabled":True}]
else:
feature_json['hasAttachments']=False
#getSymbol(lyr,symbols[featureName],lyr.name)
#opLayers = content_items_json['operationalLayers']=getOperationalLayers(operationalLayers,serverName,serviceName)
file=saveJSON(servicesDestinationPath + "/FeatureServer."+str(layerIds[lyr.name])+".json",feature_json)
LoadService(sqliteDb,serviceName,"FeatureServer", layerIds[lyr.name],"",file)
#now create a MapServer json file
mapserver_json=openJSON(templatePath + "/name.MapServer.id.json")
mapserver_json['indexes']=feature_json['indexes']
mapserver_json['extent']=feature_json['extent']
mapserver_json['fields']=feature_json['fields']
mapserver_json['templates']=feature_json['templates']
mapserver_json['drawingInfo']=feature_json['drawingInfo']
mapserver_json['geometryType']=feature_json['geometryType']
file=saveJSON(servicesDestinationPath + "/MapServer."+str(layerIds[lyr.name])+".json",feature_json)
LoadService(sqliteDb,serviceName,"MapServer", layerIds[lyr.name],"",file)
#save replica file
feature_json=openJSON(templatePath + "/name.FeatureServer.id.json")
#steps: save layer to blank mxd, save it, run arcpy.CreateRuntimeContent on mxd
createSingleReplica(templatePath,dataFrame,lyr,replicaDestinationPath,toolkitPath,feature_json,serverName,serviceName,username,id)
#save mapserver .map file
saveMapfile(mapfileDestinationPath + "/"+lyr.name+".map",lyr,desc,dataDestinationPath,mapserver_json)
id = id+1
#create a JSON geometry file for each feature layer