本文整理汇总了Python中pyndn.Name类的典型用法代码示例。如果您正苦于以下问题:Python Name类的具体用法?Python Name怎么用?Python Name使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Name类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: apply_exclude
def apply_exclude(self, last_node, exclude):
"""
@param last_node - the node to start search from
@param exlucde - exclude filter the interest contains
@returns all nodes that fullfil the selector
"""
_id = last_node._id
query = 'START s=node(%s)\n' % _id + \
'MATCH (s)-[:%s]->(m)\n' % (RELATION_C2C) + \
'RETURN (m)'
records = neo4j.CypherQuery(self.db_handler, query).execute()
_nodes = [record.values[0] for record in records.data]
if not exclude:
return _nodes
nodes = []
for node in _nodes:
name = Name()
name.set(node.get_properties()[PROPERTY_COMPONENT])
comp = name.get(0)
if not exclude.matches(comp):
nodes.append(node)
return nodes
示例2: wrap_content
def wrap_content(self, name, content, key=None, key_locator=None):
"""
@param name - name of the data
@param content - data to be wrapped
@param key - key used to sign the data
@return the content object created
wraps the given name and content into a content object
"""
co = Data(Name(name))
co.setContent(content)
co.getMetaInfo().setFreshnessPeriod(5000)
co.getMetaInfo().setFinalBlockID(Name("/%00%09")[0])
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
identityManager = IdentityManager(identityStorage, privateKeyStorage)
keyChain = KeyChain(identityManager, None)
# Initialize the storage.
keyName = Name("/ndn/bms/DSK-default")
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)
keyChain.sign(co, certificateName)
_data = co.wireEncode()
return _data.toRawStr()
示例3: onInterest
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
示例4: __init__
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)
示例5: addCertificate
def addCertificate(self, key, issuerId):
"""
Add a self-signed certificate made from the key and issuer ID.
:param PibKey key: The key for the certificate.
:param str issuerId: The issuer ID name component for the certificate
name.
:return: The new certificate.
:rtype: CertificateV2
"""
certificateName = Name(key.getName())
certificateName.append(issuerId).appendVersion(3)
certificate = CertificateV2()
certificate.setName(certificateName)
# Set the MetaInfo.
certificate.getMetaInfo().setType(ContentType.KEY)
# One hour.
certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0)
# Set the content.
certificate.setContent(key.getPublicKey())
params = SigningInfo(key)
# Validity period of 10 days.
now = Common.getNowMilliseconds()
params.setValidityPeriod(
ValidityPeriod(now, now + 10 * 24 * 3600 * 1000.0))
self._keyChain.sign(certificate, params)
return certificate
示例6: generateData
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
示例7: main
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()
示例8: generateData
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
示例9: processInterest
def processInterest(interest, onData, onTimeout, onNetworkNack):
try:
# Create another key for the same identity and sign it properly.
parentKey = self._fixture._keyChain.createKey(
self._fixture._subIdentity)
requestedKey = self._fixture._subIdentity.getKey(interest.getName())
# Copy the Name.
certificateName = Name(requestedKey.getName())
certificateName.append("looper").appendVersion(1)
certificate = CertificateV2()
certificate.setName(certificateName)
# Set the MetaInfo.
certificate.getMetaInfo().setType(ContentType.KEY)
# Set the freshness period to one hour.
certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0)
# Set the content.
certificate.setContent(requestedKey.getPublicKey())
# Set SigningInfo.
params = SigningInfo(parentKey)
# Validity period from 10 days before to 10 days after now.
now = Common.getNowMilliseconds()
params.setValidityPeriod(ValidityPeriod(
now - 10 * 24 * 3600 * 1000.0, now + 10 * 24 * 3600 * 1000.0))
self._fixture._keyChain.sign(certificate, params)
onData(interest, certificate)
except Exception as ex:
self.fail("Error in InfiniteCertificateChain: " + repr(ex))
示例10: main
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()
示例11: test_compare
def test_compare(self):
c7f = Name("/%7F").get(0)
c80 = Name("/%80").get(0)
c81 = Name("/%81").get(0)
self.assertTrue(c81.compare(c80) > 0, "%81 should be greater than %80")
self.assertTrue(c80.compare(c7f) > 0, "%80 should be greater than %7f")
示例12: generateVersionedName
def generateVersionedName(self):
fullName = Name(self.dataName)
# currently we need to provide the version ourselves when we
# poke the repo
ts = int(time.time()*1000)
fullName.appendVersion(int(ts))
return fullName
示例13: _createCertificateFromRequest
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
示例14: onPublishInterest
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())
示例15: onDataInterest
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())