Ejemplo n.º 1
0
 def handleException(self, type, value, tb):
     # Log the exception in the logger
     zexception = None
     if isinstance(value, ZException):
         zexception = value
     elif isinstance(value, Exception):
         zexception = ZException(rootCause=value)
     else:
         zexception = ZException(unicode(value), None, (type, value, tb))
     getLoggerService().exception(zexception)
     # Show the error to the user.
     ZShowExceptionWithFeedback(getApplicationModel().getTopWindow(),
                                zexception)
Ejemplo n.º 2
0
 def _verifyHttpURL(self, url):
     tempFilePath = os.path.join(getApplicationModel().getUserProfile().getTempDirectory(), u"tmp_url_mstore_ztest.bin") #$NON-NLS-1$
     downloader = ZHttpBinaryFileDownload(url, tempFilePath)
     try:
         if not downloader.send():
             raise ZException(_extstr(u"mediastorageztest.FileNotFoundError") % url) #$NON-NLS-1$
         ct = downloader.getContentType()
         if not (ct == u"image/png"): #$NON-NLS-1$
             raise ZException(_extstr(u"mediastorageztest.IncorrectContentTypeError") % (ct, url)) #$NON-NLS-1$
         numBytes = downloader.getResponse()
         if numBytes != 222: # Note: the test file is 222 bytes in size
             raise ZException(_extstr(u"mediastorageztest.TestFileWrongSizeError")) #$NON-NLS-1$
     finally:
         if os.path.isfile(tempFilePath):
             os.remove(tempFilePath)
Ejemplo n.º 3
0
 def run(self):
     success = False
     try:
         success = self._runTask()
     except Exception, e:
         zex = ZException(rootCause=e)  #$NON-NLS-1$
         zex.printStackTrace()
Ejemplo n.º 4
0
    def setProperty(self, _xpath, value, autoCommit=True):
        u"""Sets a user or system property.  Takes an xpath, value, and optional boolean flag 'system' which
        indicates whether to change the user or system properties.  Raises a ValueError if the xpath is not
        a valid (already-existing) node or attribute.""" #$NON-NLS-1$
        self.lock.acquire()

        node = self.getPropertyNode(_xpath)
        if not node:
            node = self.createPropertyNode(_xpath)
        if not node:
            raise ValueError

        if isinstance(value, unicode) or isinstance(value, str):
            node.setText(value)
        elif isinstance(value, ZElement):
            node.removeAllChildren()
            value = node.ownerDocument.importNode(value, True)
            node.appendChild(value)
        else:
            raise ZException(u"Unsupported value type for setProperty: %s" %
                             unicode(type(value)))  #$NON-NLS-1$

        # Now save the files (pretty print)
        if autoCommit:
            self.saveProperties()
        self.lock.release()

        self._fireEvent(_xpath, value)
Ejemplo n.º 5
0
    def start(self, listener = _NULL_STARTUP_LISTENER):
        listener.engineStarting()

        # Get the list of service extension points.
        extensionPoints = self._getServiceExtensionPoints()
        listener.engineCreatingServices(len(extensionPoints))

        # Create all of the IZService objects.
        createdServices = []
        numFailed = 0
        for extensionPoint in extensionPoints:
            extPointId = extensionPoint.getId()
            try:
                theClass = extensionPoint.loadClass()
                if not issubclass(theClass, IZService):
                    raise ZEngineException(_extstr(u"engine.ErrorCreatingService") % extensionPoint.getClass()) #$NON-NLS-1$
                theService = theClass()
                if not isinstance(theService, IZService):
                    raise ZEngineException(_extstr(u"engine.ErrorCreatingService") % extensionPoint.getClass()) #$NON-NLS-1$
                listener.engineServiceCreated(extPointId)
                createdServices.append( (extPointId, theService) )
            except ZException, ze:
                listener.engineServiceCreationFailed(extPointId, ze.getStackTrace())
                numFailed += 1
            except Exception, e:
                listener.engineServiceCreationFailed(extPointId, ZException(rootCause = e).getStackTrace())
                numFailed += 1
