示例#1
0
    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
示例#2
0
 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()
示例#3
0
    def decrypt(self, key, serialization=SERIALIZATION.TURTLE):
        '''
        Decrypt with SessionKey.
        
        Using encrypted string to recover the original Object.
        @return a new Obj decrypted from cipertext, without those additional types like EncryptedReference and Reference, which
        were inserted by encrypt() method before.    
        '''

        if self.encryptedStringRepresentation is not None:
            if isinstance(key, RSA._RSAobj):
                decryptedString, symkey = SmartAPICrypto().asymmetricDecrypt(
                    key, self.encryptedStringRepresentation)
            else:
                decryptedString = SmartAPICrypto().symmetricDecrypt(
                    key, self.encryptedStringRepresentation)

            model = Tools().fromString(decryptedString, serialization)
            # find the resource which was encrypted
            rootRes = Tools().getTopNode(model)[0]
            # figure out its SMARTAPI Class
            seasCls = Tools().getResourceClass(rootRes)
            # recover it to Obj or its subclass Object
            recoveredObj = seasCls.parse(rootRes)
            # remove EncryptedReference and Reference types.
            recoveredObj.types.remove(URIRef(RESOURCE.ENCRYPTEDREFERENCE))
            recoveredObj.types.remove(URIRef(RESOURCE.REFERENCE))
            self.__dict__.update(recoveredObj.__dict__)
            return recoveredObj
        else:
            pass
示例#4
0
	def fromString(self, data, serialization):
		try:
			return Request().parse(Tools().getResourceByType(RESOURCE.REQUEST, Tools().fromString(data, serialization)))
		except:
			print "Unable to parse Evaluation by type smartapi:Request from the given string."
			traceback.print_exc()
			return None
示例#5
0
	def fromString(cls, data, serialization):
		from SmartAPI.common.Tools import Tools		
		try:
			return cls.parse(Tools().getResourceByType(RESOURCE.REQUEST, Tools().fromString(data, serialization)));
		except:
			print "Unable to parse Request from the given string."
			traceback.print_exc() 
			return None
示例#6
0
 def fromString(self, data, serialization):
     try:
         return Response().parse(Tools().getResourceByType(
             RESOURCE.RESPONSE,
             Tools().fromString(data, serialization)))
     except:
         print "Unable to parse Response by type seas:Response from the given string."
         traceback.print_exc()
         return None
示例#7
0
 def fromString(self, data, serialization):
     try:
         return Evaluation().parse(Tools().getResourceByType(
             RESOURCE.COMMAND,
             Tools().fromString(data, serialization)))
     except:
         print "Unable to parse Evaluation by type seas:Command from the given string."
         traceback.print_exc()
         return None
示例#8
0
 def fromString(self, data, serialization):
     try:
         return Notification().parse(Tools().getResourceByType(
             RESOURCE.NOTIFICATION,
             Tools().fromString(data, serialization)))
     except:
         print "Unable to parse Evaluation by type seas:Notification from the given string."
         traceback.print_exc()
         return None
示例#9
0
 def fromString(cls, data, serialization):
     try:
         return cls.parse(Tools().getResourceByType(
             RESOURCE.ALIVERESPONSE,
             Tools().fromString(data, serialization)))
     except:
         print "Unable to parse AliveResponse from the given string."
         traceback.print_exc()
         return None
示例#10
0
	def parseStatement(self, statement):
		
			# get predicate
			predicate = str(statement.getPredicate())
			
			if predicate == PROPERTY.KEY:
				
				try:
					self.setKey(statement.getString())
				except:
					print "Unable to interpret seas:key value as literal for Parameter."
					traceback.print_exc()
				return
			
			if predicate == PROPERTY.RDF_VALUE:
				target_class = Tools().getResourceClass(statement.getResource())

				if target_class is not None:
					try:
						self.addValue(target_class().parse(statement.getResource()))
					except:
						print "Unable to interpret rdf:value as value for Parameter."
						traceback.print_exc()
					return
				elif statement.getResource().model.is_list(statement.getObject()):
					l = []
					statement.getResource().model.parse_list(l, statement.getObject())
					self.addValue(l)
				else:
					self.addValue(Variant().parse(statement))
				return
			
			# pass on to Object
			super(Parameter, self).parseStatement(statement)
