Exemplo n.º 1
0
def _resume(attributes):
    '''
    Pauses a VM.

    @param attributes: the dictionary of the attributes that will be used to
                        pause a virtual machine
    @type attributes: dict
    '''
    vm = _get_VM(attributes)

    if _get_status(attributes) == "PAUSED":
        conn = Connection(attributes["cm_nova_url"], username="", password="")
        tenant_id, x_auth_token = _get_keystone_tokens(attributes)
        body = '{"unpause": null}'
        headers = {"Content-type": "application/json", "x-auth-token": x_auth_token.encode()}
        uri = tenant_id + "/servers/" + vm['id'] + "/action"
        resp = conn.request_post(uri, body=body, headers=headers)
        status = resp[u'headers']['status']
        if status == '200' or status == '304' or status == '202':
            log.info("VM is unpaused and status is %s" % _get_status(attributes))
        else:
            log.error("_resume: Bad HTTP return code: %s" % status)

    else:
        raise ResourceException("The VM must be paused")

    return _get_status(attributes)
Exemplo n.º 2
0
def _set_flavor(attributes, vm_id, current_flavor, new_flavor):
    vm_status = _get_status(attributes)
    conn = Connection(attributes["cm_nova_url"], username="", password="")
    tenant_id, x_auth_token = _get_keystone_tokens(attributes)
    if (vm_status == 'ACTIVE' and current_flavor != new_flavor):
        body = '{"resize": {"flavorRef":"'+ new_flavor + '"}}'
        headers = {"Content-type": "application/json", "x-auth-token": x_auth_token.encode()}
        uri = tenant_id + "/servers/" + vm_id + "/action"
        resp = conn.request_post(uri, body=body, headers=headers)
        status = resp[u'headers']['status']
        if status == '200' or status == '304' or status == '202':
            return _get_flavor(attributes, vm_id)
        else:
            log.error("Bad HTTP return code: %s" % status)
    elif (vm_status == 'RESIZE'):
        log.error("Wait for VM resizing before confirming action")
    elif (vm_status == 'VERIFY_RESIZE'):
        body = '{"confirmResize": null}'
        headers = {"Content-type": "application/json", "x-auth-token": x_auth_token.encode()}
        uri = tenant_id + "/servers/" + vm_id + "/action"
        resp = conn.request_post(uri, body=body, headers=headers)
        status = resp[u'headers']['status']
        if status == '200' or status == '304' or status == '202':
            return _get_flavor(attributes, vm_id)
        else:
            log.error("_set_flavor: Bad HTTP return code: %s" % status)
    else:
        log.error("Wrong VM state or wring destination flavor")
 def __init__(self, conn=None):
     if not conn:
         self.conn = Connection(GENERAL_PARAMETERS['base_url'],
                                username=GENERAL_PARAMETERS['username'],
                                password=GENERAL_PARAMETERS['password'])
     else:
         self.conn = conn
Exemplo n.º 4
0
    def submit_rdfxml_from_url(self,
                               url_to_file,
                               headers={"Accept": "application/rdf+xml"}):
        """Convenience method - downloads the file from a given url, and then pushes that
           into the meta store. Currently, it doesn't put it through a parse-> reserialise
           step, so that it could handle more than rdf/xml on the way it but it is a
           future possibility."""
        import_rdf_connection = Connection(url_to_file)
        response = import_rdf_connection.request_get("", headers=headers)

        if response.get('headers') and response.get('headers').get(
                'status') in ['200', '204']:
            request_headers = {}

            # Lowercase all response header fields, to make matching easier.
            # According to HTTP spec, they should be case-insensitive
            response_headers = response['headers']
            for header in response_headers:
                response_headers[header.lower()] = response_headers[header]

            # Set the body content
            body = response.get('body').encode('UTF-8')

            # Get the response mimetype
            rdf_type = response_headers.get('content-type', None)

            return self._put_rdf(body, mimetype=rdf_type)
Exemplo n.º 5
0
class NESClient(object):
    '''
    classdocs
    '''


    def __init__(self, appId, servId):
        '''
        Constructor
        '''
        self.ip="pre.3rd.services.telefonica.es"
        self.port="444"
        self.protocol="https"
        self.path="/services/BA/REST/UCSS/UCSSServer/"
        self.appId = appId
        self.servId = servId 
        self.headers = {'appId' : self.appId, 'servId' : self.servId}
        
    def set_connection(self):
        self.base_url= self.protocol + "://" + self.ip +":"+ str(self.port) + self.path
        self.conn = Connection(self.base_url, username='******', password='******')
        
    def create_subscription(self, json_data):
        
        response = self.conn.request_post("nes/subscriptions/",body=json_data, headers=self.headers)
        print "create_subscription"
        
        return response['headers']['status'], response['headers']['location'], response['body']
    
    def delete_subscription(self, correlators_list):
        
        response = self.conn.request_delete("nes/subscriptions?correlators="+correlators_list, headers=self.headers)
        print "delete_subscription"
        
        return response['headers']['status'], response['body']
Exemplo n.º 6
0
 def __init__(self, domain, domain_key, endpoint=None, user="******", timeout=5, cache_dir=".cache"):
     if not endpoint:
         endpoint = "http://%s" % domain
     Connection.__init__(self, endpoint)
     self.domain = domain
     self.domain_key = domain_key
     self.user = user
     self.timeout=timeout
Exemplo n.º 7
0
 def __init__(self, agent_url, verbose=False):
     self._logger.setLevel(logging.DEBUG if verbose else logging.NOTSET)
     if not agent_url.endswith('/'):
         agent_url += '/'
     self.agent_url = agent_url
     base_url = urljoin(agent_url, 'rest')
     self._conn = Connection(base_url)
     self._conn = Connection(self.get_session_url())
Exemplo n.º 8
0
def _delete_VM(attributes):
    conn = Connection(attributes["cm_nova_url"], username="", password="")
    tenant_id, x_auth_token = _get_keystone_tokens(attributes)
    vm = _get_VM(attributes)
    vm_id = vm['id']
    resp = conn.request_delete("/" + tenant_id +"/servers/" + vm_id, args={}, headers={'content-type':'application/json', 'accept':'application/json', 'x-auth-token':x_auth_token})

    return _get_status(attributes)
