def toString(cls, element, serialization=SERIALIZATION.TURTLE): ''' serialize Seas Obj or its subclass Obj to string. ''' cls.serializedObjs.clear() model = Factory().createModel() if isinstance(element, list) or isinstance( element, OrderedList) or isinstance( element, ItemizedList) or isinstance(element, NudeList): # Raw top level list. We need some blank node to hold the list holder_element = Resource(model=model) holder_element.addProperty(Property(RDF.first), element) top_element = Resource(model=model) top_element.addProperty(Property(PROPERTY.LIST), holder_element) cls.addRecursivelyToModel(top_element, model) elif isinstance(element, LinkedList): top_element = Resource(model=model) top_element.addProperty(Property(PROPERTY.LIST), element) cls.addRecursivelyToModel(top_element, model) else: cls.addRecursivelyToModel(element, model) # serialize messageBody = "" try: messageBody = model.serialize(format=serialization) except: print "Exception while converting model into string" traceback.print_exc() return messageBody
def fromString(cls, strng, serialization=None): model = Factory().createModel() try: model.parse(data=strng, format=serialization) except: print "Could not parse the input into a model" traceback.print_exc() cls.parsedObjs.clear() return model
def fetchKeyFromNotary(cls, senderId, referenceId, hash, signature, notary): ''' @type senderId, referenceId, hash, signature, notary: all strings @return: the fetched session Key as string ''' transaction = None try: transaction = Factory.createTransaction(referenceId, senderId) except: traceback.print_exc() return None transaction.setSigner(senderId) message = Message() message.setHashCode(hash) message.setSignature(signature) transaction.setMessage(message) map = cls.fetchFromTransactionServer(senderId, notary, transaction) transFound = map.get(referenceId) if transFound is None: print 'TransactionAgent error: Requested transaction can not be found from notary!' else: return transFound.getMessage().getSessionKey()
def makeStandardRequest(self, method, entity, temporalContext, timeSeries, serviceUri, publicKey, *valueObjects): ''' @return: Activity ''' from SmartAPI.factory.Factory import Factory from SmartAPI.common.Tools import Tools from SmartAPI.model.Response import Response req = Factory.createRequest(publicKey, method, Factory.defaultIdentity, entity, temporalContext, timeSeries, *valueObjects) # from the object, find activity that is for the required method and that supports most of the valueObjects a = Tools.getMostCommonActivity(method, False, entity, *valueObjects) if serviceUri is None: serviceUri = self._findHTTPInterfaceUri(entity, a) resp = None try: resp, headers = self.sendPost( serviceUri, Tools.toString(req), seasMethod=self.SMARTAPI_METHOD_REQUEST) resp = Response.fromString(resp, 'text/turtle') if resp.hasActivity(): if resp.firstActivity().hasEntity(): return resp.firstActivity() else: return None except: print "object request with HTTP client failed. Method: ", method traceback.print_exc() return None
def fromFile(self, filename, serialization): model = Factory.createModel() try: f = open(filename) model.parse(file=filename, format=serialization) f.close() except: print "Could not read the file into a model" traceback.print_exc() return model
def _findHTTPInterfaceUri(self, entity, activity): from SmartAPI.factory.Factory import Factory uri = '' if activity is not None: ia = activity.getHTTPInterface() if ia is not None: uri = ia.getInterfaceUri() return uri if uri == '': uri = Factory.createStandardInterface( entity.getDomain()).getInterfaceUri() return uri
def sendKeyToNotary(cls, senderId, referenceId, hash, key, signature, notary): # first create Transaction Object keyTransferTransaction = None try: keyTransferTransaction = Factory.createTransaction( referenceId, senderId) except: traceback.print_exc() return False keyTransferTransaction.setSigner(senderId) message = Message() message.setHashCode(hash) message.setSignature(signature) message.setSessionKey(key) keyTransferTransaction.setMessage(message) # then send to server to store return cls.storeToTransactionServer(senderId, notary, keyTransferTransaction)
def storeToTransactionServer(cls, senderId, notary, *args): ''' @param senderId: URI string @param notary: URI string @param args: a variable number of Transaction Objects @return a boolean value ''' try: client = HttpClient() # create an empty MIME multipart message sentHttpMessage = HttpMessage() # construct Request object req = RequestFactory().create(senderId) req.setMethod(RESOURCE.WRITE) cls.messageIdCounter = cls.messageIdCounter + 1 req.setMessageId(cls.messageIdCounter) a = Activity() req.addActivity(a) i = Input() a.addInput(i) system = SystemOfInterest() system.setSameAs(notary) i.setSystemOfInterest(system) param = Parameter() param.setKey("transactions") param.setName("Transaction id list") param.setDescription( "List of ids of transactions that are sent for storing into the database." ) for transaction in args: param.addValue(transaction.getIdentifierUri()) i.addParameter(param) # save Request object to multipart message, Main part mainRequestString = Tools.toString(req) sentHttpMessage.addMainpart(mainRequestString) mainRequestHash = SmartAPICrypto().createEncodedMessageDigest( mainRequestString) requestSignature = SmartAPICrypto().sign( CryptoKeyWallet.getPrivateKey(), mainRequestHash) # create transaction for the main request if cls.transactionIdentifierUriPrefix == '': transactionIdentifierUri = senderId + uuid.uuid4().get_hex() else: transactionIdentifierUri = cls.transactionIdentifierUriPrefix + uuid.uuid4( ).get_hex() requestTransaction = Factory.createTransaction( transactionIdentifierUri, senderId) requestTransaction.setSigner(senderId) requestTransactionMessage = Message() requestTransactionMessage.setMessageId(req.getMessageId()) requestTransactionMessage.setHashCode(mainRequestHash) requestTransactionMessage.setSignature(requestSignature) requestTransaction.setMessage(requestTransactionMessage) # save requestTransaction to multipart message, non-Main part requestTransactionString = Tools.toString(requestTransaction) sentHttpMessage.add(transactionIdentifierUri, requestTransactionString) # save transactions that are sent to multipart message, non-Main part for trans in args: sentHttpMessage.add(trans.getIdentifierUri(), Tools.toString(trans)) # send out this multipart message payload = removeFrontHeader(sentHttpMessage.asString()) #print '*** sent ****' #print payload #print '*************' resp, contentType = client.sendPost( notary, payload, sentHttpMessage.getContentType()) #print "----response -----" #print resp return True except: traceback.print_exc() return False
def fetchFromTransactionServer(cls, senderId, notary, *args): ''' @param senderId: URI string @param notary: URI string @param args: a variable number of Transaction Objects @return a dictionary, key is SeasIdentifierUri of each transaction, value is Transaction Object ''' try: client = HttpClient() # create an empty MIME multipart message sentHttpMessage = HttpMessage() # main request req = RequestFactory().create(senderId) req.setMethod(RESOURCE.READ) cls.messageIdCounter = cls.messageIdCounter + 1 req.setMessageId(cls.messageIdCounter) a = Activity() req.addActivity(a) i = Input() a.addInput(i) system = SystemOfInterest() system.setSameAs(notary) i.setSystemOfInterest(system) param = Parameter() param.setKey("transactions") param.setName("Transaction id list") param.setDescription( "List of ids of transactions that are sent to be fetched the database." ) for transaction in args: param.addValue(transaction.getIdentifierUri()) i.addParameter(param) # save Request object to multipart message, Main part mainRequestString = Tools.toString(req) sentHttpMessage.addMainpart(mainRequestString) mainRequestHash = SmartAPICrypto().createEncodedMessageDigest( mainRequestString) requestSignature = SmartAPICrypto().sign( CryptoKeyWallet.getPrivateKey(), mainRequestHash) #create transaction for the main request if cls.transactionIdentifierUriPrefix == '': transactionIdentifierUri = senderId + uuid.uuid4().get_hex() else: transactionIdentifierUri = transactionIdentifierUri + uuid.uuid4( ).get_hex() requestTransaction = Factory.createTransaction( transactionIdentifierUri, senderId) requestTransaction.setSigner(senderId) requestTransactionMessage = Message() requestTransactionMessage.setMessageId(req.getMessageId()) requestTransactionMessage.setHashCode(mainRequestHash) requestTransactionMessage.setSignature(requestSignature) requestTransaction.setMessage(requestTransactionMessage) # add requestTransaction to multipart message, non-Main part requestTransactionString = Tools.toString(requestTransaction) sentHttpMessage.add(transactionIdentifierUri, requestTransactionString) # add transactions that are sent to multipart message, non-Main part for trans in args: sentHttpMessage.add(trans.getIdentifierUri(), Tools.toString(trans)) # send out this multipart message payload = removeFrontHeader(sentHttpMessage.asString()) resp, contentType = client.sendPost( notary, payload, sentHttpMessage.getContentType()) receivedHttpMessagestr = addFrontHeader(resp, contentType) receivedHttpMessage = parseMIMEmessage(receivedHttpMessagestr) map = {} if isinstance(receivedHttpMessage, HttpMessageSingle): non_main_parts_dict = {} else: non_main_parts_dict = receivedHttpMessage.getNonMainPartsAsDict( ) counter = 0 for part in non_main_parts_dict.values(): counter = counter + 1 # recover the part from string to Seas Obj model = Tools().fromString(part, SERIALIZATION.TURTLE) rootRes = Tools().getTopNode(model)[0] seasCls = Tools().getResourceClass(rootRes) recoveredObj = seasCls.parse(rootRes) if isinstance( recoveredObj, Transaction ): # We want to save the Transaction that hold the requested data map[recoveredObj.getIdentifierUri()] = recoveredObj return map except: traceback.print_exc()