示例#11
0
    def parse(self, statement):
        # get predicate and object
        predicate = str(statement.getPredicate())
        objectNode = statement.getObject()

        # if literal object
        dataType = None
        if isinstance(objectNode, Literal):
            return Variant(objectNode.toPython())

        elif (statement.getResource() is not None):
            resource = statement.getResource()
            klass = Tools().getResourceClass(resource, default=Obj)
            if klass is not None:
                v = klass().parse(resource)
            else:
                # None found, resort to Obj (the base class)
                v = Obj().parse(resource)

            return v

        elif isinstance(objectNode, BNode):
            l = []
            statement.getResource().getModel().parse_list(l, objectNode, None)
            return l

        elif isinstance(objectNode, URIRef):
            return Variant(objectNode)

        # could not identify datatype
        print "Parsing variant failed. Unable to detect RDFDatatype (" + str(
            dataType) + ") for literal."
        return Variant("")
示例#12
0
 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)       
示例#13
0
    def sendPostWithRequest(self,
                            server_uri,
                            request_obj,
                            serialization=SERIALIZATION.getMimeType(
                                SERIALIZATION.TURTLE)):
        ''' 	
 		It serializes Request message into a string (no MIME headers) and send out via HTTP POST. Then 
 		it parses received response message into Response object.
 		Note: this function assumes HTTP server generates Smart API Response string in payload without MIME header 
 			 		
 		@param server_uri: uri string of the remote server 
 		@param request_obj: Request object
 		@return Response object 
 		'''
        from SmartAPI.common.Tools import Tools

        payload, content_type = Tools.serializeRequest(request_obj,
                                                       serialization)
        response_body, response_headers = self.sendPost(
            server_uri, payload, content_type=content_type)

        resp = Tools.parseResponse(response_body, content_type)
        return resp
示例#14
0
    def generateRegistrationMessage(self, entity = None):
        if entity:
            self.addEntity(entity)
            
        # check that there is something to register
        if len(self.entities) < 1:
            raise InsufficientDataException("No SMARTAPI entities found in registration.")

        # build registration request
        request = RequestFactory().createRegistrationRequest(self.identity)

        for e in self.entities:
            request.addEntity(e)
            
        # store timestamp for later to check if registration was successful
        self.timestamp = request.getGeneratedAt();
        
        return Tools().toString(request, self.serialization)
示例#15
0
    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)
示例#16
0
    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)
示例#17
0
    def _parse_list_entry(self, entry, klass=None, from_nude=False):
        from SmartAPI.model.ValueObject import ValueObject
        from SmartAPI.rdf.Variant import Variant
        from SmartAPI.common.Tools import Tools

        if from_nude and klass is not None:
            item = klass()
            item.fromNude(entry)
            return item

        if isinstance(entry, Literal):
            return Variant(entry.toPython())
        elif isinstance(entry, URIRef):
            if entry == RDF.nil:
                return None
            return Variant(entry)
        else:
            if klass is None:
                types = []
                sl = self.listStatements(subject=entry,
                                         predicate=URIRef(PROPERTY.RDF_TYPE),
                                         object=None)
                for s in sl:
                    types.append(s.getResource().toString())
                klass = Tools().mapper.getClass(types, default=Variant)

            item = klass()
            for s in self.find_statements_for_node(entry):
                if s.predicate == NS.SMARTAPI + "valueObject":
                    itemv = ValueObject()
                    for sv in self.find_statements_for_node(s.object):
                        itemv.parse(sv)
                    item.addValueObject(itemv)
                else:
                    item.parseStatement(s)
            return item
示例#18
0
    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