Exemplo n.º 9
0
    def handle(self, request, data):
        print "++++++++++++ ////////////// data = %s" % data
        uri = request.get_full_path()
        match = re.search('/project/ipsec/([^/]+)/preaddlink/', uri)
        vpn_id = match.group(1)
        print "++++++++++++ ////////////// RBA RBA vpn_id = %s" % vpn_id

        self.p_tk = request.user.token.id
        try:
            messages.success(
                request,
                _("Link in process of establishement... Pushing low level network configuration..."
                  ))
            pgsplit = re.split(r'\.', str(data['p_gw']))
            self.p_site = pgsplit[0] + '.' + pgsplit[1]
            egsplit = re.split(r'\.', str(data['e_gw']))
            self.e_site = egsplit[0] + '.' + egsplit[1]

            print "++++++ data to plugin : vpn=%s, psite=%s, pgw=%s, pnets=%s, ptk=%s, esite=%s, egw=%s, enets=%s, etk=%s, bw=%s" % (
                vpn_id, self.p_site, data['p_gw'], data['p_nets'], self.p_tk,
                self.e_site, data['e_gw'], data['e_nets'], self.e_tk,
                data['bw'])

            # should use a modular client below once it supports complex jsons:
            #api.elasticnet.elasticnet_add_link(request, vpn_id, self.p_site, str(data['p_gw']) , str(data['p_nets']), self.p_tk, self.e_site, str(data['e_gw']) , str(data['e_nets']), self.e_tk, str(data['bw']))
            if str(request.user.username).startswith("acme"):
                o = urlparse.urlparse(url_for(request, "ipsecvpn"))
            else:
                o = urlparse.urlparse(url_for(request, "vpn"))

            conn0 = Connection("http://" + str(o.hostname) + ":9797",
                               "ericsson", "ericsson")
            uri0 = "/v1.0/tenants/acme/networks/" + str(vpn_id) + "/links.json"
            LOG.debug("http://" + str(o.hostname) + ":9797")
            LOG.debug(uri0)
            header = {}
            header["Content-Type"] = "application/json"
            jsonbody='{"sites": [{"id":"'+str(self.p_site)+'", "gateway":"'+ str(data['p_gw']) +'", "network":"'+  str(data['p_nets']) +'", "token_id":"'+str(self.p_tk)+ '"}, {"id":"' \
+ str(self.e_site)+'", "gateway":"'+ str(data['e_gw']) +'", "network":"'+  str(data['e_nets']) +'", "token_id":"'+str(self.e_tk)+ '"}], "qos":{"bandwidth":"' \
+ str(data['bw'])+'", "eir":"'+ str(data['eir'])+ '", "cbs":"'+ str(data['cbs'])+ '", "pbs":"'+ str(data['pbs'])+ '"}}'
            print "+++ ewan result json body =%s" % jsonbody
            result = conn0.request_post(uri0, body=jsonbody, headers=header)
            print "+++ ewan result body =%s" % result["body"]
            body = json.loads(result["body"])
            print "+++ewan body=%s" % body
            linkid = str(body['link']['id'])
            print "+++ewan linkid=%s" % linkid

            messages.success(request, _("Link added successfully."))
            shortcuts.redirect("horizon:project:ipsec:index")
            return True
        except Exception as e:
            msg = _(
                'Failed to authorize Link from remote Enterprise Site crendentials : %s'
            ) % e.message
            LOG.info(msg)
            return shortcuts.redirect("horizon:project:ipsec:index")
Exemplo n.º 10
0
def _get_images(attributes):
    conn = Connection(attributes["cm_nova_url"], username="", password="")
    tenant_id, x_auth_token = _get_keystone_tokens(attributes)
    resp = conn.request_get("/" + tenant_id + "/images", args={}, headers={'content-type':'application/json', 'accept':'application/json', 'x-auth-token':x_auth_token})
    status = resp[u'headers']['status']
    if status == '200' or status == '304':
        images = json.loads(resp['body'])
        return images['images']
    else:
        log.error("_get_images: Bad HTTP return code: %s" % status)
Exemplo n.º 11
0
    def handle(self, request, data):
        print "++++++++++++ ////////////// data = %s" % data
        uri = request.get_full_path()
        match = re.search('/project/vpns/([^/]+)/autoburst/', uri)
        vpn_id = match.group(1)
        print "++++++++++++ ////////////// RBA RBA vpn_id = %s" % vpn_id

        self.p_tk = request.user.token.id
        try:
            messages.success(
                request,
                _("AutoBurst is enabled on the remote VMs using this elastic wan..."
                  ))
            pgsplit = re.split(r'\.', str(data['p_gw']))
            self.p_site = pgsplit[0] + '.' + pgsplit[1]
            egsplit = re.split(r'\.', str(data['e_gw']))
            self.e_site = egsplit[0] + '.' + egsplit[1]

            # should use a modular client below once it supports complex jsons:
            #api.elasticnet.elasticnet_add_link(request, vpn_id, self.p_site, str(data['p_gw']) , str(data['p_nets']), self.p_tk, self.e_site, str(data['e_gw']) , str(data['e_nets']), self.e_tk, str(data['bw']))
            if str(request.user.username).startswith("acme"):
                o = urlparse.urlparse(url_for(request, "ipsecvpn"))
            else:
                o = urlparse.urlparse(url_for(request, "vpn"))

            conn0 = Connection("http://" + str(o.hostname) + ":9797",
                               "ericsson", "ericsson")
            uri0 = "/v1.0/tenants/acme/networks/" + str(vpn_id) + "/links.json"
            LOG.debug("http://" + str(o.hostname) + ":9797")
            LOG.debug(uri0)
            bw = None
            header = {}
            header["Content-Type"] = "application/json"
            jsonbody='{"sites": [{"id":"'+str(self.p_site)+'", "gateway":"'+ str(data['p_gw']) +'", "network":"'+  str(data['p_nets']) +'", "token_id":"'+str(self.p_tk)+ '"}, {"id":"' \
              + str(self.e_site)+'", "gateway":"'+ str(data['e_gw']) +'", "network":"'+  str(data['e_nets']) +'", "token_id":"'+str(self.e_tk)+ '"}], "qos":{"bandwidth":"' \
              + str(bw)+'"}, "usecase":{"action":"autoburst", "vmuuid":"' \
+ str(data['e_servers'])+'", "vmtenantid":"'+str(self.vmtenantid)+'", "vmsla":"'+str(data['sla'])+'"}}'
            print "+++ ewan result json body =%s" % jsonbody
            result = conn0.request_post(uri0, body=jsonbody, headers=header)
            print "+++ ewan result body =%s" % result["body"]
            body = json.loads(result["body"])
            print "+++ewan body=%s" % body
            linkid = str(body['link']['id'])
            print "+++ewan linkid=%s" % linkid

            messages.success(request, _("Link added successfully."))
            shortcuts.redirect("horizon:project:vpns:index")
            return True
        except Exception as e:
            msg = _(
                'Failed to authorize Link from remote Enterprise Site crendentials : %s'
            ) % e.message
            LOG.info(msg)
            return shortcuts.redirect("horizon:project:vpns:index")
Exemplo n.º 12
0
 def getBusesPositions(self):
     lcord = []
     conn = Connection("http://mc933.lab.ic.unicamp.br:8017/onibus")
     response = conn.request_get("")
     
     buses = json.loads(response["body"])
     
     for i in buses:
         response = conn.request_get(str(i))
         lcord.append(json.loads(response["body"]))
     #conn.request_put("/sidewinder", {'color': 'blue'}, headers={'content-type':'application/json', 'accept':'application/json'})
     return lcord