Ejemplo n.º 6
0
 def _runTask(self):
     newValue = self.getPage()._getSiteUrl()
     # fire evt to start busy animation
     self.refreshPage(u"begin-autodiscover", newValue)  #$NON-NLS-1$
     rval = False
     try:
         # reset previous value
         self.getSession().setProperty(u"siteurl-page.discover-info",
                                       None)  #$NON-NLS-1$
         discoverInfo = self.getPage()._getModel().autodiscover(newValue)
         #print u"ZAutodiscoverTask info",discoverInfo #$NON-NLS-1$ FIXME (PJ) remove this debug line
         self.getSession().setProperty(u"siteurl-page.discover-info",
                                       discoverInfo)  #$NON-NLS-1$
         # cache successful results
         if discoverInfo and discoverInfo.siteId:
             cacheMap = self.getSession().getProperty(
                 u"siteurl-page.discover-info-cache")  #$NON-NLS-1$
             if cacheMap is None:
                 cacheMap = {}
                 self.getSession().setProperty(
                     u"siteurl-page.discover-info-cache",
                     cacheMap)  #$NON-NLS-1$
             cacheMap[newValue] = discoverInfo
         rval = True
     except Exception, e:
         # FIXME (PJ) show friendly error messages
         # fire evt to show error message to user.
         zex = ZException(rootCause=e)
         data = (u"Auto discovery error", zex.getStackTrace(), zex
                 )  #$NON-NLS-1$
         self.refreshPage(u"error-autodiscover", data)  #$NON-NLS-1$
Ejemplo n.º 7
0
 def deleteFile(self, fileName, metaData):  #@UnusedVariable
     photoEditMediaLink = self._getEditMediaLinkFromMetaData(metaData)
     if not photoEditMediaLink:
         raise ZException(
             u"Cannot delete Picasa resource. Edit-Media link metadata not found."
         )  #$NON-NLS-1$
     self._getPicasaServer().deleteResource(photoEditMediaLink)
Ejemplo n.º 8
0
 def execute(self, mediaStore, session): #@UnusedVariable
     url = session[u"upload.url"] #$NON-NLS-1$
     if url.startswith(u"http"): #$NON-NLS-1$
         self._verifyHttpURL(url)
     else: # assume file path
         if not os.path.isfile(url):
             raise ZException(_extstr(u"mediastorageztest.FailedToVerifyURLError") % url) #$NON-NLS-1$
Ejemplo n.º 9
0
    def _initFromString(self, dtString):
        m = DATE_TIME_PATTERN.match(dtString)
        if not m:
            raise ZException(
                _extstr(u"schematypes.FailedToParseDateTimeString") %
                dtString)  #$NON-NLS-1$

        year = m.group(2)
        month = m.group(3)
        day = m.group(4)
        hour = m.group(5)
        minute = m.group(6)
        second = m.group(7)

        isUTC = (not m.group(10)) or (m.group(10) == u"Z")  #$NON-NLS-1$
        tz = UTC_TIMEZONE
        if not isUTC:
            tzDir = m.group(12)
            tzHr = m.group(13)
            tzMin = m.group(14)
            tz = ZSimpleTimeZone(tzHr, tzMin, tzDir)

        # Note: not sure about the millis param...
        self._initFromYYYYMMDDHHMMSS(int(year), int(month), int(day),
                                     int(hour), int(minute), int(second), tz)
Ejemplo n.º 10
0
 def _uploadStream(self, fileName, fileStream, metaData):  #@UnusedVariable
     albumName = self._getAlbumName()
     if not albumName:
         raise ZException(
             u"LJ Fotobilder web album name is required.")  #$NON-NLS-1$
     fotoBilderUploadResult = self._getPhotoBilderServer().uploadFile(
         fileStream, gallery=albumName)
     if fotoBilderUploadResult:
         if fotoBilderUploadResult.getUploadPicResponseNode():
             return ZUploadResponse(
                 fotoBilderUploadResult.getUrl(),
                 metaData=fotoBilderUploadResult.getUploadPicResponseNode())
         else:
             return ZUploadResponse(fotoBilderUploadResult.getUrl())
     else:
         raise ZException(u"LJ FotoBilder upload failed.")  #$NON-NLS-1$