示例#19
0
    def serializeToReference(self, model):
        '''
        serialize to an encrypted version of this Object. Its actual content is saved in Tools.messageParts
                
        @return: a rdf Resource
        '''
        from SmartAPI.agents.TransactionAgent import TransactionAgent

        # generate a SeasIdentifierUri for this object if not yet exist. Anonymous is not allowed here.
        if (self.hasIdentifierUri() == False):
            self.setIdentifierUri(self.referenceUriPrefix + str(uuid.uuid4()))

        # convert current Object to string for later encryption
        self.serializeAsReference = False
        partString = Tools().toString(self, SERIALIZATION.TURTLE)

        # TODO: formalize this to a proper encoding method
        partString = partString.replace("\n", "\r\n")
        partString = partString.replace("\r\n\r\n", "\r\n")

        # using the string to generate encrypted string
        crypto = SmartAPICrypto()
        if self.encrypted:
            #    encrypting the normally serialized Object
            # symmetric with notary
            if self.getEncryptionKeyType() == RESOURCE.NOTARIZEDSESSIONKEY:
                sessionkey = crypto.generateSymmetricKey()
                partString = crypto.symmetricEncrypt(sessionkey, partString)

                # encrypt session key with recipient's public key
                encryptedKey = crypto.encryptAndEncodeKey(
                    self.encryptKey, sessionkey)

                # calculate hashcode
                hash = crypto.createEncodedMessageDigest(partString)
                self.setHashCode(hash)

                if self.signed:
                    signature = crypto.sign(self.privateKey, partString)
                    self.setSignature(signature)

                # send encryptedKey to notary for storing
                if not TransactionAgent.sendKeyToNotary(
                        self.senderId, self.getIdentifierUri(), hash,
                        encryptedKey, self.getSignature(), self.getNotary()):
                    raise Exception(
                        "Sending notarized session key to notary failed.")

            # with public key
            if self.getEncryptionKeyType() == RESOURCE.PUBLICKEY:
                # encrypt data with encrypted session key attached
                partString = crypto.asymmetricEncrypt(self.encryptKey,
                                                      partString)[0]

            # with only session key. *insecure*
            if self.getEncryptionKeyType() == RESOURCE.SESSIONKEY:
                # encrypt data
                partString = crypto.symmetricEncrypt(self.encryptKey,
                                                     partString)

                # save key to reference
                sessionkeyAsString = base64.b64encode(self.encryptKey)
                self.setSessionKey(sessionkeyAsString)

        if not self.hasHashCode():
            hash = crypto.createEncodedMessageDigest(partString)
            self.setHashCode(hash)

        if self.signed and (not self.hasSignature()):
            signature = crypto.sign(self.privateKey, partString)
            self.setSignature(signature)

        # save encrypted or unencrypted partString and its uri to multipart as body part
        Tools.saveForMessageParts(self.getIdentifierUri(), partString)

        # add all these to the new Resource
        # Note: MULTIPARTREFERENCE type is not included in encrypted string representation.
        self.addType(RESOURCE.MULTIPARTREFERENCE)
        resource = model.createResource(self.getIdentifierUri())

        # type
        typeProp = model.createProperty(PROPERTY.RDF_TYPE)
        for type in self.types:
            try:
                serialized = type.serialize(model)
            except:
                serialized = URIRef(type)
            resource.addProperty(typeProp, serialized)

        #sessionKey
        if self.hasSessionKey():
            resource.addProperty(
                model.createProperty(PROPERTY.SESSIONKEY),
                model.createTypedLiteral(self.sessionKey, XSD.string))

        #signature
        if self.hasSignature():
            resource.addProperty(
                model.createProperty(PROPERTY.SIGNATURE),
                model.createTypedLiteral(self.signature, XSD.string))

        # hashcode
        if self.hasHashCode():
            resource.addProperty(
                model.createProperty(PROPERTY.HASHCODE),
                model.createTypedLiteral(self.hashCode, XSD.string))

        # encryptionKeyType
        if self.hasEncryptionKeyType():
            resource.addProperty(
                model.createProperty(PROPERTY.ENCRYPTIONKEYTYPE),
                model.createResource(self.getEncryptionKeyType()))

        # notary
        if self.hasNotary():
            resource.addProperty(model.createProperty(PROPERTY.NOTARY),
                                 model.createResource(self.getNotary()))

        return resource
示例#20
0
    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()
示例#21
0
    def parseStatement(self, statement):
        '''
        It takes in statement as input, add property to existing model Class object.
        Return None
        '''
        from SmartAPI.model.Parameter import Parameter
        from SmartAPI.model.Provenance import Provenance
        from SmartAPI.model.Activity import Activity
        from SmartAPI.model.Offering import Offering

        # get predicate and object
        predicate = str(statement.getPredicate())
        objectNode = statement.getObject()

        # type
        if predicate == PROPERTY.RDF_TYPE:
            self.addType(URIRef(statement.getResource().toString()))
            return

        # sameas
        if predicate == PROPERTY.SAMEAS:
            self.setSameAs(statement.getResource().toString())
            return

        # generatedby
        if predicate == PROPERTY.GENERATEDBY:
            self.setGeneratedBy(Activity.parse(statement.getResource()))
            return

        # generatedat
        if predicate == PROPERTY.GENERATEDAT:
            self.setGeneratedAt(statement.getObject().toPython())
            return

        # provenance
        if predicate == PROPERTY.PROVENANCE:
            self.addProvenance(Provenance.parse(statement.getResource()))
            return

        # offerings
        if predicate == PROPERTY.OFFERS:
            self.addOffering(Offering.parse(statement.getResource()))
            return

        # target
        if predicate == PROPERTY.TARGET:
            self.addTarget(statement.getString())
            return

        # label
        if predicate == PROPERTY.RDFS_LABEL:
            self.setName(statement.getString())
            return

        # comment
        if predicate == PROPERTY.COMMENT:
            self.setDescription(statement.getString())
            return

        # sessionKey
        if predicate == PROPERTY.SESSIONKEY:
            self.setSessionKey(statement.getString())
            return

        # signature
        if predicate == PROPERTY.SIGNATURE:
            self.setSignature(statement.getString())
            return

        # hashcode
        if predicate == PROPERTY.HASHCODE:
            self.setHashCode(statement.getString())
            return

        # encryptionKeyType
        if predicate == PROPERTY.ENCRYPTIONKEYTYPE:
            self.setEncryptionKeyType(statement.getResource().toString())
            return

        # notary
        if predicate == PROPERTY.NOTARY:
            self.setNotary(statement.getResource().toString())
            return

        # parameters
        if predicate == PROPERTY.PARAMETER:
            p = Parameter().parse(statement.getResource())
            self.add(p.getKey(), p.getValues())
            return

        # if literal object
        if isinstance(objectNode, Literal):
            self.add(URIRef(predicate), objectNode.toPython())
            #print 'DEBUG: ', objectNode.datatype, '...', objectNode
            #           if ((objectNode.datatype is not None) and objectNode.datatype == XSD.duration):
            #               self.add(URIRef(predicate), statement.getString())
            #           else:
            #               self.add(URIRef(predicate), objectNode.toPython())
            return