Exemplo n.º 13
0
class DiffsClient(object):

    _logger = logging.getLogger('DiffsClient')
    _logger.addHandler(logging.StreamHandler(sys.stderr))

    def __init__(self, agent_url, verbose=False):
        self._logger.setLevel(logging.DEBUG if verbose else logging.NOTSET)
        if not agent_url.endswith('/'):
            agent_url += '/'
        self.agent_url = agent_url
        base_url = urljoin(agent_url, 'rest')
        self._conn = Connection(base_url)
        self._conn = Connection(self.get_session_url())

    def get_session_url(self):
        url = '/diffs/sessions'
        response = self._post(url)
        return response['headers']['location']

    def get_diffs(self, pair_key, range_start, range_end):
        url = '/?pairKey={0}&range-start={1}&range-end={2}'.format(
                pair_key,
                range_start.strftime(DATETIME_FORMAT),
                range_end.strftime(DATETIME_FORMAT))
        response = self._get(url)
        return json.loads(response['body'])

    def get_diffs_zoomed(self, range_start, range_end, bucketing):
        "A dictionary of pair keys mapped to lists of bucketed diffs"
        url = '/zoom?range-start={0}&range-end={1}&bucketing={2}'.format(
                range_start.strftime(DATETIME_FORMAT),
                range_end.strftime(DATETIME_FORMAT),
                bucketing)
        response = self._get(url)
        return json.loads(response['body'])

    def _get(self, url):
        self._logger.debug("GET %s", self._rebuild_url(url))
        response = self._conn.request_get(url)
        self._logger.debug(response)
        return response
    
    def _post(self, url):
        self._logger.debug("POST %s", self._rebuild_url(url))
        response = self._conn.request_post(url)
        self._logger.debug(response)
        return response

    def _rebuild_url(self, url):
        return self._conn.url.geturl() + url

    def __repr__(self):
        return "DiffsClient(%s)" % repr(self.agent_url)
Exemplo n.º 14
0
    def getBusesPositions(self):
        lcord = []
        conn = Connection("http://mc933.lab.ic.unicamp.br:8017/onibus")
        response = conn.request_get("")

        buses = json.loads(response["body"])

        for i in buses:
            response = conn.request_get(str(i))
            lcord.append(json.loads(response["body"]))
        #conn.request_put("/sidewinder", {'color': 'blue'}, headers={'content-type':'application/json', 'accept':'application/json'})
        return lcord
Exemplo n.º 15
0
def _get_keystone_tokens(attributes):
    conn = Connection(attributes["cm_keystone_url"])
    body = '{"auth": {"tenantName":"'+ attributes["cm_tenant_name"] + '", "passwordCredentials":{"username": "******"cm_username"] + '", "password": "******"cm_password"] + '"}}}'
    resp = conn.request_post("/tokens", body=body, headers={'Content-type':'application/json'})
    status = resp[u'headers']['status']
    if status == '200' or status == '304':
        data = json.loads(resp['body'])
        tenant_id = data['access']['token']['tenant']['id']
        x_auth_token = data['access']['token']['id']
        return tenant_id, x_auth_token
    else:
        log.error("_get_keystone_tokens: Bad HTTP return code: %s" % status)
Exemplo n.º 16
0
def _create_VM(res_id, attributes, dict_vm):
    conn_nova = Connection(attributes["cm_nova_url"], username="", password="")
    tenant_id, x_auth_token = _get_keystone_tokens(attributes)
    body = '{"server": {"name":"'+ dict_vm['name'].encode() + '", "imageRef":"' + dict_vm['image'].encode() + '", "key_name": "' + dict_vm['key'].encode() + '", "user_data":"' + dict_vm['user-data'] + '", "flavorRef":"' + dict_vm['flavor'] + '", "max_count": 1, "min_count": 1, "security_groups": [{"name": "default"}]}}'
    headers = {"Content-type": "application/json", "x-auth-token": x_auth_token.encode()}
    uri = tenant_id + "/servers"
    resp = conn_nova.request_post(uri, body=body, headers=headers)
    status = resp[u'headers']['status']
    if status == '200' or status == '304':
        data = json.loads(resp['body'])
        return _get_status(attributes)
    else:
        log.error("_create_VM: Bad HTTP return code: %s" % status)
Exemplo n.º 17
0
 def restful_caller(self, url, method, parameters, http_method):
     try:
         conn = Connection(url)
     except:
         return 'Cant connect with ' + url
     ret = None
     if http_method.upper() == 'GET':
         try:
             ret = conn.request_get(resource=method, args=parameters,
                                    headers={'Content-type': 'text/xml', 'Accept': 'text/xml'})
         except:
             ret = 'Problem with method ' + method
     return ret
Exemplo n.º 18
0
    def __init__(self, base_store_url, username=None, password=None):
        """ Base URL for the store should be pretty self-explanatory. E.g. something like
            "http://api.talis.com/stores/store_name"
            Only needs to enter the username/password if this class is going to tinker
            with things."""
        if base_store_url.endswith('/'):
            base_store_url = base_store_url[:-1]

        self.base_store_url = base_store_url
        # Split the given URL
        if base_store_url:
            self.conn = Connection(base_store_url,
                                   username=username,
                                   password=password)
Exemplo n.º 19
0
    def handle(self, request, data):
        print "++++++++++++ ////////////// data = %s"%data
        uri = request.get_full_path()
        match = re.search('/project/vpns/([^/]+)/autoburst/', uri)
        vpn_id = match.group(1)
        print "++++++++++++ ////////////// RBA RBA vpn_id = %s"%vpn_id


        self.p_tk=request.user.token.id
        try:
                messages.success(request, _("AutoBurst is enabled on the remote VMs using this elastic wan..."))
                pgsplit=re.split(r'\.',str(data['p_gw']))
                self.p_site=pgsplit[0]+'.'+pgsplit[1]
                egsplit=re.split(r'\.',str(data['e_gw']))
                self.e_site=egsplit[0]+'.'+egsplit[1]

                # should use a modular client below once it supports complex jsons:
                #api.elasticnet.elasticnet_add_link(request, vpn_id, self.p_site, str(data['p_gw']) , str(data['p_nets']), self.p_tk, self.e_site, str(data['e_gw']) , str(data['e_nets']), self.e_tk, str(data['bw']))
                if str(request.user.username).startswith("acme"):
                  o = urlparse.urlparse(url_for(request, "ipsecvpn"))
                else:
                  o = urlparse.urlparse(url_for(request, "vpn"))


                conn0 = Connection("http://"+str(o.hostname)+":9797", "ericsson", "ericsson")
                uri0 = "/v1.0/tenants/acme/networks/"+str(vpn_id)+"/links.json"
                LOG.debug("http://"+str(o.hostname)+":9797")
                LOG.debug(uri0)
		bw=None
                header = {}
                header["Content-Type"]= "application/json"
                jsonbody='{"sites": [{"id":"'+str(self.p_site)+'", "gateway":"'+ str(data['p_gw']) +'", "network":"'+  str(data['p_nets']) +'", "token_id":"'+str(self.p_tk)+ '"}, {"id":"' \
                  + str(self.e_site)+'", "gateway":"'+ str(data['e_gw']) +'", "network":"'+  str(data['e_nets']) +'", "token_id":"'+str(self.e_tk)+ '"}], "qos":{"bandwidth":"' \
                  + str(bw)+'"}, "usecase":{"action":"autoburst", "vmuuid":"' \
		  + str(data['e_servers'])+'", "vmtenantid":"'+str(self.vmtenantid)+'", "vmsla":"'+str(data['sla'])+'"}}'
                print "+++ ewan result json body =%s"%jsonbody
                result=conn0.request_post(uri0, body=jsonbody, headers=header)
                print "+++ ewan result body =%s"%result["body"]
                body=json.loads(result["body"])
                print "+++ewan body=%s"%body
                linkid=str(body['link']['id'])
                print "+++ewan linkid=%s"%linkid

                messages.success(request, _("Link added successfully."))
                shortcuts.redirect("horizon:project:vpns:index")
                return True
        except Exception as e:
            msg = _('Failed to authorize Link from remote Enterprise Site crendentials : %s') % e.message
            LOG.info(msg)
            return shortcuts.redirect("horizon:project:vpns:index")
