def createHtmlElement(parentElement, elementName, attrMap={}, elementText=None): u"""createHtmlElement(Node, string, map, string) -> Node Creates a element given element name, attribute map and optional element node text. If the parentElement node is None, then element is under new document (zdom). """ #$NON-NLS-1$ element = None elementName = getNoneString(elementName) elementText = getNoneString(elementText) if not elementName: return None dom = None if parentElement: dom = parentElement.ownerDocument else: dom = ZDom() dom.loadXML(ELEMENT_TEMPLATE) parentElement = dom.documentElement try: element = dom.createElement(elementName) parentElement.appendChild(element) for (n, v) in attrMap.iteritems(): if n and v: element.setAttribute(n, v) if elementText: element.setText(elementText) except: pass return element
def createHtmlElement(parentElement, elementName, attrMap = {}, elementText = None): u"""createHtmlElement(Node, string, map, string) -> Node Creates a element given element name, attribute map and optional element node text. If the parentElement node is None, then element is under new document (zdom). """ #$NON-NLS-1$ element = None elementName = getNoneString(elementName) elementText = getNoneString(elementText) if not elementName: return None dom = None if parentElement: dom = parentElement.ownerDocument else: dom = ZDom() dom.loadXML(ELEMENT_TEMPLATE) parentElement = dom.documentElement try: element = dom.createElement(elementName) parentElement.appendChild(element) for (n,v) in attrMap.iteritems(): if n and v: element.setAttribute(n,v) if elementText: element.setText(elementText) except: pass return element
def _serializeResponseInfo(self, metaFile, connectionRespInfo, dataFilename): dom = ZDom() dom.loadXML(u"""<http-connection-response />""") #$NON-NLS-1$ rootElem = dom.documentElement urlElem = dom.createElement(u"url") #$NON-NLS-1$ urlElem.setText(connectionRespInfo.getURL()) rootElem.appendChild(urlElem) dataFileElem = dom.createElement(u"data-file") #$NON-NLS-1$ dataFileElem.setText(dataFilename) rootElem.appendChild(dataFileElem) respCodeElem = dom.createElement(u"response-code") #$NON-NLS-1$ respCodeElem.setText(unicode(connectionRespInfo.getCode())) rootElem.appendChild(respCodeElem) respMsgElem = dom.createElement(u"response-message") #$NON-NLS-1$ respMsgElem.setText(unicode(connectionRespInfo.getMessage())) rootElem.appendChild(respMsgElem) headersElem = dom.createElement(u"response-headers") #$NON-NLS-1$ rootElem.appendChild(headersElem) for headerName in connectionRespInfo.getHeaders(): headerVal = connectionRespInfo.getHeader(headerName) headerElem = dom.createElement(u"header") #$NON-NLS-1$ headerElem.setAttribute(u"name", headerName) #$NON-NLS-1$ headerElem.setText(headerVal) headersElem.appendChild(headerElem) dom.save(metaFile, True)
def _process(self): xhtmlDocument = self._getContext().getXhtmlDocument() pubMetaData = self._getContext().getPubMetaData() if not pubMetaData or not pubMetaData.isAddPoweredBy(): return bodyNode = xhtmlDocument.getDom().selectSingleNode( u"xhtml:body") #$NON-NLS-1$ pNL = bodyNode.selectNodes( u"//xhtml:p[@class='poweredbyzoundry']") #$NON-NLS-1$ if pNL and len(pNL) > 0 and pNL[-1]: # FIXME (PJ) check if the 'Zoundry BW' if so, change to 'Raven'. # grab the last para from the list # do we have a link to Zoundry? aLinkNode = pNL[-1].selectSingleNode( u"xhtml:a[@class='poweredbyzoundry_link']") #$NON-NLS-1$ if aLinkNode: href = aLinkNode.getAttribute(u"href") #$NON-NLS-1$ if href and href.find(u"zoundry.com") != -1: #$NON-NLS-1$ # we already have a link. return # No link. Continue and add a link in a new para to the end of the post xhtml = u'<p class="poweredbyzoundry">Powered by <a class="poweredbyzoundry_link" href="http://www.zoundryraven.com" rel="nofollow">Zoundry Raven</a></p>' #$NON-NLS-1$ newDom = ZDom() newDom.loadXML(xhtml) poweredbyParaNode = xhtmlDocument.getDom().importNode( newDom.documentElement, True) bodyNode.appendChild(poweredbyParaNode)
def _doHandleError(self, url, dndContext): ZShowInfoMessage(dndContext.getWindow(), _extstr(u"commonvideo.ErrorDiscoveringVideoEmbedInfoMsg"), _extstr(u"commonvideo.ErrorDiscoveringVideoEmbedInfoTitle")) #$NON-NLS-2$ #$NON-NLS-1$ dom = ZDom() dom.loadXML(u"<a href='' />") #$NON-NLS-1$ dom.documentElement.setAttribute(u"href", url) #$NON-NLS-1$ dom.documentElement.setText(url) return dom.serialize()
def serialize(self, entry): dom = ZDom() dom.loadXML(u"<resource-entry xmlns='%s' />" % self.namespace) #$NON-NLS-1$ root = dom.documentElement root.setAttribute(u"id", entry.getId()) #$NON-NLS-1$ self._serializeAttributes(entry,root) return dom
def _loadProfilesDom(self): domPath = self._getProfilesXmlPath() dom = ZDom() if not os.path.exists(domPath): dom.loadXML(DEFAULT_PROFILES_XML) else: dom.load(domPath) return dom
def serialize(self, template): templateDom = ZDom() templateDom.loadXML(u"<template xmlns='%s' />" % self.namespace) #$NON-NLS-1$ templateElem = templateDom.documentElement templateElem.setAttribute(u"template-id", template.getId()) #$NON-NLS-1$ self._serializeTemplate(templateElem, template) self._saveDom(templateDom, template.getTemplateDirectory())
def clone(self): u"""clone() -> ZXhtmlDocument() Returns copy based on cloning the underlying ZDom instance for this document.""" #$NON-NLS-1$ newDom = ZDom() newDom.loadXML(self.dom.serialize()) newDom.setNamespaceMap(XHTML_NSS_MAP) xhtmlDoc = ZXhtmlDocument(newDom) xhtmlDoc.docTypeString = self.docTypeString xhtmlDoc.mRootAbsPath = self.mRootAbsPath return xhtmlDoc
def enableEclipsePluginLoggerOutput(self, bEnable): exists = self.outputMap.has_key(u"Eclipse Console") #$NON-NLS-1$ if not exists and bEnable: dom = ZDom() dom.loadXML(ECLIPSE_PLUGIN_LOGGER_TEMPLATE) self._addLogOutput(dom.documentElement) elif exists and not bEnable: output = self.outputMap.pop(u"Eclipse Console") #$NON-NLS-1$ if output: output.close()
def enableConsoleDebugLoggerOutput(self, bEnable): exists = self.outputMap.has_key(u"Console Logger") #$NON-NLS-1$ if not exists and bEnable: dom = ZDom() dom.loadXML(CONSOLE_LOGGER_TEMPLATE) self._addLogOutput(dom.documentElement) elif exists and not bEnable: output = self.outputMap.pop(u"Console Logger") #$NON-NLS-1$ if output: output.close()
def enableMasterDebugLoggerOutput(self, bEnable): exists = self.outputMap.has_key(u"Master Debug Log File") #$NON-NLS-1$ if not exists and bEnable: dom = ZDom() dom.loadXML(MASTER_DEBUG_FILE_LOGGER_TEMPLATE) self._addLogOutput(dom.documentElement) elif exists and not bEnable: output = self.outputMap.pop(u"Master Debug Log File") #$NON-NLS-1$ if output: output.close()
def _extractEmbedMarkup(self, xhtmlReq): resp = xhtmlReq.getResponse() match = EMBED_PATTERN.search(resp) if match is not None: inputMarkup = match.group(1) dom = ZDom() dom.loadXML(inputMarkup) embedStr = dom.documentElement.getAttribute(u"value") #$NON-NLS-1$ return embedStr else: return None
def _doHandleError(self, url, dndContext): ZShowInfoMessage( dndContext.getWindow(), _extstr(u"commonvideo.ErrorDiscoveringVideoEmbedInfoMsg"), _extstr(u"commonvideo.ErrorDiscoveringVideoEmbedInfoTitle" )) #$NON-NLS-2$ #$NON-NLS-1$ dom = ZDom() dom.loadXML(u"<a href='' />") #$NON-NLS-1$ dom.documentElement.setAttribute(u"href", url) #$NON-NLS-1$ dom.documentElement.setText(url) return dom.serialize()
def serialize(self, store): storeDom = ZDom() storeDom.loadXML(u"<store xmlns='%s' />" % self.namespace) #$NON-NLS-1$ storeElem = storeDom.documentElement storeElem.setAttribute(u"store-id", store.getId()) #$NON-NLS-1$ storeElem.setAttribute(u"media-site-id", store.getMediaSiteId()) #$NON-NLS-1$ storeElem.setAttribute(u"name", store.getName()) #$NON-NLS-1$ self._serializeProperties(store.getProperties(), storeElem) return storeDom
def serialize(self, account): accountDom = ZDom() accountDom.loadXML(u"<account xmlns='%s' />" % self.namespace) #$NON-NLS-1$ accountElem = accountDom.documentElement accountElem.setAttribute(u"type", u"weblog") #$NON-NLS-2$ #$NON-NLS-1$ accountElem.setAttribute(u"account-id", account.getId()) #$NON-NLS-1$ self._serializeAttributes(account, accountElem) self._serializeAPIInfo(account.getAPIInfo(), accountElem) self._serializeBlogs(account.getBlogs(), accountElem) self._saveDom(accountDom, account.getDirectoryPath())
def serialize(self, task): taskDom = ZDom() taskDom.loadXML(u"<task xmlns='%s' />" % IZAppNamespaces.RAVEN_TASK_NAMESPACE_2006_05) #$NON-NLS-1$ taskElem = taskDom.documentElement taskElem.setAttribute(u"task-id", task.getId()) #$NON-NLS-1$ taskElem.setAttribute(u"class", unicode(task.__class__)) #$NON-NLS-1$ self._serializeStandardAttributes(task, taskElem) self._serializeError(task, taskElem) self._serializeCustomAttributes(task, taskElem) return taskDom
def serialize(self, document, serializationContext): documentDom = ZDom() documentDom.loadXML(u"<entry xmlns='%s' />" % self.namespace) #$NON-NLS-1$ entryElem = documentDom.documentElement entryElem.setAttribute(u"entry-id", document.getId()) #$NON-NLS-1$ self._serializeAttributes(document, entryElem) self._serializeBlogs(document.getBlogInfoList(), entryElem) self._serializePubMetaData(document.getPubMetaDataList(), entryElem) self._serializeTagwords(document.getTagwordsList(), entryElem) self._serializeContent(document.getContent(), entryElem, serializationContext) self._serializeTrackbacks(document.getTrackbacks(), entryElem) return documentDom
def _createTagsPNode(self, linkFormatterList, listOfWords): allSitesHtml = u"" #$NON-NLS-1$ count = 0 for formatter in linkFormatterList: tagHtml = self._createTagSiteHtml(formatter, listOfWords) allSitesHtml = allSitesHtml + tagHtml count = count + 1 if len ( linkFormatterList ) > 1 and count < len( linkFormatterList ): allSitesHtml = allSitesHtml + u" <br/>\n " #$NON-NLS-1$ html = ZAddTagwordsPrePublishHandler.TAGS_TEMPLATE % allSitesHtml html = html.replace(u'&', u'&') #$NON-NLS-1$ #$NON-NLS-2$ newDom = ZDom() newDom.loadXML(html) return newDom.documentElement
def _createTagsPNode(self, linkFormatterList, listOfWords): allSitesHtml = u"" #$NON-NLS-1$ count = 0 for formatter in linkFormatterList: tagHtml = self._createTagSiteHtml(formatter, listOfWords) allSitesHtml = allSitesHtml + tagHtml count = count + 1 if len(linkFormatterList) > 1 and count < len(linkFormatterList): allSitesHtml = allSitesHtml + u" <br/>\n " #$NON-NLS-1$ html = ZAddTagwordsPrePublishHandler.TAGS_TEMPLATE % allSitesHtml html = html.replace(u'&', u'&') #$NON-NLS-1$ #$NON-NLS-2$ newDom = ZDom() newDom.loadXML(html) return newDom.documentElement
def _createDocument(self, xhtmlString, throwOnError = False): u"""Creates and loads the given string into the zDom.""" #$NON-NLS-1$ xhtmlString = xhtmlString.lstrip() if xhtmlString.startswith(u"<!DOCTYPE"): #$NON-NLS-1$ xhtmlString = xhtmlString[xhtmlString.find(u">") + 1:] #$NON-NLS-1$ try: dom = ZDom() dom.setNamespaceMap(XHTML_NSS_MAP) dom.loadXML(xhtmlString) return dom except: if throwOnError: raise return None
def serialize(self, spellChecker, path): u"""serialize(ZSpellChecker, string) -> None Serializes a spell checker to a string. The path is a directory.""" #$NON-NLS-1$ dom = ZDom() dom.loadXML(u"""<spellchecker xmlns="%s" />""" % IZAppNamespaces.RAVEN_SPELLCHECKER_NAMESPACE) #$NON-NLS-1$ spellCheckerElem = dom.documentElement self._serializeDictionaryLanguage(spellCheckerElem, spellChecker.dictionaryLang) self._serializeProvider(spellCheckerElem, spellChecker.provider) self._serializePersonalDictionary(spellCheckerElem, spellChecker.personalWordList) self._serializeAutoCorrections(spellCheckerElem, spellChecker.autoCorrections) if not os.path.isdir(path): os.makedirs(path) filePath = os.path.join(path, u"spellchecker.xml") #$NON-NLS-1$ dom.save(filePath, True)
def _createDocument(self, xhtmlString, throwOnError=False): u"""Creates and loads the given string into the zDom.""" #$NON-NLS-1$ xhtmlString = xhtmlString.lstrip() if xhtmlString.startswith(u"<!DOCTYPE"): #$NON-NLS-1$ xhtmlString = xhtmlString[xhtmlString.find(u">") + 1:] #$NON-NLS-1$ try: dom = ZDom() dom.setNamespaceMap(XHTML_NSS_MAP) dom.loadXML(xhtmlString) return dom except: if throwOnError: raise return None
def serialize(self, packet): dom = ZDom() dom.loadXML(u"<zup:usage-packet xmlns:zup='%s' />" % IZBlogAppNamespaces.RAVEN_USAGE_STATS_NAMESPACE) #$NON-NLS-1$ rootElem = dom.documentElement rootElem.setAttribute(u"packet-id", packet.getId()) #$NON-NLS-1$ for key in packet.getAttributes(): value = packet.getAttributes()[key] attrElem = dom.createElement(u"zup:attribute", IZBlogAppNamespaces.RAVEN_USAGE_STATS_NAMESPACE) #$NON-NLS-1$ rootElem.appendChild(attrElem) attrElem.setAttribute(u"name", key) #$NON-NLS-1$ attrElem.setText(value) return dom
def _save(self): if not self.registryFile: return mediaStorageDir = os.path.basename(self.registryFile) dom = ZDom() dom.loadXML(u"<registry/>") #$NON-NLS-1$ registryElem = dom.documentElement for fileName in self.fileMap: (size, timestamp, uploadResponse) = self.fileMap[fileName] relativeFileName = makeRelativePath(mediaStorageDir, fileName) url = uploadResponse.getUrl() embedFragment = uploadResponse.getEmbedFragment() metaData = uploadResponse.getMetaData() entryElem = dom.createElement(u"entry") #$NON-NLS-1$ entryElem.setAttribute(u"size", unicode(size)) #$NON-NLS-1$ entryElem.setAttribute(u"timestamp", unicode(timestamp)) #$NON-NLS-1$ fileElem = dom.createElement(u"file") #$NON-NLS-1$ urlElem = dom.createElement(u"url") #$NON-NLS-1$ embedElem = dom.createElement(u"embed") #$NON-NLS-1$ metaDataElem = dom.createElement(u"metaData") #$NON-NLS-1$ # When in portable mode, save the file paths as relative (which will # only happen when the image is on the same drive as the app). if isPortableEnabled(): fileElem.setText(relativeFileName) else: fileElem.setText(fileName) entryElem.appendChild(fileElem) if url: urlElem.setText(unicode(url)) entryElem.appendChild(urlElem) if embedFragment is not None: embedElem.appendChild(dom.importNode(embedFragment, True)) entryElem.appendChild(embedElem) if metaData is not None: metaDataElem.appendChild(dom.importNode(metaData, True)) entryElem.appendChild(metaDataElem) registryElem.appendChild(entryElem) dom.save(self.registryFile, True)
def getMimimalMetaDataNode(self): u"""getMimimalMetaDataNode() -> ZElement or None Returns node with minimal meta data (e.g. just id, title, edit links etc). """ #$NON-NLS-1$ if self.getNode(): id = self.getId() title = self.getTitle() url = self.getUrl() ct = self.getContentType() editLink = self.getEditLink() editMediaLink = self.getEditMediaLink() editMediaCT = self.getEditMediaContentType() xml = PICASA_MINIMAL_PHOTO_ENTRY_TEMPLATE % (id, title, url, ct, editLink, editMediaLink, editMediaCT) dom = ZDom() dom.loadXML(xml) return dom.documentElement else: return None
def importPersonalDictionary(self): joeyConfigDom = self._getJoeyUserConfigDom() if not joeyConfigDom: return try: node = joeyConfigDom.selectSingleNode(u"/joey/user-config/spell-check/language") #$NON-NLS-1$ if not node: return spellcheckLang = getNoneString( node.getText()) if not spellcheckLang: return # FIXME (EPW) we could support other languages... if not spellcheckLang == u"en_US": #$NON-NLS-1$ return # 1) read all words from ZBW personal-dictionary.xml file # 2) create new spellchecker.xml DOM # 3) save new Raven spellchecker file to 'PROFILE\LANG\spellchecker.xml' joeyDictFile = os.path.join(self.pathToJoeyProfile, u"spelling/personal-dictionary.xml") #$NON-NLS-1$ dom = ZDom() dom.load(joeyDictFile) dom.setNamespaceMap(ZBW_PERSONAL_DICTIONARY_NSS_MAP) wordNodeList = dom.selectNodes(u"/pd:personal-dictionary/pd:word") #$NON-NLS-1$ newDom = ZDom() newDom.loadXML(ZBlogWriterDictionaryImporter.SPELLCHECK_TEMPLATE) newDom.setNamespaceMap(RAVEN_SPELLCHECK_NSS_MAP) personalDictElem = newDom.selectSingleNode(u"/spl:spellchecker/spl:personal-dictionary") #$NON-NLS-1$ for wordNode in wordNodeList: word = wordNode.getText() newWordElem = newDom.createElement(u"word", IZBlogAppNamespaces.RAVEN_SPELLCHECKER_NAMESPACE) #$NON-NLS-1$ newWordElem.setText(word) personalDictElem.appendChild(newWordElem) outputDir = os.path.join(self.pathToRavenProfile, u"spellcheck/en_US") #$NON-NLS-1$ os.makedirs(outputDir) outputFile = os.path.join(outputDir, u"spellchecker.xml") #$NON-NLS-1$ newDom.save(outputFile, True) except ZException, ze: # FIXME (EPW) need to report errors in some way ze.printStackTrace()
def serialize(self, packet): dom = ZDom() dom.loadXML( u"<zup:usage-packet xmlns:zup='%s' />" % IZBlogAppNamespaces.RAVEN_USAGE_STATS_NAMESPACE) #$NON-NLS-1$ rootElem = dom.documentElement rootElem.setAttribute(u"packet-id", packet.getId()) #$NON-NLS-1$ for key in packet.getAttributes(): value = packet.getAttributes()[key] attrElem = dom.createElement( u"zup:attribute", IZBlogAppNamespaces.RAVEN_USAGE_STATS_NAMESPACE) #$NON-NLS-1$ rootElem.appendChild(attrElem) attrElem.setAttribute(u"name", key) #$NON-NLS-1$ attrElem.setText(value) return dom
def _journal(self, message, args = None): if not JOURNAL: return if self.journalFile is None: self._openJournal() if args is None: args = () journalMessage = message % args dom = ZDom() dom.loadXML(u"<journalEntry />") #$NON-NLS-1$ elem = dom.documentElement elem.setAttribute(u"timestamp", unicode(ZSchemaDateTime())) #$NON-NLS-1$ elem.setText(journalMessage) self.journalFile.write(elem.serialize()) self.journalFile.write(u"\n") #$NON-NLS-1$ self.journalFile.flush()
def _uploadStream(self, fileName, fileStream, metaData): #@UnusedVariable data = { u"xml" : u"yes", #$NON-NLS-1$ #$NON-NLS-2$ u"fileupload" : fileStream #$NON-NLS-1$ } code = self._getRegistrationCode() if code: data[u"cookie"] = code #$NON-NLS-1$ imageShackUrl = u"http://www.imageshack.us/index.php" #$NON-NLS-1$ request = ZSimpleTextHTTPRequest(imageShackUrl) ok = request.send( data ) if ok: respData = request.getResponse() dom = ZDom() dom.loadXML( respData ) url = dom.selectSingleNodeText(u"/links/image_link") #$NON-NLS-1$ return ZUploadResponse(url) else: code = unicode( request.getHttpStatusCode() ) msg = unicode( request.getHttpStatusMessage() ) raise ZException(u"ImageShackMedia upload failed. HTTP response: %s %s" % (code, msg)) #$NON-NLS-1$
def _uploadStream(self, fileName, fileStream, metaData): #@UnusedVariable data = { u"xml": u"yes", #$NON-NLS-1$ #$NON-NLS-2$ u"fileupload": fileStream #$NON-NLS-1$ } code = self._getRegistrationCode() if code: data[u"cookie"] = code #$NON-NLS-1$ imageShackUrl = u"http://www.imageshack.us/index.php" #$NON-NLS-1$ request = ZSimpleTextHTTPRequest(imageShackUrl) ok = request.send(data) if ok: respData = request.getResponse() dom = ZDom() dom.loadXML(respData) url = dom.selectSingleNodeText(u"/links/image_link") #$NON-NLS-1$ return ZUploadResponse(url) else: code = unicode(request.getHttpStatusCode()) msg = unicode(request.getHttpStatusMessage()) raise ZException( u"ImageShackMedia upload failed. HTTP response: %s %s" % (code, msg)) #$NON-NLS-1$
def _process(self): xhtmlDocument = self._getContext().getXhtmlDocument() pubMetaData = self._getContext().getPubMetaData() if not pubMetaData or not pubMetaData.isAddPoweredBy(): return bodyNode = xhtmlDocument.getDom().selectSingleNode(u"xhtml:body") #$NON-NLS-1$ pNL = bodyNode.selectNodes(u"//xhtml:p[@class='poweredbyzoundry']") #$NON-NLS-1$ if pNL and len(pNL) > 0 and pNL[-1]: # FIXME (PJ) check if the 'Zoundry BW' if so, change to 'Raven'. # grab the last para from the list # do we have a link to Zoundry? aLinkNode = pNL[-1].selectSingleNode(u"xhtml:a[@class='poweredbyzoundry_link']") #$NON-NLS-1$ if aLinkNode: href= aLinkNode.getAttribute(u"href") #$NON-NLS-1$ if href and href.find(u"zoundry.com") != -1: #$NON-NLS-1$ # we already have a link. return # No link. Continue and add a link in a new para to the end of the post xhtml = u'<p class="poweredbyzoundry">Powered by <a class="poweredbyzoundry_link" href="http://www.zoundryraven.com" rel="nofollow">Zoundry Raven</a></p>' #$NON-NLS-1$ newDom = ZDom() newDom.loadXML(xhtml) poweredbyParaNode = xhtmlDocument.getDom().importNode(newDom.documentElement, True) bodyNode.appendChild(poweredbyParaNode)
def _loadDefaultLoggerNode(self): dom = ZDom() dom.loadXML(DEFAULT_LOG_XML) return dom.selectSingleNode(u"/") #$NON-NLS-1$
def save(self, defaultTranslation): self._journal(u"--save--") #$NON-NLS-1$ localeStr = self.locale.toString() baseFileName = os.path.join(self.bundleDirectory, u"zoundry.base_%s.xml" % localeStr) #$NON-NLS-1$ appFrameworkFileName = os.path.join(self.bundleDirectory, u"zoundry.appframework_%s.xml" % localeStr) #$NON-NLS-1$ blogAppFileName = os.path.join(self.bundleDirectory, u"zoundry.blogapp_%s.xml" % localeStr) #$NON-NLS-1$ if DEBUG: outputLogFileName = os.path.join(self.bundleDirectory, u"debug_save_%s.log" % localeStr) #$NON-NLS-1$ outputLog = open(outputLogFileName, u"w") #$NON-NLS-1$ self.debug(outputLog, u"Saving translation") #$NON-NLS-1$ try: baseDom = ZDom() baseDom.loadXML(BUNDLE_TEMPLATE % localeStr) baseDom.documentElement.addTextNode(u"\n") #$NON-NLS-1$ self.debug(outputLog, u"baseDom created") #$NON-NLS-1$ appFrameworkDom = ZDom() appFrameworkDom.loadXML(BUNDLE_TEMPLATE % localeStr) appFrameworkDom.documentElement.addTextNode(u"\n") #$NON-NLS-1$ self.debug(outputLog, u"appFrameworkDom created") #$NON-NLS-1$ blogAppDom = ZDom() blogAppDom.loadXML(BUNDLE_TEMPLATE % localeStr) blogAppDom.documentElement.addTextNode(u"\n") #$NON-NLS-1$ self.debug(outputLog, u"blogAppDom created") #$NON-NLS-1$ bundleStrings = self.getBundleStrings() keys = bundleStrings.keys() keys.sort() for key in keys: self.debug(outputLog, u"Writing key: %s" % key) #$NON-NLS-1$ try: value = bundleStrings[key] dom = None if key in defaultTranslation.getBaseKeys(): dom = baseDom elif key in defaultTranslation.getAppFrameworkKeys(): dom = appFrameworkDom elif key in defaultTranslation.getBlogAppKeys(): dom = blogAppDom elem = dom.documentElement stringElem = dom.createElement(u"zb:string", BUNDLE_NS) #$NON-NLS-1$ stringElem.setAttribute(u"name", key) #$NON-NLS-1$ stringElem.setText(value) elem.addTextNode(u" ") #$NON-NLS-1$ elem.appendChild(stringElem) elem.addTextNode(u"\n") #$NON-NLS-1$ except Exception, e: getLoggerService().exception(e) self.debug(outputLog, u"Done writing key: %s" % key) #$NON-NLS-1$ self.debug(outputLog, u"Done writing all keys.") #$NON-NLS-1$ self.debug(outputLog, u"Backing up old translations.") #$NON-NLS-1$ backup_baseFileName = os.path.join(self.bundleDirectory, u"BACKUP_zoundry.base_%s.xml" % self.locale.toString()) #$NON-NLS-1$ backup_appFrameworkFileName = os.path.join(self.bundleDirectory, u"BACKUP_zoundry.appframework_%s.xml" % self.locale.toString()) #$NON-NLS-1$ backup_blogAppFileName = os.path.join(self.bundleDirectory, u"BACKUP_zoundry.blogapp_%s.xml" % self.locale.toString()) #$NON-NLS-1$ if os.path.exists(baseFileName): shutil.copy2(baseFileName, backup_baseFileName) if os.path.exists(appFrameworkFileName): shutil.copy2(appFrameworkFileName, backup_appFrameworkFileName) if os.path.exists(blogAppFileName): shutil.copy2(blogAppFileName, backup_blogAppFileName) self.debug(outputLog, u"Saving DOMs") #$NON-NLS-1$ baseDom.save(baseFileName) self.debug(outputLog, u"Successfully saved baseDom") #$NON-NLS-1$ appFrameworkDom.save(appFrameworkFileName) self.debug(outputLog, u"Successfully saved appFrameworkDom") #$NON-NLS-1$ blogAppDom.save(blogAppFileName) self.debug(outputLog, u"Successfully saved blogAppDom") #$NON-NLS-1$ deleteFile(backup_baseFileName) deleteFile(backup_appFrameworkFileName) deleteFile(backup_blogAppFileName) self.debug(outputLog, u"Deleted backup files.") #$NON-NLS-1$
def _createEmptyFeed(self): # create place holder dom dom = ZDom() dom.loadXML(ATOM_10_EMPTY_FEED_XML) self._setDomNSS(dom) return dom
def applyTemplateToDocument(template, document, mode = APPLY_TEMPLATE_MODE_FULL): u"""applyTemplateToDocument(IZTemplate, IZDocument) -> ZXHtmlDocument""" #$NON-NLS-1$ logger = getLoggerService() if template is None or document is None: logger.warning(u"applyTemplateToDocument:: Either template or document were None - skipping.") #$NON-NLS-1$ return None title = getSafeString(document.getTitle()) xhtmlDoc = None content = document.getContent() if content is not None: xhtmlDoc = content.getXhtmlDocument() if xhtmlDoc is None: logger.warning(u"applyTemplateToDocument:: XHtml document was None, skipping.") #$NON-NLS-1$ return None analyzer = ZXhtmlBodyFindingAnalyser() xhtmlDoc.analyse(analyzer) xhtmlBody = analyzer.getBody() # At this point, we have the document's title and body. logger.debug(u"applyTemplateToDocument:: title: %s" % title) #$NON-NLS-1$ # Get the path to the template file we want to use. templateDir = template.getTemplateDirectory() templateFileName = template.getAllFileName() if mode == APPLY_TEMPLATE_MODE_TITLE_AND_BODY: templateFileName = template.getTitleAndBodyFileName() elif mode == APPLY_TEMPLATE_MODE_BODY_ONLY: templateFileName = template.getBodyOnlyFileName() templateFilePath = os.path.join(templateDir, templateFileName) logger.debug(u"applyTemplateToDocument:: templateFileName: %s" % templateFileName) #$NON-NLS-1$ logger.debug(u"applyTemplateToDocument:: templateFilePath: %s" % templateFilePath) #$NON-NLS-1$ if os.path.isfile(templateFilePath) and xhtmlBody is not None: templateContent = getFileContents(templateFilePath) templateContent = _preprocessTemplateContent(templateContent, templateDir) templateDom = ZDom() templateDom.loadXML(templateContent) templateXHtml = ZXhtmlDocument(templateDom) # Get the DOCTYPE value from the root file (if any) rootFilePath = template.getResolvedRootFile() rootFileContent = None if os.path.isfile(rootFilePath): rootFile = open(rootFilePath, u"r") #$NON-NLS-1$ try: rootFileContent = rootFile.read() finally: rootFile.close() if rootFileContent: results = DOCTYPE_RE.findall(rootFileContent) if results: docTypeString = results[0] templateXHtml.setDocTypeString(docTypeString) # Find the template body elements. visitor = ZTemplateBodyFindingVisitor() visitor.visit(templateDom) templateBodyElements = visitor.getBodyElements() if not templateBodyElements: logger.warning(u"applyTemplateToDocument:: failed to find any template body elements") #$NON-NLS-1$ # Find the template title elements. visitor = ZTemplateTitleFindingVisitor() visitor.visit(templateDom) templateTitleElements = visitor.getTitleElements() if not templateTitleElements: logger.warning(u"applyTemplateToDocument:: failed to find any template title elements") #$NON-NLS-1$ # Do title stuff - replace the ravenTitle elem with a span containing the title for templateTitleElem in templateTitleElements: titleParentElem = templateTitleElem.parentNode newTitleElem = templateDom.createElement(u"span") #$NON-NLS-1$ newTitleElem.setText(title) titleParentElem.replaceChild(newTitleElem, templateTitleElem) # Do body stuff - insert all children of xhtmlBody, then remove the ravenBody elem for templateBodyElem in templateBodyElements: bodyParentElem = templateBodyElem.parentNode for node in xhtmlBody.getChildren(): bodyParentElem.insertBefore(templateDom.importNode(node, True), templateBodyElem) bodyParentElem.removeChild(templateBodyElem) # IE hates empty DIVs and %20's in attributes. Dunno why. _fixupIECrappiness(templateDom) return templateXHtml else: logger.warning(u"applyTemplateToDocument:: template file not found") #$NON-NLS-1$ return xhtmlDoc