[z3-checkins] r13846 - in z3/zemantic/trunk/src/zemantic: . browser
browser/jars index lib tests
michelp at codespeak.net
michelp at codespeak.net
Sat Jun 25 13:35:20 CEST 2005
Author: michelp
Date: Sat Jun 25 13:35:17 2005
New Revision: 13846
Added:
z3/zemantic/trunk/src/zemantic/adapters.py
z3/zemantic/trunk/src/zemantic/graph.py
Removed:
z3/zemantic/trunk/src/zemantic/browser/contents.py
z3/zemantic/trunk/src/zemantic/browser/istore_view.pt
z3/zemantic/trunk/src/zemantic/browser/jars/
z3/zemantic/trunk/src/zemantic/browser/ont_view.pt
z3/zemantic/trunk/src/zemantic/browser/tstore_view.pt
z3/zemantic/trunk/src/zemantic/browser/viz_view.pt
z3/zemantic/trunk/src/zemantic/cataloger.py
z3/zemantic/trunk/src/zemantic/events.py
z3/zemantic/trunk/src/zemantic/expressions.py
z3/zemantic/trunk/src/zemantic/index/
z3/zemantic/trunk/src/zemantic/informationstore.py
z3/zemantic/trunk/src/zemantic/lib/
z3/zemantic/trunk/src/zemantic/query.py
z3/zemantic/trunk/src/zemantic/resources.py
z3/zemantic/trunk/src/zemantic/result.py
z3/zemantic/trunk/src/zemantic/tests/test1.rdf
z3/zemantic/trunk/src/zemantic/tests/test_istore.py
z3/zemantic/trunk/src/zemantic/tests/test_query.py
z3/zemantic/trunk/src/zemantic/triplestore.py
z3/zemantic/trunk/src/zemantic/utils.py
Modified:
z3/zemantic/trunk/src/zemantic/__init__.py
z3/zemantic/trunk/src/zemantic/browser/__init__.py
z3/zemantic/trunk/src/zemantic/browser/configure.zcml
z3/zemantic/trunk/src/zemantic/configure.zcml
z3/zemantic/trunk/src/zemantic/interfaces.py
z3/zemantic/trunk/src/zemantic/public.py
Log:
just for Paul
Modified: z3/zemantic/trunk/src/zemantic/__init__.py
==============================================================================
--- z3/zemantic/trunk/src/zemantic/__init__.py (original)
+++ z3/zemantic/trunk/src/zemantic/__init__.py Sat Jun 25 13:35:17 2005
@@ -12,14 +12,3 @@
#
##############################################################################
-# Handy query constants and classes
-
-Any = None
-
-from rdflib.URIRef import URIRef
-from rdflib.BNode import BNode
-from rdflib.Literal import Literal
-
-from query import Query, UnionChain, IntersectionChain
-
-from expressions import ZemanticExpr
Added: z3/zemantic/trunk/src/zemantic/adapters.py
==============================================================================
--- (empty file)
+++ z3/zemantic/trunk/src/zemantic/adapters.py Sat Jun 25 13:35:17 2005
@@ -0,0 +1,44 @@
+
+
+from zope.interface import implements
+from zope.i18nmessageid import MessageIDFactory
+from interfaces import IRDF
+
+_ = MessageIDFactory('zemantic')
+
+class XMLtoRDF(object):
+ """ Adapts RDF/XML to IRDF """
+
+ implements(IRDF)
+
+ def __init__(self, context):
+ self.context = context
+
+ def relations(self):
+ pass
+
+
+class NTtoRDF(object):
+ """ Adapts RDF/NT to IRDF """
+
+ implements(IRDF)
+
+ def __init__(self, context):
+ self.context = context
+
+ def relations(self):
+ pass
+
+
+class DCtoRDF(object):
+
+ """ Adapts IDublinCore to IRDF """
+
+ implements(IRDF)
+
+ def __init__(self, context):
+ self.context = context
+
+ def relations(self):
+ pass
+
Modified: z3/zemantic/trunk/src/zemantic/browser/__init__.py
==============================================================================
--- z3/zemantic/trunk/src/zemantic/browser/__init__.py (original)
+++ z3/zemantic/trunk/src/zemantic/browser/__init__.py Sat Jun 25 13:35:17 2005
@@ -11,234 +11,3 @@
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
-
-
-__rdf_description__ = '''\
-<rdf:RDF xmlns="http://web.resource.org/cc/"
-xmlns:dc="http://purl.org/dc/elements/1.1/"
-xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
-<Work rdf:about="http://zemantic.org/zemantic/browser.py"
- dc:title="zemantic.browser"
- dc:date="2005"
- dc:description="Browser views for z3.">
- <dc:creator>
- <Agent dc:title="Michel Pelletier"/>
- </dc:creator>
- <dc:rights>
- <Agent dc:title="Michel Pelletier"/>
- </dc:rights>
- <license rdf:resource="http://zemantic.org/LICENSE.txt/"/>
-</Work>
-</rdf:RDF>
-'''
-
-Any = None
-
-from zope.i18nmessageid import MessageIDFactory
-from zope.app import zapi
-from zope.security.proxy import removeSecurityProxy
-
-from rdflib.URIRef import URIRef
-from rdflib.BNode import BNode
-from rdflib.Literal import Literal
-from rdflib.Identifier import Identifier
-from rdflib.exceptions import ParserError
-
-from zemantic.utils import TripleStoreToDotAdapter
-from zemantic.query import Query
-import popen2
-import urllib, os, time
-from xml import sax
-from tempfile import NamedTemporaryFile
-from StringIO import StringIO
-
-from zemantic.triplestore import TripleStore
-from zemantic.resources import FileResource, DirectoryResource
-from zemantic.result import ResultSet
-
-_ = MessageIDFactory('zemantic')
-
-class TripleStoreView:
-
- def shorty(self, s):
- """ dumb ui method """
- if len(s) > 30:
- return s[:15]+'...'+s[-15:]
- return s
-
- def n3(self, obj):
- return obj.n3()
-
- def uniquePredicatesView(self):
- r = []
- for i in self.context.uniquePredicates():
- r.append(i)
- return r
-
- def clear(self):
- self.context.clear()
-
- def query(self, subject, predicate, object):
- q = Query(subject, predicate, object)
-
- return self.context.query(q)
-
- def queryRDF(self, subject, predicate, object):
- if subject in ('Any', 'None'):
- subject = Any
- if predicate in ('Any', 'None'):
- predicate = Any
- if object in ('Any', 'None'):
- object = Any
- q = Query(subject, predicate, object)
- self.request.response.setHeader('content-type', 'text/xml')
- return ResultSet(self.context.query(q)).rdfxml()
-
- def quote(self, str):
- return urllib.quote(str)
-
- def genSVG(self):
- x = TripleStoreToDotAdapter(self.context, "RDF Graph")
- d = x.toDot()
- i = NamedTemporaryFile()
- i.write(d)
- i.flush()
- self.request.response.setHeader('content-type', 'image/svg+xml')
- return getoutput('dot -Tsvg %s' % i.name)
-
- def genJPG(self):
- x = TripleStoreToDotAdapter(self.context, "RDF Graph")
- d = x.toDot()
- i = NamedTemporaryFile()
- o = NamedTemporaryFile()
- i.write(d)
- i.flush()
- getoutput('dot -Tjpg %s -o %s' % (i.name, o.name))
- f = open(o.name)
- self.request.response.setHeader('content-type', 'image/jpg')
- return f.read()
-
- def genDOT(self):
- x = TripleStoreToDotAdapter(self.context, "RDF Graph")
- return x.toDot()
-
- def addURL(self):
- url = self.request.form['add_url']
- f = urllib.urlopen(url)
- self.context.parse(f)
- self.request.response.redirect('zemantic.html')
-
- def clear(self):
- self.context.clear()
- self.request.response.redirect('zemantic.html')
-
-class InformationStoreView:
-
- def loadstuff(self):
- print 'getting directory'
- dircon = 'http://www.schemaweb.info/DirectoryMeta.aspx'
- directory = urllib.urlopen(dircon)
- print 'got directory'
- dircon = URIRef(dircon)
- self.context.parse(directory, dircon)
- n = 0
- import pdb; pdb.set_trace()
- q = Query(Any, u'<http://www.schemaweb.info/schemas/meta/rdf/rdf-meta>', Any, dircon)
- for result in self.context.query(q):
- if result is not None:
- time.sleep(1)
- try:
- print 'fetching %s' % result.object
- f = urllib.urlopen(removeSecurityProxy(result.object))
- y = TripleStore()
- y.parse(f)
- q = Query(Any, u'<http://www.schemaweb.info/schemas/meta/rdf/namespace>', Any)
- for result2 in y.query(q):
-
- u2 = 'http://www.schemaweb.info/webservices/rest/GetRDF.aspx?namespace=%s' % urllib.quote_plus(removeSecurityProxy(result2.object))
- print 'fetching %s' % u2
- f = urllib.urlopen(removeSecurityProxy(u2))
- print 'parsing'
- self.context.parse(f, URIRef(removeSecurityProxy(result2.object)))
- get_transaction().commit()
- except (LookupError, sax.SAXParseException, ParserError):
- print "Can't load %s" % result.object
-
- self.request.response.redirect('contents.html')
-
- def getClassNames(self):
- for name, child in self.context.items():
- for klass in self.child.classes.keys():
- yield klass
-
- def getPropertyNames(self):
- for name, child in self.context.items():
- for prop in self.child.properties.keys():
- yield prop
-
- def getClassLen(self):
- return 0 # too expensive
- s = 0
- for name, child in self.context.items():
- s += len(child.classes)
- return s
-
- def getPropertyLen(self):
- return 0 # too expensive
- s = 0
- for name, child in self.context.items():
- s += len(child.properties)
- return s
-
- def getUniqueSubjectLen(self):
- s = 0
- for name, child in self.context.items():
- s += len(list(child.uniqueSubjects()))
- return s
-
- def getUniquePredicateLen(self):
- s = 0
- for name, child in self.context.items():
- s += len(list(child.uniquePredicates()))
- return s
-
- def getUniqueObjectLen(self):
- s = 0
- for name, child in self.context.items():
- s += len(list(child.uniqueObjects()))
- return s
-
- def getTotalTriples(self):
- s = 0
- for context in self.context.getContexts():
- s += len(context)
- return s
-
- def getTotalContexts(self):
- return len(self.context)
-
-
-from zope.app.container.browser.contents import Contents
-
-
-# Get the output from a shell command into a string.
-# The exit status is ignored; a trailing newline is stripped.
-# Assume the command will work with '{ ... ; } 2>&1' around it..
-#
-def getoutput(cmd):
- """Return output (stdout or stderr) of executing cmd in a shell."""
- return getstatusoutput(cmd)[1]
-
-
-# Ditto but preserving the exit status.
-# Returns a pair (sts, output)
-#
-def getstatusoutput(cmd):
- """Return (status, output) of executing cmd in a shell."""
- import os
- sout = os.popen(cmd, 'r')
- text = sout.read()
- sts = sout.close()
- if sts is None: sts = 0
- if text[-1:] == '\n': text = text[:-1]
- return sts, text
Modified: z3/zemantic/trunk/src/zemantic/browser/configure.zcml
==============================================================================
--- z3/zemantic/trunk/src/zemantic/browser/configure.zcml (original)
+++ z3/zemantic/trunk/src/zemantic/browser/configure.zcml Sat Jun 25 13:35:17 2005
@@ -4,131 +4,10 @@
i18n_domain="zemantic">
<browser:addMenuItem
- class="zemantic.triplestore.TripleStore"
- description="A Semantic Web Triple Store"
- title="Triple Store"
+ class="zemantic.graph.GraphUtility"
+ description="Utility for rdflib Graphs"
+ title="RDF Graph"
permission="zope.ManageContent"
/>
-
- <browser:addMenuItem
- class="zemantic.informationstore.InformationStore"
- description="A Semantic Web Information Store"
- title="Information Store"
- permission="zope.ManageContent"
- />
-
- <browser:page
- for="zemantic.interfaces.ITripleStore"
- name="zemantic.html"
- class=".TripleStoreView"
- template="tstore_view.pt"
- menu="zmi_views"
- title="Triple Store"
- permission="zope.ManageContent"
- />
-
-
-<!--
- <browser:page
- for="zemantic.interfaces.ITripleStore"
- name="graph.svg"
- class=".TripleStoreView"
- attribute="genSVG"
- permission="zope.ManageContent"
- />
-
-
- <browser:page
- for="zemantic.interfaces.ITripleStore"
- name="graph.jpg"
- class=".TripleStoreView"
- attribute="genJPG"
- permission="zope.ManageContent"
- />
-
-
- <browser:page
- for="zemantic.interfaces.ITripleStore"
- name="graph.dot"
- class=".TripleStoreView"
- attribute="genDOT"
- permission="zope.ManageContent"
- />
-
--->
-
- <browser:page
- for="zemantic.interfaces.ITripleStore"
- name="queryRDF"
- class="zemantic.browser.TripleStoreView"
- attribute="queryRDF"
- permission="zope.ManageContent"
- />
-
- <browser:page
- for="zemantic.interfaces.ITripleStore"
- name="addURL"
- class=".TripleStoreView"
- attribute="addURL"
- permission="zope.ManageContent"
- />
-
- <browser:page
- for="zemantic.interfaces.ITripleStore"
- name="clear"
- class=".TripleStoreView"
- attribute="clear"
- permission="zope.ManageContent"
- />
-
-
- <browser:page
- for="zemantic.interfaces.ITripleStore"
- name="commonTasks"
- class="zemantic.triplestore.TripleStore"
- template="commontasks.pt"
- permission="zope.ManageContent"
- />
-
-<!--
-
- < browser:page
- for="zemantic.interfaces.ITripleStore"
- name="viz.html"
- class=".TripleStoreView"
- template="viz_view.pt"
- menu="zmi_views"
- title="Visualize"
- permission="zope.ManageContent"
- />
-
--->
-
-
- <browser:page
- for="zemantic.interfaces.IInformationStore"
- name="loadStuff"
- class=".InformationStoreView"
- attribute="loadstuff"
- permission="zope.ManageContent"
- />
-
-
- <browser:page
- for="zemantic.interfaces.IInformationStore"
- name="information.html"
- class=".InformationStoreView"
- template="istore_view.pt"
- menu="zmi_views"
- title="InformationStore"
- permission="zope.ManageContent"
- />
-
- <browser:resourceDirectory
- name="lib"
- permission="zope.ManageContent"
- directory="jars/"
- />
-
</configure>
\ No newline at end of file
Deleted: /z3/zemantic/trunk/src/zemantic/browser/contents.py
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/browser/contents.py Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,392 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""View Class for the Container's Contents view.
-
-$Id: contents.py 27409 2004-09-02 07:05:38Z pruggera $
-"""
-__docformat__ = 'restructuredtext'
-
-from zope.exceptions import NotFoundError
-from zope.security.interfaces import Unauthorized
-from zope.security import checkPermission
-
-from zope.app import zapi
-from zope.app.size.interfaces import ISized
-from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile
-from zope.app.publisher.browser import BrowserView
-from zope.app.i18n import ZopeMessageIDFactory as _
-from zope.app.dublincore.interfaces import IZopeDublinCore
-from zope.app.dublincore.interfaces import IDCDescriptiveProperties
-from zope.app.copypastemove.interfaces import IPrincipalClipboard
-from zope.app.copypastemove.interfaces import IObjectCopier
-from zope.app.copypastemove.interfaces import IObjectMover
-from zope.app.copypastemove import rename
-
-from zope.app.container.browser.adding import BasicAdding
-from zope.app.container.interfaces import IContainer
-from zope.app.container.interfaces import IContainerNamesContainer
-
-class Contents(BrowserView):
-
- __used_for__ = IContainer
-
- error = ''
- message = ''
- normalButtons = False
- specialButtons = False
- supportsRename = False
-
- def listContentInfo(self):
- request = self.request
-
- if "container_cancel_button" in request:
- if "type_name" in request:
- del request.form['type_name']
- if "rename_ids" in request and "new_value" in request:
- del request.form['rename_ids']
- if "retitle_id" in request and "new_value" in request:
- del request.form['retitle_id']
-
- return self._normalListContentsInfo()
-
- elif "container_rename_button" in request and not request.get("ids"):
- self.error = _("You didn't specify any ids to rename.")
- elif "container_add_button" in request:
- if "single_type_name" in request \
- and "single_new_value" in request:
- request.form['type_name'] = request['single_type_name']
- request.form['new_value'] = request['single_new_value']
- self.addObject()
- elif 'single_type_name' in request \
- and 'single_new_value' not in request:
- request.form['type_name'] = request['single_type_name']
- request.form['new_value'] = ""
- self.addObject()
- elif "type_name" in request and "new_value" in request:
- self.addObject()
- elif "rename_ids" in request and "new_value" in request:
- self.renameObjects()
- elif "retitle_id" in request and "new_value" in request:
- self.changeTitle()
- elif "container_cut_button" in request:
- self.cutObjects()
- elif "container_copy_button" in request:
- self.copyObjects()
- elif "container_paste_button" in request:
- self.pasteObjects()
- elif "container_delete_button" in request:
- self.removeObjects()
- else:
- return self._normalListContentsInfo()
-
- if self.error:
- return self._normalListContentsInfo()
-
- status = request.response.getStatus()
- if status not in (302, 303):
- # Only redirect if nothing else has
- request.response.redirect(request.URL)
- return ()
-
- def normalListContentInfo(self):
- return self._normalListContentsInfo()
-
- def _normalListContentsInfo(self):
- request = self.request
-
- self.specialButtons = (
- 'type_name' in request or
- 'rename_ids' in request or
- ('container_rename_button' in request
- and request.get("ids")) or
- 'retitle_id' in request
- )
- self.normalButtons = not self.specialButtons
-
- info = map(self._extractContentInfo, self.context.items())
-
- self.supportsCut = info
- self.supportsCopy = info
- self.supportsPaste = self.pasteable()
- self.supportsRename = (
- self.supportsCut and
- not IContainerNamesContainer.providedBy(self.context)
- )
-
- return info
-
-
- def _extractContentInfo(self, item):
- request = self.request
-
-
- rename_ids = {}
- if "container_rename_button" in request:
- for rename_id in request.get('ids', ()):
- rename_ids[rename_id] = rename_id
- elif "rename_ids" in request:
- for rename_id in request.get('rename_ids', ()):
- rename_ids[rename_id] = rename_id
-
-
- retitle_id = request.get('retitle_id')
-
- id, obj = item
- info = {}
- info['id'] = info['cb_id'] = id
- info['object'] = obj
-
- info['url'] = id
- info['rename'] = rename_ids.get(id)
- info['retitle'] = id == retitle_id
-
-
- zmi_icon = zapi.queryView(obj, 'zmi_icon', self.request)
- if zmi_icon is None:
- info['icon'] = None
- else:
- info['icon'] = zmi_icon()
-
- dc = IZopeDublinCore(obj, None)
- if dc is not None:
- info['retitleable'] = checkPermission(
- 'zope.app.dublincore.change', dc) and id != retitle_id
- info['plaintitle'] = 0
-
- title = self.safe_getattr(dc, 'title', None)
- if title:
- info['title'] = title
-
- formatter = self.request.locale.dates.getFormatter(
- 'dateTime', 'short')
-
- created = self.safe_getattr(dc, 'created', None)
- if created is not None:
- info['created'] = formatter.format(created)
-
- modified = self.safe_getattr(dc, 'modified', None)
- if modified is not None:
- info['modified'] = formatter.format(modified)
- else:
- info['retitleable'] = 0
- info['plaintitle'] = 1
-
-
- sized_adapter = ISized(obj, None)
- if sized_adapter is not None:
- info['size'] = sized_adapter
- return info
-
- def safe_getattr(self, obj, attr, default):
- """Attempts to read the attr, returning default if Unauthorized."""
- try:
- return getattr(obj, attr, default)
- except Unauthorized:
- return default
-
- def renameObjects(self):
- """Given a sequence of tuples of old, new ids we rename"""
- request = self.request
- ids = request.get("rename_ids")
- newids = request.get("new_value")
-
- for oldid, newid in map(None, ids, newids):
- if newid != oldid:
- rename(self.context, oldid, newid)
-
- def changeTitle(self):
- """Given a sequence of tuples of old, new ids we rename"""
- request = self.request
- id = request.get("retitle_id")
- new = request.get("new_value")
-
- item = self.context[id]
- dc = IDCDescriptiveProperties(item)
- dc.title = new
-
- def addObject(self):
- request = self.request
- if IContainerNamesContainer.providedBy(self.context):
- new = ""
- else:
- new = request["new_value"]
-
- adding = zapi.queryView(self.context, "+", request)
- if adding is None:
- adding = BasicAdding(self.context, request)
- else:
- # Set up context so that the adding can build a url
- # if the type name names a view.
- # Note that we can't so this for the "adding is None" case
- # above, because there is no "+" view.
- adding.__parent__ = self.context
- adding.__name__ = '+'
-
- adding.action(request['type_name'], new)
-
- def removeObjects(self):
- """Remove objects specified in a list of object ids"""
- request = self.request
- ids = request.get('ids')
- if not ids:
- self.error = _("You didn't specify any ids to remove.")
- return
-
- container = self.context
- for id in ids:
- del container[id]
-
- def copyObjects(self):
- """Copy objects specified in a list of object ids"""
- request = self.request
- ids = request.get('ids')
- if not ids:
- self.error = _("You didn't specify any ids to copy.")
- return
-
- container_path = zapi.getPath(self.context)
-
- user = self.request.principal
- annotationsvc = zapi.getService('PrincipalAnnotation')
- annotations = annotationsvc.getAnnotations(user)
- clipboard = IPrincipalClipboard(annotations)
- clipboard.clearContents()
- items = []
- for id in ids:
- items.append(zapi.joinPath(container_path, id))
- clipboard.addItems('copy', items)
-
- def cutObjects(self):
- """move objects specified in a list of object ids"""
- request = self.request
- ids = request.get('ids')
- if not ids:
- self.error = _("You didn't specify any ids to cut.")
- return
-
- container_path = zapi.getPath(self.context)
-
- user = self.request.principal
- annotationsvc = zapi.getService('PrincipalAnnotation')
- annotations = annotationsvc.getAnnotations(user)
- clipboard = IPrincipalClipboard(annotations)
- clipboard.clearContents()
- items = []
- for id in ids:
- items.append(zapi.joinPath(container_path, id))
- clipboard.addItems('cut', items)
-
-
- def pasteable(self):
- """Decide if there is anything to paste
- """
- target = self.context
- user = self.request.principal
- annotationsvc = zapi.getService('PrincipalAnnotation')
- annotations = annotationsvc.getAnnotations(user)
- clipboard = IPrincipalClipboard(annotations)
- items = clipboard.getContents()
- for item in items:
- try:
- obj = zapi.traverse(target, item['target'])
- except NotFoundError:
- pass
- else:
- if item['action'] == 'cut':
- mover = IObjectMover(obj)
- if not mover.moveableTo(target):
- return False
- elif item['action'] == 'copy':
- copier = IObjectCopier(obj)
- if not copier.copyableTo(target):
- return False
- else:
- raise
-
- return True
-
-
- def pasteObjects(self):
- """Paste ojects in the user clipboard to the container
- """
- target = self.context
- user = self.request.principal
- annotationsvc = zapi.getService('PrincipalAnnotation')
- annotations = annotationsvc.getAnnotations(user)
- clipboard = IPrincipalClipboard(annotations)
- items = clipboard.getContents()
- moved = False
- for item in items:
- try:
- obj = zapi.traverse(target, item['target'])
- except NotFoundError:
- pass
- else:
- if item['action'] == 'cut':
- mover = IObjectMover(obj)
- mover.moveTo(target)
- moved = True
- elif item['action'] == 'copy':
- copier = IObjectCopier(obj)
- copier.copyTo(target)
- else:
- raise
-
- if moved:
- # Clear the clipboard if we do a move, but not if we only do a copy
- clipboard.clearContents()
-
-
- def hasClipboardContents(self):
- """ interogates the `PrinicipalAnnotation` to see if
- clipboard contents exist """
-
- if not self.supportsPaste:
- return False
-
- user = self.request.principal
-
- annotationsvc = zapi.getService('PrincipalAnnotation')
- annotations = annotationsvc.getAnnotations(user)
-
- # touch at least one item to in clipboard confirm contents
- clipboard = IPrincipalClipboard(annotations)
- items = clipboard.getContents()
- for item in items:
- try:
- zapi.traverse(self.context, item['target'])
- except NotFoundError:
- pass
- else:
- return True
-
- return False
-
- contents = ViewPageTemplateFile('contents.pt')
- contentsMacros = contents
-
- _index = ViewPageTemplateFile('index.pt')
-
- def index(self):
- if 'index.html' in self.context:
- self.request.response.redirect('index.html')
- return ''
-
- return self._index()
-
-class JustContents(Contents):
- """Like Contents, but does't delegate to item named index.html"""
-
- def index(self):
- return self._index()
Deleted: /z3/zemantic/trunk/src/zemantic/browser/istore_view.pt
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/browser/istore_view.pt Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,30 +0,0 @@
-<html metal:use-macro="context/@@standard_macros/view">
-<body>pp
-
- <p>Schemata</p>
-
- <p id="error"
- tal:condition="request/error | nothing"
- tal:content="request/error" />
-
- <p id="message"
- tal:condition="request/message | nothing"
- tal:content="request/message" />
-
- <div metal:fill-slot="body">
-
- <p>Total Triples <span tal:content="view/getTotalTriples"/></p>
- <p>Total Contexts <span tal:content="view/getTotalContexts"/></p>
-
- <p>Clicking "Load Stuff" will snarf down 200+ ontologies from <a
- href="http://schemaweb.info">schemaweb.info</a>. This could take
- several minutes to load the 100K+ triples.</p>
-
- <form action="./@@loadStuff">
- <input type="submit" name="loadStuff" value="Load Stuff">
- </form>
-
- </div>
-
-</body>
-</html>
Deleted: /z3/zemantic/trunk/src/zemantic/browser/ont_view.pt
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/browser/ont_view.pt Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,28 +0,0 @@
-<html metal:use-macro="context/@@standard_macros/view">
-<body>
-
- <p>Schemata</p>
-
- <p id="error"
- tal:condition="request/error | nothing"
- tal:content="request/error" />
-
- <p id="message"
- tal:condition="request/message | nothing"
- tal:content="request/message" />
-
-
- <div metal:fill-slot="body">
-
- <p>Total Triples <span tal:content="view/getTotalTriples"/></p>
- <p>Unique Subjects <span tal:content="view/getUniqueSubjectLen"/></p>
- <p>Unique Predicates <span tal:content="view/getUniquePredicateLen"/></p>
- <p>Unique Objects <span tal:content="view/getUniqueObjectLen"/></p>
-
- <p tal:condition="view/getClassLen">Classes <span tal:content="view/getClassLen"/></p>
- <p tal:condition="view/getPropertyLen">Properties <span tal:content="view/getPropertyLen"/></p>
-
- </div>
-
-</body>
-</html>
Deleted: /z3/zemantic/trunk/src/zemantic/browser/tstore_view.pt
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/browser/tstore_view.pt Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,73 +0,0 @@
-<html metal:use-macro="context/@@standard_macros/view">
-<body>
-
- <p>Zemantic</p>
-
- <p id="error"
- tal:condition="request/error | nothing"
- tal:content="request/error" />
-
- <p id="message"
- tal:condition="request/message | nothing"
- tal:content="request/message" />
-
-
- <div metal:fill-slot="body"
- tal:define="subject request/subject | nothing;
- predicate request/predicate | nothing;
- object request/object | nothing;
-
- subarg python: subject and '&subject=' + view.quote(subject) or '';
- predarg python: predicate and '&predicate=' + view.quote(predicate) or '';
- objarg python: object and '&object=' + view.quote(object) or '';
- clear request/clear | nothing;
- cleared python: clear and view.clear();
- reset python: subject or predicate or object;">
-
- <p>Query Zemantic with the following terms:
-
- <p tal:condition="subject"><b>Current Subject Term</b>: <span tal:content="subject"/> </p>
- <p tal:condition="predicate"><b>Current Predicate Term</b>: <span tal:content="predicate"/> </p>
- <p tal:condition="object"><b>Current Object Term</b>: <b tal:content="object"/></p>
-
- <form action="." method="get">
- <select class="form-element" name=":action"
- onChange="location.href='./zemantic.html?predicate='+this.options[this.selectedIndex].value">
- <option value="." disabled>Select Predicate...</option>
- <option tal:repeat="item context/uniquePredicates"
- tal:attributes="value python: view.quote(item.n3())"
- tal:content="item/n3">Select predicate...</option>
- </select>
- </form>
- <form action="./zemantic.html" method="get">
- <input type="text" name="object"/>
- </form>
- <p tal:condition="reset"><a href="./zemantic.html">Click here to reset query</a></p>
-
- <table border>
- <tr>
- <th tal:content="python: subject or 'Subject'">Subject</th>
- <th tal:content="python: predicate or 'Predicate'">Predicate</th>
- <th tal:content="python: object or 'Object'">Object</th>
- </tr>
- <div tal:repeat="result python: view.query(subject, predicate, object)" >
- <tr tal:define="subject python: result.subject.n3();
- predicate python: result.predicate.n3();
- object python: result.object.n3();
- sq python: view.quote(subject);
- pq python: view.quote(predicate);
- oq python: view.quote(object);"
->
-
- <td><a tal:content="python: view.shorty(subject)"
- tal:attributes="href string: ./zemantic.html?subject=$sq$predarg$objarg">subject</a></td>
- <td><a tal:content="python: view.shorty(predicate)"
- tal:attributes="href string: ./zemantic.html?predicate=$pq$subarg$objarg">predicate</a></td>
- <td><a tal:content="python: view.shorty(object)"
- tal:attributes="href string: ./zemantic.html?object=$oq$subarg$predarg">object</a></td>
- </tr>
- </div>
- </table>
-</div>
-</body>
-</html>
Deleted: /z3/zemantic/trunk/src/zemantic/browser/viz_view.pt
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/browser/viz_view.pt Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,28 +0,0 @@
-<html metal:use-macro="context/@@standard_macros/view">
-<body>
- <p id="error"
- tal:condition="request/error | nothing"
- tal:content="request/error" />
- <p id="message"
- tal:condition="request/message | nothing"
- tal:content="request/message" />
- <div metal:fill-slot="body"
- tal:define="subject request/subject | nothing;
- predicate request/predicate | nothing;
- obj request/obj | nothing;
-
- subarg python: subject and '&subject=' + subject or '';
- predarg python: predicate and '&predicate=' + predicate or '';
- objarg python: obj and '&obj=' + obj or '';
- clear request/clear | nothing;
- cleared python: clear and view.clear();
-
- reset python: subject or predicate or obj;">
-
-
- <p>Download the catalog graph in <a href="./@@graph.dot">DOT Format</a>.</p>
- <p>Download the catalog graph in <a href="./@@graph.svg">SVG</a>.</p>
- <p>Download the catalog graph in <a href="./@@graph.jpg">JPG</a>.</p>
-</div>
-</body>
-</html>
Deleted: /z3/zemantic/trunk/src/zemantic/cataloger.py
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/cataloger.py Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,84 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2004-1005 Michel Pelletier
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-
-
-__rdf_description__ = '''\
-<rdf:RDF xmlns="http://web.resource.org/cc/"
-xmlns:dc="http://purl.org/dc/elements/1.1/"
-xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
-<Work rdf:about="http://zemantic.org/zemantic/cataloger.py"
- dc:title="zemantic.cataloger"
- dc:date="2005"
- dc:description="Sample auto-cataloging code. See examples/library/cataloger.py.">
- <dc:creator>
- <Agent dc:title="Michel Pelletier"/>
- </dc:creator>
- <dc:rights>
- <Agent dc:title="Michel Pelletier"/>
- </dc:rights>
- <license rdf:resource="http://zemantic.org/LICENSE.txt/"/>
-</Work>
-</rdf:RDF>
-'''
-
-from zope.app import zapi
-from zope.app.container.interfaces import IObjectAddedEvent
-from zope.app.container.interfaces import IObjectRemovedEvent
-from zope.app.event.interfaces import IObjectModifiedEvent
-from interfaces import IRDFXML, ITripleStore
-
-from StringIO import StringIO
-
-# This is an example cataloger that hooks Zope 3 container events.
-# Your application should create their own catalogers for their
-# content types so that they can exactly control cataloging. See
-# examples/library/cataloger.py
-
-class Cataloger(object):
- """Class to handle automatic cataloging/uncataloging on container
- events."""
-
- def __init__(self, iface):
- self._iface = iface
-
- def __call__(self, event):
- """Called by the event system."""
- if self._iface.providedBy(event.object):
-
- if IObjectAddedEvent.providedBy(event):
- self.handleAdded(event.object)
-
- elif IObjectModifiedEvent.providedBy(event):
- self.handleModified(event.object)
-
- elif IObjectRemovedEvent.providedBy(event):
- self.handleRemoved(event.object)
-
- def handleAdded(self, object):
- c = zapi.queryUtility(ITripleStore)
- if c is not None:
- pass # add your logic here
-
- def handleModified(self, object):
- c = zapi.queryUtility(ITripleStore)
- if c is not None:
- pass # add your logic here
-
- def handleRemoved(self, object):
- c = zapi.queryUtility(ITripleStore)
- if c is not None:
- pass # add your logic here
-
-
-cataloger = Cataloger(ITripleStore)
Modified: z3/zemantic/trunk/src/zemantic/configure.zcml
==============================================================================
--- z3/zemantic/trunk/src/zemantic/configure.zcml (original)
+++ z3/zemantic/trunk/src/zemantic/configure.zcml Sat Jun 25 13:35:17 2005
@@ -3,90 +3,61 @@
xmlns:browser="http://namespaces.zope.org/browser"
i18n_domain="zemantic">
- <content class=".triplestore.TripleStore">
- <implements interface="zope.app.annotation.IAttributeAnnotatable" />
- <implements interface="zope.app.utility.interfaces.ILocalUtility" />
- <allow interface=".interfaces.ITripleStore" />
- </content>
-
- <content class=".informationstore.InformationStore">
- <implements interface="zope.app.annotation.IAttributeAnnotatable" />
- <implements interface="zope.app.utility.interfaces.ILocalUtility" />
- <allow interface=".interfaces.IInformationStore" />
- </content>
+ <localUtility class=".graph.GraphUtility">
+ <factory
+ id="zemantic.graph"
+ />
+ <require
+ interface=".interfaces.IGraphUtility"
+ permission="zope.ManageContent"
+ />
+ </localUtility>
<module module="rdflib.BNode">
<allow attributes="BNode" />
</module>
<module module="rdflib.URIRef">
- <allow attributes="URIRef" />
+ <allow attributes="URIRef"/>
</module>
<module module="rdflib.Literal">
- <allow attributes="Literal" />
+ <allow attributes="Literal"/>
</module>
<module module="rdflib.Identifier">
- <allow attributes="Identifier" />
+ <allow attributes="Identifier"/>
</module>
<content class="rdflib.BNode.BNode">
- <implements interface=".interfaces.IIdentifier" />
- <allow interface=".interfaces.IIdentifier" />
+ <implements interface=".interfaces.IIdentifier"/>
+ <allow interface=".interfaces.IIdentifier"/>
</content>
-
<content class="rdflib.URIRef.URIRef">
- <implements interface=".interfaces.IIdentifier" />
- <allow interface=".interfaces.IIdentifier" />
+ <implements interface=".interfaces.IIdentifier"/>
+ <allow interface=".interfaces.IIdentifier"/>
</content>
<content class="rdflib.Literal.Literal">
- <implements interface=".interfaces.IIdentifier" />
- <allow interface=".interfaces.IIdentifier" />
+ <implements interface=".interfaces.IIdentifier"/>
+ <allow interface=".interfaces.IIdentifier"/>
</content>
<content class="rdflib.Identifier.Identifier">
- <implements interface=".interfaces.IIdentifier" />
- <allow interface=".interfaces.IIdentifier" />
- </content>
-
-
- <content class=".result.Result">
- <implements interface=".interfaces.IResult" />
- <allow interface=".interfaces.IResult" />
+ <implements interface=".interfaces.IIdentifier"/>
+ <allow interface=".interfaces.IIdentifier"/>
</content>
- <content class=".query.Query">
- <implements interface=".interfaces.IQuery" />
- <allow interface=".interfaces.IQuery" />
- </content>
-
- <content class=".query.UnionChain">
- <implements interface=".interfaces.IQueryChain" />
- <allow interface=".interfaces.IQueryChain" />
- </content>
-
- <content class=".query.IntersectionChain">
- <implements interface=".interfaces.IQueryChain" />
- <allow interface=".interfaces.IQueryChain" />
- </content>
-
-<adapter
- factory=".triplestore.TripleStoreSized"
- provides="zope.app.size.interfaces.ISized"
- for=".interfaces.ITripleStore"
- />
-
+ <adapter for=".interfaces.IRDFXML"
+ provides=".interfaces.IRDF"
+ factory=".adapters.XMLtoRDF"/>
-<adapter
- factory=".informationstore.InformationStore"
- provides="zope.app.size.interfaces.ISized"
- for=".interfaces.IInformationStore"
- />
+ <adapter for=".interfaces.IRDFNT"
+ provides=".interfaces.IRDF"
+ factory=".adapters.NTtoRDF"/>
- <include package=".browser" />
+ <include package=".browser"/>
</configure>
Deleted: /z3/zemantic/trunk/src/zemantic/events.py
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/events.py Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,75 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2004-1005 Michel Pelletier
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-
-
-__rdf_description__ = '''\
-<rdf:RDF xmlns="http://web.resource.org/cc/"
-xmlns:dc="http://purl.org/dc/elements/1.1/"
-xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
-<Work rdf:about="http://zemantic.org/zemantic/zemantic.py"
- dc:title="zemantic.events"
- dc:date="2005"
- dc:description="Catalog events and default handling.">
- <dc:creator>
- <Agent dc:title="Michel Pelletier"/>
- </dc:creator>
- <dc:rights>
- <Agent dc:title="Michel Pelletier"/>
- </dc:rights>
- <license rdf:resource="http://zemantic.org/LICENSE.txt/"/>
-</Work>
-</rdf:RDF>
-'''
-
-from rdflib.URIRef import URIRef
-from rdflib.BNode import BNode
-from rdflib.Literal import Literal
-from rdflib.Identifier import Identifier
-
-from query import Query
-from interfaces import IZemanticEvent, ITripleAfterAddEvent, ITripleBeforeRemoveEvent
-
-from zope.interface import implements
-from zope.interface.verify import verifyClass
-
-from zope.event import notify
-
-class ZemanticEvent(object):
- """
- A zemantic event. Instanciated by zemantic catalogs when the
- store is manipluated.
- """
-
- implements(IZemanticEvent)
-
- def __init__(self, data=()):
- self.data = data
-
-
-class TripleAfterAddEvent(ZemanticEvent):
-
- implements(ITripleAfterAddEvent)
-
-
-class TripleBeforeRemoveEvent(ZemanticEvent):
-
- implements(ITripleBeforeRemoveEvent)
-
-
-def afterAdd(data):
- notify(TripleAfterAddEvent(data))
-
-
-def beforeRemove(data):
- notify(TripleBeforeRemoveEvent(data))
Deleted: /z3/zemantic/trunk/src/zemantic/expressions.py
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/expressions.py Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,231 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2004-1005 Michel Pelletier
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-
-__rdf_description__ = '''\
-<rdf:RDF xmlns="http://web.resource.org/cc/"
-xmlns:dc="http://purl.org/dc/elements/1.1/"
-xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
-<Work rdf:about="http://zemantic.org/zemantic/expressions.py"
- dc:title="zemantic.expressions"
- dc:date="2005"
- dc:description="TALES Zemantic expressions.">
- <dc:creator>
- <Agent dc:title="Michel Pelletier"/>
- </dc:creator>
- <dc:rights>
- <Agent dc:title="Michel Pelletier"/>
- </dc:rights>
- <license rdf:resource="http://zemantic.org/LICENSE.txt/"/>
-</Work>
-</rdf:RDF>
-'''
-
-from zope.app import zapi
-from types import UnicodeType, TupleType
-from zope.interface import implements
-from zope.security.proxy import removeSecurityProxy
-from zope.tales.tales import _valid_name, _parse_expr, NAME_RE, Undefined, CompilerError
-from zope.tales.interfaces import ITALESExpression, ITALESFunctionNamespace
-
-from rdflib.URIRef import URIRef
-from rdflib.BNode import BNode
-from rdflib.Literal import Literal
-from rdflib.Identifier import Identifier
-
-from interfaces import *
-from query import Query, UnionChain
-from result import ResultSet
-
-import sys
-from zope.tales.engine import Engine
-from zope.tales.tales import Context
-
-class ZemanticExpr(object):
- """\
-Zemantic query expressions.
-
- A zemantic expression has the triple expression form:
-
- (<s expr>, <p expr>, <o expr>)
-
- The results of each sub expression in the triple pattern are used to
- query the nearest zemantic catalog site utility.
-
- Sub-expressions can be any kind of TALES expression (string, nocall,
- not, path, python etc.) but the expression must return one of the
- following:
-
- None - Matches all ident
-
- string or unicode - a string or unicode identifier in N3 format.
-
- IIdentifier implementor (BNode, URIRef, Literal) - an identifier
- object.
-
- Inner queries can be defined by returning:
-
- 3-tuple - defines standard inner query.
-
- IQuery implementor - defines custom inner query.
-
- The actual query logic is not implemented by the expression, for
- that look at zemantic.query.Query.
-
- """
-
- implements(ITALESExpression)
-
- def __init__(self, name, expr, engine):
- self._s = expr
- self._name = name
- self.engine = engine
- self.expr = self._compile(expr)
-
- def _compile(self, expression):
- m = _parse_expr(expression)
- if m:
- type = m.group(1)
- expr = expression[m.end():]
- else:
- type = "python"
- expr = expression
- try:
- handler = self.engine.getTypes()[type]
- except KeyError:
- raise CompilerError, ('Unrecognized expression type "%s".' % type)
- return handler(type, expr, self.engine)
-
-
- def __call__(self, econtext):
-
- c = zapi.queryUtility(ITripleStore)
- o = zapi.queryUtility(IInformationStore)
-
- # eval each expression, stuffing the result in a Query object.
- # Query will raise an error if the argument is not proper
- # like.
-
- if c is not None:
- econtext.setLocal('zem', c)
- if o is not None:
- econtext.setLocal('zon', o)
-
- econtext.setLocal('Any', None)
- econtext.setLocal('URIRef', URIRef)
- econtext.setLocal('BNode', BNode)
- econtext.setLocal('Literal', Literal)
-
- q = self.expr(econtext)
-
- if type(q) is TupleType:
- if len(q) != 3:
- raise ValueError, "Zemantic expression must be a " \
- "3 element tuple or provide IQuery"
- s, p, o = q
- q = Query(removeSecurityProxy(s),
- removeSecurityProxy(p),
- removeSecurityProxy(o))
-
- elif not IQuery.providedBy(q):
- raise ValueError, "Zemantic expression must be a " \
- "3 element tuple or provide IQuery"
- else:
- q = removeSecurityProxy(q)
-
- for result in c.query(q):
- yield result
-
- def __str__(self):
- return self._s
-
- def __repr__(self):
- return '<ZemanticExpr %s>' % self._s
-
-
-class RDFExpr(object):
- """\
- Render results of a Zemantic expression into RDF XML.
-
- """
-
- implements(ITALESExpression)
-
- def __init__(self, name, expr, engine):
- self._s = expr
- self._name = name
- self.engine = engine
- self.expr = self._compile(expr)
-
- def _compile(self, expression):
- m = _parse_expr(expression)
- if m:
- type = m.group(1)
- expr = expression[m.end():]
- else:
- type = "zemantic"
- expr = expression
- try:
- handler = self.engine.getTypes()[type]
- except KeyError:
- raise CompilerError, ('Unrecognized expression type "%s".' % type)
- return handler(type, expr, self.engine)
-
-
- def __call__(self, econtext):
-
- c = zapi.queryUtility(ITripleStore)
- o = zapi.queryUtility(IInformationStore)
-
- if c is not None:
- econtext.setLocal('zem', c)
- if o is not None:
- econtext.setLocal('zon', o)
-
-
- econtext.setLocal('Any', None)
- econtext.setLocal('URIRef', URIRef)
- econtext.setLocal('BNode', BNode)
- econtext.setLocal('Literal', Literal)
-
- # eval each expression, stuffing the result in a Query object.
- # Query will raise an error if the argument is not proper
- # like.
-
- return ResultSet(self.expr(econtext)).rdfxml()
-
- def __str__(self):
- return self._s
-
- def __repr__(self):
- return '<RDFExpr %s>' % self._s
-
-def eval(expr, context=None):
-
- c = zapi.queryUtility(ITripleStore, context=context)
- o = zapi.queryUtility(IInformationStore, context=context)
-
- econtext = Context(Engine, {})
-
- if c is not None:
- econtext.setLocal('zem', c)
- if o is not None:
- econtext.setLocal('zon', o)
-
- econtext.setLocal('Any', None)
- econtext.setLocal('URIRef', URIRef)
- econtext.setLocal('BNode', BNode)
- econtext.setLocal('Literal', Literal)
-
- bytecode = Engine.compile(expr)
- return bytecode(econtext)
Added: z3/zemantic/trunk/src/zemantic/graph.py
==============================================================================
--- (empty file)
+++ z3/zemantic/trunk/src/zemantic/graph.py Sat Jun 25 13:35:17 2005
@@ -0,0 +1,70 @@
+##############################################################################
+#
+# Copyright (c) 2004, 2005 Michel Pelletier
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+
+from zope.interface import implements
+
+from zope.app.container.interfaces import IContainer
+from zope.app.container.contained import Contained, setitem, uncontained
+from zope.app.annotation.interfaces import IAttributeAnnotatable
+
+from persistent import Persistent
+from BTrees.OOBTree import OOBTree
+
+from rdflib import Graph as rdflibGraph
+from rdflib.backends import ZODB as ZODBBackend
+
+from interfaces import *
+
+class GraphUtility(Contained, Persistent):
+ """ A utility container for rdflib graphs. """
+
+ implements(IGraphUtility)
+
+ def __init__(self):
+ self.__graph = ZODBBackend.ZODB()
+
+ def getGraph(self):
+ return rdflibGraph(backend=self.__graph)
+
+ def graph(self, ob):
+ rdf = IRDF(ob)
+ graph = self.getGraph()
+ for relation in rdf.relations():
+ graph.add(relation)
+
+ def regraph(self, ob):
+ ungraph(ob)
+ graph(ob)
+
+ def ungraph(self, ob):
+ rdf = IRDF(ob)
+ graph = self.getGraph()
+ for relation in rdf.relations():
+ graph.remove(relation)
+
+def indexDocSubscriber(event):
+ """A subscriber to IntIdAddedEvent"""
+ for cat in zapi.getAllUtilitiesRegisteredFor(IGraphUtility):
+ gm.graph(event.object)
+
+def reindexDocSubscriber(event):
+ """A subscriber to IntIdAddedEvent"""
+ for cat in zapi.getAllUtilitiesRegisteredFor(IGraphUtility):
+ gm.regraph(event.object)
+
+def unindexDocSubscriber(event):
+ """A subscriber to IntIdAddedEvent"""
+ for cat in zapi.getAllUtilitiesRegisteredFor(IGraphUtility):
+ gm.ungraph(event.object)
+
Deleted: /z3/zemantic/trunk/src/zemantic/informationstore.py
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/informationstore.py Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,171 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2004-1005 Michel Pelletier
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-
-
-__rdf_description__ = '''\
-<rdf:RDF xmlns="http://web.resource.org/cc/"
-xmlns:dc="http://purl.org/dc/elements/1.1/"
-xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
-<Work rdf:about="http://zemantic.org/zemantic/informationstore.py"
- dc:title="zemantic.informationstore"
- dc:date="2005"
- dc:description="Information store catalogs.">
- <dc:creator>
- <Agent dc:title="Michel Pelletier"/>
- </dc:creator>
- <dc:rights>
- <Agent dc:title="Michel Pelletier"/>
- </dc:rights>
- <license rdf:resource="http://zemantic.org/LICENSE.txt/"/>
-</Work>
-</rdf:RDF>
-'''
-from persistent import Persistent
-from persistent.dict import PersistentDict
-
-from rdflib.InformationStore import InformationStore as rdflibInformationStore # not pickleable
-from rdflib.InformationStore import ContextBackend
-from rdflib.URIRef import URIRef
-from rdflib.BNode import BNode
-from rdflib.Literal import Literal
-from rdflib.Identifier import Identifier
-import urllib
-
-from query import Query
-from result import Result
-from triplestore import TripleStore
-from lib.ZODBBackend import ZODBBackend
-from lib.IOZODBContextBackend import IOZODBContextBackend
-from interfaces import ITripleStore, IInformationStore, IContext
-from events import afterAdd, beforeRemove
-
-from zope.interface import implements
-from zope.interface.verify import verifyClass
-from zope.app.size.interfaces import ISized
-
-class InformationStore(Persistent):
- """
- A wrapper around a persistent rdflib backend that is used to
- construct an rdflib informationstore.
-
- >>> c = InformationStore()
- >>> IInformationStore.providedBy(c)
- True
- >>> verifyClass(IInformationStore, InformationStore)
- True
-
- """
-
- implements(IInformationStore)
-
- _v_store = backend = __parent__ = __name__ = None
- notify = False
-
- def __init__(self, backend=None):
- if backend is None:
- backend = IOZODBContextBackend()
- self.backend = backend
-
- def clear(self):
- """
- Clear information store.
- """
- for context in self.getContexts():
- for t in self.triples((None, None, None), context):
- self.remove(t, context)
-
- def notifyOn(self):
- """
- Turn on event notification.
- """
- self.notify = True
-
- def notifyOff(self):
- self.notify = False
-
- def getStore(self):
- """
- Returns a InformationStore wrapping the semantic storage.
- """
- if self._v_store is None:
- self._v_store = rdflibInformationStore(backend=self.backend) # not pickleable
- return self._v_store
-
- store = property(getStore)
-
- def parse(self, rdf, context, format="xml"):
- """
- Parse RDF information. The optional"format" argument can be "xml"
- (the default) or "nt". Note, I have not tested nt yet. Also a
- bug in rdflib requires you pass a file like object.
- """
- self.getContext(context).parse(rdf, format=format)
-
- def add(self, (subject, predicate, object), context):
- """
- Add a triple to the storage.
- """
- t = (subject, predicate, object)
- self.store.add(t, context)
-
- if self.notify:
- afterAdd(t)
-
- def remove(self, (subject, predicate, object), context):
- """
- Add a triple to the storage.
- """
- t = (subject, predicate, object)
- if self.notify:
- beforeRemove(t)
-
- self.store.remove(t, context)
-
- def triples(self, (subject, predicate, object), context, *args):
- """
- Query the triple storage. The argument is a triple pattern
- which can contain a valid value or None to indicate any value
- is desired.
- """
-
- for triple in self.store.triples((subject, predicate, object), context):
- yield triple
-
- def query(self, q):
- """
- Query zemantic with a query object.
- """
- return q(self)
-
- def getContext(self, context):
- return TripleStore(backend=ContextBackend(self.store, context))
-
- def getContexts(self):
- for context in self.store.contexts():
- yield self.getContext(context)
-
- def __len__(self):
- return len(list(self.store.contexts()))
-
-class InformationStoreSized(object):
- implements(ISized)
-
- def __init__(self, istore):
- self._istore = istore
-
- def sizeForSorting(self):
- return ('item', len(self._istore))
-
- def sizeForDisplay(self):
- return str(len(self._istore)) + ' triples'
Modified: z3/zemantic/trunk/src/zemantic/interfaces.py
==============================================================================
--- z3/zemantic/trunk/src/zemantic/interfaces.py (original)
+++ z3/zemantic/trunk/src/zemantic/interfaces.py Sat Jun 25 13:35:17 2005
@@ -12,158 +12,48 @@
#
##############################################################################
-__rdf_description__ = '''\
-<rdf:RDF xmlns="http://web.resource.org/cc/"
-xmlns:dc="http://purl.org/dc/elements/1.1/"
-xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
-<Work rdf:about="http://zemantic.org/zemantic/interfaces.py"
- dc:title="zemantic.interfaces"
- dc:date="2005"
- dc:description="Interface definitions for Zemantic components.">
- <dc:creator>
- <Agent dc:title="Michel Pelletier"/>
- </dc:creator>
- <dc:rights>
- <Agent dc:title="Michel Pelletier"/>
- </dc:rights>
- <license rdf:resource="http://zemantic.org/LICENSE.txt/"/>
-</Work>
-</rdf:RDF>
-'''
-
from zope.i18nmessageid import MessageIDFactory
from zope.interface import Interface, classImplements, Attribute, Invalid
_ = MessageIDFactory('zemantic')
-class IRDFThreeTuples(Interface):
- """ Interface for a component that wants to generate RDF XML."""
-
- def threeTuples():
- """ Return a sequence of three-tuples describing of this component.
-
- o All values must be unicode.
-
- o URIs must be contained within <>.
-
- o Literals must be contained within "" (*inside* the Unicode string!).
-
- E.g.:
-
- [('<http://example.com/path/to/object>',
- '<http://purl.org/dc/elements/1.1/#Title>",
- '"Example Title"'),
- ('<http://example.com/path/to/object>',
- '<http://purl.org/dc/elements/1.1/#Description>",
- '"This is an example description."'),
- ]
- """
-
-class IRDFXML(Interface):
- """ Interface for a component that wants to generate RDF XML."""
-
- def xml():
- """ Return the RDF XML description of this component. """
-
-
-class IRDAbout(Interface):
- """ Interface for a component that wants to generate RDF XML."""
-
- def about():
- """ Return the RDF XML description of this component. """
-
-class IQuery(Interface):
-
- """ Any callable. Returns a result set or None (no results) or
- throws an exception. """
-
- def __call__(store, *args):
- """ Eval a query with given args. Returns a result Set.
- Queries throw QueryException to indicate failure."""
-
-
-class IQueryChain(IQuery):
-
- """ Abstract class to combine a "chain" of queries into one result
- set. QueryChains are themselves Queries, and can be nested. """
-
-
- def add(query):
- """ Append a query onto the chain """
-
- def getQueries():
- """ Return the chain of queries. """
-
-
-class IQueryable(Interface):
- """ A generic catalog interface, there is nothing specificly in
- this interface about zemantic or semantic web notions, it provides
- for a query operation of any kind and could be used for other
- forms of catalogs like a port of textindexng. ."""
-
- def query(query):
- """ Query the catalog with a query object, returning a sequence of results. """
-
-class IZemanticEvent(Interface):
- """ When triples are added or removed from the storage, these
- events are fired. Not sure if this interface is even necessary."""
-
-
-class ITripleAfterAddEvent(Interface):
- """ When triples are added or removed from the storage, these
- events are fired. Not sure if this interface is even necessary."""
-
-
-class ITripleBeforeRemoveEvent(Interface):
- """ When triples are added or removed from the storage, these
- events are fired. Not sure if this interface is even necessary."""
-
+class IGraphUtility(Interface):
+ """ """
-class ITripleStore(IQueryable):
- '''\
- Semantic Web Catalog.
+ def getGraph():
+ """ Return the rdflib.Graph backing this utility."""
- Zemantic "catalogs" (ie indexes) data expressed in the Resource
- Description Framework (RDF). Any kind of content, whether inside Zope
- or from some outside source, can be cataloged if it can describe
- itself using the RDF standard. Any kind of RDF vocabulary like RSS,
- OWL, DAML+OIL, Dublin Core, or any kind of XML schema or data can be
- expressed into the catalog.
+ def graph(ob):
+ """ Graph a component. The object must be adaptable to IRDF."""
- Once data is cataloged into Zemantic it can be queried using either
- the Python query interface or a TALES-based RDF query expression
- language. Results of a query can be either a generator of result
- records or RDF in xml or NT format.
+ def regraph(ob):
+ """ Regraph a component. The object must be adaptable to
+ IRDF."""
+
+ def ungraph(ob):
+ """ unGraph a component. The object must be adaptable to
+ IRDF."""
+
+
+class IGraph(Interface):
+ """\
+ An rdflib.Graph indexes data expressed in the Resource Description
+ Framework (RDF). Any kind of content, whether inside Zope or from
+ some outside source, can be cataloged if it can describe itself
+ using the RDF standard. Any kind of RDF vocabulary like RSS, OWL,
+ DAML+OIL, Dublin Core, or any kind of XML schema or data can be
+ expressed into the graph.
+
+ Once data is graphed it can be queried using either the Python
+ query interface, a TALES-based RDF query expression language, or
+ the sparql rdf query language. Results of a query can be either a
+ generator of result records or RDF in xml or NT format.
- Zemantic has two main components that are both configured as a local
- Zope 3 site utility. The Zemantic utility is the actual catalog of
- meta-data and the Zontology utility is used to managed registered
- ontologies, or schemas, such as Dublin Core, FoaF
- (Friend-of-a-Friend), OWL, etc.
-
- In Semantic Web terms, Zemantic is a persistent triple store. RDF
+ In Semantic Web terms, a graph is a persistent triple store. RDF
is broken down into subject, predicate, and object relations
(called triples) and each relation is indexed. The triple store
can then be queried for triples that match patterns.
-
- A Zemantic is queried by calling its query() method with a query
- object that provide zemantic.interfaces.IQuery. See
- zemantic.query.Query for an example of such an object or the
- zemantic.expressions modules for example of query expressions.
-
- '''
-
- def notifyOn():
- """ Turn on triple add and remove notification. """
-
- def notifyOff():
- """ Turn off triple add and remove notification. """
-
- def clear():
- """ Clear the catalog. Removes all relations. """
-
- def getStore():
- """ Return the catalog rdflib backend storage. """
+ """
def parse(rdf, format="xml"):
""" Parse RDF-XML into the catalog. """
@@ -201,15 +91,6 @@
def transitive_subjects(predicate, object, remember=None):
""" """
- def uniqueSubjects():
- """ All unique subjects. """
-
- def uniquePredicates():
- """ All unique predicates. """
-
- def uniqueObjects():
- """ All unique objects. """
-
def rdfxml():
""" Returns rdf xml representation of store. """
@@ -221,54 +102,36 @@
expensive."""
-class IContext(ITripleStore):
-
- def __str__():
- """ Returns context as string. """
-
-
-class IInformationStore(IQueryable):
- """ An rdflib-style information store. """
-
- def notifyOn():
- """ Turn on triple add and remove notification. """
-
- def notifyOff():
- """ Turn off triple add and remove notification. """
+class IRDF(Interface):
- def clear():
- """ Clear the catalog. Removes all relations. """
+ """ Interface for a component that wants to generate RDF
+ relationships."""
- def getStore():
- """ Return the catalog rdflib backend storage. """
-
- def parse(rdf, context, format="xml"):
- """ Parse RDF-XML into the catalog. """
+ def relations():
+ """ Return a sequence of three-tuples describing of this
+ component as a set of RDF relationships. All elements must be
+ valid rdflib identifiers (URIRef, BNode, or Literal).
- def add((subject, predicate, object), context):
- """ Add one triple to the catalog in a given context. """
+ """
- def remove((subject, predicate, object), context):
- """ Remove one triple from the catalog in a given context. """
+class IRDFNT(Interface):
+
+ """ Interface for a componen t that wnats to generate RDF as NT.
+ A Zemantic graph adapts this interface to IRDF. """
- def triples((subject, predicate, object), context, *args):
- """ Query the information store. """
+ def nt():
+ """ Returns RDF NT description of this component. """
- def getContext(context):
- """ Return a triple store of the given context. """
+class IRDFXML(Interface):
+
+ """ Interface for a component that wants to generate RDF XML. A
+ Zemantic graph adapts this interface to IRDF."""
- def getContexts():
- """ Return a generator of all contexts in the information store. """
+ def xml():
+ """ Return the RDF XML description of this component. """
- def __len__():
- """ Return number of contexts in store. """
-
-# we have to assert all of these interfaces here so that they work with Zope 3
-from rdflib.URIRef import URIRef
-from rdflib.BNode import BNode
-from rdflib.Literal import Literal
-from rdflib.Identifier import Identifier
+from rdflib import *
class IIdentifier(Interface):
@@ -281,25 +144,7 @@
def __cmp__(other):
""" dummy. """
-classImplements(Identifier, IIdentifier)
-classImplements(URIRef, IIdentifier)
-classImplements(BNode, IIdentifier)
-classImplements(Literal, IIdentifier)
-
-class IResult(Interface):
- subject = Attribute("Result subject.")
- predicate = Attribute("Result predicate.")
- object = Attribute("Result object.")
-
- def triple():
- """ """
-
-class IResultSet(Interface):
-
- def rdfxml():
- """ Return rdfxml of result set. """
-
- def rdfnt():
- """ Return nt format of result set. """
-
-
+#classImplements(Identifier, IIdentifier)
+#classImplements(URIRef, IIdentifier)
+#classImplements(BNode, IIdentifier)
+#classImplements(Literal, IIdentifier)
Modified: z3/zemantic/trunk/src/zemantic/public.py
==============================================================================
--- z3/zemantic/trunk/src/zemantic/public.py (original)
+++ z3/zemantic/trunk/src/zemantic/public.py Sat Jun 25 13:35:17 2005
@@ -1,16 +1,18 @@
+##############################################################################
+#
+# Copyright (c) 2004-1005 Michel Pelletier
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
Any = None
-
from interfaces import *
-
-from rdflib.URIRef import URIRef
-from rdflib.BNode import BNode
-from rdflib.Literal import Literal
-from rdflib.Identifier import Identifier
-
-from triplestore import TripleStore
-from informationstore import InformationStore
-from query import Query
-from result import Result, ResultSet
-
-from expressions import eval
+from rdflib import *
+from graph import *
Deleted: /z3/zemantic/trunk/src/zemantic/query.py
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/query.py Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,337 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2004-1005 Michel Pelletier
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-
-"""
-Queries are any callable object (like a function) that query the
-triple store. These are technically not agents, just agent helpers.
-QueryChains are queries that chains other queries in various ways
-(union, intersection).
-
-"""
-
-__rdf_description__ = '''\
-<rdf:RDF xmlns="http://web.resource.org/cc/"
-xmlns:dc="http://purl.org/dc/elements/1.1/"
-xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
-<Work rdf:about="http://zemantic.org/zemantic/query.py"
- dc:title="zemantic.query"
- dc:date="2005"
- dc:description="Queries and stock query logic.">
- <dc:creator>
- <Agent dc:title="Michel Pelletier"/>
- </dc:creator>
- <dc:rights>
- <Agent dc:title="Michel Pelletier"/>
- </dc:rights>
- <license rdf:resource="http://zemantic.org/LICENSE.txt/"/>
-</Work>
-</rdf:RDF>
-'''
-
-from types import UnicodeType, NoneType, TupleType
-from rdflib.Identifier import Identifier
-from rdflib.URIRef import URIRef
-from rdflib.BNode import BNode
-from rdflib.Literal import Literal
-
-from zope.interface import implements
-from interfaces import IQuery, IQueryChain, IIdentifier
-from result import Result
-
-import BTrees
-from BTrees.OOBTree import OOSet as Set
-
-class QueryException(Exception):
-
- """ Thrown by a query to indicate a query exception."""
-
-class BadQueryException(QueryException):
-
- """ Throw by a query to indicate a query is malformed."""
-
-class Query(object):
-
- """ A generic query logic class. A straightforward interface to
- zemantic.TripleStore.triples() with support for inner queries.
-
- This class does simple triple pattern queries on a catalog. If an
- identifier term is a nested query (3-tuple or IQuery implementor)
- then it performs the inner query first, applying each of the
- results of the inner query to the outer query.
-
- When called, returns a result generator or None (no results) or
- throws an exception.
-
- >>> from triplestore import TripleStore
- >>> c = TripleStore()
- >>> q = Query(None, None, None)
- >>> c.query(q) is not None
- True
-
- """
-
- implements(IQuery)
-
- inner = False
-
- def __init__(self, subject=None, predicate=None, object=None, context=None):
- s, p, o, c = subject, predicate, object, context
-
- ts = type(s)
- if ts is UnicodeType:
- if s.startswith("<"):
- s = URIRef(s[1:-1])
- elif s.startswith('"'):
- raise ValueError, "Literals cannot be subjects."
- elif s.startswith('_'):
- s = BNode(s)
- else:
- raise ValueError, "Unicode subject term %s is not a well formed N3 identifier" % s
- elif ts is TupleType or IQuery.providedBy(s):
- self.inner = True
- elif ts is NoneType or IIdentifier.providedBy(s):
- pass # it's cool
- else:
- raise ValueError, "Subject term must be None unicode, IIdentifier, IQuery or 3-tuple."
-
-
- tp = type(p)
- if tp is UnicodeType:
- if p.startswith("<"):
- p = URIRef(p[1:-1])
- elif p.startswith('"'):
- raise ValueError, "Literals cannot be predicates."
- elif p.startswith('_'):
- raise ValueError, "BNodes cannot be predicates."
- else:
- raise ValueError, "Unicode predicate term %s is not a well formed N3 identifier" % p
- elif tp is TupleType or IQuery.providedBy(p):
- self.inner = True
- elif tp is NoneType or IIdentifier.providedBy(p):
- pass # it's cool
- else:
- raise ValueError, "Subject term must be None unicode, IIdentifier, IQuery or 3-tuple."
-
-
- to = type(o)
- if to is UnicodeType:
- if o.startswith("<"):
- o = URIRef(o[1:-1])
- elif o.startswith('"'):
- o = Literal(o[1:-1])
- elif o.startswith('_'):
- o = BNode(o)
- else:
- raise ValueError, "Unicode object term %s is not a well formed N3 identifier" % o
-
- elif to is TupleType or IQuery.providedBy(o):
- self.inner = True
- elif to is NoneType or IIdentifier.providedBy(o):
- pass # it's cool
- else:
- raise ValueError, "Object term must be None, unicode, IIdentifier, IQuery or 3-tuple."
-
-
- tc = type(c)
- if tc is UnicodeType:
- if c.startswith("<"):
- c = URIRef(c[1:-1])
- elif c.startswith('"'):
- raise ValueError, "Literals cannot be contexts."
- elif c.startswith('_'):
- raise ValueError, "BNodes cannot be contexts."
- else:
- raise ValueError, "Unicode context term %s is not a well formed N3 identifier" % o
-
- elif tc is TupleType or IQuery.providedBy(c):
- self.inner = True
- elif tc is NoneType or IIdentifier.providedBy(c):
- pass # it's cool
- else:
- raise ValueError, "Context term must be None, unicode, IIdentifier, IQuery or 3-tuple."
-
- self.s = s
- self.p = p
- self.o = o
- self.c = c
-
- def __call__(self, store):
-
- # common path, no inner queries
- try:
- if not self.inner:
- for result in store.triples((self.s, self.p, self.o), self.c):
- yield Result(result)
- else:
-
- # inner query logic here is definitely _not_ optimized, I
- # imagine there is all kinds of query optimization and
- # algebraic reduction that can be applied but that's not
- # the point, users will have to be aware of the fact that
- # broad inner queries can significantly impact
- # performance.
-
- # first, determine inner subjects
-
- if self.s is None:
- isresult = []
- for s in store.uniqueSubjects():
- isresult.append(Result((s, None, None)))
-
- elif type(self.s) is TupleType or IQuery.providedBy(self.s):
- if type(self.s) is TupleType:
- q = apply(Query, self.s)
- else:
- q = self.s
- isresult = store.query(q)
- else:
- isresult = [Result((self.s, None, None))]
-
- # determine inner predicates
-
- if self.p is None:
- ipresult = []
- for p in store.uniquePredicates():
- ipresult.append(Result((None, p, None)))
-
- elif type(self.p) is TupleType or IQuery.providedBy(self.p):
- if type(self.p) is TupleType:
- q = apply(Query, self.p)
- else:
- q = self.p
- ipresult = store.query(q)
-
- else:
- ipresult = [Result((None, self.p, None))]
-
- # determine inner objects
-
- if self.o is None:
- ioresult = []
- for o in self.uniqueObjects():
- ioresult.append(Result((None, None, o)))
-
- elif type(self.o) is TupleType or IQuery.providedBy(self.o):
- if type(self.o) is TupleType:
- q = apply(Query, self.o)
- else:
- q = self.o
- ioresult = store.query(q)
-
- else:
- ioresult = [Result((None, None, self.o))]
-
- # put it all together
-
- for sresult in isresult:
- for presult in ipresult:
- for oresult in ioresult:
- yield Result((sresult.subject, presult.predicate, oresult.object))
- except KeyError:
- raise StopIteration
-
- def __repr__(self):
- return "<Query: %s, %s, %s>" % (self.s, self.p, self.o)
-
-class QueryChain(Query):
-
- """ Abstract class to combine a "chain" of queries into one result
- set. QueryChains are themselves Queries, and can be nested. """
-
- implements(IQueryChain)
-
- _queries = None
-
- def __init__(self, *queries):
- Query.__init__(self)
- self._queries = []
- for x in queries:
- self.add(x)
-
- def add(self, query):
- """ Append a query onto the chain """
- self._queries.append(query)
-
- def getQueries(self):
- """ Return the chain of queries. """
- return self._queries
-
- def __call__(self, store):
- """ Eval a query chain with given args. Queries throw
- QueryException to stop chain procesing and declare failure."""
-
- raise NotImplementedError
-
-
-
-class UnionChain(QueryChain):
- """
- Take the union of a chain of queries.
-
- >>> from triplestore import TripleStore
- >>> c = TripleStore()
- >>> u = UnionChain(c, Query())
- >>> u = UnionChain(c, Query(), Query())
-
- """
- def _union(self, x, y):
- """ Slow but obviously correct Python implementations of basic ops """
- result = list(x)
- for e in y:
- found = False
- for item in result:
- if e.triple() == item.triple():
- found = True
- break
- if not found:
- result.append(e)
- result.sort()
- return result
-
- def __call__(self, store):
- if len(self._queries) == 0:
- pass
- else:
- results = []
- for query in self._queries:
- results = self._union(results, (list(query(store))))
- #results = BTrees.OOBTree.union(results, Set(list(query(store))))
- for result in results:
- yield result
-
-class IntersectionChain(QueryChain):
- """
- Take the intersection of a chain of queries.
-
- >>> from triplestore import TripleStore
- >>> c = TripleStore()
- >>> i = IntersectionChain(c, Query())
- >>> i = IntersectionChain(c, Query(), Query())
-
- XXX this is broken for now
- """
-
- def __call__(self, store):
- if len(self._queries) == 0:
- pass
- elif len(self._queries) == 1:
- results = self._queries[0](store)
- for result in results:
- yield result
- else:
- results = Set(list(self._queries[0](store)))
- for query in self._queries[1:]:
- results = BTrees.OOBTree.intersection(results, Set(list(query(store))))
- for result in results:
- yield result
Deleted: /z3/zemantic/trunk/src/zemantic/resources.py
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/resources.py Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,46 +0,0 @@
-
-import os, sys
-
-def package_home(gdict):
- filename = gdict["__file__"]
- return os.path.dirname(filename)
-
-class Resource(object):
-
- def __init__(self, filename, _prefix=None):
- path = self.get_path_from_prefix(_prefix)
- self.filename = os.path.join(path, filename)
- if not self.checkResource():
- raise ValueError("No such resource", self.filename)
-
- def get_path_from_prefix(self, _prefix):
- if isinstance(_prefix, str):
- path = _prefix
- else:
- if _prefix is None:
- _prefix = sys._getframe(2).f_globals
- path = package_home(_prefix)
- return path
-
- def checkResource(self):
- return True
-
-
-class DirectoryResource(Resource):
-
- def checkResource(self):
- return os.path.isdir(self.filename)
-
- def list(self):
- return os.listdir(self.filename)
-
- def path(self):
- return self.filename
-
-class FileResource(Resource):
-
- def open(self, mode="r"):
- return open(self.filename, mode)
-
- def checkResource(self):
- return os.path.isfile(self.filename)
Deleted: /z3/zemantic/trunk/src/zemantic/result.py
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/result.py Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,77 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2004-1005 Michel Pelletier
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-
-
-__rdf_description__ = '''\
-<rdf:RDF xmlns="http://web.resource.org/cc/"
-xmlns:dc="http://purl.org/dc/elements/1.1/"
-xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
-<Work rdf:about="http://zemantic.org/zemantic/result.py"
- dc:title="zemantic.result"
- dc:date="2005"
- dc:description="Result objects.">
- <dc:creator>
- <Agent dc:title="Michel Pelletier"/>
- </dc:creator>
- <dc:rights>
- <Agent dc:title="Michel Pelletier"/>
- </dc:rights>
- <license rdf:resource="http://zemantic.org/LICENSE.txt/"/>
-</Work>
-</rdf:RDF>
-'''
-
-
-from interfaces import IResult, IResultSet
-from zope.interface import implements
-from zope.security.proxy import removeSecurityProxy
-
-from BTrees.OOBTree import OOSet
-from rdflib.TripleStore import TripleStore
-from rdflib.backends.InMemoryBackend import InMemoryBackend
-
-class Result(object):
-
- implements(IResult)
-
- def __init__(self, (subject, predicate, object)):
- self.subject = subject
- self.predicate = predicate
- self.object = object
-
- def triple(self):
- return self.subject, self.predicate, self.object
-
- def __str__(self):
- return "<%s, %s, %s>" % (`self.subject`, `self.predicate`, `self.object`)
-
-class ResultSet(object):
-
- implements(IResultSet)
-
- def __init__(self, data):
- self.data = TripleStore(backend=InMemoryBackend())
- for result in data:
- if result is not None:
- s, p, o = result.triple()
- s = removeSecurityProxy(s)
- p = removeSecurityProxy(p)
- o = removeSecurityProxy(o)
- self.data.add((s, p, o))
-
- def rdfxml(self):
- return self.data.serialize()
-
- def rdfnt(self):
- return self.data.serialize("nt")
Deleted: /z3/zemantic/trunk/src/zemantic/tests/test1.rdf
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/tests/test1.rdf Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,47 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- This RDF template is used by the BookToRDFXMLAdapter to represent -->
-<!-- IBook content objects to the semantic catalog (or any resource that can parse RDF). -->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:tal="http://xml.zope.org/namespaces/tal"
- xmlns:rss="http://purl.org/rss/1.0/"
- xmlns="http://purl.org/dc/elements/1.1/">
- <rss:item
- rdf:about="http://url/"
- tal:attributes="rdf:about options/path"
- tal:define = "book options/book;
- title book/Title | nothing;
- creator book/Creator | nothing;
- subject book/Subject | nothing;
- description book/Description | nothing;
- publisher book/Publisher | nothing;
- contributors book/Contributors | nothing;
- date book/Date | nothing;
- creationdate book/CreationDate | nothing;
- effectivedate book/EffectiveDate | nothing;
- expirationdate book/ExpirationDate | nothing;
- modificationdate book/ModificationDate | nothing;
- type book/Type | nothing;
- format book/Format | nothing;
- identifier book/Identifier | nothing;
- language book/Language | nothing;
- rights book/Rights | nothing;">
- <rss:link tal:content="options/path"/>
- <title tal:condition="title" tal:content="title"/>
- <creator tal:repeat="i creator" tal:content="i"/>
- <subject tal:repeat="i subject" tal:content="i"/>
- <description tal:condition="description" tal:content="description"/>
- <publisher tal:condition="publisher" tal:content="publisher"/>
- <contributors tal:condition="contributors" tal:content="contributors"/>
- <date tal:condition="date" tal:content="date"/>
- <creationdate tal:condition="creationdate" tal:content="creationdate"/>
- <effectivedate tal:condition="effectivedate" tal:content="effectivedate"/>
- <expirationdate tal:condition="expirationdate" tal:content="expirationdate"/>
- <modificationdate tal:condition="modificationdate" tal:content="modificationdate"/>
- <type tal:condition="type" tal:content="type"/>
- <format tal:condition="format" tal:content="format"/>
- <identifier tal:condition="identifier" tal:content="identifier"/>
- <language tal:condition="language" tal:content="language"/>
- <rights tal:condition="rights" tal:content="rights"/>
- </rss:item>
-</rdf:RDF>
\ No newline at end of file
Deleted: /z3/zemantic/trunk/src/zemantic/tests/test_istore.py
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/tests/test_istore.py Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,24 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2004-1005 Michel Pelletier and Contributors
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-
-import unittest
-from zope.testing.doctestunit import DocTestSuite
-
-def test_suite():
- return unittest.TestSuite((
- DocTestSuite('zemantic.informationstore'),
- ))
-
-if __name__ == '__main__':
- unittest.main(defaultTest='test_suite')
Deleted: /z3/zemantic/trunk/src/zemantic/tests/test_query.py
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/tests/test_query.py Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,189 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2004-1005 Michel Pelletier and Contributors
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-import unittest
-
-from rdflib.URIRef import URIRef
-from rdflib.Literal import Literal
-
-from zope.testing.doctestunit import DocTestSuite
-
-from zemantic.triplestore import TripleStore
-from zemantic.query import UnionChain
-from zemantic.public import *
-
-class QueryTestCase(unittest.TestCase):
-
- def _getSampleCatalog(self):
- store = TripleStore()
-
- store.add((URIRef(u'Tarek'), URIRef(u'likes'), URIRef(u'pizza')))
- store.add((URIRef(u'Bob'), URIRef(u'likes'), URIRef(u'cheese')))
- store.add((URIRef(u'Bob'), URIRef(u'hates'), URIRef(u'pizza')))
- store.add((URIRef(u'Robert'), URIRef(u'likes'), URIRef(u'pizza')))
- store.add((URIRef(u'Marie'), URIRef(u'likes'), URIRef(u'cheese')))
- store.add((URIRef(u'Tarek'), URIRef(u'likes'), URIRef(u'cheese')))
- store.add((URIRef(u'Michel'), URIRef(u'likes'), URIRef(u'cheese')))
- store.add((URIRef(u'Michel'), URIRef(u'likes'), URIRef(u'pizza')))
-
- return store
-
- def _getSampleCatalog2(self):
- store = TripleStore()
-
- store.add((URIRef(u'Tarek'), URIRef(u'likes'), Literal(u'pizza')))
- store.add((URIRef(u'Bob'), URIRef(u'likes'), Literal(u'cheese')))
- store.add((URIRef(u'Bob'), URIRef(u'hates'), Literal(u'pizza')))
- store.add((URIRef(u'Robert'), URIRef(u'likes'), Literal(u'pizza')))
- store.add((URIRef(u'Marie'), URIRef(u'likes'), Literal(u'cheese')))
- store.add((URIRef(u'Tarek'), URIRef(u'likes'), Literal(u'cheese')))
- store.add((URIRef(u'Michel'), URIRef(u'likes'), Literal(u'cheese')))
- store.add((URIRef(u'Michel'), URIRef(u'likes'), Literal(u'pizza')))
-
- return store
-
- def stest_repr(self):
- ob = self._getSampleCatalog()
- repr_ = ob.__repr__()
- self.assertNotEquals(repr_, None)
-
- def stest_simpleQueries(self):
- ob = self._getSampleCatalog()
-
- res = ob.query(Query(Any, Any, Any))
- res = list(res)
- self.assertEquals(len(res), 8)
-
- res = ob.query(Query(Any, u'<likes>', Any))
- res = list(res)
- self.assertEquals(len(res), 7)
-
- res = ob.query(Query(Any, u'<hates>', Any))
- res = list(res)
- self.assertEquals(len(res), 1)
-
- res = ob.query(Query(u'<Bob>', Any, Any))
- res = list(res)
- self.assertEquals(len(res), 2)
-
- res = ob.query(Query(u'<Bob>', Any, u'<cheese>'))
- res = list(res)
- self.assertEquals(len(res), 1)
-
- res = ob.query(Query(u'<Bob>', u'<likes>', u'<cheese>'))
- res = list(res)
- self.assertEquals(len(res), 1)
-
-
- res = ob.query(Query(u'<Bob>', u'<hates>', u'<cheese>'))
- res = list(res)
- self.assertEquals(len(res), 0)
-
- def stest_unionQueries(self):
- ob = self._getSampleCatalog()
-
- # testing with one query
- q1 = Query(Any, Any, Any)
- direct = ob.query(q1)
- direct = list(direct)
-
- q1 = UnionChain(q1)
-
- self.assertNotEquals(q1, None)
-
- res = ob.query(q1)
- self.assertNotEquals(res, None)
- res = list(res)
-
- self.assertEquals(len(res), len(direct))
-
- # testing with two queries : what bob likes or hates
- q1 = Query(u'<Bob>', u'<likes>', Any)
- q2 = Query(u'<Bob>', u'<hates>', Any)
-
- q1_and_q2 = UnionChain(q1, q2)
- self.assertNotEquals(q1_and_q2, None)
-
- res = ob.query(q1_and_q2)
- self.assertNotEquals(res, None)
- res = list(res)
- self.assertEquals(len(res), 2)
-
- # testing empty query
- res = ob.query(UnionChain())
- res = list(res)
- self.assertEquals(len(res), 0)
-
- def stest_complexQueries(self):
-
- ob = self._getSampleCatalog()
-
- # testing with two queries : what bob likes or hates
- q1 = Query(u'<Bob>', u'<likes>', Any)
- q2 = Query(u'<Bob>', u'<hates>', Any)
-
- q1_and_q2 = UnionChain(q1, q2)
- self.assertNotEquals(q1_and_q2, None)
-
- res = ob.query(q1_and_q2)
- self.assertNotEquals(res, None)
- res = list(res)
- self.assertEquals(len(res), 2)
-
- # people who likes cheese *or* pizza
- q1 = Query(Any, u'<likes>', u'<cheese>')
- q2 = Query(Any, u'<likes>', u'<pizza>')
-
- q1_or_q2 = UnionChain(q1, q2)
- res = ob.query(q1_or_q2)
- res = list(res)
- self.assertEquals(len(res), 7)
-
- # what bob likes and hates *or* people who likes cheese or pizza
- q1_or_q2 = UnionChain(q1_and_q2, q1_or_q2)
- res = ob.query(q1_or_q2)
- res = list(res)
- self.assertEquals(len(res), 8)
-
- def test_indexing(self):
- ob = self._getSampleCatalog2()
-
- # full value
- query = Query(u'<Bob>', u'<hates>', u'"pizza"')
- res = ob.query(query)
- res = list(res)
- self.assertEquals(len(res), 1)
-
- query = Query(u'<Bob>', u'<hates>', u'"piz*"')
- res = ob.query(query)
- res = list(res)
- self.assertEquals(len(res), 1)
-
-
- query = UnionChain(Query(Any, u'<hates>', u'"p*"'))
- res = ob.query(query)
- res = list(res)
- self.assertEquals(len(res), 1)
-
- query = Query(u'<Bob>', u'<hates>', u'"aezlpfhkezapihaz"')
- res = ob.query(query)
- res = list(res)
- self.assertEquals(len(res), 0)
-
-
-def test_suite():
- return unittest.TestSuite((unittest.makeSuite(QueryTestCase),
- DocTestSuite('zemantic.query')))
-
-if __name__ == '__main__':
- unittest.main(defaultTest='test_suite')
Deleted: /z3/zemantic/trunk/src/zemantic/triplestore.py
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/triplestore.py Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,324 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2004-1005 Michel Pelletier
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-
-__rdf_description__ = '''\
-<rdf:RDF xmlns="http://web.resource.org/cc/"
-xmlns:dc="http://purl.org/dc/elements/1.1/"
-xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
-<Work rdf:about="http://zemantic.org/zemantic/triplestore.py"
- dc:title="zemantic.triplestore"
- dc:date="2005"
- dc:description="Triple store catalogs.">
- <dc:creator>
- <Agent dc:title="Michel Pelletier"/>
- </dc:creator>
- <dc:rights>
- <Agent dc:title="Michel Pelletier"/>
- </dc:rights>
- <license rdf:resource="http://zemantic.org/LICENSE.txt/"/>
-</Work>
-</rdf:RDF>
-'''
-from persistent import Persistent
-from persistent.dict import PersistentDict
-
-from rdflib.TripleStore import TripleStore as rdflibTripleStore # not pickleable
-from rdflib.URIRef import URIRef
-from rdflib.BNode import BNode
-from rdflib.Literal import Literal
-from rdflib.Identifier import Identifier
-
-from query import Query
-from result import Result
-from lib.ZODBBackend import ZODBBackend
-from lib.IOZODBBackend import IOZODBBackend
-from lib.IOZODBTextIndexBackend import IOZODBTextIndexBackend
-from interfaces import ITripleStore
-from events import afterAdd, beforeRemove
-
-from zope.interface import implements
-from zope.interface.verify import verifyClass
-from zope.app.size.interfaces import ISized
-
-class TripleStore(Persistent):
- """
- A semantic zemantic. A wrapper around a persistent rdflib backend
- that is used to construct an rdflib triplestore.
-
- >>> c = TripleStore()
- >>> ITripleStore.providedBy(c)
- True
- >>> verifyClass(ITripleStore, TripleStore)
- True
-
- See Zontology class doctests for more tests.
-
- """
-
- implements(ITripleStore)
-
- _v_store = backend = __parent__ = __name__ = None
- notify = False
-
- def __init__(self, backend=None):
- if backend is None:
- backend = IOZODBTextIndexBackend()
- self.backend = backend
-
- def clear(self):
- """
- Clear zemantic.
- """
- for t in self.triples((None, None, None)):
- self.remove(t)
-
- def notifyOn(self):
- """
- Turn on event notification.
- """
- self.notify = True
-
- def notifyOff(self):
- self.notify = False
-
- def getStore(self):
- """
- Returns a TripleStore wrapping the semantic storage.
- """
- if self._v_store is None:
- self._v_store = rdflibTripleStore(backend=self.backend) # not pickleable
- return self._v_store
-
- store = property(getStore)
-
- def parse(self, rdf, format="xml"):
- """
- Parse RDF information. The optional"format" argument can be "xml"
- (the default) or "nt". Note, I have not tested nt yet. Also a
- bug in rdflib requires you pass a file like object.
-
- First, test the default (XML) parser.
-
- >>> from StringIO import StringIO
- >>> faux_rdf_file = StringIO(FAUX_RDF_FILE)
- >>> c = TripleStore()
- >>> len(allTriples(c))
- 0
- >>> c.parse(faux_rdf_file)
- >>> len(allTriples(c))
- 1
- >>> allTriples(c)[0][0]
- u'http://zemantic.org/zemantic/zemantic.py'
- >>> allTriples(c)[0][1]
- u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'
- >>> allTriples(c)[0][2]
- u'http://web.resource.org/cc/Work'
-
- Then, test the explicit version.
-
- >>> faux_rdf_file = StringIO(FAUX_RDF_FILE)
- >>> c = TripleStore()
- >>> len(allTriples(c))
- 0
- >>> c.parse(faux_rdf_file, 'xml')
- >>> len(allTriples(c))
- 1
- >>> allTriples(c)[0][0]
- u'http://zemantic.org/zemantic/zemantic.py'
- >>> allTriples(c)[0][1]
- u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'
- >>> allTriples(c)[0][2]
- u'http://web.resource.org/cc/Work'
-
- Now, test the NT version.
-
- >>> faux_nt_file = StringIO(FAUX_NT_FILE)
- >>> c = TripleStore()
- >>> len(allTriples(c))
- 0
- >>> c.parse(faux_nt_file, 'nt')
- >>> len(allTriples(c))
- 1
- >>> allTriples(c)[0][0]
- u'http://zemantic.org/zemantic/zemantic.py'
- >>> allTriples(c)[0][1]
- u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'
- >>> allTriples(c)[0][2]
- u'http://web.resource.org/cc/Work'
-
- """
- # Could we get a list of the parsed statements back from rdflib?
- # If so, then we could call 'afterAdd' with them.
- self.store.parse(rdf, format=format)
-
- def add(self, (subject, predicate, object)):
- """
- Add a triple to the storage.
-
- >>> c = TripleStore()
- >>> len(allTriples(c))
- 0
- >>> from rdflib.URIRef import URIRef
- >>> from rdflib.URIRef import Literal
- >>> c.add((URIRef('http://zope.org'), \
- URIRef('http://purl.org/dc/1.1/#Title'), \
- Literal('Zope Community Site')))
- >>> len(allTriples(c))
- 1
- >>> allTriples(c)[0][0]
- u'http://zope.org'
- >>> allTriples(c)[0][1]
- u'http://purl.org/dc/1.1/#Title'
- >>> allTriples(c)[0][2]
- u'Zope Community Site'
- """
- t = (subject, predicate, object)
- self.store.add(t)
-
- if self.notify:
- afterAdd(t)
-
- def addTriples(self, statements):
- """
- Add a set of statments to the store.
-
- >>> c = TripleStore()
- >>> len(allTriples(c))
- 0
- >>> from rdflib.URIRef import URIRef
- >>> from rdflib.URIRef import Literal
- >>> c.addTriples( \
- [(URIRef('http://zope.org'), \
- URIRef('http://purl.org/dc/1.1/#Title'), \
- Literal('Zope Community Site')), \
- (URIRef('http://zope.org'), \
- URIRef('http://purl.org/dc/1.1/#Description'), \
- Literal('Site for downloading Zope and contributed add-ons')),\
- ])
- >>> len(allTriples(c))
- 2
- >>> allTriples(c)[0][0]
- u'http://zope.org'
- >>> allTriples(c)[1][1]
- u'http://purl.org/dc/1.1/#Title'
- >>> allTriples(c)[1][2]
- u'Zope Community Site'
- """
- # Should 'afterAdd' take either one or many statements? If
- # so, then we could call it only once.
- for statement in statements:
- self.add(statement)
-
- def remove(self, (subject, predicate, object)):
- """
- Remove a triple from the storage.
-
- >>> c = TripleStore()
- >>> from rdflib.URIRef import URIRef
- >>> from rdflib.URIRef import Literal
- >>> c.add((URIRef('http://zope.org'), \
- URIRef('http://purl.org/dc/1.1/#Title'), \
- Literal('Zope Community Site')))
- >>> c.add((URIRef('http://www.zemantic.org'), \
- URIRef('http://purl.org/dc/1.1/#Title'), \
- Literal('Zemantic Web Site')))
- >>> len(allTriples(c))
- 2
- >>> c.remove((URIRef('http://zope.org'), \
- URIRef('http://purl.org/dc/1.1/#Title'), \
- Literal('Zope Community Site')))
- >>> len(allTriples(c))
- 1
- >>> allTriples(c)[0][0]
- u'http://www.zemantic.org'
- """
- t = (subject, predicate, object)
- if self.notify:
- beforeRemove(t)
-
- self.store.remove(t)
-
- def triples(self, (subject, predicate, object), *args):
- """
- Query the triple storage. The argument is a triple pattern
- which can contain a valid value or None to indicate any value
- is desired.
- """
-
- for triple in self.store.triples((subject, predicate, object)):
- yield triple
-
- def query(self, q):
- """
- Query zemantic with a query object.
- """
-
- return q(self)
-
- # no need to test the rest, they're all based on triples()
-
- def subjects(self, predicate=None, object=None):
- return self.store.subjects(predicate, object)
-
- def predicates(self, subject=None, object=None):
- return self.store.predicates(subject, object)
-
- def objects(self, subject=None, predicate=None):
- return self.store.objects(subject, predicate)
-
- def subject_predicates(self, object=None):
- return self.store.subject_predicates(object)
-
- def subject_objects(self, predicate=None):
- return self.store.subject_objects(predicate)
-
- def predicate_objects(self, subject=None):
- return self.store.predicate_objects(subject)
-
- def transitive_objects(self, subject, property, remember=None):
- return self.store.transitive_objects(subject, property, remember)
-
- def transitive_subjects(self, predicate, object, remember=None):
- return self.store.transitive_subjects(predicate, object, remember)
-
- def uniqueSubjects(self):
- return self.backend.uniqueSubjects()
-
- def uniquePredicates(self):
- return self.backend.uniquePredicates()
-
- def uniqueObjects(self):
- return self.backend.uniqueObjects()
-
- def rdfxml(self):
- return self.store.serialize()
-
- def rdfnt(self):
- return self.store.serialize("nt")
-
- def __len__(self):
- return len(self.store)
-
-
-class TripleStoreSized(object):
- implements(ISized)
-
- def __init__(self, zemantic):
- self._zemantic = zemantic
-
- def sizeForSorting(self):
- return ('item', len(self._zemantic))
-
- def sizeForDisplay(self):
- return str(len(self._zemantic)) + ' triples'
Deleted: /z3/zemantic/trunk/src/zemantic/utils.py
==============================================================================
--- /z3/zemantic/trunk/src/zemantic/utils.py Sat Jun 25 13:35:17 2005
+++ (empty file)
@@ -1,94 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2004-1005 Michel Pelletier
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-
-
-__rdf_description__ = '''\
-<rdf:RDF xmlns="http://web.resource.org/cc/"
-xmlns:dc="http://purl.org/dc/elements/1.1/"
-xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
-<Work rdf:about="http://zemantic.org/zemantic/utils.py"
- dc:title="zemantic.utils"
- dc:date="2005"
- dc:description="Misc stuff.">
- <dc:creator>
- <Agent dc:title="Michel Pelletier"/>
- </dc:creator>
- <dc:rights>
- <Agent dc:title="Michel Pelletier"/>
- </dc:rights>
- <license rdf:resource="http://zemantic.org/LICENSE.txt/"/>
-</Work>
-</rdf:RDF>
-'''
-
-from lib.ZODBBackend import ZODBBackend
-from interfaces import ITripleStore
-from zope.interface import implements
-from urllib import quote, quote_plus
-
-from rdflib.Literal import Literal
-from rdflib.BNode import BNode
-from rdflib.URIRef import URIRef
-
-from triplestore import TripleStore
-from query import Query
-
-class TripleStoreToDotAdapter(object):
-
- def __init__(self, cat, title=''):
- """
- Turn zemantic into a DOT graph
-
- """
- self.cat = cat
- self.title = title
-
- def toDot(self):
- out = []
- bcount = 0
- lcount = 0
- out.append('digraph "%s" {' % self.title)
-# out.append('node [fontname="Courier",fontsize=10,color=Black,fontcolor=Blue];')
-# out.append('edge [fontname="Courier",fontsize=10,color=Darkgreen,fontcolor=Red];')
- out.append('rankdir=LR;')
- cat = self.cat
- for r in cat.query(Query()):
-
- sname = oname = None
- if r.subject.startswith('_'):
- bcount += 1
- sname = 'Blank_' + str(bcount)
- else:
- sname = r.subject.n3()
-
- if r.object.startswith('"'):
- lcount += 1
- oname = 'Literal_' + str(lcount)
- else:
- oname = r.object.n3()
-
- out.append('%s [label="%s"];' % (sname.replace('"', ''), r.subject.n3().replace('"', '\"')))
- out.append('%s -> %s [label="%s"];' % (sname.replace('"', ''), oname.replace('"', ''), r.predicate.n3().replace('"', '\"')))
- out.append('%s [shape="box", label="%s"];' % (oname.replace('"', ''), r.object.n3().replace('"', '\"')))
-
- out.append('}')
- return '\n'.join(out)
-
-
-def shorten(s):
- if s > 30:
- return s[:13]+'...'+s[-13:]
- return s
-
-