Exemplo n.º 20
0
    def handle(self, request, data):
        print "++++++++++++ ////////////// data = %s"%data
        uri = request.get_full_path()
        match = re.search('/project/ipsec/([^/]+)/preaddlink/', uri)
        vpn_id = match.group(1)
        print "++++++++++++ ////////////// RBA RBA vpn_id = %s"%vpn_id

	self.p_tk=request.user.token.id
	try:
        	messages.success(request, _("Link in process of establishement... Pushing low level network configuration..."))
		pgsplit=re.split(r'\.',str(data['p_gw']))
		self.p_site=pgsplit[0]+'.'+pgsplit[1]
        	egsplit=re.split(r'\.',str(data['e_gw']))
        	self.e_site=egsplit[0]+'.'+egsplit[1]

	        print "++++++ data to plugin : vpn=%s, psite=%s, pgw=%s, pnets=%s, ptk=%s, esite=%s, egw=%s, enets=%s, etk=%s, bw=%s"%(vpn_id, self.p_site, data['p_gw'] , data['p_nets'], 
		   self.p_tk, self.e_site, data['e_gw'] , data['e_nets'], self.e_tk, data['bw'])
		
		# should use a modular client below once it supports complex jsons: 
		#api.elasticnet.elasticnet_add_link(request, vpn_id, self.p_site, str(data['p_gw']) , str(data['p_nets']), self.p_tk, self.e_site, str(data['e_gw']) , str(data['e_nets']), self.e_tk, str(data['bw']))
		if str(request.user.username).startswith("acme"):
		  o = urlparse.urlparse(url_for(request, "ipsecvpn"))
		else:
		  o = urlparse.urlparse(url_for(request, "vpn"))

		conn0 = Connection("http://"+str(o.hostname)+":9797", "ericsson", "ericsson")
	        uri0 = "/v1.0/tenants/acme/networks/"+str(vpn_id)+"/links.json"
                LOG.debug("http://"+str(o.hostname)+":9797")
                LOG.debug(uri0)
                header = {}
                header["Content-Type"]= "application/json"
                jsonbody='{"sites": [{"id":"'+str(self.p_site)+'", "gateway":"'+ str(data['p_gw']) +'", "network":"'+  str(data['p_nets']) +'", "token_id":"'+str(self.p_tk)+ '"}, {"id":"' \
		  + str(self.e_site)+'", "gateway":"'+ str(data['e_gw']) +'", "network":"'+  str(data['e_nets']) +'", "token_id":"'+str(self.e_tk)+ '"}], "qos":{"bandwidth":"' \
		  + str(data['bw'])+'", "eir":"'+ str(data['eir'])+ '", "cbs":"'+ str(data['cbs'])+ '", "pbs":"'+ str(data['pbs'])+ '"}}'
                print "+++ ewan result json body =%s"%jsonbody
                result=conn0.request_post(uri0, body=jsonbody, headers=header)
                print "+++ ewan result body =%s"%result["body"]
                body=json.loads(result["body"])
                print "+++ewan body=%s"%body
                linkid=str(body['link']['id'])
                print "+++ewan linkid=%s"%linkid

                messages.success(request, _("Link added successfully."))
		shortcuts.redirect("horizon:project:ipsec:index")
		return True
        except Exception as e:
	    msg = _('Failed to authorize Link from remote Enterprise Site crendentials : %s') % e.message
            LOG.info(msg)
	    return shortcuts.redirect("horizon:project:ipsec:index")
Exemplo n.º 21
0
def _get_VMs(attributes):
    conn = Connection(attributes["cm_nova_url"], username="", password="")
    tenant_id, x_auth_token = _get_keystone_tokens(attributes)
    resp = conn.request_get("/" + tenant_id +"/servers", args={}, headers={'content-type':'application/json', 'accept':'application/json', 'x-auth-token':x_auth_token})
    status = resp[u'headers']['status']
    if status == '200' or status == '304':
        servers = json.loads(resp['body'])
        i = 0
        vms = []
        for r in servers['servers']:
            vms.append(r['name'])
            i = i+1
        return vms
    else:
        log.error("_get_VMs: Bad HTTP return code: %s" % status)
Exemplo n.º 22
0
def test_rest(myLat, myLng):
	# http://api.spotcrime.com/crimes.json?lat=40.740234&lon=-73.99103400000001&radius=0.01&callback=jsonp1339858218680&key=MLC
	spotcrime_base_url = "http://api.spotcrime.com"
	
	conn = Connection(spotcrime_base_url)

	resp = conn.request_get("/crimes.json", args={	'lat'	: myLat,
													'lon'	: myLng,		
													'radius': '0.01',
													'key' 	: 'MLC'},
											headers={'Accept': 'text/json'})
	
	
	resp_body = resp["body"]
	return resp_body
Exemplo n.º 23
0
def sendPost(serviceId, instanceId, monitoringEndpoint, kpiName, value):
    timestamp = time.mktime(datetime.now().timetuple()) #UTC-Seconds
    timestamp = long(timestamp) 

    conn = Connection(monitoringEndpoint)
    response = conn.request_post("/data/" + serviceId , args={"serviceId":serviceId, "instanceid":instanceId, "kpiName":kpiName, "value":value, "timestamp":timestamp})
    print "Response: ", response

    status = response.get('headers').get('status')
    if status not in ["200", 200, "204", 204]:
        print >> sys.stderr, "Call failed, status:", status 
        return False

    print "Call successful"
    return True
Exemplo n.º 24
0
class LocalClient(object):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        self.ip="localhost"
        self.port="81"
        self.protocol="http"
        self.path="/nes_server"
         
        
    def set_connection(self):
        self.base_url= self.protocol + "://" + self.ip +":"+ str(self.port) + self.path
        self.conn = Connection(self.base_url)
        
    def create_subscription(self, json_data):
        response = self.conn.request_post("/subs.json")
        response['headers']['location']="http://212.179.159.77/nesphase2/nes/subscriptions/1234567891321"
        return response['headers']['status'],response['headers']['location'], response['body']

    def delete_subscription(self, correlators_list):
        
        return 200, "{}"    
Exemplo n.º 25
0
	def __init__(self, api_key, username, password):
		self.username = username
		login_username = api_key + "%" + username

		connection_base = CTCTConnection.API_BASE_URL + username + "/"

		self.connection = Connection(connection_base, username=login_username, password=password)