Ejemplo n.º 11
0
    def _doRun(self):
        service = getApplicationModel().getService(
            IZBlogAppServiceIDs.PRODUCTS_SERVICE_ID)

        userPrefs = getApplicationModel().getUserProfile().getPreferences()
        zoundryId = userPrefs.getUserPreference(
            IZBlogAppUserPrefsKeys.ZOUNDRY_ID, None)
        if not zoundryId:
            zoundryId = u"*****@*****.**"  #$NON-NLS-1$

        self.logger.debug(
            u"Converting link %s using zoundry id %s." %
            (unicode(self.url), unicode(zoundryId)))  #$NON-NLS-1$

        self._fireWorkDoneEvent(
            1, _extstr(
                u"blogeditoractions.Invoking_Zoundry_Service"))  #$NON-NLS-1$
        newUrl = service.convertProductLink(self.url, zoundryId)

        if newUrl:
            self.logger.debug(u"Link successfully converted to %s" %
                              unicode(newUrl))  #$NON-NLS-1$
            self._fireWorkDoneEvent(
                1, _extstr(u"blogeditoractions.SuccessfullyConvertedLink"
                           ))  #$NON-NLS-1$

            if not self.isCancelled():
                self.zoundryProductUrl = newUrl
        else:
            raise ZException(_extstr(
                u"blogeditoractions.FailedToConvertLink"))  #$NON-NLS-1$
Ejemplo n.º 12
0
 def setText(self, value):
     value = convertToUnicode(value)
     try:
         self.attr.nodeValue = value
     except Exception, e:
         raise ZException(u"Error setting the text of an attribute.",
                          e)  #$NON-NLS-1$
Ejemplo n.º 13
0
def main():
    try:
        app = RavenApplication()
        app.run()
    except Exception, e:
        ZException(e).printStackTrace()
        # Need to do something here - show some kind of UI message.
        raise e
Ejemplo n.º 14
0
 def listFiles(self, relativePath=None):  #@UnusedVariable
     albumName = self._getAlbumName()
     if not albumName:
         raise ZException(
             u"Picasa web album name is required to list photos."
         )  #$NON-NLS-1$
     albumEntry = self._getPicasaAlbumEntry(albumName)
     if not albumEntry:
         raise ZException(
             u"Can not list photos. Picasa web album '%s' does not exist." %
             albumName)  #$NON-NLS-1$
     rval = []
     photoEntries = self._getPicasaServer().listPhotosByAlbumName(
         albumEntry.getAlbumName())
     for entry in photoEntries:
         rval.append(entry.getTitle())
     return rval
Ejemplo n.º 15
0
    def _reportException(self, exception):
        if not isinstance(exception, ZException):
            exception = ZException(
                _extstr(u"backgroundtaskimpl.UnexpectedBGTaskError") %
                self.getName(), exception)  #$NON-NLS-1$
        self.logger.exception(exception)

        self._raiseError(exception.getMessage(), exception.getStackTrace())
Ejemplo n.º 16
0
    def execute(self, mediaStore, session):
        testImageName = u"z_raven_test_image.png" #$NON-NLS-1$
        testImagePath = getApplicationModel().getResourceRegistry().getImagePath(u"images/common/ztest/%s" % testImageName) #$NON-NLS-1$
        rval = None

        try:
            rval = mediaStore.upload(testImagePath, bypassRegistry = True)
        except Exception, e:
            raise ZException(_extstr(u"mediastorageztest.FailedToUploadTestFileError") % mediaStore.getName(), e) #$NON-NLS-1$
Ejemplo n.º 17
0
 def saveProperties(self):
     try:
         tempSysPropsFileName = self.sysPropsFileName + u".t"  #$NON-NLS-1$
         self.sysPropsDoc.save(tempSysPropsFileName, True)
         deleteFile(self.sysPropsFileName)
         renameFile(tempSysPropsFileName, self.sysPropsFileName)
     except Exception, e:
         raise ZException(
             _extstr(u"sysprops.ErrorSavingPropsFile") %
             self.sysPropsFileName, e)  #$NON-NLS-1$
Ejemplo n.º 18
0
def ZShowTemplateManager():
    global TEMPLATE_MANAGER_WINDOW
    try:
        if TEMPLATE_MANAGER_WINDOW is None:
            TEMPLATE_MANAGER_WINDOW = ZTemplateManagerWindow(None)
        TEMPLATE_MANAGER_WINDOW.Show()
        TEMPLATE_MANAGER_WINDOW.Raise()
        return TEMPLATE_MANAGER_WINDOW
    except Exception, e:
        ZShowExceptionMessage(None, ZException(u"Error opening Background Task Manager", e)) #$NON-NLS-1$
