本文整理汇总了Python中pyndn.Name.toUri方法的典型用法代码示例。如果您正苦于以下问题:Python Name.toUri方法的具体用法?Python Name.toUri怎么用?Python Name.toUri使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyndn.Name
的用法示例。
在下文中一共展示了Name.toUri方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import toUri [as 别名]
def main():
# Silence the warning from Interest wire encode.
Interest.setDefaultCanBePrefix(True)
loop = asyncio.get_event_loop()
face = ThreadsafeFace(loop, "memoria.ndn.ucla.edu")
# Counter will stop the ioService after callbacks for all expressInterest.
counter = Counter(loop, 3)
# Try to fetch anything.
name1 = Name("/")
dump("Express name ", name1.toUri())
# These call to exressIinterest is thread safe because face is a ThreadsafeFace.
face.expressInterest(name1, counter.onData, counter.onTimeout)
# Try to fetch using a known name.
name2 = Name("/ndn/edu/ucla/remap/demo/ndn-js-test/hello.txt/%FDU%8D%9DM")
dump("Express name ", name2.toUri())
face.expressInterest(name2, counter.onData, counter.onTimeout)
# Expect this to time out.
name3 = Name("/test/timeout")
dump("Express name ", name3.toUri())
face.expressInterest(name3, counter.onData, counter.onTimeout)
# Run until the Counter calls stop().
loop.run_forever()
face.shutdown()
示例2: onBootstrapData
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import toUri [as 别名]
def onBootstrapData(self, interest, data):
dump("Bootstrap data received.")
if (self._accessControlManager.verifyDataWithHMACKey(data, self._bootstrapKey)):
dump("Verified")
content = json.loads(data.getContent().toRawStr(), encoding="latin-1")
deviceNewIdentity = Name(content["deviceNewIdentity"])
controllerIdentity = Name(content["controllerIdentity"])
controllerPublicKeyInfo = content["controllerPublicKey"]
#add prefix to device profile
self._deviceProfile.setPrefix(deviceNewIdentity.toUri())
seed = HMACKey(content["seedSequence"], 0, str(content["seed"]), "seedName")
self._seed = seed
configurationTokenSequence = content["configurationTokenSequence"]
#generate configuration token
configurationTokenName = controllerIdentity.toUri()+"/"+str(configurationTokenSequence)
configurationTokenKey = hmac.new(seed.getKey(), configurationTokenName, sha256).digest()
self._configurationToken = HMACKey(configurationTokenSequence, 0, configurationTokenKey, configurationTokenName)
#register new identity
dump("Registered new prefix: ", deviceNewIdentity.toUri())
self.face.registerPrefix(content["deviceNewIdentity"],self.onInterest,self.onRegisterFailed)
#set new identity as default and generate default key-pair with KSK Certificate
self._identityStorage.addIdentity(deviceNewIdentity)
self._identityManager.setDefaultIdentity(deviceNewIdentity)
try:
self._identityManager.getDefaultKeyNameForIdentity(deviceNewIdentity)
dump("device identity already exists")
except SecurityException:
#generate new key-pair and certificate for new identity
dump("Install new identity as default\nGenerate new key-pair and self signed certificate")
newKey = self._identityManager.generateRSAKeyPairAsDefault(Name(deviceNewIdentity), isKsk=True)
newCert = self._identityManager.selfSign(newKey)
self._identityManager.addCertificateAsIdentityDefault(newCert)
#add controller's identity and public key
keyType = controllerPublicKeyInfo["keyType"]
keyName = Name(controllerPublicKeyInfo["keyName"])
keyDer = Blob().fromRawStr(controllerPublicKeyInfo["publicKeyDer"])
self._identityStorage.addIdentity(controllerIdentity)
try:
self._identityStorage.addKey(keyName, keyType, keyDer)
dump("Controller's identity, key and certificate installled")
except SecurityException:
dump("Controller's identity, key, certificate already exists.")
#express an certificate request interest
#defaultKeyName = self._identityManager.getDefaultKeyNameForIdentity(self._keyChain.getDefaultIdentity() )
#self.requestCertificate(defaultKeyName)
else:
dump("Not verified")
示例3: test_append
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import toUri [as 别名]
def test_append(self):
# could possibly split this into different tests
uri = "/localhost/user/folders/files/%00%0F"
name = Name(uri)
name2 = Name("/localhost").append(Name("/user/folders/"))
self.assertEqual(len(name2), 3, 'Name constructed by appending names has ' + str(len(name2)) + ' components instead of 3')
self.assertTrue(name2[2].getValue() == Blob("folders"), 'Name constructed with append has wrong suffix')
name2 = name2.append("files")
self.assertEqual(len(name2), 4, 'Name constructed by appending string has ' + str(len(name2)) + ' components instead of 4')
name2 = name2.appendSegment(15)
self.assertTrue(name2[4].getValue() == Blob(bytearray([0x00, 0x0F])), 'Name constructed by appending segment has wrong segment value')
self.assertTrue(name2 == name, 'Name constructed with append is not equal to URI constructed name')
self.assertEqual(name2.toUri(), name.toUri(), 'Name constructed with append has wrong URI')
示例4: status_put
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import toUri [as 别名]
def status_put(name, data):
# Use the system default key chain and certificate name to sign commands.
keyChain = KeyChain()
face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
# Also use the default certificate name to sign data packets.
echo = Echo(keyChain, keyChain.getDefaultCertificateName(), data)
prefix = Name(name)
dump("Register prefix", prefix.toUri())
logging.debug('Register prefix ' + prefix.toUri())
face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)
face.processEvents()
示例5: onDataInterest
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import toUri [as 别名]
def onDataInterest(prefix, interest, transport, pxID):
'''
For publishing face
'''
# just make up some data and return it
interestName = interest.getName()
logger.info("Interest for " + interestName.toUri())
## CURRENTLY ASSUMES THERE'S A VERSION/SEGMENT SUFFIX!
dataName = Name(interestName.getPrefix(-1))
ts = (time.time())
segmentId = 0
try:
segmentId = interestName().get(-1).toSegment()
except:
logger.debug("Could not find segment id!")
dataName.appendSegment(segmentId)
versionStr = interestName.get(-2).getValue().toRawStr()
logger.debug('publishing ' + versionStr)
info = getInfoForVersion(versionStr)
d = Data(dataName)
content = "(" + str(ts) + ") Data named " + dataName.toUri()
d.setContent(content)
d.getMetaInfo().setFinalBlockID(segmentId)
keychain.sign(d, certName)
encodedData = d.wireEncode()
now = time.time()
if info is not None:
info['publish_time'] = now
transport.send(encodedData.toBuffer())
示例6: onInterest
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import toUri [as 别名]
def onInterest(self, prefix, interest, transport, registeredPrefixId):
print "received interest"
initInterest = Name(interest.getName())
print "interest name:",initInterest.toUri()
d = Data(interest.getName().append(self.deviceComponent))
try:
print "start to set data's content"
currentString = ','.join(currentList)
d.setContent("songList of " +self.device+":"+currentString+ "\n")
self.face.registerPrefix(self.changePrefix,self.onInterest,self.onRegisterFailed)
except KeyboardInterrupt:
print "key interrupt"
sys.exit(1)
except Exception as e:
print e
d.setContent("Bad command\n")
finally:
self.keychain.sign(d,self.certificateName)
encodedData = d.wireEncode()
transport.send(encodedData.toBuffer())
print d.getName().toUri()
print d.getContent()
self.loop.close()
self.face.shutdown()
self.face = None
示例7: main
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import toUri [as 别名]
def main():
# The default Face will connect using a Unix socket, or to "localhost".
face = Face()
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(
IdentityManager(identityStorage, privateKeyStorage), None)
keyChain.setFace(face)
# Initialize the storage.
keyName = Name("/testname/DSK-123")
certificateName = keyName.getSubName(0, keyName.size() - 1).append(
"KEY").append(keyName[-1]).append("ID-CERT").append("0")
identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
privateKeyStorage.setKeyPairForKeyName(
keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)
echo = Echo(keyChain, certificateName)
prefix = Name("/testecho")
dump("Register prefix", prefix.toUri())
face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)
while echo._responseCount < 1:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
face.shutdown()
示例8: main
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import toUri [as 别名]
def main():
face = Face("localhost")
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(
IdentityManager(identityStorage, privateKeyStorage), None)
keyChain.setFace(face)
# Initialize the storage.
keyName = Name("/testname/DSK-reposerver")
certificateName = keyName.getSubName(0, keyName.size() - 1).append(
"KEY").append(keyName[-1]).append("ID-CERT").append("0")
identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_PUBLIC_KEY_DER))
privateKeyStorage.setKeyPairForKeyName(
keyName, DEFAULT_PUBLIC_KEY_DER, DEFAULT_PRIVATE_KEY_DER)
echo = RepoServer(keyChain, certificateName)
prefix = Name("/ndn/ucla.edu/bms")
dump("Register prefix", prefix.toUri())
face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)
while True:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
face.shutdown()
示例9: onPublishInterest
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import toUri [as 别名]
def onPublishInterest(self, prefix, interest, transport, pxID):
'''
For publishing face
'''
# just make up some data and return it
interestName = interest.getName()
logger.info("Interest for " + interestName.toUri())
## CURRENTLY ASSUMES THERE'S A VERSION+SEGMENT SUFFIX!
dataName = Name(interestName)
ts = (time.time())
segmentId = 0
#try:
# segmentId = interestName.get(-1).toSegment()
#except:
#logger.debug("Could not find segment id!")
#dataName.appendSegment(segmentId)
versionStr = str(interestName.get(-2).getValue())
logger.debug('Publishing ' + versionStr + ' @ ' + str(ts))
d = Data(dataName)
content = "(" + str(ts) + ") Data named " + dataName.toUri()
d.setContent(content)
d.getMetaInfo().setFinalBlockID(segmentId)
d.getMetaInfo().setFreshnessPeriod(1000)
self.keychain.sign(d, self.certificateName)
encodedData = d.wireEncode()
stats.insertDataForVersion(versionStr, {'publish_time': time.time()})
transport.send(encodedData.toBuffer())
示例10: _createCertificateFromRequest
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import toUri [as 别名]
def _createCertificateFromRequest(self, message):
"""
Generate an IdentityCertificate from the public key information given.
"""
# TODO: Verify the certificate was actually signed with the private key
# matching the public key we are issuing a cert for!!
keyComponents = message.command.keyName.components
keyName = Name("/".join(keyComponents))
self.log.debug("Key name: " + keyName.toUri())
if not self._policyManager.getEnvironmentPrefix().match(keyName):
# we do not issue certs for keys outside of our network
return None
keyDer = Blob(message.command.keyBits)
keyType = message.command.keyType
try:
self._identityStorage.addKey(keyName, keyType, keyDer)
except SecurityException:
# assume this is due to already existing?
pass
certificate = self._identityManager.generateCertificateForKey(keyName)
self._keyChain.sign(certificate, self.getDefaultCertificateName())
# store it for later use + verification
self._identityStorage.addCertificate(certificate)
self._policyManager._certificateCache.insertCertificate(certificate)
return certificate
示例11: __init__
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import toUri [as 别名]
def __init__(self, prefix, maxCount=1):
self.keyChain = KeyChain()
self.prefix = Name(prefix)
self.isDone = False
# Initialize list for Data packet storage.
# We'll treat the indices as equivalent to the sequence
# number requested by Interests.
self.data = []
finalBlock = Name.Component.fromNumberWithMarker(maxCount - 1, 0x00)
hourMilliseconds = 3600 * 1000
# Pre-generate and sign all of Data we can serve.
# We can also set the FinalBlockID in each packet
# ahead of time because we know the entire sequence.
for i in range(maxCount):
dataName = Name(prefix).appendSegment(i)
data = Data(dataName)
data.setContent("Hello, " + dataName.toUri())
data.getMetaInfo().setFinalBlockID(finalBlock)
data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)
self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())
self.data.append(data)
示例12: generateData
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import toUri [as 别名]
def generateData(self, baseName):
'''
This appends the segment number to the data name, since repo-ng tends to expect it
'''
# just make up some data and return it
ts = (time.time())
segmentId = 0 # compatible with repo-ng test: may change to test segmented data
versionStr = baseName.get(-1).toEscapedString()
dataName = Name(baseName)
dataName.appendSegment(segmentId)
d = Data(dataName)
content = "(" + str(ts) + ") Data named " + dataName.toUri()
d.setContent(content)
d.getMetaInfo().setFinalBlockID(segmentId)
d.getMetaInfo().setFreshnessPeriod(-1)
if shouldSign:
self.keychain.sign(d, self.certificateName)
else:
d.setSignature(self.fakeSignature)
stats.insertDataForVersion(versionStr, {'publish_time':time.time()})
logger.debug('Publishing: '+d.getName().toUri())
return d
示例13: main
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import toUri [as 别名]
def main():
# Silence the warning from Interest wire encode.
Interest.setDefaultCanBePrefix(True)
# The default Face will connect using a Unix socket, or to "localhost".
face = Face()
counter = Counter()
if sys.version_info[0] <= 2:
word = raw_input("Enter a word to echo: ")
else:
word = input("Enter a word to echo: ")
name = Name("/testecho")
name.append(word)
dump("Express name ", name.toUri())
face.expressInterest(name, counter.onData, counter.onTimeout)
while counter._callbackCount < 1:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
face.shutdown()
示例14: generateData
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import toUri [as 别名]
def generateData(baseName):
'''
This appends the segment number to the data name
'''
# just make up some data and return it
ts = (time.time())
segmentId = 0 # compatible with repo-ng test: may change to test segmented data
versionComponent = baseName.get(-1) # should have a ts
dataName = Name(baseName)
dataName.appendSegment(segmentId)
d = Data(dataName)
content = "(" + str(ts) + ") Data named " + dataName.toUri()
d.setContent(content)
d.getMetaInfo().setFinalBlockID(segmentId)
d.getMetaInfo().setFreshnessPeriod(-1)
if shouldSign:
keychain.sign(d, certName)
else:
d.setSignature(fakeSignature)
if shouldCollectStats:
info = getInfoForVersion(versionComponent.toEscapedString())
if info is not None:
info['publish_time'] = ts
return d
示例15: sendData
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import toUri [as 别名]
def sendData(self, prefix, interest, face, registeredPrefixId, content): #onInterest
#transport.send(encodedData.toBuffer())
#print(prefix)
# Publish segments
dataSize = len(content)
print("Dat size: ",dataSize)
segmentBegin = 0
segmentNo = 0
print "Start"
while segmentBegin < dataSize:
segmentEnd = segmentBegin + 2000 #Common.MAX_NDN_PACKET_SIZE
if segmentEnd > dataSize:
segmentEnd = dataSize
# Make and sign a Data packet.
print("Prefix: ")
print(prefix)
if not "%" in str(prefix)[-7:]:
segmentName = prefix
#print("NO % in name: ", segmentName)
segmentName.appendSegment(segmentNo)
else:
segmentName = str(prefix)[:-1]
#print("% in name: ",segmentName)
segmentName += str(segmentNo)
segmentName = Name(segmentName)
print("Segment Name: ")
print(segmentName)
print("Segment Name appended: ", segmentName)
print "Segmenting data from %d to %d" % (segmentBegin, segmentEnd)
print("COntent: ")
print(content[segmentBegin:segmentEnd])
data = Data(segmentName)
data.setContent(content[segmentBegin:segmentEnd])
data.getMetaInfo().setFreshnessPeriod(2000)
self._keyChain.sign(data, self._certificateName)
if segmentEnd >= dataSize:
print("yes")
data.getMetaInfo().setFinalBlockId(segmentName[-1])
#encodedData = data.wireEncode()
segmentBegin = segmentEnd
print "Sending data " + segmentName.toUri()
#transport.send(encodedData.toBuffer())
face.putData(data)
segmentNo += 1
time.sleep(0.5)
print "Finish"