Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/creactistore/_templates/lib/semanticxo/datastore.py~
blob: 4c83d6f0a381cb42adecc0560f1db143dba7ae2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
'''
Created on 24 Sep 2011

@author: cgueret
'''
# python import
import httplib, time

# rdflib import
from rdflib_ import ConjunctiveGraph, RDF, URIRef, Namespace, Literal

# semanticxo import
from semanticxo.sparql import SPARQL

OLPC = Namespace("http://example.org/")
OLPC_TERMS = Namespace("http://example.org/terms#")

_QUERY_INT_KEY = ['timestamp', 'filesize', 'creation_time']

class TripleStore(object):
    '''
    The TripleStore is a generic object interface with a triple store
    '''
    
    def __init__(self, hostname=None):
        '''
        Constructor of the TripleStore
        if an hostname is indicated, query the triple store of that machine
        instead of the one at localhost
        '''
        if hostname == None:
            hostname = 'localhost'
        self.store_url = '%s:8080' % hostname
        self.device_uid = 'ABC1234567890' #TODO find how to get the serial number


    def _get_resource(self, uid):
        '''
        Return the URI associated to a particular UID
        '''
        return URIRef(OLPC['resource/%s' % uid])


    def get_uids(self):
        '''
        Return all the UIDs of the DSObjects stored in that store
        '''
        query = """
        SELECT ?uid WHERE {
            ?entry <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <%s>.
            ?entry <%s> ?uid.
        }
        """ % (OLPC_TERMS['DSObject'], OLPC_TERMS['uid'])
        uids = []
        sparql = SPARQL(self.store_url)
        for result in sparql.execute_select(query):
            uids.append(result['uid'])
        return uids

    
    def get_object(self, uid, properties=None):
        '''
        Get a specific object associated to this UID
        '''
        metadata = {}
        query = 'SELECT ?p ?o WHERE { <%s> ?p ?o. }' % self._get_resource(uid)
        sparql = SPARQL(self.store_url)
        for result in sparql.execute_select(query):
            if result['p'].startswith(OLPC_TERMS):
                key = result['p'].split(OLPC_TERMS)[1]
                if key in _QUERY_INT_KEY:
                    metadata[key] = int(result['o'])
                else:
                    metadata[key] = result['o']
                    
        # HACK: This is expected to be always present
        if 'creation_time' not in metadata:
            metadata['creation_time'] = int(time.time())

        return metadata

    
    def store_object(self, uid, metadata):
        '''
        Store an object defined by a uid and its associated metadata
        '''
        metadata['uid'] = uid
        
        # Preprocess the metadata
        props = {}
        for key, value in metadata.items():

            # Hack to support activities that still pass properties named as
            # for example title:text.
            if ':' in key:
                key = key.split(':', 1)[0]

            # Re-encode strings
            if isinstance(value, unicode):
                value = value.encode('utf-8')
            elif not isinstance(value, basestring):
                value = str(value)
            
            # Save new binding
            props[key] = value

        # Compose and save the graph
        graph = ConjunctiveGraph()
        resource = self._get_resource(uid)
        graph.add((resource, RDF.type, OLPC_TERMS['DSObject']))
        for key, value in props.items():
            if isinstance(key, basestring) and isinstance(value, basestring):
                key = OLPC_TERMS[key]
                try:
                    value = Literal(value)
                    graph.add((resource, key, value))
                except:
                    pass
        headers = { 'Accept' : '*/*', 'Content-Type': 'application/rdf+xml' }
        conn = httplib.HTTPConnection(self.store_url)
        conn.request("PUT", "/data/%s" % resource, body=graph.serialize(), headers=headers)
        conn.getresponse()
        conn.close()