Exemplo n.º 26
0
def test_rest(myLat, myLng):
    # http://api.spotcrime.com/crimes.json?lat=40.740234&lon=-73.99103400000001&radius=0.01&callback=jsonp1339858218680&key=MLC
    spotcrime_base_url = "http://api.spotcrime.com"

    conn = Connection(spotcrime_base_url)

    resp = conn.request_get("/crimes.json",
                            args={
                                'lat': myLat,
                                'lon': myLng,
                                'radius': '0.01',
                                'key': 'MLC'
                            },
                            headers={'Accept': 'text/json'})

    resp_body = resp["body"]
    return resp_body
Exemplo n.º 27
0
def _get_flavor(attributes, vm_id):
    conn = Connection(attributes["cm_nova_url"], username="", password="")
    tenant_id, x_auth_token = _get_keystone_tokens(attributes)
    resp = conn.request_get("/" + tenant_id +"/servers/" + vm_id, args={}, headers={'content-type':'application/json', 'accept':'application/json', 'x-auth-token':x_auth_token})
    status = resp[u'headers']['status']
    if status == '200' or status == '304':
        server = json.loads(resp['body'])
        flavor_id = server['server']['flavor']['id']
    else:
        log.error("Bad HTTP return code: %s" % status)
    resp = conn.request_get("/" + tenant_id +"/flavors/" + flavor_id, args={}, headers={'content-type':'application/json', 'accept':'application/json', 'x-auth-token':x_auth_token})
    status = resp[u'headers']['status']
    if status == '200' or status == '304':
        flavor = json.loads(resp['body'])
    else:
        log.error("_get_flavor: Bad HTTP return code: %s" % status)
    return flavor['flavor']
Exemplo n.º 28
0
def _get_VM(attributes):
    conn = Connection(attributes["cm_nova_url"], username="", password="")
    tenant_id, x_auth_token = _get_keystone_tokens(attributes)
    resp = conn.request_get("/" + tenant_id +"/servers/detail", args={}, headers={'content-type':'application/json', 'accept':'application/json', 'x-auth-token':x_auth_token})
    status = resp[u'headers']['status']
    found = 0
    if status == '200' or status == '304':
        servers = json.loads(resp['body'])
        for vm in servers['servers']:
            if attributes['name'] == vm['name']:
                found = 1
                return vm
        if found == 0:
            #return False
            raise ResourceException("vm %s not found" % attributes['name'])
    else:
        log.error("_get_VM: Bad HTTP return code: %s" % status)
Exemplo n.º 29
0
class Server:

    def __init__(self, root_url="http://led-o-matic.appspot.com"):
    	self.root_url = root_url
    	self.conn = Connection(self.root_url)
    	self.name = ""

    def getPinStatus(self, pins_name, pin_id):
        request = self.name + '/' + pins_name + '/' + pin_id
        response = self.conn.request_get(request)
        return response['body']
  

    def login(self, name):
		self.name = name
		response = self.conn.request_post('/' + name)
		return self.root_url + '/' + self.name + response['body']
Exemplo n.º 30
0
def get_style_from_geoserver(request):
    if request.method == 'GET':
        layerName = request.GET.get('layer_name')
        baseUrl = openthingis.settings.GEOSERVER_REST_SERVICE
        conn = Connection(
            baseUrl, 
            username=openthingis.settings.GEOSERVER_USER, 
            password=openthingis.settings.GEOSERVER_PASS
        )
        
        layerInfo = conn.request_get("/layers/" + layerName + '.json')
        dict = layerInfo['body']
        layer = simplejson.loads(dict)
        deafultStyle = layer['layer']['defaultStyle']['name']
        
        sld = conn.request_get("/styles/" + deafultStyle + '.sld')
        sld_body = sld['body']
        return HttpResponse(sld_body, content_type="application/xml")
Exemplo n.º 31
0
    def __init__(self, host, email, password):
        """
        Set up a connection with the sensorbase host
        """
        
        self.host = host
        self.email = email
        self.password = password

        self.connection = Connection(self.host, self.email, self.password)
Exemplo n.º 32
0
def get_tariff(tariff_id, phone):
    # Should also work with https protocols
    rest_user = "******"
    rest_pass = "******"
    rest_url = "http://test.lincom3000.com.ua/api"

    conn = Connection(rest_url, username=rest_user, password=rest_pass)

    #nibble_rate
    t = "/tariff/%i/%s/" % (int(tariff_id), phone)
    response = conn.request_get(t, headers={'Accept':'text/json'})
    headers = response.get('headers')
    status = headers.get('status', headers.get('Status'))

    if status in ["200", 200]:
        body = simplejson.loads(response.get('body').encode('UTF-8'))
        return body.get('rate')
    else:
        return None
Exemplo n.º 33
0
def getIncidents(numberOfIncidents, sortedby):
	base_url = PAGER_DUTY
	conn = Connection(base_url)

	yesterdayDateTime, todayDateTime = getLast24Hours()
	fields = 'status,created_on,assigned_to_user'

	# Specify authorization token
	# Specify content type - json
	resp = conn.request_get("/api/v1/incidents", args={'limit': numberOfIncidents, 'since': yesterdayDateTime, 'until': todayDateTime, 'sort_by' : sortedby, 'fields' : fields}, headers={'Authorization': 'Token token=' + AUTHORIZATION_CODE, 'content-type':'application/json', 'accept':'application/json'})
	status = resp[u'headers']['status']
	body = json.loads(resp[u'body'])

	# check that we got a successful response (200) 
	if status == '200':
		print json.dumps(body, sort_keys=False, indent=4, separators=(',', ': '))
	   
	else:
	    print 'Error status code: ', status
	    print "Response", json.dumps(body, sort_keys=False, indent=4, separators=(',', ': '))
Exemplo n.º 34
0
    def __init__(self, base_store_url, username=None, password=None):
        """ Base URL for the store should be pretty self-explanatory. E.g. something like
            "http://api.talis.com/stores/store_name"
            Only needs to enter the username/password if this class is going to tinker
            with things."""
        if base_store_url.endswith('/'):
            base_store_url = base_store_url[:-1]

        self.base_store_url = base_store_url
        # Split the given URL
        if base_store_url:
            self.conn = Connection(base_store_url, username=username, password=password)
def main():
    logging.basicConfig(level=logging.DEBUG)
    try:
        os.remove('out.sqlite3')
    except OSError as e:
        if e.errno != 2:
            raise

    db = create_database('out.sqlite3')

    logging.info('requesting new topic tree...')
    base_url = 'http://www.khanacademy.org/api/v1/'
    conn = Connection(base_url)
    response = conn.request_get('/topictree')
    logging.info('parsing json response...')
    tree = json.loads(response.get('body'))
    logging.info('writing to file...')
    with open('../topictree', 'w') as f:
        f.write(json.dumps(tree))

    logging.info('loading topic tree file...')
    with open('../topictree', 'r') as f:
        tree = json.loads(f.read())

    # stick videos in one list and topics in another for future batch insert
    topics = []
    videos = []
    topicvideos = []
    logging.info('parsing tree...')
    parse_topic(tree, '', topics, videos, topicvideos)

    logging.info('inserting topics...')
    insert_topics(db, topics)
    logging.info('inserting videos...')
    insert_videos(db, videos)
    logging.info('inserting topicvideos...')
    insert_topicvideos(db, topicvideos)

    db.commit()
    logging.info('done!')