#       if isinstance(objectNode, URIRef):
#           print "parse URI resource ", objectNode
#           self.add(URIRef(predicate), objectNode)
#           return

# if resource
        if isinstance(objectNode, URIRef):
            resource = statement.getResource()

            # first check if resource has a type implemented built-in
            # and parse using that
            klass = Tools().getResourceClass(resource, default=Obj)

            if klass is not None:
                self.add(URIRef(predicate), klass.parse(resource))
            else:
                # None found, resort to Obj (the base class)
                self.add(URIRef(predicate), Obj.parse(resource))

            return

        # Nothing else matches, use BNode as blank default entry
        if isinstance(objectNode, BNode):
            try:
                klass = Tools().getResourceClass(statement.getResource(),
                                                 default=None)
            except:
                klass = None
            if klass is not None:
                self.add(URIRef(predicate),
                         klass.parse(statement.getResource()))
            else:
                self.add(URIRef(predicate), objectNode.toPython())
            return
示例#22
0
    def parse(cls, element):
        '''
        factory method and class method. It takes in Resource as parameter, create a Seas Obj or 
        its subClass object. 
        
        @return: this newly created object, which could be either a real Obj or its subclass Object 
        or a Reference, whose actual content is in multipart message's body part  
        '''

        if isinstance(element, Resource) and Tools.parsedObjs.has_key(
                element.toString()):
            return Tools.parsedObjs.get(element.toString())

        elif isinstance(
                element,
                Resource) and not Tools.parsedObjs.has_key(element.toString()):
            if not element.isAnon():
                obj = cls(element.toString())
            else:
                obj = cls()

            Tools.parsedObjs[element.toString()] = obj

            for i in element.findProperties():
                obj.parseStatement(i)

            # check whether this Obj is a reference
            if obj.isOfType(RESOURCE.MULTIPARTREFERENCE):
                if obj.hasIdentifierUri():
                    if (len(Tools.messagePartsForParse) >
                            0) and (obj.getIdentifierUri()
                                    in Tools.messagePartsForParse):
                        stringRepresentation = Tools.messagePartsForParse[
                            obj.getIdentifierUri()]

                        # if this Obj is EncryptedReference, it will be decrypted later by decrypt() call.
                        if obj.isOfType(RESOURCE.ENCRYPTEDREFERENCE):
                            obj.encryptedStringRepresentation = stringRepresentation
                        else:  # if not encrypted, replace this reference Obj with a new Object,
                            # which is deserialzed from the stringRepresentation, containing actual content.
                            # This happens in the case of digital signature
                            model = Tools().fromString(stringRepresentation,
                                                       SERIALIZATION.TURTLE)

                            # find the root Resource
                            rootRes = Tools().getTopNode(model)[0]

                            # figure out its SMARTAPI Class
                            seasCls = Tools().getResourceClass(rootRes)

                            # recover it to Obj or its subclass Object
                            recoveredObj = seasCls.parse(rootRes)

                            # copy signature, hashcode from reference Obj to recovered Obj
                            recoveredObj.setSignature(obj.getSignature())
                            recoveredObj.setHashCode(obj.getHashCode())

                            recoveredObj.types.remove(
                                URIRef(RESOURCE.REFERENCE))
                            obj = recoveredObj

                        del Tools.messagePartsForParse[obj.getIdentifierUri()]
                    else:
                        raise Exception(
                            '******* ERROR: can not find the encrypted string representation of {}'
                            .format(obj.getIdentifierUri()))
                        #try:
                        #   raise Exception('just to check!!!')
                        #except:
                        #   traceback.print_stack()
                else:
                    raise Exception(
                        '***** ERROR: reference Obj has to be named!!!*******')

            return obj

        return None