Ejemplo n.º 19
0
def deleteDirectory(path, alsoDeleteDir=True, deleteFilter=EVERYTHING_FILTER):
    u"""deleteDirectory(string, boolean?) -> None
    Recursively deletes the contents of the given directory.  If the
    alsoDeleteDir boolean flag is True, then the directory itself
    is also deleted.  If it is False, then only the contents of the
    directory are deleted.""" #$NON-NLS-1$

    # If the path doesn't exist, just return 0.
    if not os.path.exists(path):
        return 0

    # Throw if the root path is given as the param!
    if path == u"/" or path.endswith(u":/") or path.endswith(
            u":\\"):  #$NON-NLS-3$ #$NON-NLS-2$ #$NON-NLS-1$
        raise ZException(
            _extstr(u"fileutil.FailedToDeleteRootPathMsg"))  #$NON-NLS-1$

    # If the path exists, but is not a directory, that's an error.
    if not os.path.isdir(path):
        raise ZException(_extstr(u"fileutil.InvalidDirPath") %
                         path)  #$NON-NLS-1$

    try:
        count = 0
        files = os.listdir(path)
        for file in files:
            fullFile = os.path.join(path, file)
            if os.path.isfile(fullFile):
                if deleteFilter(fullFile):
                    deleteFile(fullFile)
                    count = count + 1
            else:
                shouldDeleteDir = deleteFilter(fullFile)
                count = count + deleteDirectory(fullFile, shouldDeleteDir,
                                                deleteFilter)

        if alsoDeleteDir:
            os.rmdir(path)
        return count
    except Exception, e:
        raise ZException(_extstr(u"fileutil.DirDeleteFailed") % path,
                         e)  #$NON-NLS-1$
Ejemplo n.º 20
0
    def _getPhotoBilderServer(self):
        if not self.fotobilderServer:
            url = None
            username = None
            password = None
            if u"url" in self.properties:  #$NON-NLS-1$
                url = self.properties[u"url"]  #$NON-NLS-1$

            if u"username" in self.properties:  #$NON-NLS-1$
                username = self.properties[u"username"]  #$NON-NLS-1$
            else:
                raise ZException(u"LJ FotoBilder account username is required."
                                 )  #$NON-NLS-1$
            if u"password" in self.properties:  #$NON-NLS-1$
                password = self.properties[u"password"]  #$NON-NLS-1$
            else:
                raise ZException(u"LJ FotoBilder account password is required."
                                 )  #$NON-NLS-1$
            self.fotobilderServer = ZFotoBilderServer(username, password, url)
        return self.fotobilderServer
Ejemplo n.º 21
0
 def run(self):
     self.done = False
     try:
         if self.runnable:
             self.runnable.run()
         else:
             self._run()
     except Exception, e:
         self._handleException(
             ZException(_extstr(u"zthread.UnexpectedErrorInThread"),
                        e))  #$NON-NLS-1$
Ejemplo n.º 22
0
def deleteFile(path):
    # If the path does not exist, just return.
    if not os.path.exists(path):
        return

    # If the path exists but is not a file, that's an error.
    if not os.path.isfile(path):
        raise ZException(_extstr(u"fileutil.InvalidFilePath") %
                         path)  #$NON-NLS-1$

    os.remove(path)
Ejemplo n.º 23
0
 def _copyAspellDirToTemp(self, spellingDir):
     osutil = getOSUtil()
     tempDir = osutil.getSystemTempDirectory()
     if not os.path.isdir(tempDir):
         raise ZException(u"System temp directory not found.")  #$NON-NLS-1$
     tempSpellingDir = os.path.join(tempDir,
                                    u"_RavenSpellcheck_tmp")  #$NON-NLS-1$
     if not os.path.exists(tempSpellingDir):
         os.mkdir(tempSpellingDir)
     copyFiles(spellingDir, tempSpellingDir)
     return tempSpellingDir
Ejemplo n.º 24
0
 def _verifyHttpURL(self, url):
     tempFilePath = os.path.join(getApplicationModel().getUserProfile().getTempDirectory(), u"tmp_url_mstore_ztest.bin") #$NON-NLS-1$
     downloader = ZHttpBinaryFileDownload(url, tempFilePath)
     try:
         downloader.send()
         ct = downloader.getContentType()
         numBytes = downloader.getResponse()
         if (ct == u"image/png") and (numBytes == 222): #$NON-NLS-1$
             raise ZException(_extstr(u"mediastorageztest.FileStillExistsError") % url) #$NON-NLS-1$
     finally:
         if os.path.isfile(tempFilePath):
             os.remove(tempFilePath)
Ejemplo n.º 25
0
    def trim(self):
        xhtmlDoc = loadXhtmlDocumentFromFile(self._getRootFile())
        xhtmlDom = xhtmlDoc.getDom()
        vizzy = ZTemplateBodyFindingVisitor()
        vizzy.visit(xhtmlDom)
        elem = vizzy.getResult()
        if elem is None:
            raise ZException(
                u"Failed to find Raven template marker content.")  #$NON-NLS-1$

        self._doTrim(elem)
        self._save(xhtmlDom)