def main():
    logging.basicConfig(level=logging.DEBUG)
    try:
        os.remove('out.sqlite3')
    except OSError as e:
        if e.errno != 2:
            raise

    db = create_database('out.sqlite3')

    logging.info('requesting new topic tree...')
    base_url = 'http://www.khanacademy.org/api/v1/'
    conn = Connection(base_url)
    response = conn.request_get('/topictree')
    logging.info('parsing json response...')
    tree = json.loads(response.get('body'))
    logging.info('writing to file...')
    with open('../topictree', 'w') as f:
        f.write(json.dumps(tree))

    logging.info('loading topic tree file...')
    with open('../topictree', 'r') as f:
        tree = json.loads(f.read())

    # stick videos in one list and topics in another for future batch insert
    topics = []
    videos = []
    topicvideos = []
    logging.info('parsing tree...')
    parse_topic(tree, '', topics, videos, topicvideos)

    logging.info('inserting topics...')
    insert_topics(db, topics)
    logging.info('inserting videos...')
    insert_videos(db, videos)
    logging.info('inserting topicvideos...')
    insert_topicvideos(db, topicvideos)

    db.commit()
    logging.info('done!')
Exemplo n.º 37
0
def sendPost(serviceId, instanceId, monitoringEndpoint, kpiName, value):
    timestamp = time.mktime(datetime.now().timetuple())  #UTC-Seconds
    timestamp = long(timestamp)

    conn = Connection(monitoringEndpoint)
    response = conn.request_post("/data/" + serviceId,
                                 args={
                                     "serviceId": serviceId,
                                     "instanceid": instanceId,
                                     "kpiName": kpiName,
                                     "value": value,
                                     "timestamp": timestamp
                                 })
    print "Response: ", response

    status = response.get('headers').get('status')
    if status not in ["200", 200, "204", 204]:
        print >> sys.stderr, "Call failed, status:", status
        return False

    print "Call successful"
    return True
Exemplo n.º 38
0
    def __init__(self, server, search="/search", index="/index", debug=False, username=False, password=False):

        self.server = server
        self.search = search
        self.index = index
        self.debug = debug
        self.un = username
        self.pw = password

        # docs:
        # http://code.google.com/p/python-rest-client/wiki/Using_Connection
        self.ua = Connection(server)

        # interrogate server
        resp = self.ua.request_get("/")
        # pprint.pprint(resp)
        paths = json.loads(resp["body"])
        self.searcher = Connection(paths["search"])
        self.indexer = Connection(paths["index"], username=username, password=password)
        self.commit_uri = paths["commit"]
        self.rollback_uri = paths["rollback"]
        self.fields = paths["fields"]
        self.facets = paths["facets"]
Exemplo n.º 39
0
class Tinyurl(object):
    def __init__(self):
        self._conn = Connection(TINYURL_ENDPOINT)
        # TODO test availability
        self.active = True

    def get(self, url):
        # Handcraft the ?url=XXX line as Tinyurl doesn't understand urlencoded
        # params - at least, when I try it anyway...
        response = self._conn.request_get("?%s=%s" % (TINYURL_PARAM, url))
        http_status = response['headers'].get('status')
        if http_status == "200":
            return response.get('body').encode('UTF-8')
        else:
            raise ConnectionError
Exemplo n.º 40
0
    def __init__(self, username, password):
        """Set up a REST connection to Vcast Server
        
        Returns id_usr user id or raises exception"""
        self.username = username
        self.password = password

        url = 'http://www.vcast.it/faucetpvr/api/1.0/server_rest.php'
        self.connection = Connection(url)
        self.connection.add_rest_credentials(username, password)
        
        c = self.connection.request_get('/faucetid')
        if c['body'] == 'Access Denied':
            raise Exception('Wrong credentials')
        self.id_usr = simplejson.loads(c['body'])['id_usr']
Exemplo n.º 41
0
 def __init__(self):
     # In this example we use rest client provided by
     # http://code.google.com/p/python-rest-client/
     # Of course you are free to use any other client.
     self._connection = Connection(self.BASE_HOST)
Exemplo n.º 42
0
 def __init__(self, username, password):
     self._conn = Connection(TWITTER_ENDPOINT, username, password)
Exemplo n.º 43
0
def trans():
    base_url = "https://partunlimited.demo.triggermesh.io:8080/api"  # The API endpoint for the parts store
    conn = Connection(base_url)

    ce = request.get_json(force=True)
    print(request.data)
    print(request.headers)
    ceSource = request.headers['Ce-Source']

    headers = {}
    headers['Ce-Specversion'] = '1.0'
    headers['Ce-Time'] = request.headers['Ce-Time']
    headers['Ce-Id'] = request.headers['Ce-Id']
    headers[
        'Ce-Source'] = 'translators.triggermesh.io/partsunlimited-demo-translator'

    # For events we don't care about, just return
    if ceSource is not None and not ceSource.startswith(
            'tmtestdb.demo.triggermesh.com/'):
        print("invalid source: " + ceSource)
        return sink()

    # Handle the replenishment event by posting a message to Zendesk
    if ceSource == "tmtestdb.demo.triggermesh.com/replenish":
        headers['Ce-Type'] = 'com.zendesk.ticket.create'
        # Need to extract the manufacturer details
        resp = conn.request_get("/product/" + str(ce["new"]["ID"]))
        respBody = json.loads(resp[u'body'])

        if ce["op"] == "UPDATE" and ce["new"]["QUANTITY"] == 1:
            body = {
                "subject":
                "Parts Unlimited Replenishment Request",
                "body":
                "It is time to reorder " + respBody["name"] + " from " +
                respBody["manufacturer"]["manufacturer"]
            }

            return app.response_class(response=json.dumps(body),
                                      headers=headers,
                                      status=200,
                                      mimetype='application/json')
        else:
            print("invalid replenish")
            return sink()

    # Handle the new order event by sending it to an Oracle Cloud function
    if ceSource == "tmtestdb.demo.triggermesh.com/neworder":
        headers[
            'Ce-Type'] = 'com.triggermesh.targets.oracle.function.partsunlimited-neworder'
        # Need to extract the order details
        resp = conn.request_get("/order/" + str(ce["new"]["ID"]))
        respBody = json.loads(resp[u'body'])

        if ce["op"] == "INSERT":
            body = {
                "name": respBody["user"]["name"],
                "address": respBody["user"]["address"],
                "totalCost": respBody["totalCost"],
                "paymentMethod": respBody["paymentType"],
                "ordered": respBody["dateOrdered"]
            }

            return app.response_class(response=json.dumps(body),
                                      headers=headers,
                                      status=200,
                                      mimetype='application/json')
        else:
            print("invalid neworder")
            return sink()

    else:
        print("unknown source" + ceSource)
        return sink()
Exemplo n.º 44
0
#!/usr/bin/python

