def get_shh():
    """Connect to an AGOL organization or Portal"""

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'  # LDAP, NTLM, OAuth, Portal, PKI, ArcGIS
    securityinfo['username'] = wordlist.username
    securityinfo['password'] = wordlist.password
    securityinfo['org_url'] = wordlist.orgURL
    securityinfo['proxy_url'] = None
    securityinfo['proxy_port'] = None
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    try:
        shh = securityhandlerhelper.securityhandlerhelper(securityinfo=securityinfo)

        if not shh.valid:
            return shh.message
        else:
            return shh
    except:
        return 'error'
def connect_to_layer(username, password, server_url, service_url):
    """Connect to ArcGIS Online or Portal for ArcGIS layer"""
    proxy_port = None
    proxy_url = None

    si = {}
    si['security_type'] = 'Portal'  # LDAP, NTLM, OAuth, Portal, PKI
    si['username'] = username
    si['password'] = password
    si['org_url'] = server_url
    si['proxy_url'] = proxy_url
    si['proxy_port'] = proxy_port
    si['referer_url'] = None
    si['token_url'] = None
    si['certificatefile'] = None
    si['keyfile'] = None
    si['client_id'] = None
    si['secret_id'] = None

    shh = securityhandlerhelper.securityhandlerhelper(securityinfo=si)
    if not shh.valid:
        raise Exception(shh.message)

    fl = FeatureLayer(url=service_url,
                      securityHandler=shh.securityhandler,
                      proxy_port=proxy_port,
                      proxy_url=proxy_url,
                      initialize=True)

    return fl
def connect_to_layer(username, password, server_url, service_url):
    """Connect to ArcGIS Online or Portal for ArcGIS layer"""
    proxy_port = None
    proxy_url = None

    si = {}
    si['security_type'] = 'Portal'  # LDAP, NTLM, OAuth, Portal, PKI
    si['username'] = username
    si['password'] = password
    si['org_url'] = server_url
    si['proxy_url'] = proxy_url
    si['proxy_port'] = proxy_port
    si['referer_url'] = None
    si['token_url'] = None
    si['certificatefile'] = None
    si['keyfile'] = None
    si['client_id'] = None
    si['secret_id'] = None

    shh = securityhandlerhelper.securityhandlerhelper(securityinfo=si)
    if not shh.valid:
        raise Exception(shh.message)

    fl = FeatureLayer(
        url=service_url,
        securityHandler=shh.securityhandler,
        proxy_port=proxy_port,
        proxy_url=proxy_url,
        initialize=True)

    return fl
Ejemplo n.º 4
0
def add_item(securityinfo,filename,metadata):    
    try:
        shh = securityhandlerhelper.securityhandlerhelper(securityinfo)
        if shh.valid == False:
            print(shh.message)
        else:
            admin = arcrest.manageorg.Administration(
                securityHandler=shh.securityhandler)
            content = admin.content
            userInfo = content.users.user()
            itemParams = arcrest.manageorg.ItemParameter()
            itemParams.title = metadata['title']
            itemParams.description = metadata['description']
            itemParams.tags = metadata['tags']
            itemParams.type = metadata['type']
            itemParams.thumbnail = metadata['thumbnail']
            item = userInfo.addItem(
                itemParameters=itemParams,
                filePath= filename,
                overwrite=True,
                relationshipType=None,
                originItemId=None,
                destinationItemId=None,
                serviceProxyParams=None,
                metadata=None)
            print(item.title + " created")
            i = content.getItem(item.id)
            i.shareItem(everyone=True)
            return(item)

    except:
        line, filename, synerror = trace()
        print("error on line: %s" % line)
        print("error in file name: %s" % filename)
        print("with error message: %s" % synerror)
Ejemplo n.º 5
0
    def getToken(self):
        if self.securityType == 'AGS':
            sh = arcrest.AGSTokenSecurityHandler(token_url=self.securityConfiguration['org_url'] + ':6443/arcgis/admin/generateToken'
                    , username=self.securityConfiguration['username']
                    , password=self.securityConfiguration['password'])
                    #, proxy_url=self.securityConfiguration['proxy_url']
                    #, proxy_port=self.securityConfiguration['proxy_port'])
            ags = arcrest.ags.server.Server(url=self.securityConfiguration['org_url'].replace('https','http') + ':6080/arcgis'
                    , securityHandler=sh)

            if sh.valid == False:
                print sh.message
            else:
                self.admin = ags
                self.token = sh.token

        else: # security type == Portal or ArcGIS
            shh = securityhandlerhelper.securityhandlerhelper(self.securityConfiguration)

            if shh.valid == False:
                print shh.message
            else:
                self.admin = arcrest.manageorg.Administration(url=self.agolURL, securityHandler=shh.securityhandler)
                content = self.admin.content
                userInfo = content.users.user()

                self.token = shh.securityhandler.token
def get_security_handler(args):
    """
    Creates the security handler for the AGOL/Portal Org
    :param args: The argparser arguments object
    :return: The security handler
    """
    logger = logging.getLogger()
    securityinfo = {}
    securityinfo['security_type'] = args.security_type
    securityinfo['username'] = args.username
    securityinfo['password'] = args.password
    securityinfo['org_url'] = args.org_url
    securityinfo['proxy_url'] = args.proxy_url
    securityinfo['proxy_port'] = args.proxy_port
    securityinfo['referer_url'] = args.referer_url
    securityinfo['token_url'] = args.token_url
    securityinfo['certificatefile'] = args.certificate_file
    securityinfo['keyfile'] = args.keyfile
    securityinfo['client_id'] = args.client_id
    securityinfo['secret_id'] = args.secret_id
    # Authenticate
    logger.debug("Authenticating...")
    shh = securityhandlerhelper.securityhandlerhelper(securityinfo)
    if not shh.valid:
        logger.critical("Failed to Authenticate")
        logger.critical(shh.message)
        sys.exit(-1)
    else:
        return shh
def update_agol(url, fld, sequence_value, interval, seq_format='{}'):
    """Update fetures in an agol/portal service with id values
    Return next valid sequence value"""

    # Connect to org
    securityinfo = {}
    securityinfo[
        'security_type'] = 'Portal'  # LDAP, NTLM, OAuth, Portal, PKI, ArcGIS
    securityinfo['username'] = username
    securityinfo['password'] = password
    securityinfo['org_url'] = orgURL
    securityinfo['proxy_url'] = None
    securityinfo['proxy_port'] = None
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    shh = securityhandlerhelper.securityhandlerhelper(
        securityinfo=securityinfo)

    if not shh.valid:
        return 'Could not connect to {}. Please verify paths and credentials.'.format(
            url)

    fl = FeatureLayer(url=url,
                      securityHandler=shh.securityhandler,
                      proxy_port=None,
                      proxy_url=None,
                      initialize=True)

    # Build SQL query to find features missing id
    sql = """{} is null""".format(fld)

    out_fields = ['objectid', fld]

    # Get features without id
    resFeats = fl.query(where=sql, out_fields=','.join(out_fields))

    # For each feature
    for feat in resFeats:
        id_value = seq_format.format(sequence_value)

        # Update id
        feat.set_value(fld, id_value)

        # Increment sequence value
        sequence_value += interval

    update_results = fl.updateFeature(features=resFeats)

    for res in update_results['updateResults']:
        if res['success'] == False:
            return 'error {}: {}'.format(res['error']['code'],
                                         res['error']['description'])

    return sequence_value
Ejemplo n.º 8
0
 def update_areas_for_features(self):
     token = securityhandlerhelper.securityhandlerhelper(
         self._config.agolconfig)
     fs = FeatureService(url=self._json_object["url"],
                         securityHandler=token.securityhandler,
                         initialize=True)
     for layer in fs.layers:
         self._config.log.do_message('LAYER:' + layer.name, "debug")
         self.update_features_for_area(layer)
Ejemplo n.º 9
0
def connectToAGOL():

    global token, config

    with open('config.json') as json_data:
        config = json.load(json_data)

    token = securityhandlerhelper.securityhandlerhelper(config)

    arcpy.AddMessage("Connected to AGOL")
Ejemplo n.º 10
0
 def update_features_asset_info(self):
     token = securityhandlerhelper.securityhandlerhelper(
         self._config.agolconfig)
     fs = FeatureService(url=self._json_object["url"],
                         securityHandler=token.securityhandler,
                         initialize=True)
     for layer in fs.layers:
         self._config.log.do_message('LAYER:' + layer.name, "debug")
         self.process_features(layer)
     for table in fs.tables:
         self._config.log.do_message('TABLE:' + table.name, "debug")
         self.process_features(table)