Ejemplo n.º 26
0
def ZShowBackgroundTaskManager():
    global BGTASK_MANAGER_WINDOW
    try:
        if BGTASK_MANAGER_WINDOW is None:
            BGTASK_MANAGER_WINDOW = ZBackgroundTaskManagerWindow(None)
        BGTASK_MANAGER_WINDOW.Show()
        BGTASK_MANAGER_WINDOW.Raise()
    except Exception, e:
        ZShowExceptionMessage(None,
                              ZException(
                                  u"Error opening Background Task Manager",
                                  e))  #$NON-NLS-1$
Ejemplo n.º 27
0
 def _getPicasaServer(self):
     if not self.picasaServer:
         username = None
         password = None
         if u"username" in self.properties:  #$NON-NLS-1$
             username = getNoneString(
                 self.properties[u"username"])  #$NON-NLS-1$
         if not username:
             raise ZException(
                 u"Picasa web album account username is required."
             )  #$NON-NLS-1$
         if u"password" in self.properties:  #$NON-NLS-1$
             password = getNoneString(
                 self.properties[u"password"])  #$NON-NLS-1$
         if not password:
             raise ZException(
                 u"Picasa web album account password is required."
             )  #$NON-NLS-1$
         self.picasaServer = ZPicasaServer(username, password)
         self.picasaServer.setLogger(getLoggerService())
     return self.picasaServer
Ejemplo n.º 28
0
    def __repr__(self):
        try:
            rval = u"Omega Node\n"  #$NON-NLS-1$
            if self.plugin:
                id = self.plugin.getId()
                rval = u"\n" + id.rjust(len(id) + self.depth * 3)  #$NON-NLS-1$
            for child in self.children:
                rval = rval + child.__repr__()

            return rval
        except Exception, e:
            return ZException(rootCause=e).getStackTrace()
Ejemplo n.º 29
0
    def _uploadStream(self, fileName, fileStream, metaData):  #@UnusedVariable
        u"""_uploadStream(string, stream, ZElement) -> IZUploadResponse
        Called to upload a file stream to the remote media storage.
        Returns the URL of the uploaded file.""" #$NON-NLS-1$

        photoEditMediaLink = self._getEditMediaLinkFromMetaData(metaData)
        self._logDebug(u"upload file %s" % fileName)  #$NON-NLS-1$
        self._logDebug(u"photoEditMediaLink is %s" %
                       photoEditMediaLink)  #$NON-NLS-1$
        photoEntry = None
        if photoEditMediaLink:
            # update existing file.
            photoEntry = self._getPicasaServer().updatePhotoFile(
                photoEditMediaLink, fileStream)
        else:
            # add new photo
            albumName = self._getAlbumName()
            self._logDebug(u"upload albumName %s" % albumName)  #$NON-NLS-1$
            if not getNoneString(albumName):
                self._logError(
                    u"Picasa web album name is required.")  #$NON-NLS-1$
                raise ZException(
                    u"Picasa web album name is required.")  #$NON-NLS-1$
            albumEntry = self._getPicasaAlbumEntry(albumName)
            if not albumEntry:
                self._logError(u"Picasa web album '%s' does not exist." %
                               albumName)  #$NON-NLS-1$
                raise ZException(u"Picasa web album '%s' does not exist." %
                                 albumName)  #$NON-NLS-1$
            photoEntry = self._getPicasaServer().addPhotoFile(
                albumEntry.getAlbumName(), fileStream)
        if not photoEntry:
            self._logError(u"Picasa web album upload failed for file %s" %
                           fileName)  #$NON-NLS-1$
            raise ZException(u"Picasa web album upload failed for file %s" %
                             fileName)  #$NON-NLS-1$

        return ZUploadResponse(photoEntry.getUrl(),
                               metaData=photoEntry.getNode())
Ejemplo n.º 30
0
 def doCommand(self):
     u"""Sequentially invokes doCommand on each of the commands in the collection."""  #$NON-NLS-1$
     for command in self.getCommands():
         if not self.isCancelled():
             try:
                 command.doCommand()
             except Exception, e:
                 self._handleException(
                     ZException(
                         _extstr(u"zcommand.UnexpectedErrorInDoCommand"),
                         e))  #$NON-NLS-1$
             except:
                 self._handleException(