示例#23
0
	def fromString(cls, data, serialization):
		m = Tools().fromString(data, serialization)
		res = Tools().getResourceByType(RESOURCE.ALIVEREQUEST, m)
		return cls.parse(res)
		
示例#24
0
 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)
示例#25
0
 def on_mqtt_publish(self, client, userdata, msg):
     n = Tools.parseNotification(msg.payload)
     self._cb(n)
示例#26
0
    def parseStatement(self, statement):
        from SmartAPI.model.Availability import Availability
        from SmartAPI.model.Input import Input
        from SmartAPI.model.Output import Output
        from SmartAPI.model.InterfaceAddress import InterfaceAddress
        from SmartAPI.model.Entity import Entity
        from SmartAPI.model.TimeSeries import TimeSeries
        from SmartAPI.model.TemporalContext import TemporalContext

        predicate = str(statement.getPredicate())

        # method
        if predicate == PROPERTY.METHOD:
            try:
                self.setMethod(statement.getResource().toString())
            except:
                print "Unable to interpret smartapi:method value as literal string."
                traceback.print_exc()
            return

        # input data
        if predicate == PROPERTY.HASINPUT:
            try:
                self.addInput(Input.parse(statement.getResource()))
            except:
                print "Unable to interpret smartapi:hasInput value as resource."
                traceback.print_exc()
            return

        # input reference
        if predicate == PROPERTY.HASREFINPUT:
            try:
                input = Input.parse(statement.getResource())
                input.setInputType(Input.TYPE_REFERENCE)
                self.addInput(input)
            except:
                print "Unable to interpret smartapi:hasRefInput value as resource."
                traceback.print_exc()
            return

        # output
        if predicate == PROPERTY.HASOUTPUT:
            try:
                self.addOutput(Output.parse(statement.getResource()))
            except:
                print "Unable to interpret smartapi:hasOutput value as resource."
                traceback.print_exc()
            return

        # availability
        if predicate == PROPERTY.HASAVAILABILITY:
            try:
                self.addAvailability(
                    Availability.parse(statement.getResource()))
            except:
                print "Unable to interpret smartapi:hasAvailability value as resource."
                traceback.print_exc()
            return

        # data availability
        if predicate == PROPERTY.HASDATAAVAILABILITY:
            try:
                self.addDataAvailability(
                    Availability.parse(statement.getResource()))
            except:
                print "Unable to interpret smartapi:hasDataAvailability value as resource."
                traceback.print_exc()
            return

        # interfaceaddress
        if predicate == PROPERTY.INTERFACE:
            try:
                self.addInterface(
                    InterfaceAddress.parse(statement.getResource()))
            except:
                print "Unable to interpret smartapi:interface value as resource."
                traceback.print_exc()
            return

        # entity
        if predicate == PROPERTY.ENTITY:
            try:
                self.addEntity(Tools.fromResourceAsObj(
                    statement.getResource()))
            except:
                print "Unable to interpret smartapi:entity value (of type smartapi:Entity) as resource."
                traceback.print_exc()
            return

        # temporalcontext
        if predicate == PROPERTY.TEMPORALCONTEXT:
            try:
                self.setTemporalContext(TemporalContext().parse(
                    statement.getResource()))
            except:
                print "Unable to interpret smartapi:temporalContext value as resource."
                traceback.print_exc()
            return

        # timeserie
        if predicate == PROPERTY.TIMESERIES:
            try:
                self.addTimeSerie(TimeSeries().parse(statement.getResource()))
            except:
                print "Unable to interpret smartapi:timeSeries value as resource."
                traceback.print_exc()
            return

        # pass on to Object
        super(Activity, self).parseStatement(statement)
示例#27
0
 def turtleFormat(self):
     return Tools.toString(self)
 def generateSearchMessage(self):
     request = RequestFactory().create(self.identity)
     request.setMethod(RESOURCE.READ)
     request.addEntity(self.entity)
     return Tools().toString(request, self.serialization)
示例#29
0
 def asTime(self):
     try:
         return Tools().stringToDate(str(self.variant)).time()
     except:
         return None