import time
import csv
import simplejson as json
from restful_lib import Connection
#conn = Connection("http://mc933.lab.ic.unicamp.br:8010")
while 1:
    #mc933.lab.ic.unicamp.br
    #response = conn.request_get("/getPosition")
    try:
        conn = Connection("http://mc933.lab.ic.unicamp.br/getBusesPositions")
        response = conn.request_get("")
    except:
        print "Connection failed: waiting 10 seconds"
        time.sleep(10)
        continue
    
    buses = json.loads(response["body"])
    try:
        f = open('positions.csv')
        read = csv.reader(f)
                            
                #for row in read:
                #    txt+= str(row) + "</br>"
                #return txt)
        # 0 - systemDatetime
        # 1 - moduleDatetime
        # 2 - licensePlate
        # 3 - latitude
        # 4 - longitude
Exemplo n.º 45
0
from rpc_class import coinrpc
from restful_lib import Connection
from bitcoinrpc.authproxy import AuthServiceProxy

# get bitcoin rpc config
bitcoinrpc = coinrpc("../../bitcoin-0.10.2/bitcoin/bitcoin.conf").rpccon()

# get litecoin rpc config
litecoinrpc = coinrpc("../../litcoin-xxx/bitcoin/bitcoin.conf").rpccon()

# make a new bitcoin address to receive the shifted funds
newaddress = bitcoinrpc.getnewaddress()

# connect to shapeshift API
base_url = "https://shapeshift.io"
conn = Connection(base_url)

# change litecoin to bitcoin
post_data = {"withdrawal": newaddress, "pair": "ltc_btc"}
btc_shift = conn.request_post("/shift/", post_data)

for item in btc_shift:
    if item == "body":
        response = json.loads(btc_shift[item])

for key, value in response.iteritems():
    if key == "deposit":
        depositaddr = value

# send to deposit address
litecoinrpc.sendtoaddress(depositaddr, 10)
Exemplo n.º 46
0
class AdflyApi():
    BASE_HOST = 'https://api.adf.ly'
    # TODO: Replace this with your secret key.
    SECRET_KEY = setting.SECRET_KEY
    # TODO: Replace this with your public key.
    PUBLIC_KEY = setting.PUBLIC_KEY
    # TODO: Replace this with your user id.
    USER_ID = setting.USER_ID
    AUTH_TYPE = dict(basic=1, hmac=2)

    def __init__(self):
        # In this example we use rest client provided by
        # http://code.google.com/p/python-rest-client/
        # Of course you are free to use any other client.
        self._connection = Connection(self.BASE_HOST)

    def shorten(self, urls, domain=None, advert_type=None, group_id=None):
        params = dict()
        if domain:
            params['domain'] = domain
        if advert_type:
            params['advert_type'] = advert_type
        if group_id:
            params['group_id'] = group_id

        if type(urls) == list:
            for i, url in enumerate(urls):
                params['url[%d]' % i] = url
        elif type(urls) == str:
            params['url'] = urls

        response = self._connection.request_post('/v1/shorten',
                                                 args=self._get_params(
                                                     params,
                                                     self.AUTH_TYPE['basic']))
        return json.loads(response['body'])

    def _get_params(self, params={}, auth_type=None):
        """Populates request parameters with required parameters,
        such as _user_id, _api_key, etc.
        """
        auth_type = auth_type or self.AUTH_TYPE['basic']

        params['_user_id'] = self.USER_ID
        params['_api_key'] = self.PUBLIC_KEY

        if self.AUTH_TYPE['basic'] == auth_type:
            pass
        elif self.AUTH_TYPE['hmac'] == auth_type:
            # Get current unix timestamp (UTC time).
            params['_timestamp'] = int(time.time())
            params['_hash'] = self._do_hmac(params)
        else:
            raise RuntimeError

        return params

    def _do_hmac(self, params):
        if type(params) != dict:
            raise RuntimeError

        # Get parameter names.
        keys = params.keys()
        # Sort them using byte ordering.
        # So 'param[10]' comes before 'param[2]'.
        keys.sort()
        queryParts = []

        # Url encode query string. The encoding should be performed
        # per RFC 1738 (http://www.faqs.org/rfcs/rfc1738)
        # which implies that spaces are encoded as plus (+) signs.
        for key in keys:
            quoted_key = urllib.quote_plus(str(key))
            if params[key] is None:
                params[key] = ''

            quoted_value = urllib.quote_plus(str(params[key]))
            queryParts.append('%s=%s' % (quoted_key, quoted_value))

        return hmac.new(self.SECRET_KEY, '&'.join(queryParts),
                        hashlib.sha256).hexdigest()
Exemplo n.º 47
0
#
#   Implementation of views
#

from flask import g, render_template, request, jsonify, Response

from restful_lib import Connection
from ast import literal_eval

import json, re
from main import app

# connection to FMRD result web service
base_url = "http://fmrdlight.herokuapp.com"
result = Connection(base_url)

#
# error handling
#


@app.errorhandler(400)
def bad_request(error=None):
    message = {'status': 400, 'message': "Bad request."}
    resp = jsonify(message)
    resp.status_code = 400

    return resp

Exemplo n.º 48
0
base_url = os.getenv("BASEURL")
if base_url is None:
    base_url = _testConf.get('DEFAULT', 'BaseURL')

secure_url = os.getenv("SECUREURL")
if secure_url is None:
    secure_url = _testConf.get('DEFAULT', 'SecureURL')

user_tag = _testConf.get('DEFAULT', 'tagUsername')
user_prop = _testConf.get('DEFAULT', 'propUsername')
user_prop2 = _testConf.get('DEFAULT', 'propUsername2')
user_chan = _testConf.get('DEFAULT', 'channelUsername')
user_chan2 = _testConf.get('DEFAULT', 'channelUsername2')
user_admin = _testConf.get('DEFAULT', 'username')

conn_none = Connection(base_url)
conn_none_secure = Connection(secure_url)
conn_tag   = Connection(secure_url, username=user_tag,   \
                        password=_testConf.get('DEFAULT', 'tagPassword'))
conn_tag_plain = Connection(base_url, username=user_tag,   \
                        password=_testConf.get('DEFAULT', 'tagPassword'))
conn_prop  = Connection(secure_url, username=user_prop,  \
                        password=_testConf.get('DEFAULT', 'propPassword'))
conn_prop_plain = Connection(base_url, username=user_prop,  \
                        password=_testConf.get('DEFAULT', 'propPassword'))
conn_prop2 = Connection(secure_url, username=user_prop2, \
                        password=_testConf.get('DEFAULT', 'propPassword2'))
conn_chan  = Connection(secure_url, username=user_chan,  \
                        password=_testConf.get('DEFAULT', 'channelPassword'))
conn_chan_plain = Connection(base_url, username=user_chan,  \
                        password=_testConf.get('DEFAULT', 'channelPassword'))
