def search(self): from SmartAPI.model.Response import Response # serialize data messageBody = self._generateSearchMessage() if self.debug: print '\n Request to SEAS Search Service:' print messageBody, '\n' try: # send message responseStr = self.httpClient.sendPost(self.rsUri, messageBody, self.serialization, self.serialization, seasMethod=self.httpClient.SMARTAPI_METHOD_REQUEST)[0] response = Response.fromString(responseStr, self.serialization) if response is not None: if self.debug: print '\n Response from SEAS Search Service:' print Tools.toString(response, self.serialization) Tools.printErrors(response) return response.getEntities() else: if self.debug: print '\n Response from SEAS Search Service:' print responseStr, '\n' return None except: print 'Exception while sending an HTTP request to ', self.rsUri traceback.print_exc()
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 _generateSearchMessage(self): from SmartAPI.factory.RequestFactory import RequestFactory request = RequestFactory().create(self.generatedBy) request.setMethod(RESOURCE.READ) request.addEntity(self.entity) return Tools.toString(request, self.serialization)
def explain(self): ''' Similar is seasPrint() method, but add detailed explaination for each concept ''' from rdflib import Graph, resource, URIRef, RDF, Literal from sets import Set from SmartAPI.common.NS import NS from SmartAPI.common.Tools import Tools # if this Obj has no SeasIdentifierUri, add a temporary one in order to make Resource creating easier. temporaryURI = False if self.getIdentifierUri() is None: temporaryURI = True self.setIdentifierUri('http://temporary.org/rdflib/seas#temporary') # get the underlying rdf graph st = Tools.toString(self, 'text/turtle') g = Graph() g.parse(data=st, format='turtle') g.bind('smartapi', NS.SMARTAPI) g.bind('geo', NS.GEO) g.bind('qudt', NS.QUDT) g.bind('unit', NS.UNIT) g.bind('quantity', NS.QUANTITY) g.bind('owl', NS.OWL) g.bind('vcard', NS.VCARD) g.bind('gr', NS.GR) g.bind('dc', NS.DC) # get the root resource root = resource.Resource(g, URIRef(self.getIdentifierUri())) indent = '' if temporaryURI: # delete the temporary URI. It is not useful any more. self.setIdentifierUri(None) self.treePrint(root, indent)
def printOut(self): ''' show structure and datatype of this Obj. It corresponds to print() method in Obj.java. ''' from rdflib import Graph, resource, URIRef, RDF, Literal from sets import Set from SmartAPI.common.NS import NS # if this Obj has no SeasIdentifierUri, add a temporary one in order to make Resource creating easier. temporaryURI = False if self.getIdentifierUri() is None: temporaryURI = True self.setIdentifierUri('http://temporary.org/rdflib/seas#temporary') # get the underlying rdf graph st = Tools.toString(self, 'text/turtle') g = Graph() g.parse(data=st, format='turtle') g.bind('smartapi', NS.SMARTAPI) g.bind('geo', NS.GEO) g.bind('qudt', NS.QUDT) g.bind('unit', NS.UNIT) g.bind('quantity', NS.QUANTITY) g.bind('owl', NS.OWL) g.bind('vcard', NS.VCARD) g.bind('gr', NS.GR) # get the root resource root = resource.Resource(g, URIRef(self.getIdentifierUri())) indent = '' if temporaryURI: # delete the temporary URI. It is not useful any more. self.setIdentifierUri(None) self.treePrintNoDetails(root, indent)
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()
def turtleFormat(self): return Tools.toString(self)
def turtlePrint(self): #raise Exception('turtlePrint is deprecated. Use turtleFormat and print out output yourself instead.') print '****** WARNING: turtlePrint is deprecated. Use turtleFormat and print out output yourself instead.' print Tools.toString(self)