def main(args):
    """
    This
    :param args: arguments from argparse
    :return:
    """
    securityinfo = {}
    securityinfo['security_type'] = args.security_type
    securityinfo['username'] = args.username
    securityinfo['password'] = args.password
    securityinfo['org_url'] = args.org_url
    securityinfo['proxy_url'] = args.proxy_url
    securityinfo['proxy_port'] = args.proxy_port
    securityinfo['referer_url'] = args.referer_url
    securityinfo['token_url'] = args.token_url
    securityinfo['certificatefile'] = args.certificate_file
    securityinfo['keyfile'] = args.keyfile
    securityinfo['client_id'] = args.client_id
    securityinfo['secret_id'] = args.secret_id
    try:
        # Authenticate
        shh = securityhandlerhelper.securityhandlerhelper(securityinfo)
        if not shh.valid:
            print(shh.message)
        else:
            # Get portal instance
            portal_admin = arcrest.manageorg.Administration(
                securityHandler=shh.securityhandler)
            # Update each map by the provided id
            for map_id in args.map_ids:
                try:
                    # Get item
                    item = portal_admin.content.getItem(itemId=map_id).userItem
                    # Get the map data json
                    map_data = item.item.itemData('json')
                    # configure the GNSS popup fields
                    map_data = configure_gnss_popup(map_data,
                                                    visible=args.visible)
                    # Update the item
                    item_params = arcrest.manageorg.ItemParameter()
                    item.updateItem(itemParameters=item_params,
                                    clearEmptyFields=True,
                                    data=None,
                                    serviceUrl=None,
                                    text=json.dumps(map_data).encode(
                                        'utf8', errors='replace'))
                    print("Successfully Configured Map Item Id: {}".format(
                        map_id))
                except Exception as e:
                    print("Error Configuring id: {}".format(map_id))
                    print(e)
    except Exception as e:
        print(e)
Ejemplo n.º 12
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""  #<UserName>
    securityinfo['password'] = ""  #<Password>
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    username = ""  #Username to add
    groupname = ""  #Group Name

    try:
        shh = securityhandlerhelper.securityhandlerhelper(
            securityinfo=securityinfo)
        if shh.valid == False:
            print(shh.message)
        else:
            admin = arcrest.manageorg.Administration(
                securityHandler=shh.securityhandler)
            community = admin.community
            groups = community.groups
            groupIds = community.getGroupIDs(groupNames=groupname)
            if groupIds is None:
                print("Group not found")
            if len(groupIds) == 0:
                print("Group not found")
            groupId = groupIds[0]

            group = groups.group(groupId=groupId)
            if group is None:
                print("Group not found")
            res = group.addUsersToGroups(users=username)

            print(res)
    except (common.ArcRestHelperError), e:
        print("error in function: %s" % e[0]['function'])
        print("error on line: %s" % e[0]['line'])
        print("error in file name: %s" % e[0]['filename'])
        print("with error message: %s" % e[0]['synerror'])
        if 'arcpyError' in e[0]:
            print("with arcpy message: %s" % e[0]['arcpyError'])
Ejemplo n.º 13
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""#<UserName>
    securityinfo['password'] = ""#<Password>
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    username = "" #Username to add
    groupname = "" #Group Name

    try:
        shh = securityhandlerhelper.securityhandlerhelper(securityinfo=securityinfo)
        if shh.valid == False:
            print (shh.message)
        else:
            admin = arcrest.manageorg.Administration(securityHandler=shh.securityhandler)
            community = admin.community
            groups = community.groups
            groupIds = community.getGroupIDs(groupNames=groupname)
            if groupIds is None:
                print ("Group not found")
            if len(groupIds) == 0:
                print ("Group not found")
            groupId = groupIds[0]

            group = groups.group(groupId=groupId)
            if group is None:
                print ("Group not found")
            res = group.addUsersToGroups(users=username)

            print (res)
    except (common.ArcRestHelperError),e:
        print ("error in function: %s" % e[0]['function'])
        print ("error on line: %s" % e[0]['line'])
        print ("error in file name: %s" % e[0]['filename'])
        print ("with error message: %s" % e[0]['synerror'])
        if 'arcpyError' in e[0]:
            print ("with arcpy message: %s" % e[0]['arcpyError'])
Ejemplo n.º 14
0
def main():
    proxy_port = None
    proxy_url = None    

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = "******"
    securityinfo['password'] = "******"
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None   


    itemId = "<ID if item>"    
    upload_file = r"<Path to File>"
    try:      

        shh = securityhandlerhelper.securityhandlerhelper(securityinfo)
        if shh.valid == False:
            print shh.message
        else:        
            portalAdmin = arcrest.manageorg.Administration(securityHandler=shh.securityhandler)
            uc = portalAdmin.content.usercontent()
            itemParams = arcrest.manageorg.ItemParameter()
            
            itemParams.filename = upload_file        
            res = uc.updateItem(itemId=itemId,
                                              updateItemParameters=itemParams,
                                              folderId=None,
                                              clearEmptyFields=True,
                                              filePath=upload_file,
                                              url=None,
                                              text=None,
                                              multipart = False
                                              )

            print res

    except:
        line, filename, synerror = trace()
        print("error on line: %s" % line)
        print("error in file name: %s" % filename)
        print("with error message: %s" % synerror)
Ejemplo n.º 15
0
def main():
    proxy_port = None
    proxy_url = None    

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = "******"
    securityinfo['password'] = "******"
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None   


    itemId = "<ID if item>"    
    upload_file = r"<Path to File>"
    try:      

        shh = securityhandlerhelper.securityhandlerhelper(securityinfo)
        if shh.valid == False:
            print shh.message
        else:        
            portalAdmin = arcrest.manageorg.Administration(securityHandler=shh.securityhandler)
            uc = portalAdmin.content.usercontent()
            itemParams = arcrest.manageorg.ItemParameter()
            
            itemParams.filename = upload_file        
            res = uc.updateItem(itemId=itemId,
                                              updateItemParameters=itemParams,
                                              folderId=None,
                                              clearEmptyFields=True,
                                              filePath=upload_file,
                                              url=None,
                                              text=None,
                                              multipart = False
                                              )

            print res

    except:
        line, filename, synerror = trace()
        print "error on line: %s" % line 
        print "error in file name: %s" % filename 
        print "with error message: %s" % synerror 
Ejemplo n.º 16
0
    def __init__(self):
        super(AreaUpdateHelper, self).__init__()
        if not self._config.areaupdate or "areaservice" not in self._config.areaupdate:
            raise Exception(
                "Cannot update areas for features no area service defined")

        self._geom_filters = {}
        token = securityhandlerhelper.securityhandlerhelper(
            self._config.agolconfig)
        self._area_fl = FeatureLayer(
            url=self._config.areaupdate["areaservice"],
            securityHandler=token.securityhandler,
            initialize=True)
        self._overlay_task = \
            filter(lambda task: task.name == "OverlayLayers", analysis(securityHandler=token.securityhandler).tasks)[0]
Ejemplo n.º 17
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""
    securityinfo['password'] = ""
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    try:

        shh = securityhandlerhelper.securityhandlerhelper(securityinfo)
        if shh.valid == False:
            print shh.message
        else:
            admin = arcrest.manageorg.Administration(
                securityHandler=shh.securityhandler)
            portal = admin.portals.portalSelf
            invList = manageorg.InvitationList()
            #Make sure to adhere to the password requirements
            #Make sure the user name is available
            invList.addUser(username="******",
                            password="******",
                            firstname="Test",
                            lastname="Test",
                            email="*****@*****.**",
                            role="account_user")
            res = portal.addUser(invitationList=invList,
                                 subject="test",
                                 html="test")
            print res

    except:
        line, filename, synerror = trace()
        print "error on line: %s" % line
        print "error in file name: %s" % filename
        print "with error message: %s" % synerror
Ejemplo n.º 18
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo["security_type"] = "Portal"  # LDAP, NTLM, OAuth, Portal, PKI
    securityinfo["username"] = ""
    securityinfo["password"] = ""
    securityinfo["org_url"] = "http://www.arcgis.com"
    securityinfo["proxy_url"] = proxy_url
    securityinfo["proxy_port"] = proxy_port
    securityinfo["referer_url"] = None
    securityinfo["token_url"] = None
    securityinfo["certificatefile"] = None
    securityinfo["keyfile"] = None
    securityinfo["client_id"] = None
    securityinfo["secret_id"] = None

    try:

        shh = securityhandlerhelper.securityhandlerhelper(securityinfo)
        if shh.valid == False:
            print shh.message
        else:
            admin = arcrest.manageorg.Administration(securityHandler=shh.securityhandler)
            portal = admin.portals.portalSelf
            invList = manageorg.InvitationList()
            # Make sure to adhere to the password requirements
            # Make sure the user name is available
            invList.addUser(
                username="******",
                password="******",
                firstname="Test",
                lastname="Test",
                email="*****@*****.**",
                role="account_user",
            )
            res = portal.addUser(invitationList=invList, subject="test", html="test")
            print res

    except:
        line, filename, synerror = trace()
        print "error on line: %s" % line
        print "error in file name: %s" % filename
        print "with error message: %s" % synerror