Exemplo n.º 49
0
class Store():
    def __init__(self, base_store_url, username=None, password=None):
        """ Base URL for the store should be pretty self-explanatory. E.g. something like
            "http://api.talis.com/stores/store_name"
            Only needs to enter the username/password if this class is going to tinker
            with things."""
        if base_store_url.endswith('/'):
            base_store_url = base_store_url[:-1]

        self.base_store_url = base_store_url
        # Split the given URL
        if base_store_url:
            self.conn = Connection(base_store_url,
                                   username=username,
                                   password=password)

    def does_snapshot_exist(self, snapshot_filename):
        # Test to see if snapshot exists:
        snapshot_path = SNAPSHOT_TEMPLATE % snapshot_filename

        response = self.conn.request(snapshot_path, method="HEAD")

        if response.get('headers') and response.get('headers').get('status'):
            status = response.get('headers').get('status')

            if status in ['200', '204']:
                return True
            elif status.startswith('4'):
                return False
            # else: raise Error?

        return False

    def schedule_reset_data(self, label, at_time=None):
        """Will request that the store is emptied, and label the request. 
           If a time is given as an ISO8601 formatted string, this will be 
           the scheduled time for the snapshot. Otherwise, it will use the current time."""
        if not at_time:
            at_time = datetime.utcnow().isoformat().split('.')[0]

        snapshot_request = RESET_STORE_TEMPLATE % (label, at_time)

        return self.conn.request_post(
            JOB_REQUESTS,
            body=snapshot_request,
            headers={'Content-Type': 'application/rdf+xml'})

    def schedule_snapshot_data(self, label, at_time=None):
        """Will request a snapshot be made of the store. 
           If a time is given as an ISO8601 formatted string, this will be 
           the scheduled time for the snapshot. Otherwise, it will use the current time."""
        if not at_time:
            at_time = datetime.utcnow().isoformat().split('.')[0]

        snapshot_request = SNAPSHOT_STORE_TEMPLATE % (label, at_time)

        return self.conn.request_post(
            JOB_REQUESTS,
            body=snapshot_request,
            headers={'Content-Type': 'application/rdf+xml'})

    def schedule_snapshot_restore(self,
                                  label,
                                  snapshot_filename,
                                  at_time=None):
        """Will request that the store is restored from a snapshot. If a time is given as
           an ISO8601 formatted string, this will be the scheduled time for
           the recovery. Otherwise, it will use the current time."""
        if not at_time:
            at_time = datetime.utcnow().isoformat().split('.')[0]

        # Test to see if snapshot exists:
        snapshot_path = SNAPSHOT_TEMPLATE % snapshot_filename

        if self.does_snapshot_exist(snapshot_filename):
            snapshot_uri = "%s%s" % (self.base_store_url, snapshot_path)
            snapshot_request = SNAPSHOT_RESTORE_TEMPLATE % (
                label, snapshot_uri, at_time)
            return self.conn.request_post(
                JOB_REQUESTS,
                body=snapshot_request,
                headers={'Content-Type': 'application/rdf+xml'})

    def submit_rdfxml(self, rdf_text):
        """Puts the given RDF/XML into the Talis Store"""
        return self._put_rdf(rdf_text, mimetype="application/rdf+xml")

    def _put_rdf(self, rdf_text, mimetype="application/rdf+xml"):
        """Placeholder for allowing other serialisation types to be put into a
           Talis store, whether the conversion takes place here, or if the Talis
           store starts to accept other formats."""
        if rdf_text:
            request_headers = {}
            if mimetype not in ['application/rdf+xml']:
                raise RDFFormatException(
                    "%s is not an allowed RDF serialisation format" % mimetype)
            request_headers['Content-Type'] = mimetype
            return self.conn.request_post(META_ENDPOINT,
                                          body=rdf_text,
                                          headers=request_headers)

    def _query_sparql_service(self, query, args={}):
        """Low-level SPARQL query - returns the message and response headers from the server.
           You may be looking for Store.sparql instead of this."""
        passed_args = {'query': query}
        passed_args.update(args)
        return self.conn.request_get(
            SPARQL_ENDPOINT,
            args=passed_args,
            headers={'Content-type': 'application/x-www-form-urlencoded'})

    def _query_search_service(self, query, args={}):
        """Low-level content box query - returns the message and response headers from the server.
           You may be looking for Store.search instead of this."""

        passed_args = {'query': query}
        passed_args.update(args)

        return self.conn.request_get(
            CONTENT_ENDPOINT,
            args=passed_args,
            headers={'Content-type': 'application/x-www-form-urlencoded'})

    def _list_snapshots(self, passed_args={}):
        return self.conn.request_get(SNAPSHOTS, args=passed_args, headers={})


##############################################################################
# Convenience Functions
##############################################################################

    def submit_rdfxml_from_url(self,
                               url_to_file,
                               headers={"Accept": "application/rdf+xml"}):
        """Convenience method - downloads the file from a given url, and then pushes that
           into the meta store. Currently, it doesn't put it through a parse-> reserialise
           step, so that it could handle more than rdf/xml on the way it but it is a
           future possibility."""
        import_rdf_connection = Connection(url_to_file)
        response = import_rdf_connection.request_get("", headers=headers)

        if response.get('headers') and response.get('headers').get(
                'status') in ['200', '204']:
            request_headers = {}

            # Lowercase all response header fields, to make matching easier.
            # According to HTTP spec, they should be case-insensitive
            response_headers = response['headers']
            for header in response_headers:
                response_headers[header.lower()] = response_headers[header]

            # Set the body content
            body = response.get('body').encode('UTF-8')

            # Get the response mimetype
            rdf_type = response_headers.get('content-type', None)

            return self._put_rdf(body, mimetype=rdf_type)

    def sparql(self, query, args={}):
        """Performs a SPARQL query and simply returns the body of the response if successful
           - if there is an issue, such as a code 404 or 500, this method will return False. 
           
           Use the _query_sparql_service method to get hold of
           the complete response in this case."""
        response = self._query_sparql_service(query, args)
        headers = response.get('headers')

        status = headers.get('status', headers.get('Status'))

        if status in ['200', 200, '204', 204]:
            return response.get('body').encode('UTF-8')
        else:
            return False

    def search(self, query, args={}):
        """Performs a search query and simply returns the body of the response if successful
           - if there is an issue, such as a code 404 or 500, this method will return False. 
           
           Use the _query_search_service method to get hold of
           the complete response in this case."""
        response = self._query_search_service(query, args)
        headers = response.get('headers')

        status = headers.get('status', headers.get('Status'))

        if status in ['200', 200, '204', 204]:
            parsed_atom = Atom_Search_Results(
                response.get('body').encode('UTF-8'))
            return parsed_atom.get_item_list()
        else:
            return False
Exemplo n.º 50
0
__author__ = 'chywoo.park'
import sys

sys.path.append("../python_rest_client")

import json

from restful_lib import Connection

base_url = "http://jira.score/rest/api/latest"
conn = Connection(base_url, username="******", password="******")
res = conn.request("/issue/TS-17952",
                   headers={
                       'Authorization':
                       'Basic Y2h5d29vLnBhcms6dGl6ZW5zZGsqMTA=',
                       'Content-type': 'application/json',
                       'Accept': 'application/json'
                   },
                   args={})

if res[u'headers']['status'] != "200":
    print("Fail to get issue data")
    exit(1)

body = json.loads(res[u'body'])
print(body.keys())
print("Key: " + body[u'key'])
# print("Status: %s\n" % res[u'headers']['status'])
Exemplo n.º 51
0
#!/usr/bin/python

from restful_lib import Connection
conn = Connection("http://localhost:8888")
response = conn.request_get("/getNearestBusStops?lat=-22.8177;lon=-47.0683")

print response['body']

conn.request_put("/sidewinder", {'color': 'blue'}, headers={'content-type':'application/json', 'accept':'application/json'})