def xpathQuery(self, ctx, sysConfig, xpath): # Get the database configuration try: db = self._getDatabase(sysConfig) if (not isinstance(xpath, str)): node = libxml2.xmlNode(_obj=xpath[0]) xpath = node.content content = db.xpathQuery(None, xpath) # See if this looks like an XML result if (content.startswith("<?xml")): doc = XMLFragment(content) # Extract the expected result set now that we've converted into libxml format. result = doc.xpathEval("/results/*") self.cleanupList.append(doc) else: doc = XMLFragment(libxml2.newDoc("1.0")) result = [doc.newDocText(content)] self.cleanupList.append(doc) return result except Exception, err: db.log.exception("DbXslExtension: Error searching")
def getItem(self, ctx, sysConfig, baseURL, id, index): try: db = self._getDatabase(sysConfig) if not isinstance(id, str): node = libxml2.xmlNode(_obj=id[0]) id = node.content if id != "": if index == 0: content = db.xpathQuery(None, "/item[@id > " + str(id) + "]") else: content = db.xpathQuery(None, "/item[@id < " + str(id) + "]") ids = libxml2.parseDoc(content).xpathEval("/results/item/@id") idList = [] for id in ids: idList.append(int(id.content)) if len(ids) > 0: idList.sort() previousID = idList[index] previous = XMLFragment(db.getRecord(None, previousID)) title = previous.getValue("/item/title") return self.itemLink(ctx, baseURL, title, previousID) else: return "" else: return "" except Exception, err: db.log.exception("DbXslExtension: Error getting previous item")
def __init__(self): self.basePath = ".." sitesConfig = XMLFragment(libxml2.parseFile(self.basePath + "/sites.xml")) results = sitesConfig.get("/sites/site") self.siteList = {} # Build up the list of sites for this instance for result in results: print "Registering site " + result["@url-base"] self.siteList[result["@url-base"]] = Site(result["@site-base"])
def __init__(self, sitePath): self.sitePath = sitePath print "Creating site at path " + sitePath # TODO: make sure the config file actually exists self.config = XMLFragment(libxml2.parseFile(sitePath + "/config/config.xml")) self.db = Database(self.config)
class Site: def __init__(self, sitePath): self.sitePath = sitePath print "Creating site at path " + sitePath # TODO: make sure the config file actually exists self.config = XMLFragment(libxml2.parseFile(sitePath + "/config/config.xml")) self.db = Database(self.config) def getConfig(self): return self.config def getDatabase(self): return self.db def getComponent(self, name): if (os.path.isdir(self.sitePath + "/components/" + name)): return Component(name, self.sitePath + "/components/") return None def getConfigValue(self, xpath, default=""): results = self.config.xpathEval(xpath) if (len(results) > 0): return results[0].content else: return default
def xpathQuery(self, txn, xpath): xmlResult = [u'<?xml version="1.0"?><results>'] files = os.listdir(self.dbPath) for file in files: doc = XMLFragment(open(self.dbPath + "/" + file).read()) results = doc.xpathEval(xpath) for result in results: result.unlinkNode() result.reconciliateNs(doc.getDocument()) content = result.serialize() if (content.startswith("<")): xmlResult.append(content) else: xmlResult.append(result.content) xmlResult.append(u"</results>") #self._applyTriggers(txn, "query", XMLFragment("\n".join(xmlResult))) return u"\n".join(xmlResult)
def respondToPost(self, transaction): request = transaction.request() response = transaction.response() # The post the trackback applies to. postID = request.extraURLPath().split('/')[1] try: spec = { '/trackback/@postID': postID, '/trackback/title': request.field('title', ""), '/trackback/url': request.field('url', ""), '#required#/trackback/url': 'The URL for the linking entry is required', '#blacklist#/trackback/url': self.weblog.configValue("/blog/blacklist-message"), '/trackback/excerpt': request.field('excerpt', ""), '#blacklist#/trackback/excerpt': self.weblog.configValue("/blog/blacklist-message"), '/trackback/blog_name': request.field('blog_name', "") } update = DocumentBuilder(self.weblog, spec) errorText = update.getErrorText() if (errorText == ""): content = update.getDocument().serialize() self.weblog.db.addRecord(None, content) doc = XMLFragment() doc.addNode("/response/error", "0") self.sendResponseText(response, doc.serialize()) else: doc = XMLFragment() doc.addNode("/response/error", "1") doc.addNode("/response/message", errorText) self.sendResponseText(response, doc.serialize()) except NotFoundError: response.setStatus(404, 'Not Found') response.write("The post being commented on could not be located.")
def updateRecord(self, txn, recordID, record): if (record == None): raise ParseError try: fileName = self.dbPath + str(recordID) + ".xml" if (not os.path.exists(fileName)): raise NotFoundError # Make sure the ID is set on the new content doc = XMLFragment(record) root = doc.getRootElement() root.setProp("id", str(recordID)) # Update the document file = open(fileName, "w") file.write(doc.serialize()) file.close() self._applyTriggers(txn, "update", doc) except libxml2.parserError, e: raise ParseError(e)
def testDeleteRecord(self): # Add an entry and the remove it id = self.db.addRecord(None, testEntry) self.db.deleteRecord(None, id) # We shouldn't be able to find it now. self.assertRaises(BaseDatabase.NotFoundError, self.db.getRecord, None, id) # Test deleteing a non-existent entry self.assertRaises(BaseDatabase.NotFoundError, self.db.deleteRecord, None, -1) # Test cascading deletes. # add an item entry id = self.db.addRecord(None, "<item/>") # add two comments that reference the item comment1 = self.db.addRecord(None, "<comment postID='" + str(id) + "'/>") comment2 = self.db.addRecord(None, "<comment postID='" + str(id) + "'/>") print "comment 1 " + str(comment1) print "comment 2 " + str(comment2) # Check to see if comment-count = 2 on the item entry tests increment # triggers entry = XMLFragment(self.db.getRecord(None, id)) self.assertEqual(entry.getValue("/item/comment-count"), "2") # Add another comment and then remove it again to check proper counting comment3 = self.db.addRecord(None, "<comment postID='" + str(id) + "'/>") entry = XMLFragment(self.db.getRecord(None, id)) # count should now be three self.assertEqual(entry.getValue("/item/comment-count"), "3") # remove the comment and the count should drop back to two self.db.deleteRecord(None, comment3) entry = XMLFragment(self.db.getRecord(None, id)) self.assertEqual(entry.getValue("/item/comment-count"), "2") # Deleting the item should also delete the comments. self.db.deleteRecord(None, id) self.assertRaises(BaseDatabase.NotFoundError, self.db.getRecord, None, id) self.assertRaises(BaseDatabase.NotFoundError, self.db.getRecord, None, comment1) self.assertRaises(BaseDatabase.NotFoundError, self.db.getRecord, None, comment2)
def respondToPost(self, transaction): request = transaction.request() response = transaction.response() entryType = request.field('type', "") fields = request.fields() try: entryDocument = DocumentBuilder(self.weblog, fields) content = entryDocument.serialize() print content # Convert the rest of the form into an XML form spec. formDocument = self._buildFormDocument(fields) errorText = "" try: # If there was a problem building the initial document we just # want to display an error. errorText = entryDocument.getErrorText() if (errorText != ""): raise ProcessingError() # Otherwise we continue processing the document. else: # Add the entry document into the form specification. formDocument.getDocument().addNode("/form/content", entryDocument.getRootElement()) # Hand the form spec to the action processor for this entry # type. content = formDocument.serialize() # print content result = self.weblog.db.runTransform(content, entryType + "/action", "", "admin/action") print result actionResult = XMLFragment(result) # If there were any errors in processing we send an error # to the user. errors = actionResult.xpathEval("/results/error-text") if (len(errors) > 0): for error in errors: errorText = error.content + "<br/>" raise ProcessingError() # Otherwise we figure ou what button was clicked so that we # forward the user to the proper place. else: button = formDocument.xpathEval("/form/button/node()")[0].name #print button style = self.getStyle(request, actionResult, "/results/action/" + button) #print style self.sendResponse(response, entryDocument, style) except ProcessingError, e: # Make sure the document actually has content and then add the # error message to it. try: root = entryDocument.getRootElement() entryDocument.getDocument().addNode("/node()/error-text", errorText, 1) except: entryDocument.getDocument().addNode("/dummy/error-text", errorText, 1) print entryDocument.serialize() style = self.getStyle(request, formDocument, "/form/action/error") self.sendResponse(response, entryDocument, style) except NotFoundError, e: doc = XMLFragment("<error-text>Document not found</error-text>") self.sendResponse(response, doc, "admin/error")