Ejemplo n.º 19
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = "******"  #<UserName>
    securityinfo['password'] = "******"  #<Password>
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    itemId = "<Item ID>"

    try:
        shh = securityhandlerhelper.securityhandlerhelper(
            securityinfo=securityinfo)
        if shh.valid == False:
            print shh.message
        else:
            portalAdmin = arcrest.manageorg.Administration(
                securityHandler=shh.securityhandler)
            content = portalAdmin.content
            adminusercontent = content.usercontent()
            item = content.getItem(itemId)
            itemParams = arcrest.manageorg.ItemParameter()

            itemParams.largeThumbnail = r"<Path to Image>"

            print adminusercontent.updateItem(itemId=itemId,
                                              updateItemParameters=itemParams,
                                              folderId=item.ownerFolder)
    except (common.ArcRestHelperError), e:
        print "error in function: %s" % e[0]['function']
        print "error on line: %s" % e[0]['line']
        print "error in file name: %s" % e[0]['filename']
        print "with error message: %s" % e[0]['synerror']
        if 'arcpyError' in e[0]:
            print "with arcpy message: %s" % e[0]['arcpyError']
Ejemplo n.º 20
0
    def _upload_to_arcgis_online(self):
        token = securityhandlerhelper.securityhandlerhelper(self._config.agolconfig)
        admin = Administration(self._config.agolconfig["org_url"], token.securityhandler)
        content = admin.content
        user = content.users.user()
        patchedUser = PatchedUser(url=user.root, securityHandler= token.securityhandler,initalize=True)
        item_params = ItemParameter()
        item_params.title = "XLSX Report" +Utility.get_file_name(self.workbook.filename)
        item_params.type = "Microsoft Excel"
        item_params.tags = "XLSX,Report"

        possible_folder = [f["id"]for f in user.folders if f["title"] == self._config.reports["reportfolder"]]
        if possible_folder:
            folder = possible_folder[0]
        else:
            folder = None

        patchedUser.patchedAddItem(filePath=self.workbook.filename, itemParameters=item_params,folder=folder)
Ejemplo n.º 21
0
    def _create_report_for_service(self):
        try:
            token = securityhandlerhelper.securityhandlerhelper(self._config.agolconfig)
            fs = FeatureService(url=self._json_object["url"], securityHandler=token.securityhandler, initialize=True)
            # get some config lookup for a particular layer

            for layer in fs.layers:
                self._domain_lookup[layer.name] = {}
                for f in layer.fields:
                    if f["domain"] is not None:
                        self._domain_lookup[layer.name][f["name"]] = f["domain"]

                result = layer.query(out_fields="*", resultType='standard',returnGeometry=True)
                self._process_features(result,layer.name)
        except Exception as e:
            self._config.log.do_message(e.message,"err")
        finally:
            self.workbook.close()
def main(args):
    """
    This
    :param args: arguments from argparse
    :return:
    """
    securityinfo = {}
    securityinfo['security_type'] = args.security_type
    securityinfo['username'] = args.username
    securityinfo['password'] = args.password
    securityinfo['org_url'] = args.org_url
    securityinfo['proxy_url'] = args.proxy_url
    securityinfo['proxy_port'] = args.proxy_port
    securityinfo['referer_url'] = args.referer_url
    securityinfo['token_url'] = args.token_url
    securityinfo['certificatefile'] = args.certificate_file
    securityinfo['keyfile'] = args.keyfile
    securityinfo['client_id'] = args.client_id
    securityinfo['secret_id'] = args.secret_id
    try:
        # Authenticate
        shh = securityhandlerhelper.securityhandlerhelper(securityinfo)
        if not shh.valid:
            print(shh.message)
        else:
            while True:
                # Get portal instance
                portal_admin = arcrest.manageorg.Administration(securityHandler=shh.securityhandler)
                # Update each map by the provided id
                for item_id in args.item_ids:
                    try:
                        # Get item
                        item = portal_admin.content.getItem(itemId=item_id).userItem
                        itemParams = arcrest.manageorg.ItemParameter()
                        datetimenow = datetime.datetime.now()
                        itemParams.description = "Modified: {}".format(datetimenow)
                        item.updateItem(itemParams)
                        print("Successfully Modified Map Item Id: {}\nModified at: {}".format(item.title, datetimenow))
                    except Exception as e:
                        print("Error Configuring id: {}".format(item_id))
                        print(e)
                sleep(30)
    except Exception as e:
        print(e)
Ejemplo n.º 23
0
def main():
    proxy_port = None
    proxy_url = None    

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = "******"#<UserName>
    securityinfo['password'] = "******"#<Password>
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None   
    
    itemId = "<Item ID>"    
    
      
    try:
        shh = securityhandlerhelper.securityhandlerhelper(securityinfo=securityinfo)
        if shh.valid == False:
            print shh.message
        else:
            portalAdmin = arcrest.manageorg.Administration(securityHandler=shh.securityhandler)
            content = portalAdmin.content
            adminusercontent = content.usercontent()
            item = content.getItem(itemId)
            itemParams = arcrest.manageorg.ItemParameter()
           
            itemParams.largeThumbnail = r"<Path to Image>"
        
            print adminusercontent.updateItem(itemId = itemId,
                                                        updateItemParameters=itemParams,
                                                        folderId=item.ownerFolder)
    except (common.ArcRestHelperError),e:
        print "error in function: %s" % e[0]['function']
        print "error on line: %s" % e[0]['line']
        print "error in file name: %s" % e[0]['filename']
        print "with error message: %s" % e[0]['synerror']
        if 'arcpyError' in e[0]:
            print "with arcpy message: %s" % e[0]['arcpyError']
Ejemplo n.º 24
0
def main(args):
    """
    This
    :param args: arguments from argparse
    :return:
    """
    securityinfo = {}
    securityinfo['security_type'] = args.security_type
    securityinfo['username'] = args.username
    securityinfo['password'] = args.password
    securityinfo['org_url'] = args.org_url
    securityinfo['proxy_url'] = args.proxy_url
    securityinfo['proxy_port'] = args.proxy_port
    securityinfo['referer_url'] = args.referer_url
    securityinfo['token_url'] = args.token_url
    securityinfo['certificatefile'] = args.certificate_file
    securityinfo['keyfile'] = args.keyfile
    securityinfo['client_id'] = args.client_id
    securityinfo['secret_id'] = args.secret_id
    try:
        # Authenticate
        shh = securityhandlerhelper.securityhandlerhelper(securityinfo)
        if not shh.valid:
            print(shh.message)
        else:
            # Get portal instance
            portal_admin = arcrest.manageorg.Administration(securityHandler=shh.securityhandler)
            # Loop over all of the item ids (feature services)
            for item_id in args.item_ids:
                try:
                    # Get the feature service item url from the id
                    item_url = portal_admin.content.getItem(itemId=item_id).url
                    # Update the definition
                    errors = update_definition(item_url,shh.securityhandler)
                    if not errors:
                        print("Successfully updated required fields for item id: {}".format(item_id))
                    else:
                        print("Failed to update service layers: {}".format(",".join(errors)))
                except Exception as e:
                    print("Error updating item id: {}. Please verify the item ID is a feature service".format(item_id))
                    print(e)
    except Exception as e:
        print(e)
Ejemplo n.º 25
0
def create_security_handler(security_type='Portal', username="", password="",
                            org_url="", proxy_url=None, proxy_port=None,
                            referer_url=None, token_url=None, certificatefile=None,
                            keyfile=None, client_id=None, secret_id=None):
    """Creates a security handler helper using the specified properties."""
    securityinfo = {}
    securityinfo['security_type'] = security_type#LDAP, NTLM, OAuth, Portal, PKI, ArcGIS
    securityinfo['username'] = username
    securityinfo['password'] = password
    securityinfo['org_url'] = org_url
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = referer_url
    securityinfo['token_url'] = token_url
    securityinfo['certificatefile'] = certificatefile
    securityinfo['keyfile'] = keyfile
    securityinfo['client_id'] = client_id
    securityinfo['secret_id'] = secret_id

    return securityhandlerhelper.securityhandlerhelper(securityinfo=securityinfo)
def main():

    login_info = {}
    login_info['security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    login_info['username'] = ""
    login_info['password'] = ""
    login_info['org_url'] = "http://www.arcgis.com"

    upload_file = r"c:\test\test.png"
    security_handler_helper = securityhandlerhelper.securityhandlerhelper(
        login_info)
    if security_handler_helper.valid == False:
        print security_handler_helper.message
    else:
        admin = arcrest.manageorg.Administration(
            securityHandler=security_handler_helper.securityhandler)
        content = admin.content
        userInfo = content.users.user()
        item_params = arcrest.manageorg.ItemParameter()
        item_params.title = 'Sample'
        item_params.type = "Image"
        item_params.overwrite = True
        item_params.description = "Test File"
        item_params.tags = "tags"
        item_params.snippet = "Test File"
        item_params.typeKeywords = "Data,Image,png"
        #itemParams.filename = upload_file
        item = userInfo.addItem(itemParameters=item_params,
                                filePath=upload_file,
                                overwrite=True,
                                relationshipType=None,
                                originItemId=None,
                                destinationItemId=None,
                                serviceProxyParams=None,
                                metadata=None)
        print item.title + " created"
Ejemplo n.º 27
0
def main():
    proxy_port = None
    proxy_url = None    
    
    # Info for the organization that currently houses the item.
    securityinfoSource = {}
    securityinfoSource['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
    securityinfoSource['username'] = ""
    securityinfoSource['password'] = ""
    securityinfoSource['org_url'] = "http://www.arcgis.com"
    securityinfoSource['proxy_url'] = proxy_url
    securityinfoSource['proxy_port'] = proxy_port
    securityinfoSource['referer_url'] = None
    securityinfoSource['token_url'] = None
    securityinfoSource['certificatefile'] = None
    securityinfoSource['keyfile'] = None
    securityinfoSource['client_id'] = None
    securityinfoSource['secret_id'] = None   
    
    # Info for the organization that the item will be copied to.
    securityinfoTarget = {}
    securityinfoTarget['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
    securityinfoTarget['username'] = ""
    securityinfoTarget['password'] = ""
    securityinfoTarget['org_url'] = "http://www.arcgis.com"
    securityinfoTarget['proxy_url'] = proxy_url
    securityinfoTarget['proxy_port'] = proxy_port
    securityinfoTarget['referer_url'] = None
    securityinfoTarget['token_url'] = None
    securityinfoTarget['certificatefile'] = None
    securityinfoTarget['keyfile'] = None
    securityinfoTarget['client_id'] = None
    securityinfoTarget['secret_id'] = None   

  
    itemId = ""#Item ID of item to copy    
    new_service_name = "" #name of new item
    try:      
        
        shhSource = securityhandlerhelper.securityhandlerhelper(securityinfoSource)
        shhTarget = securityhandlerhelper.securityhandlerhelper(securityinfoTarget)
        if shhSource.valid == False or shhTarget.valid == False:
            print shhSource.message + " "  + shhTarget.message
        else:        
          
            adminSource = arcrest.manageorg.Administration(securityHandler=shhSource.securityhandler)
            adminTarget = arcrest.manageorg.Administration(securityHandler=shhTarget.securityhandler)
            portalSource = adminSource.portals.portalSelf
            portalTarget = adminTarget.portals.portalSelf
            res = portalTarget.isServiceNameAvailable(name=new_service_name,
                                       serviceType='Feature Service')
            if 'available' in res:
                if res['available'] == False:
                    print "Pick a new name" 
                    return
            else:
                print "Pick a new name" 
                return
                
            itemSource = adminSource.content.getItem(itemId)
            
            fs = arcrest.agol.FeatureService(url=itemSource.url, securityHandler=shhSource.securityhandler, 
                                       initialize=True, 
                                       proxy_url=None, 
                                       proxy_port=None)   
          
            wkid = None
            wkt = None
            if 'wkid' in fs.initialExtent['spatialReference']:
                wkid = fs.initialExtent['spatialReference']['wkid']
            else:
                wkt = fs.initialExtent['spatialReference']['wkt']
            if fs.xssPreventionInfo is not None:
                xssPreventionEnabled = fs.xssPreventionInfo['xssPreventionEnabled']
                xssPreventionRule = fs.xssPreventionInfo['xssPreventionRule']
                xssInputRule = fs.xssPreventionInfo['xssInputRule']
            else:
                xssPreventionEnabled = None
                xssPreventionRule = None
                xssInputRule = None            
            
            #Edit tracking needs to be turned off when item is created    
            enableEditorTracking = False
            enableOwnershipAccessControl = False
            allowOthersToUpdate = False
            allowOthersToDelete = False

            if fs.syncCapabilities is not None:     
                supportsAsync = fs.syncCapabilities['supportsAsync']
                supportsRegisteringExistingData = fs.syncCapabilities['supportsRegisteringExistingData']
                supportsSyncDirectionControl = fs.syncCapabilities['supportsSyncDirectionControl']
                supportsPerLayerSync = fs.syncCapabilities['supportsPerLayerSync']
                supportsPerReplicaSync = fs.syncCapabilities['supportsPerReplicaSync']
                supportsRollbackOnFailure = fs.syncCapabilities['supportsRollbackOnFailure']
            else:
                supportsAsync = None 
                supportsRegisteringExistingData = None 
                supportsSyncDirectionControl = None 
                supportsPerLayerSync = None 
                supportsPerReplicaSync = None 
                supportsRollbackOnFailure = None

            createSerParams = arcrest.manageorg.CreateServiceParameters(
                        name=new_service_name, 
                        spatialReference=arcrest.geometry.SpatialReference(wkid=wkid, wkt=wkt), 
                        serviceDescription=fs.serviceDescription, 
                        hasStaticData=fs.hasStaticData, 
                        maxRecordCount=fs.maxRecordCount, 
                        supportedQueryFormats=fs.supportedQueryFormats, 
                        capabilities=fs.capabilities, 
                        description=fs.description, 
                        copyrightText=fs.copyrightText,
                        initialExtent=arcrest.geometry.Envelope(
                                                               xmin=fs.initialExtent['xmin'], 
                                                               ymin=fs.initialExtent['ymin'], 
                                                               xmax=fs.initialExtent['xmax'], 
                                                               ymax=fs.initialExtent['ymax'], 
                                                               wkid=wkid,
                                                               wkt=wkt), 
                        allowGeometryUpdates=fs.allowGeometryUpdates, 
                        units=fs.units, 
                        xssPreventionEnabled=xssPreventionEnabled, 
                        xssPreventionRule=xssPreventionRule, 
                        xssInputRule=xssInputRule,
                        currentVersion=fs.currentVersion,
                            enableEditorTracking = enableEditorTracking,
                            enableOwnershipAccessControl = enableOwnershipAccessControl,
                            allowOthersToUpdate = allowOthersToUpdate,
                            allowOthersToDelete = allowOthersToDelete,
                            supportsAsync = supportsAsync,
                            supportsRegisteringExistingData = supportsRegisteringExistingData,
                            supportsSyncDirectionControl = supportsSyncDirectionControl,
                            supportsPerLayerSync = supportsPerLayerSync,
                            supportsPerReplicaSync = supportsPerReplicaSync,
                            supportsRollbackOnFailure = supportsRollbackOnFailure,  
                            hasVersionedData = fs.hasVersionedData,
                            supportsDisconnectedEditing = fs.supportsDisconnectedEditing,
                            size =fs.size,
                            syncEnabled =fs.syncEnabled                                                                                              
            )
            userTarget = adminTarget.content.users.user()
            
            newServiceResult = userTarget.createService(createServiceParameter=createSerParams)
            print(newServiceResult)
            item = adminTarget.content.getItem(itemId=newServiceResult.id).userItem
          
                 
            params = arcrest.manageorg.ItemParameter()
            params.title = new_service_name
            params.licenseInfo = itemSource.licenseInfo
            params.description = itemSource.description
            params.snippet = itemSource.snippet
            params.tags = itemSource.tags
            params.accessInformation = itemSource.accessInformation
            params.extent = itemSource.extent
            params.spatialReference = itemSource.spatialReference
            
            tempDir =  tempfile.gettempdir()
            filename = new_service_name #"%s" % uuid.uuid4().get_hex()
            tempFile = itemSource.saveThumbnail(fileName = filename, filePath= tempDir)
            params.thumbnail =  tempFile
            
            updateItemResults = item.updateItem(itemParameters=params,
                                                clearEmptyFields=True,
                                                data=None,
                                                metadata=None,
                                                text=None)
            
            print(updateItemResults)
                    
            if itemSource.protected:
                print(item.protect())
            
            adminNewFS = arcrest.hostedservice.AdminFeatureService(url=newServiceResult.url, securityHandler=shhTarget.securityhandler)
            adminExistFS = fs.administration
            jsdic = {}
            exJson = adminExistFS.json
            jsdic['layers'] = exJson['layers']
            if 'tables' in exJson:
                jsdic['tables'] = exJson['tables']
            else:
                jsdic['tables'] = []
            for k in jsdic['layers']:
                k['spatialReference'] = {}
                if wkt is not None:
                    
                    k['spatialReference']['wkt'] = wkt
                if wkid is not None:
                                        
                    k['spatialReference']['wkid'] = wkid                    
                if 'adminLayerInfo' in k:
                    if 'tableName' in k['adminLayerInfo']:
                        k['adminLayerInfo'].pop('tableName',None)
            for k in jsdic['tables']:
                if 'adminLayerInfo' in k:
                    if 'tableName' in k['adminLayerInfo']:
                        k['adminLayerInfo'].pop('tableName',None)            
            res=adminNewFS.addToDefinition(json_dict=jsdic)
            print(res)
            
            
        if fs.editorTrackingInfo is not None:
      
            json_dict = {'editorTrackingInfo':{}}
            json_dict['editorTrackingInfo']['enableEditorTracking'] = fs.editorTrackingInfo['enableEditorTracking']          
            json_dict['editorTrackingInfo']['allowOthersToDelete'] = fs.editorTrackingInfo['allowOthersToDelete']
            json_dict['editorTrackingInfo']['allowOthersToUpdate'] =  fs.editorTrackingInfo['allowOthersToUpdate']
            json_dict['editorTrackingInfo']['enableOwnershipAccessControl'] = fs.editorTrackingInfo['enableOwnershipAccessControl']
            res = adminNewFS.updateDefinition(json_dict=json_dict)
            print(res)
     
    except:
        line, filename, synerror = trace()
        print("error on line: %s" % line)
        print("error in file name: %s" % filename)
        print("with error message: %s" % synerror)
Ejemplo n.º 28
0
    securityinfo = {}
    securityinfo[
        'security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI, ArcGIS
    securityinfo['username'] = ""  #User Name
    securityinfo['password'] = ""  #password
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    shh = securityhandlerhelper.securityhandlerhelper(
        securityinfo=securityinfo)
    if shh.valid == False:
        print shh.message
    else:
        fl = FeatureLayer(url=url,
                          securityHandler=shh.securityhandler,
                          proxy_port=proxy_port,
                          proxy_url=proxy_url,
                          initialize=True)

        out_fields = ['objectid']
        for fld in fieldInfo:
            out_fields.append(fld['FieldName'])

        resFeats = fl.query(where=sql, out_fields=",".join(out_fields))
        for feat in resFeats:
Ejemplo n.º 29
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfoOrg1 = {}
    securityinfoOrg1[
        'security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    securityinfoOrg1['username'] = "******"
    securityinfoOrg1['password'] = "******"
    securityinfoOrg1['org_url'] = "http://www.arcgis.com"
    securityinfoOrg1['proxy_url'] = proxy_url
    securityinfoOrg1['proxy_port'] = proxy_port
    securityinfoOrg1['referer_url'] = None
    securityinfoOrg1['token_url'] = None
    securityinfoOrg1['certificatefile'] = None
    securityinfoOrg1['keyfile'] = None
    securityinfoOrg1['client_id'] = None
    securityinfoOrg1['secret_id'] = None

    securityinfoOrg2 = {}
    securityinfoOrg2[
        'security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    securityinfoOrg2['username'] = "******"
    securityinfoOrg2['password'] = "******"
    securityinfoOrg2['org_url'] = "http://www.arcgis.com"
    securityinfoOrg2['proxy_url'] = proxy_url
    securityinfoOrg2['proxy_port'] = proxy_port
    securityinfoOrg2['referer_url'] = None
    securityinfoOrg2['token_url'] = None
    securityinfoOrg2['certificatefile'] = None
    securityinfoOrg2['keyfile'] = None
    securityinfoOrg2['client_id'] = None
    securityinfoOrg2['secret_id'] = None

    itemId = "<ID if item>"

    try:

        shhOrg1 = securityhandlerhelper.securityhandlerhelper(securityinfoOrg1)
        shhOrg2 = securityhandlerhelper.securityhandlerhelper(securityinfoOrg2)

        portalAdmin1 = arcrest.manageorg.Administration(
            securityHandler=shhOrg1.securityhandler)
        portalAdmin2 = arcrest.manageorg.Administration(
            securityHandler=shhOrg2.securityhandler)

        item = portalAdmin1.content.getItem(itemId=itemId)

        itemParams = arcrest.manageorg.ItemParameter()
        itemParams.title = item.title
        itemParams.type = item.type
        itemParams.description = item.description
        itemParams.tags = item.tags
        itemParams.snippet = item.snippet
        itemParams.typeKeywords = item.typeKeywords
        itemParams.url = item.url
        itemParams.itemData = item.itemData

        content = portalAdmin2.content
        userInfo = content.users.user()
        item = userInfo.addItem(itemParameters=itemParams,
                                overwrite=True,
                                relationshipType=None,
                                originItemId=None,
                                destinationItemId=None,
                                serviceProxyParams=None,
                                metadata=None)
        print res

    except:
        line, filename, synerror = trace()
        print "error on line: %s" % line
        print "error in file name: %s" % filename
        print "with error message: %s" % synerror
Ejemplo n.º 30
0
def testUpload():
    token = securityhandlerhelper.securityhandlerhelper(config)
Ejemplo n.º 31
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""
    securityinfo['password'] = ""
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    upload_file = r"c:\test\test.png"
    try:

        shh = securityhandlerhelper.securityhandlerhelper(securityinfo)
        if shh.valid == False:
            print shh.message
        else:
            admin = arcrest.manageorg.Administration(securityHandler=shh.securityhandler)
            content = admin.content
            userInfo = content.users.user()

            itemParams = arcrest.manageorg.ItemParameter()
            itemParams.title = 'Sample'
            #itemParams.thumbnail = None
            """
            Valid types
            "Shapefile", "CityEngine Web Scene", "Web Scene", "KML",
                         "Code Sample",
                         "Code Attachment", "Operations Dashboard Add In",
                         "CSV", "CSV Collection", "CAD Drawing", "Service Definition",
                         "Microsoft Word", "Microsoft Powerpoint",
                         "Microsoft Excel", "PDF", "Image",
                         "Visio Document", "iWork Keynote", "iWork Pages",
                         "iWork Numbers", "Map Document", "Map Package",
                         "Basemap Package", "Tile Package", "Project Package",
                         "Task File", "ArcPad Package", "Explorer Map",
                         "Globe Document", "Scene Document", "Published Map",
                         "Map Template", "Windows Mobile Package", "Pro Map",
                         "Layout", "Layer", "Layer Package", "File Geodatabase",
                         "Explorer Layer", "Geoprocessing Package", "Geoprocessing Sample",
                         "Locator Package", "Rule Package", "Workflow Manager Package",
                         "Desktop Application", "Desktop Application Template",
                         "Code Sample", "Desktop Add In", "Explorer Add In",
                         "ArcGIS Desktop Add-In", "ArcGIS Explorer Add-In",
                         "ArcGIS Explorer application configuration", "ArcGIS Explorer document"
            """
            itemParams.type = "Image"
            itemParams.overwrite = True
            itemParams.description = "Test File"
            itemParams.tags = "tags"
            itemParams.snippet = "Test File"
            itemParams.typeKeywords = "Data,Image,png"
            #itemParams.filename = upload_file
            item = userInfo.addItem(
                itemParameters=itemParams,
                filePath= upload_file,
                overwrite=True,
                relationshipType=None,
                originItemId=None,
                destinationItemId=None,
                serviceProxyParams=None,
                metadata=None)
            print item.title + " created"

    except:
        line, filename, synerror = trace()
        print "error on line: %s" % line
        print "error in file name: %s" % filename
        print "with error message: %s" % synerror
Ejemplo n.º 32
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""
    securityinfo['password'] = ""
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    itemId = "f13d20825b12491295084129a21e7a42"
    new_service_name = "NewService0"
    try:

        shh = securityhandlerhelper.securityhandlerhelper(securityinfo)
        if shh.valid == False:
            print shh.message
        else:

            admin = arcrest.manageorg.Administration(
                securityHandler=shh.securityhandler)
            portal = admin.portals.portalSelf
            res = portal.isServiceNameAvailable(name=new_service_name,
                                                serviceType='Feature Service')
            if 'available' in res:
                if res['available'] == False:
                    print "Pick a new name"
                    return
            else:
                print "Pick a new name"
                return

            item = admin.content.getItem(itemId)
            fs = arcrest.agol.FeatureService(
                url=item.url,
                securityHandler=shh.securityhandler,
                initialize=True,
                proxy_url=None,
                proxy_port=None)

            wkid = None
            wkt = None
            if 'wkid' in fs.initialExtent['spatialReference']:
                wkid = fs.initialExtent['spatialReference']['wkid']
            else:
                wkt = fs.initialExtent['spatialReference']['wkt']
            createSerParams = arcrest.manageorg.CreateServiceParameters(
                name=new_service_name,
                spatialReference=arcrest.geometry.SpatialReference(wkid=wkid,
                                                                   wkt=wkt),
                serviceDescription=fs.serviceDescription,
                hasStaticData=fs.hasStaticData,
                maxRecordCount=fs.maxRecordCount,
                supportedQueryFormats=fs.supportedQueryFormats,
                capabilities=fs.capabilities,
                description=fs.description,
                copyrightText=fs.copyrightText,
                initialExtent=arcrest.geometry.Envelope(
                    xmin=fs.initialExtent['xmin'],
                    ymin=fs.initialExtent['ymin'],
                    xmax=fs.initialExtent['xmax'],
                    ymax=fs.initialExtent['ymax'],
                    wkid=wkid,
                    wkt=wkt),
                allowGeometryUpdates=fs.allowGeometryUpdates,
                units=fs.units,
                xssPreventionEnabled=fs.
                xssPreventionInfo['xssPreventionEnabled'],
                xssPreventionRule=fs.xssPreventionInfo['xssPreventionRule'],
                xssInputRule=fs.xssPreventionInfo['xssInputRule'],
                currentVersion=fs.currentVersion,
                enableEditorTracking=fs.
                editorTrackingInfo['enableEditorTracking'],
                enableOwnershipAccessControl=fs.
                editorTrackingInfo['enableOwnershipAccessControl'],
                allowOthersToUpdate=fs.
                editorTrackingInfo['allowOthersToUpdate'],
                allowOthersToDelete=fs.
                editorTrackingInfo['allowOthersToDelete'],
                supportsAsync=fs.syncCapabilities['supportsAsync'],
                supportsRegisteringExistingData=fs.
                syncCapabilities['supportsRegisteringExistingData'],
                supportsSyncDirectionControl=fs.
                syncCapabilities['supportsSyncDirectionControl'],
                supportsPerLayerSync=fs.
                syncCapabilities['supportsPerLayerSync'],
                supportsPerReplicaSync=fs.
                syncCapabilities['supportsPerReplicaSync'],
                supportsRollbackOnFailure=fs.
                syncCapabilities['supportsRollbackOnFailure'],
                hasVersionedData=fs.hasVersionedData,
                supportsDisconnectedEditing=fs.supportsDisconnectedEditing,
                size=fs.size,
                syncEnabled=fs.syncEnabled)
            user = admin.content.users.user()

            newServiceResult = user.createService(
                createServiceParameter=createSerParams)
            print newServiceResult
            item = admin.content.getItem(itemId=newServiceResult.id).userItem

            params = arcrest.manageorg.ItemParameter()
            params.title = new_service_name
            updateItemResults = item.updateItem(itemParameters=params,
                                                clearEmptyFields=True,
                                                data=None,
                                                metadata=None,
                                                text=None)

            print updateItemResults

            adminNewFS = arcrest.hostedservice.AdminFeatureService(
                url=newServiceResult.url, securityHandler=shh.securityhandler)
            adminExistFS = fs.administration
            jsdic = {}
            exJson = adminExistFS.json
            jsdic['layers'] = exJson['layers']
            if 'tables' in exJson:
                jsdic['tables'] = exJson['tables']
            else:
                jsdic['tables'] = []
            for k in jsdic['layers']:
                if 'adminLayerInfo' in k:
                    if 'tableName' in k['adminLayerInfo']:
                        k['adminLayerInfo'].pop('tableName', None)
            for k in jsdic['tables']:
                if 'adminLayerInfo' in k:
                    if 'tableName' in k['adminLayerInfo']:
                        k['adminLayerInfo'].pop('tableName', None)
            res = adminNewFS.addToDefinition(json_dict=jsdic)
            print res

    except:
        line, filename, synerror = trace()
        print "error on line: %s" % line
        print "error in file name: %s" % filename
        print "with error message: %s" % synerror
Ejemplo n.º 33
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfo = {}
    securityinfo['security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""
    securityinfo['password'] = ""
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    upload_file = r"c:\test\test.png"
    try:

        shh = securityhandlerhelper.securityhandlerhelper(securityinfo)
        if shh.valid == False:
            print shh.message
        else:
            admin = arcrest.manageorg.Administration(
                securityHandler=shh.securityhandler)
            content = admin.content
            userInfo = content.users.user()

            itemParams = arcrest.manageorg.ItemParameter()
            itemParams.title = 'Sample'
            #itemParams.thumbnail = None
            """
            Valid types
            "Shapefile", "CityEngine Web Scene", "Web Scene", "KML",
                         "Code Sample",
                         "Code Attachment", "Operations Dashboard Add In",
                         "CSV", "CSV Collection", "CAD Drawing", "Service Definition",
                         "Microsoft Word", "Microsoft Powerpoint",
                         "Microsoft Excel", "PDF", "Image",
                         "Visio Document", "iWork Keynote", "iWork Pages",
                         "iWork Numbers", "Map Document", "Map Package",
                         "Basemap Package", "Tile Package", "Project Package",
                         "Task File", "ArcPad Package", "Explorer Map",
                         "Globe Document", "Scene Document", "Published Map",
                         "Map Template", "Windows Mobile Package", "Pro Map",
                         "Layout", "Layer", "Layer Package", "File Geodatabase",
                         "Explorer Layer", "Geoprocessing Package", "Geoprocessing Sample",
                         "Locator Package", "Rule Package", "Workflow Manager Package",
                         "Desktop Application", "Desktop Application Template",
                         "Code Sample", "Desktop Add In", "Explorer Add In",
                         "ArcGIS Desktop Add-In", "ArcGIS Explorer Add-In",
                         "ArcGIS Explorer application configuration", "ArcGIS Explorer document"
            """
            itemParams.type = "Image"
            itemParams.overwrite = True
            itemParams.description = "Test File"
            itemParams.tags = "tags"
            itemParams.snippet = "Test File"
            itemParams.typeKeywords = "Data,Image,png"
            #itemParams.filename = upload_file
            item = userInfo.addItem(itemParameters=itemParams,
                                    filePath=upload_file,
                                    overwrite=True,
                                    relationshipType=None,
                                    originItemId=None,
                                    destinationItemId=None,
                                    serviceProxyParams=None,
                                    metadata=None)
            print item.title + " created"

    except:
        line, filename, synerror = trace()
        print "error on line: %s" % line
        print "error in file name: %s" % filename
        print "with error message: %s" % synerror
import arcrest
from arcresthelper import securityhandlerhelper

#build dictionary of log in info to be used in security handler
login_info = {
    'username': raw_input("Enter User Name: "),
    'password': raw_input("Enter Password: "******"[%s]\t%s" % (item.sharing['access'], item.title)
def main():
    proxy_port = None
    proxy_url = None

    securityinfoSource = {}
    securityinfoSource[
        'security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    securityinfoSource['username'] = ""
    securityinfoSource['password'] = ""
    securityinfoSource['org_url'] = "http://www.arcgis.com"
    securityinfoSource['proxy_url'] = proxy_url
    securityinfoSource['proxy_port'] = proxy_port
    securityinfoSource['referer_url'] = None
    securityinfoSource['token_url'] = None
    securityinfoSource['certificatefile'] = None
    securityinfoSource['keyfile'] = None
    securityinfoSource['client_id'] = None
    securityinfoSource['secret_id'] = None

    securityinfoTarget = {}
    securityinfoTarget[
        'security_type'] = 'Portal'  #LDAP, NTLM, OAuth, Portal, PKI
    securityinfoTarget['username'] = ""
    securityinfoTarget['password'] = ""
    securityinfoTarget['org_url'] = "http://www.arcgis.com"
    securityinfoTarget['proxy_url'] = proxy_url
    securityinfoTarget['proxy_port'] = proxy_port
    securityinfoTarget['referer_url'] = None
    securityinfoTarget['token_url'] = None
    securityinfoTarget['certificatefile'] = None
    securityinfoTarget['keyfile'] = None
    securityinfoTarget['client_id'] = None
    securityinfoTarget['secret_id'] = None

    itemId = ""  #Item ID of item to copy
    new_service_name = ""  #name of new item
    try:

        shhSource = securityhandlerhelper.securityhandlerhelper(
            securityinfoSource)
        shhTarget = securityhandlerhelper.securityhandlerhelper(
            securityinfoTarget)
        if shhSource.valid == False or shhTarget.valid == False:
            print shhSource.message + " " + shhTarget.message
        else:

            adminSource = arcrest.manageorg.Administration(
                securityHandler=shhSource.securityhandler)
            adminTarget = arcrest.manageorg.Administration(
                securityHandler=shhTarget.securityhandler)
            portalSource = adminSource.portals.portalSelf
            portalTarget = adminTarget.portals.portalSelf
            res = portalTarget.isServiceNameAvailable(
                name=new_service_name, serviceType='Feature Service')
            if 'available' in res:
                if res['available'] == False:
                    print "Pick a new name"
                    return
            else:
                print "Pick a new name"
                return

            itemSource = adminSource.content.getItem(itemId)

            fs = arcrest.agol.FeatureService(
                url=itemSource.url,
                securityHandler=shhSource.securityhandler,
                initialize=True,
                proxy_url=None,
                proxy_port=None)

            wkid = None
            wkt = None
            if 'wkid' in fs.initialExtent['spatialReference']:
                wkid = fs.initialExtent['spatialReference']['wkid']
            else:
                wkt = fs.initialExtent['spatialReference']['wkt']
            if fs.xssPreventionInfo is not None:
                xssPreventionEnabled = fs.xssPreventionInfo[
                    'xssPreventionEnabled']
                xssPreventionRule = fs.xssPreventionInfo['xssPreventionRule']
                xssInputRule = fs.xssPreventionInfo['xssInputRule']
            else:
                xssPreventionEnabled = None
                xssPreventionRule = None
                xssInputRule = None

            #Edit tracking needs to be turned off when item is created
            enableEditorTracking = False
            enableOwnershipAccessControl = False
            allowOthersToUpdate = False
            allowOthersToDelete = False

            if fs.syncCapabilities is not None:
                supportsAsync = fs.syncCapabilities['supportsAsync']
                supportsRegisteringExistingData = fs.syncCapabilities[
                    'supportsRegisteringExistingData']
                supportsSyncDirectionControl = fs.syncCapabilities[
                    'supportsSyncDirectionControl']
                supportsPerLayerSync = fs.syncCapabilities[
                    'supportsPerLayerSync']
                supportsPerReplicaSync = fs.syncCapabilities[
                    'supportsPerReplicaSync']
                supportsRollbackOnFailure = fs.syncCapabilities[
                    'supportsRollbackOnFailure']
            else:
                supportsAsync = None
                supportsRegisteringExistingData = None
                supportsSyncDirectionControl = None
                supportsPerLayerSync = None
                supportsPerReplicaSync = None
                supportsRollbackOnFailure = None

            createSerParams = arcrest.manageorg.CreateServiceParameters(
                name=new_service_name,
                spatialReference=arcrest.geometry.SpatialReference(wkid=wkid,
                                                                   wkt=wkt),
                serviceDescription=fs.serviceDescription,
                hasStaticData=fs.hasStaticData,
                maxRecordCount=fs.maxRecordCount,
                supportedQueryFormats=fs.supportedQueryFormats,
                capabilities=fs.capabilities,
                description=fs.description,
                copyrightText=fs.copyrightText,
                initialExtent=arcrest.geometry.Envelope(
                    xmin=fs.initialExtent['xmin'],
                    ymin=fs.initialExtent['ymin'],
                    xmax=fs.initialExtent['xmax'],
                    ymax=fs.initialExtent['ymax'],
                    wkid=wkid,
                    wkt=wkt),
                allowGeometryUpdates=fs.allowGeometryUpdates,
                units=fs.units,
                xssPreventionEnabled=xssPreventionEnabled,
                xssPreventionRule=xssPreventionRule,
                xssInputRule=xssInputRule,
                currentVersion=fs.currentVersion,
                enableEditorTracking=enableEditorTracking,
                enableOwnershipAccessControl=enableOwnershipAccessControl,
                allowOthersToUpdate=allowOthersToUpdate,
                allowOthersToDelete=allowOthersToDelete,
                supportsAsync=supportsAsync,
                supportsRegisteringExistingData=supportsRegisteringExistingData,
                supportsSyncDirectionControl=supportsSyncDirectionControl,
                supportsPerLayerSync=supportsPerLayerSync,
                supportsPerReplicaSync=supportsPerReplicaSync,
                supportsRollbackOnFailure=supportsRollbackOnFailure,
                hasVersionedData=fs.hasVersionedData,
                supportsDisconnectedEditing=fs.supportsDisconnectedEditing,
                size=fs.size,
                syncEnabled=fs.syncEnabled)
            userTarget = adminTarget.content.users.user()

            newServiceResult = userTarget.createService(
                createServiceParameter=createSerParams)
            print newServiceResult
            item = adminTarget.content.getItem(
                itemId=newServiceResult['itemId']).userItem

            params = arcrest.manageorg.ItemParameter()
            params.title = new_service_name
            params.licenseInfo = itemSource.licenseInfo
            params.description = itemSource.description
            params.snippet = itemSource.snippet
            params.tags = itemSource.tags
            params.accessInformation = itemSource.accessInformation
            params.extent = itemSource.extent
            params.spatialReference = itemSource.spatialReference

            tempDir = tempfile.gettempdir()
            filename = new_service_name  #"%s" % uuid.uuid4().get_hex()
            tempFile = itemSource.saveThumbnail(fileName=filename,
                                                filePath=tempDir)
            params.thumbnail = tempFile

            updateItemResults = item.updateItem(itemParameters=params,
                                                clearEmptyFields=True,
                                                data=None,
                                                metadata=None,
                                                text=None)

            print updateItemResults

            if itemSource.protected:
                print item.protect()

            adminNewFS = arcrest.hostedservice.AdminFeatureService(
                url=newServiceResult['encodedServiceURL'],
                securityHandler=shhTarget.securityhandler)
            adminExistFS = fs.administration
            jsdic = {}
            exJson = adminExistFS.json
            jsdic['layers'] = exJson['layers']
            if 'tables' in exJson:
                jsdic['tables'] = exJson['tables']
            else:
                jsdic['tables'] = []
            for k in jsdic['layers']:
                k['spatialReference'] = {}
                if wkt is not None:

                    k['spatialReference']['wkt'] = wkt
                if wkid is not None:

                    k['spatialReference']['wkid'] = wkid
                if 'adminLayerInfo' in k:
                    if 'tableName' in k['adminLayerInfo']:
                        k['adminLayerInfo'].pop('tableName', None)
            for k in jsdic['tables']:
                if 'adminLayerInfo' in k:
                    if 'tableName' in k['adminLayerInfo']:
                        k['adminLayerInfo'].pop('tableName', None)
            res = adminNewFS.addToDefinition(json_dict=jsdic)
            print res

        if fs.editorTrackingInfo is not None:

            json_dict = {'editorTrackingInfo': {}}
            json_dict['editorTrackingInfo'][
                'enableEditorTracking'] = fs.editorTrackingInfo[
                    'enableEditorTracking']
            json_dict['editorTrackingInfo'][
                'allowOthersToDelete'] = fs.editorTrackingInfo[
                    'allowOthersToDelete']
            json_dict['editorTrackingInfo'][
                'allowOthersToUpdate'] = fs.editorTrackingInfo[
                    'allowOthersToUpdate']
            json_dict['editorTrackingInfo'][
                'enableOwnershipAccessControl'] = fs.editorTrackingInfo[
                    'enableOwnershipAccessControl']
            res = adminNewFS.updateDefinition(json_dict=json_dict)
            print res

    except:
        line, filename, synerror = trace()
        print "error on line: %s" % line
        print "error in file name: %s" % filename
        print "with error message: %s" % synerror
Ejemplo n.º 36
0
def main():
    proxy_port = None
    proxy_url = None    
    
    securityinfo = {}
    securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
    securityinfo['username'] = ""
    securityinfo['password'] = ""
    securityinfo['org_url'] = ""
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None   
    
   
    itemId = "1c2d57215d1241e3a17041a353ebf222"    
    new_service_name = "l21d12dd"
    try:      
        
        shh = securityhandlerhelper.securityhandlerhelper(securityinfo)
        if shh.valid == False:
            print shh.message
        else:        
          
            portalAdmin = arcrest.manageorg.Administration(securityHandler=shh.securityhandler)
            portal = portalAdmin.portals(portalId='self')
            res = portal.checkServiceName(name=new_service_name,
                                       serviceType='Feature Service')
            if 'available' in res:
                if res['available'] == False:
                    print "Pick a new name" 
                    return
            else:
                print "Pick a new name" 
                return
            content = portalAdmin.content
            
                
            item = content.item(itemId)
            fs = arcrest.agol.FeatureService(url=item.url, securityHandler=shh.securityhandler, 
                                       initialize=True, 
                                       proxy_url=None, 
                                       proxy_port=None)   
            
            uc = content.usercontent(username=shh.securityhandler.username)
            
            createSerParams = arcrest.manageorg.parameters.CreateServiceParameters(
                                                                                  name=new_service_name, 
                                                                                  spatialReference=arcrest.geometry.SpatialReference(wkid=fs.spatialReference['wkid']), 
                                                                                  serviceDescription=fs.serviceDescription, 
                                                                                  hasStaticData=fs.hasStaticData, 
                                                                                  maxRecordCount=fs.maxRecordCount, 
                                                                                  supportedQueryFormats=fs.supportedQueryFormats, 
                                                                                  capabilities=fs.capabilities, 
                                                                                  description=fs.description, 
                                                                                  copyrightText=fs.copyrightText, 
                                                                                  initialExtent=arcrest.geometry.Envelope(
                                                                                                                         xmin=fs.initialExtent['xmin'], 
                                                                                                                         ymin=fs.initialExtent['ymin'], 
                                                                                                                         xmax=fs.initialExtent['xmax'], 
                                                                                                                         ymax=fs.initialExtent['ymax'], 
                                                                                                                         wkid=fs.initialExtent['spatialReference']['wkid']), 
                                                                                  allowGeometryUpdates=fs.allowGeometryUpdates, 
                                                                                  units=fs.units, 
                                                                                  xssPreventionEnabled=fs.xssPreventionInfo['xssPreventionEnabled'], 
                                                                                  xssPreventionRule=fs.xssPreventionInfo['xssPreventionRule'], 
                                                                                  xssInputRule=fs.xssPreventionInfo['xssInputRule'],
                                                                                  currentVersion=fs.currentVersion,
                                                                                      enableEditorTracking = fs.editorTrackingInfo['enableEditorTracking'],
                                                                                      enableOwnershipAccessControl = fs.editorTrackingInfo['enableOwnershipAccessControl'],
                                                                                      allowOthersToUpdate = fs.editorTrackingInfo['allowOthersToUpdate'],
                                                                                      allowOthersToDelete = fs.editorTrackingInfo['allowOthersToDelete'],
                                                                                      supportsAsync = fs.syncCapabilities['supportsAsync'],
                                                                                      supportsRegisteringExistingData = fs.syncCapabilities['supportsRegisteringExistingData'],
                                                                                      supportsSyncDirectionControl = fs.syncCapabilities['supportsSyncDirectionControl'],
                                                                                      supportsPerLayerSync = fs.syncCapabilities['supportsPerLayerSync'],
                                                                                      supportsPerReplicaSync = fs.syncCapabilities['supportsPerReplicaSync'],
                                                                                      supportsRollbackOnFailure = fs.syncCapabilities['supportsRollbackOnFailure'],  
                                                                                      hasVersionedData = fs.hasVersionedData,
                                                                                      supportsDisconnectedEditing = fs.supportsDisconnectedEditing,
                                                                                      size =fs.size,
                                                                                      syncEnabled =fs.syncEnabled                                                                                              
            )
            newServiceResult = uc.createService(createServiceParameter=createSerParams)
            print newServiceResult
           
            uc = content.usercontent()           
            params = item.itemParameters
            params.title = new_service_name
            updateItemResults = uc.updateItem(itemId=newServiceResult['itemId'],
                   updateItemParameters=params,
                   folderId=None,
                   clearEmptyFields=True,
                   filePath=None,
                   url=None,
                   text=None)
            
            print updateItemResults
            
            #new_item = content.item(newServiceResult['itemId'])
             
            adminNewFS = arcrest.hostedservice.AdminFeatureService(url=newServiceResult['encodedServiceURL'], securityHandler=shh.securityhandler)
            adminExistFS = fs.administration
            jsdic = {}
            exJson = adminExistFS.json
            jsdic['layers'] = exJson['layers']
            if 'tables' in exJson:
                jsdic['tables'] = exJson['tables']
            else:
                jsdic['tables'] = []
            for k in jsdic['layers']:
                if 'adminLayerInfo' in k:
                    if 'tableName' in k['adminLayerInfo']:
                        k['adminLayerInfo'].pop('tableName',None)
            for k in jsdic['tables']:
                if 'adminLayerInfo' in k:
                    if 'tableName' in k['adminLayerInfo']:
                        k['adminLayerInfo'].pop('tableName',None)            
            res=adminNewFS.addToDefinition(json_dict=jsdic)
            print res
            
    except:
        line, filename, synerror = trace()
        print "error on line: %s" % line
        print "error in file name: %s" % filename
        print "with error message: %s" % synerror
Ejemplo n.º 37
0
def main():
    proxy_port = None
    proxy_url = None

    securityinfoOrg1 = {}
    securityinfoOrg1['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
    securityinfoOrg1['username'] = "******"
    securityinfoOrg1['password'] = "******"
    securityinfoOrg1['org_url'] = "http://www.arcgis.com"
    securityinfoOrg1['proxy_url'] = proxy_url
    securityinfoOrg1['proxy_port'] = proxy_port
    securityinfoOrg1['referer_url'] = None
    securityinfoOrg1['token_url'] = None
    securityinfoOrg1['certificatefile'] = None
    securityinfoOrg1['keyfile'] = None
    securityinfoOrg1['client_id'] = None
    securityinfoOrg1['secret_id'] = None

    securityinfoOrg2 = {}
    securityinfoOrg2['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
    securityinfoOrg2['username'] = "******"
    securityinfoOrg2['password'] = "******"
    securityinfoOrg2['org_url'] = "http://www.arcgis.com"
    securityinfoOrg2['proxy_url'] = proxy_url
    securityinfoOrg2['proxy_port'] = proxy_port
    securityinfoOrg2['referer_url'] = None
    securityinfoOrg2['token_url'] = None
    securityinfoOrg2['certificatefile'] = None
    securityinfoOrg2['keyfile'] = None
    securityinfoOrg2['client_id'] = None
    securityinfoOrg2['secret_id'] = None

    itemId = "<ID if item>"
    
    try:

        shhOrg1 = securityhandlerhelper.securityhandlerhelper(securityinfoOrg1)
        shhOrg2 = securityhandlerhelper.securityhandlerhelper(securityinfoOrg2)
        
        portalAdmin1 = arcrest.manageorg.Administration(securityHandler=shhOrg1.securityhandler)
        portalAdmin2 = arcrest.manageorg.Administration(securityHandler=shhOrg2.securityhandler)
        
        item = portalAdmin1.content.getItem(itemId=itemId)

        itemParams = arcrest.manageorg.ItemParameter()
        itemParams.title = item.title
        itemParams.type = item.type
        itemParams.description = item.description
        itemParams.tags = item.tags
        itemParams.snippet = item.snippet
        itemParams.typeKeywords = item.typeKeywords
        itemParams.url = item.url
        itemParams.itemData = item.itemData
        
        content = portalAdmin2.content
        userInfo = content.users.user()
        item = userInfo.addItem(
            itemParameters=itemParams,
            overwrite=True,
            relationshipType=None,
            originItemId=None,
            destinationItemId=None,
            serviceProxyParams=None,
            metadata=None)
        print res

    except:
        line, filename, synerror = trace()
        print "error on line: %s" % line
        print "error in file name: %s" % filename
        print "with error message: %s" % synerror
Ejemplo n.º 38
0
    securityinfo = {}
    securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI, ArcGIS
    securityinfo['username'] = "" #User Name
    securityinfo['password'] = "" #password
    securityinfo['org_url'] = "http://www.arcgis.com"
    securityinfo['proxy_url'] = proxy_url
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    shh = securityhandlerhelper.securityhandlerhelper(securityinfo=securityinfo)
    if shh.valid == False:
        print shh.message
    else:
        fl= FeatureLayer(
            url=url,
            securityHandler=shh.securityhandler,
            proxy_port=proxy_port,
            proxy_url=proxy_url,
            initialize=True)

        out_fields = ['objectid']
        for fld in fieldInfo:
            out_fields.append(fld['FieldName'])

        resFeats = fl.query(where=sql,
def move_agol_item(args, item_title, agol_directory):
    """
    this function finds the item ids for the map and directory to place map and then moves the item
    :param args:
    :param itemTitle:
    :param agol_directory:
    :return:
    """
    securityinfo = {}
    securityinfo['security_type'] = args.security_type
    securityinfo['username'] = args.username
    securityinfo['password'] = args.password
    securityinfo['org_url'] = args.org_url
    securityinfo['proxy_url'] = args.proxy_url
    securityinfo['proxy_port'] = args.proxy_port
    securityinfo['referer_url'] = args.referer_url
    securityinfo['token_url'] = args.token_url
    securityinfo['certificatefile'] = args.certificate_file
    securityinfo['keyfile'] = args.keyfile
    securityinfo['client_id'] = args.client_id
    securityinfo['secret_id'] = args.secret_id
    try:
        # Authenticate
        shh = securityhandlerhelper.securityhandlerhelper(securityinfo)
        if not shh.valid:
            print(shh.message)
        else:
            # Get portal instance
            portal_admin = arcrest.manageorg.Administration(securityHandler=shh.securityhandler)
            # Get item_id by title
            destination_folder = agol_directory
            item_title = item_title
            # Initialize objects for validation purposes
            item_object, destination_folder_id = "", ""
            try:
                user = portal_admin.content.users.user(args.username)
                # Retrieve item object from AGOL
                for item in user.items:
                    if item.title == item_title:
                        move_item = item
                        # Get item
                        item_object = portal_admin.content.getItem(itemId=move_item.id).userItem
                        # Retrieve folder id
                        try:
                            for folder in user.folders:
                                if folder['title'] == destination_folder:
                                    dest_folder = folder
                                    destination_folder_id = dest_folder['id']
                        except Exception as e:
                            print(e)
                            print("Cannont find folder...")
                        # Move the item to the destination_folder_id
                        try:
                            print("Moving {} to folder {}...".format(move_item.title, dest_folder['title']))
                            item_object.moveItem(folder=destination_folder_id)
                            datetimenow = datetime.datetime.now()
                            print("Successfully Moved Map Item Id: {}\nModified at: {}".format(move_item.title, datetimenow))
                        except Exception as e:
                            print(e)
                            print("Cannot move item to folder...")
                    else:
                        raise Exception("Cannont find item...")
            except Exception as e:
                print("Error Moving item '{}' to '{}' folder".format(item_title, destination_folder))
                print(e)
    except Exception as e:
        print(e)