Example #1
0
    def _connect(self):
        """Connect to the CacheClient.

        This method must be called before accessing ``self._client``.
        """
        # Maybe we already have a client in this instance
        if self._client is not None:
            return
        # If not, we might have one from another instance
        self._client = ContextManager.get('GenericCacheClient', None)

        if self._client is not None:
            return

        # If not, create a new one
        backend = Config.getInstance().getCacheBackend()
        if backend == 'memcached':
            self._client = MemcachedCacheClient(
                Config.getInstance().getMemcachedServers())
        elif backend == 'redis':
            self._client = RedisCacheClient(
                Config.getInstance().getRedisCacheURL())
        elif backend == 'files':
            self._client = FileCacheClient(
                Config.getInstance().getXMLCacheDir())
        else:
            self._client = NullCacheClient()

        ContextManager.set('GenericCacheClient', self._client)
 def testDeleteWithDel(self):
     """
     Delete works OK
     """
     ContextManager.set('test', 123)
     del ContextManager.get()['test']
     self.assertEqual(ContextManager.get('test', default=None), None)
Example #3
0
    def process(self):
        """
        Processes the request, analyzing the parameters, and feeding them to the
        _getAnswer() method (implemented by derived classes)
        """

        ContextManager.set('currentRH', self)

        self._checkParams()
        self._checkProtection()

        if self.CHECK_HTML:
            try:
                security.Sanitization.sanitizationCheck(self._target, self._params, self._aw, ['requestInfo'])
            except HtmlForbiddenTag as e:
                raise HTMLSecurityError('ERR-X0', 'HTML Security problem. {}'.format(e))

        if self._doProcess:
            if Config.getInstance().getProfile():
                import profile, pstats, random
                proffilename = os.path.join(Config.getInstance().getTempDir(), "service%s.prof" % random.random())
                result = [None]
                profile.runctx("result[0] = self._getAnswer()", globals(), locals(), proffilename)
                answer = result[0]
                rep = Config.getInstance().getTempDir()
                stats = pstats.Stats(proffilename)
                stats.strip_dirs()
                stats.sort_stats('cumulative', 'time', 'calls')
                stats.dump_stats(os.path.join(rep, "IndicoServiceRequestProfile.log"))
                os.remove(proffilename)
            else:
                answer = self._getAnswer()
            self._deleteTempFiles()

            return answer
Example #4
0
    def _connect(self):
        """Connect to the CacheClient.

        This method must be called before accessing ``self._client``.
        """
        # Maybe we already have a client in this instance
        if self._client is not None:
            return
        # If not, we might have one from another instance
        self._client = ContextManager.get('GenericCacheClient', None)

        if self._client is not None:
            return

        # If not, create a new one
        backend = Config.getInstance().getCacheBackend()
        if backend == 'memcached':
            self._client = MemcachedCacheClient(Config.getInstance().getMemcachedServers())
        elif backend == 'redis':
            self._client = RedisCacheClient(Config.getInstance().getRedisCacheURL())
        elif backend == 'files':
            self._client = FileCacheClient(Config.getInstance().getXMLCacheDir())
        else:
            self._client = NullCacheClient()

        ContextManager.set('GenericCacheClient', self._client)
 def testDeleteWithDel(self):
     """
     Delete works OK
     """
     ContextManager.set('test', 123)
     del ContextManager.get()['test']
     self.assertEqual(ContextManager.get('test', default=None), None)
 def testDelete(self):
     """
     Delete works OK
     """
     ContextManager.set('test', 123)
     ContextManager.delete('test')
     self.assertEqual(ContextManager.get('test', default=None), None)
Example #7
0
    def invokeMethod(self, method, params, req):

        MAX_RETRIES = 10

        # clear the context
        ContextManager.destroy()

        DBMgr.getInstance().startRequest()

        # room booking database
        _startRequestSpecific2RH()

        # notify components that the request has started
        self._notify('requestStarted', req)

        forcedConflicts = Config.getInstance().getForceConflicts()
        retry = MAX_RETRIES
        try:
            while retry > 0:
                if retry < MAX_RETRIES:
                    # notify components that the request is being retried
                    self._notify('requestRetry', req, MAX_RETRIES - retry)

                try:
                    # delete all queued emails
                    GenericMailer.flushQueue(False)

                    DBMgr.getInstance().sync()

                    try:
                        result = processRequest(method, copy.deepcopy(params), req)
                    except MaKaC.errors.NoReportError, e:
                        raise NoReportError(e.getMsg())
                    rh = ContextManager.get('currentRH')

                    # notify components that the request has ended
                    self._notify('requestFinished', req)
                    # Raise a conflict error if enabled. This allows detecting conflict-related issues easily.
                    if retry > (MAX_RETRIES - forcedConflicts):
                        raise ConflictError
                    _endRequestSpecific2RH( True )
                    DBMgr.getInstance().endRequest(True)
                    GenericMailer.flushQueue(True) # send emails
                    if rh._redisPipeline:
                        try:
                            rh._redisPipeline.execute()
                        except RedisError:
                            Logger.get('redis').exception('Could not execute pipeline')
                    break
                except ConflictError:
                    _abortSpecific2RH()
                    DBMgr.getInstance().abort()
                    retry -= 1
                    continue
                except ClientDisconnected:
                    _abortSpecific2RH()
                    DBMgr.getInstance().abort()
                    retry -= 1
                    time.sleep(MAX_RETRIES - retry)
                    continue
Example #8
0
    def _setParam(self):

        ContextManager.set('dateChangeNotificationProblems', {})

        if (self._pTime < self._target.getStartDate()):
            raise ServiceError(
                "ERR-E3", "Date/time of end cannot " +
                "be lower than data/time of start")
        self._target.setDates(self._target.getStartDate(),
                              self._pTime.astimezone(timezone("UTC")),
                              moveEntries=0)

        dateChangeNotificationProblems = ContextManager.get(
            'dateChangeNotificationProblems')

        if dateChangeNotificationProblems:
            warningContent = []
            for problemGroup in dateChangeNotificationProblems.itervalues():
                warningContent.extend(problemGroup)

            return Warning(_('Warning'), [
                _('The end date of your event was changed correctly.'),
                _('However, there were the following problems:'),
                warningContent
            ])
        else:
            return None
Example #9
0
    def process(self):
        """
        Processes the request, analyzing the parameters, and feeding them to the
        _getAnswer() method (implemented by derived classes)
        """

        ContextManager.set('currentRH', self)

        self._checkParams()
        self._checkProtection()

        if self.CHECK_HTML:
            try:
                security.Sanitization.sanitizationCheck(self._target, self._params, self._aw, ['requestInfo'])
            except HtmlForbiddenTag as e:
                raise HTMLSecurityError('ERR-X0', 'HTML Security problem. {}'.format(e))

        if self._doProcess:
            if Config.getInstance().getProfile():
                import profile, pstats, random
                proffilename = os.path.join(Config.getInstance().getTempDir(), "service%s.prof" % random.random())
                result = [None]
                profile.runctx("result[0] = self._getAnswer()", globals(), locals(), proffilename)
                answer = result[0]
                rep = Config.getInstance().getTempDir()
                stats = pstats.Stats(proffilename)
                stats.strip_dirs()
                stats.sort_stats('cumulative', 'time', 'calls')
                stats.dump_stats(os.path.join(rep, "IndicoServiceRequestProfile.log"))
                os.remove(proffilename)
            else:
                answer = self._getAnswer()
            self._deleteTempFiles()

            return answer
Example #10
0
    def _connect(self):
        # Maybe we already have a client in this instance
        if self._client is not None:
            return
        # If not, we might have one from another instance
        self._client = ContextManager.get('GenericCacheClient', None)

        if self._client is not None:
            return

        # If not, create a new one
        backend = Config.getInstance().getCacheBackend()
        if backend == 'memcached':
            import memcache
            self._client = memcache.Client(
                Config.getInstance().getMemcachedServers())
        elif backend == 'redis':
            self._client = RedisCacheClient(
                Config.getInstance().getRedisCacheURL())
        elif backend == 'files':
            self._client = FileCacheClient(
                Config.getInstance().getXMLCacheDir())
        else:
            self._client = NullCacheClient()

        ContextManager.set('GenericCacheClient', self._client)
Example #11
0
    def _setParam(self):

        ContextManager.set("dateChangeNotificationProblems", {})

        if self._pTime < self._target.getStartDate():
            raise ServiceError("ERR-E3", "Date/time of end cannot " + "be lower than data/time of start")
        self._target.setDates(self._target.getStartDate(), self._pTime.astimezone(timezone("UTC")), moveEntries=0)

        dateChangeNotificationProblems = ContextManager.get("dateChangeNotificationProblems")

        if dateChangeNotificationProblems:
            warningContent = []
            for problemGroup in dateChangeNotificationProblems.itervalues():
                warningContent.extend(problemGroup)

            return Warning(
                _("Warning"),
                [
                    _("The end date of your event was changed correctly."),
                    _("However, there were the following problems:"),
                    warningContent,
                ],
            )
        else:
            return None
 def testDelete(self):
     """
     Delete works OK
     """
     ContextManager.set('test', 123)
     ContextManager.delete('test')
     self.assertEqual(ContextManager.get('test', default=None), None)
Example #13
0
    def _runObj(self, obj):
        # create the context
        ContextManager.create()

        try:
            obj.run()
        except Exception, e:
            self._printOutput(e)
            self._sendErrorEmail(e)
Example #14
0
    def _runObj(self, obj):
        # create the context
        ContextManager.create()

        try:
            obj.run()
        except Exception, e:
            self._printOutput(e)
            self._sendErrorEmail(e)
Example #15
0
    def invokeMethod(self, method, params, req):

        MAX_RETRIES = 10

        # clear the context
        ContextManager.destroy()

        DBMgr.getInstance().startRequest()

        # room booking database
        _startRequestSpecific2RH()

        # notify components that the request has started
        self._notify('requestStarted', req)

        forcedConflicts = Config.getInstance().getForceConflicts()
        retry = MAX_RETRIES
        try:
            while retry > 0:
                if retry < MAX_RETRIES:
                    # notify components that the request is being retried
                    self._notify('requestRetry', req, MAX_RETRIES - retry)

                try:
                    # delete all queued emails
                    GenericMailer.flushQueue(False)

                    DBMgr.getInstance().sync()

                    try:
                        result = processRequest(method, copy.deepcopy(params),
                                                req)
                    except MaKaC.errors.NoReportError, e:
                        raise NoReportError(e.getMsg())

                    # notify components that the request has ended
                    self._notify('requestFinished', req)
                    # Raise a conflict error if enabled. This allows detecting conflict-related issues easily.
                    if retry > (MAX_RETRIES - forcedConflicts):
                        raise ConflictError
                    _endRequestSpecific2RH(True)
                    DBMgr.getInstance().endRequest(True)
                    GenericMailer.flushQueue(True)  # send emails
                    break
                except ConflictError:
                    _abortSpecific2RH()
                    DBMgr.getInstance().abort()
                    retry -= 1
                    continue
                except ClientDisconnected:
                    _abortSpecific2RH()
                    DBMgr.getInstance().abort()
                    retry -= 1
                    time.sleep(MAX_RETRIES - retry)
                    continue
Example #16
0
    def _getAnswer(self):

        ContextManager.set("dateChangeNotificationProblems", {})

        if self._startDate > self._endDate:
            raise ServiceError("ERR-E3", "Date/time of start cannot " + "be greater than date/time of end")

        try:
            self._target.setDates(self._startDate, self._endDate, moveEntries=1)
        except TimingError, e:
            raise ServiceError("ERR-E2", e.getMsg())
Example #17
0
    def send(cls, notification, skipQueue=False):
        if isinstance(notification, dict):
            # Wrap a raw dictionary in a notification class
            from MaKaC.webinterface.mail import GenericNotification
            notification = GenericNotification(notification)
        # enqueue emails if we have a rh and do not skip queuing, otherwise send immediately
        rh = ContextManager.get('currentRH', None)
        mailData = cls._prepare(notification)

        if mailData:
            if skipQueue or not rh:
                cls._send(mailData)
            else:
                ContextManager.setdefault('emailQueue', []).append(mailData)
Example #18
0
    def send(cls, notification, skipQueue=False):
        if isinstance(notification, dict):
            # Wrap a raw dictionary in a notification class
            from MaKaC.webinterface.mail import GenericNotification
            notification = GenericNotification(notification)
        # enqueue emails if we have a rh and do not skip queuing, otherwise send immediately
        rh = ContextManager.get('currentRH', None)
        mailData = cls._prepare(notification)

        if mailData:
            if skipQueue or not rh:
                cls._send(mailData)
            else:
                ContextManager.setdefault('emailQueue', []).append(mailData)
Example #19
0
    def _add(self, obj, actions):
        """
        Adds a provided object to the temporary index.
        Actions: ['moved','deleted',..]
        """

        cm_set = ContextManager.get('indico.ext.livesync:actions').setdefault(
            obj, set([]))

        # the context may not be initialized
        if cm_set != None:
            cm_set |= set(actions)
        uid = uniqueId(obj)
        if uid is not None and uid != '':
            ContextManager.get('indico.ext.livesync:ids').setdefault(obj, uid)
Example #20
0
    def _handleSet(self):

        # Account for possible retries (due to conflicts)
        # If 'minutesFileId' is defined, there was a previous try
        fileId = ContextManager.setdefault("minutesFileId", None)

        minutes = self._target.getMinutes()
        if not minutes:
            minutes = self._target.createMinutes()
        minutes.setText(self._text, forcedFileId=fileId)

        # save the fileId, in case there is a conflict error
        # in the worst case scenario the file will be rewritten multiple times
        res = minutes.getResourceById("minutes")
        ContextManager.set("minutesFileId", res.getRepositoryId())
Example #21
0
    def _getAnswer(self):

        ContextManager.set('dateChangeNotificationProblems', {})

        if (self._startDate > self._endDate):
            raise ServiceError(
                "ERR-E3", "Date/time of start cannot " +
                "be greater than date/time of end")

        try:
            self._target.setDates(self._startDate,
                                  self._endDate,
                                  moveEntries=1)
        except TimingError, e:
            raise ServiceError("ERR-E2", e.getMsg())
Example #22
0
    def _handleSet(self):

        # Account for possible retries (due to conflicts)
        # If 'minutesFileId' is defined, there was a previous try
        fileId = ContextManager.setdefault('minutesFileId', None)

        minutes = self._target.getMinutes()
        if not minutes:
            minutes = self._target.createMinutes()
        minutes.setText(self._text, forcedFileId=fileId)

        # save the fileId, in case there is a conflict error
        # in the worst case scenario the file will be rewritten multiple times
        res = minutes.getResourceById('minutes')
        ContextManager.set('minutesFileId', res.getRepositoryId())
Example #23
0
def _build_folder_legacy_api_data(folder):
    avatar = ContextManager.get("currentAW").getUser()
    user = avatar.user if avatar else None
    if not folder.can_access(user):
        return None

    resources = [
        _build_attachment_legacy_api_data(attachment)
        for attachment in folder.attachments if attachment.can_access(user)
    ]
    if not resources:  # Skipping empty folders for legacy API
        return None

    type_ = (folder.legacy_mapping.material_id.title()
             if folder.legacy_mapping is not None
             and not folder.legacy_mapping.material_id.isdigit() else
             'Material')
    return {
        '_type': type_,
        '_fossil': 'materialMetadata',
        '_deprecated': True,
        'title': folder.title,
        'id': str(folder.id),
        'resources': resources
    }
Example #24
0
    def _add(self, obj, actions):
        """
        Adds a provided object to the temporary index.
        Actions: ['moved','deleted',..]
        """

        cm_set = ContextManager.get('indico.ext.livesync:actions').setdefault(
            obj, set([]))

        # the context may not be initialized
        if cm_set != None:
            cm_set |= set(actions)
        uid = uniqueId(obj)
        if uid is not None and uid != '':
            ContextManager.get('indico.ext.livesync:ids').setdefault(
                obj, uid)
Example #25
0
    def _getRequestInfo(self):
        rh = ContextManager.get('currentRH', None)
        info = ['Additional information:']

        try:
            info.append('Request: %s' % request.id)
            info.append('URL: %s' % request.url)

            if request.url_rule:
                info.append('Endpoint: {0}'.format(request.url_rule.endpoint))

            info.append('Method: %s' % request.method)
            if rh:
                info.append('Params: %s' % rh._getTruncatedParams())

            if session:
                try:
                    info.append('User: {0}'.format(session.user))
                except POSError:
                    # If the DB connection is closed getting the avatar may fail
                    info.append('User id: {0}'.format(
                        session.get('_avatarId')))
            info.append('IP: %s' % request.remote_addr)
            info.append('User Agent: %s' % request.user_agent)
            info.append('Referer: %s' % (request.referrer or 'n/a'))
        except RuntimeError, e:
            info.append('Not available: %s' % e)
Example #26
0
    def __init__(self, **params):
        self._userLoggedIn = params.get("userLoggedIn", False)
        self._target = params.get("target", None)
        self._page = params.get("page", 1)
        self._noQuery = False

        if self._userLoggedIn:
            self._sessionHash = "%s_%s" % (ContextManager.get("currentRH", None)._getSession().getId(), ContextManager.get("currentUser", None).getId())
        else:
            self._sessionHash = 'PUBLIC'

        if type(self._target) == conference.Category:
            # we're dealing with a category
            if self._target.isRoot():
                # perform global search
                self._marcQuery = ''
            else:
                # if not on root, search using path
                self._marcQuery = '650_7:"'+self._buildCategoryHierarchy(self._target)+'*" '

        elif type(self._target) == conference.Conference:
            # we're looking inside an event
            # search for event identifier
            self._marcQuery = 'AND 970__a:"INDICO.%s.*"' % self._target.getId()
            self._searchCategories = False

        else:
            raise Exception("Unknown target type.")
Example #27
0
    def cloneEvent(cls, confToClone, params):
        """ we'll clone only the chat rooms created by the user who is cloning the conference """
        conf = params['conf']
        user = params['user']
        options = params['options']
        ContextManager.setdefault('mailHelper', MailHelper())

        if options.get("chatrooms", True):
            crList = DBHelpers().getChatroomList(confToClone)
            ownersList = [cr.getOwner() for cr in crList]
            if PluginsWrapper('InstantMessaging', 'XMPP').isActive():
                 for cr in crList:
                     if user is cr.getOwner():
                         cls()._notify('addConference2Room', {'room':cr, 'conf':conf.getId()})

        ContextManager.get('mailHelper').sendMails()
Example #28
0
    def _getRequestInfo(self):
        rh = ContextManager.get('currentRH', None)
        info = ['Additional information:']

        try:
            info.append('Request: %s' % request.id)
            info.append('URL: %s' % request.url)

            if request.url_rule:
                info.append('Endpoint: {0}'.format(request.url_rule.endpoint))

            info.append('Method: %s' % request.method)
            if rh:
                info.append('Params: %s' % rh._getTruncatedParams())

            if session:
                try:
                    info.append('User: {0}'.format(session.user))
                except POSError:
                    # If the DB connection is closed getting the avatar may fail
                    info.append('User id: {0}'.format(session.get('_avatarId')))
            info.append('IP: %s' % request.remote_addr)
            info.append('User Agent: %s' % request.user_agent)
            info.append('Referer: %s' % (request.referrer or 'n/a'))
        except RuntimeError, e:
            info.append('Not available: %s' % e)
Example #29
0
    def _connect(self):
        # Maybe we already have a client in this instance
        if self._client is not None:
            return
        # If not, we might have one from another instance
        self._client = ContextManager.get('GenericCacheClient', None)
        if self._client is not None:
            return
        # If not, create a new one
        backend = Config.getInstance().getCacheBackend()
        if backend == 'memcached':
            import memcache
            self._client = memcache.Client(Config.getInstance().getMemcachedServers())
        else:
            self._client = FileCacheClient(Config.getInstance().getXMLCacheDir())

        ContextManager.set('GenericCacheClient', self._client)
Example #30
0
    def _getAnswer(self):
        ContextManager.set("dateChangeNotificationProblems", {})

        if self._shiftTimes:
            moveEntries = 1
        else:
            moveEntries = 0

        # first sanity check
        if self._startDate > self._endDate:
            raise ServiceError("ERR-E3", "Date/time of start cannot " "be greater than date/time of end")

        # catch TimingErrors that can be returned by the algorithm
        try:
            with track_time_changes():
                self._target.setDates(self._startDate, self._endDate, moveEntries=moveEntries)
        except TimingError, e:
            raise TimingNoReportError(e.getMessage(), title=_("Cannot set event dates"), explanation=e.getExplanation())
Example #31
0
    def performOperation(cls, operation, conf, room, *args):
        """ The 4 operations of this class are quite the same, so we pass the name of the operation, the conference they belong to,
            the chat room for which we are creating the operation and, finally, a list of the arguments needed for the operation"""

        # get the list of users that will receive emails
        pf = PluginFieldsWrapper('InstantMessaging', 'XMPP')
        userList = list(pf.getOption('additionalEmails'))
        if pf.getOption('sendMailNotifications'):
            userList.extend( [user.getEmail() for user in pf.getOption('admins')] )
        if not len(userList) is 0:
            try:
                cn = ChatroomsNotification(room, userList)
                ContextManager.get('mailHelper').newMail(GenericMailer.sendAndLog, getattr(cn, operation)(*args), \
                                         conf, \
                                         "MaKaC/plugins/InstantMessaging/XMPP/components.py", \
                                         room.getOwner())
            except Exception, e:
                raise ServiceError(message=_('There was an error while contacting the mail server. No notifications were sent: %s'%e))
Example #32
0
    def process(self):
        """
        Processes the request, analyzing the parameters, and feeding them to the
        _getAnswer() method (implemented by derived classes)
        """

        ContextManager.set('currentRH', self)

        self._setLang()
        self._checkParams()
        self._checkProtection()

        try:
            security.Sanitization.sanitizationCheck(self._target,
                                   self._params,
                                   self._aw)
        except (HtmlScriptError, HtmlForbiddenTag), e:
            raise HTMLSecurityError('ERR-X0','HTML Security problem. %s ' % str(e))
Example #33
0
    def process(self):
        """
        Processes the request, analyzing the parameters, and feeding them to the
        _getAnswer() method (implemented by derived classes)
        """

        ContextManager.set('currentRH', self)

        self._setLang()
        self._checkParams()
        self._checkProtection()

        try:
            security.Sanitization.sanitizationCheck(self._target, self._params,
                                                    self._aw)
        except (HtmlScriptError, HtmlForbiddenTag), e:
            raise HTMLSecurityError('ERR-X0',
                                    'HTML Security problem. %s ' % str(e))
Example #34
0
 def flushQueue(cls, send):
     queue = ContextManager.get('emailQueue', None)
     if not queue:
         return
     if send:
         # send all emails
         for mail in queue:
             cls._send(mail)
     # clear the queue no matter if emails were sent or not
     del queue[:]
Example #35
0
    def getVars(self):
        from MaKaC.plugins.Collaboration.handlers import RCCollaborationAdmin
        from MaKaC.webinterface.rh.admins import RCAdmin

        vars = wcomponents.WTemplated.getVars(self)
        user = ContextManager.get("currentUser")
        vars["user"] = user
        vars["IsAdmin"] = RCAdmin.hasRights(self._rh)
        vars["IsCollaborationAdmin"] = RCCollaborationAdmin.hasRights(user)
        return vars
Example #36
0
    def _invokeMethodSuccess(self):
        rh = ContextManager.get('currentRH')

        flush_after_commit_queue(True)  # run after-commit functions
        GenericMailer.flushQueue(True)  # send emails
        if rh._redisPipeline:
            try:
                rh._redisPipeline.execute()
            except RedisError:
                Logger.get('redis').exception('Could not execute pipeline')
Example #37
0
    def getVars(self):
        from MaKaC.plugins.Collaboration.handlers import RCCollaborationAdmin
        from MaKaC.webinterface.rh.admins import RCAdmin

        vars = wcomponents.WTemplated.getVars(self)
        user = ContextManager.get("currentUser")
        vars["user"] = user
        vars["IsAdmin"] = RCAdmin.hasRights(self._rh)
        vars["IsCollaborationAdmin"] = RCCollaborationAdmin.hasRights(user)
        return vars
Example #38
0
    def _invokeMethodSuccess(self):
        rh = ContextManager.get('currentRH')

        flush_after_commit_queue(True)  # run after-commit functions
        GenericMailer.flushQueue(True)  # send emails
        if rh._redisPipeline:
            try:
                rh._redisPipeline.execute()
            except RedisError:
                Logger.get('redis').exception('Could not execute pipeline')
Example #39
0
 def flushQueue(cls, send):
     queue = ContextManager.get('emailQueue', None)
     if not queue:
         return
     if send:
         # send all emails
         for mail in queue:
             cls._send(mail)
     # clear the queue no matter if emails were sent or not
     del queue[:]
Example #40
0
    def testWithThreads(self):
        t1 = threading.Thread(target=self.thread1)
        t2 = threading.Thread(target=self.thread2)

        t1.start()
        t2.start()

        t1.join()
        t2.join()

        self.assertEquals(ContextManager.get('samevariable').__class__, ContextManager.DummyContext)
Example #41
0
 def _getRequestInfo(self):
     rh = ContextManager.get('currentRH', None)
     if not rh:
         return ''
     info = ['Additional information:']
     info.append('URL: %s' % rh.getRequestURL())
     info.append('Params: %s' % rh._getTruncatedParams())
     info.append('IP: %s' % rh._req.remote_ip)
     info.append('User Agent: %s' % rh._req.headers_in.get('User-Agent', 'n/a'))
     info.append('Referer: %s' % rh._req.headers_in.get('Referer', 'n/a'))
     return '\n\n%s' % '\n'.join(info)
Example #42
0
 def _getRequestInfo(self):
     rh = ContextManager.get('currentRH', None)
     if not rh:
         return ''
     info = ['Additional information:']
     info.append('URL: %s' % rh.getRequestURL())
     info.append('Params: %s' % rh._getTruncatedParams())
     info.append('IP: %s' % rh._req.remote_ip)
     info.append('User Agent: %s' % rh._req.headers_in.get('User-Agent', 'n/a'))
     info.append('Referer: %s' % rh._req.headers_in.get('Referer', 'n/a'))
     return '\n\n%s' % '\n'.join(info)
Example #43
0
    def process(self, filteredParams):

        self._filteredParams = filteredParams
        phrase = self._filteredParams.get('p', '')
        if phrase.strip() == '':
            self._noQuery = True

        params = copy.copy(self._filteredParams)
        
        nEvtRec, nContRec = 0, 0
        numEvtHits, numContHits = 0, 0
        eventResults, contribResults = [], []
        
        numEvtHits, evtShortResult, nEvtRec, eventResults = self._getResults(self._pagination)
        params['evtShortResult'] = evtShortResult

        params['p'] = cgi.escape(phrase, quote=True)
        params['f'] = cgi.escape(filteredParams.get('f', ''), quote=True)

        params['eventResults'] = eventResults
        params['contribResults'] = contribResults
                
        categories = {}

        for cat in conference.CategoryManager().getList():
            catparent = cat.getOwner()
            if catparent and catparent.getCategory().getId() == '0':
                categories[cat.getId()] = cat.name

        #keywords = []
#         for conf in conference.ConferenceHolder().getValuesToList():
#             for keyword in conf.getKeywords().split('\n'):
#                 if not(keyword in keywords) and not(keyword.startswith('smr')) and not(keyword.startswith('expparts')) and not(keyword.startswith('siscode')) and keyword != '':
#                     keywords.append(keyword)
                    
        # To get a faster response, comment the above lines and use a static keywords definitions.
        #keywords.sort()
        
        params['categories'] = categories
        params['avakeywords'] = keywords

        params['nEventResult'] = nEvtRec
        params['nContribResult'] = nContRec

        params['numHits'] = numEvtHits + numContHits
        params['page'] = self._page

        params['targetObj'] = self._target

        params['searchingPublicWarning'] = self.isSearchTypeOnlyPublic() and not self._userLoggedIn
        params['accessWrapper'] = ContextManager().get("currentRH", None).getAW()

        return params
Example #44
0
class ConferenceStartEndDateTimeModification(ConferenceModifBase):
    """ Conference start date/time modification
        When changing the start date / time, the _setParam method will be called by DateTimeModificationBase's _handleSet method.
        The _setParam method will return None (if there are no problems),
        or a Warning object if the event start date change was OK but there were side problems,
        such as an object observing the event start date change could not perform its task
        (Ex: a videoconference booking could not be moved in time according with the conference's time change)
        For this, it will check the 'dateChangeNotificationProblems' context variable.
    """
    def _checkParams(self):

        ConferenceModifBase._checkParams(self)

        pm = ParameterManager(self._params.get('value'),
                              timezone=self._conf.getTimezone())

        self._startDate = pm.extract('startDate', pType=datetime.datetime)
        self._endDate = pm.extract('endDate', pType=datetime.datetime)

    def _getAnswer(self):

        ContextManager.set('dateChangeNotificationProblems', {})

        if (self._startDate > self._endDate):
            raise ServiceError(
                "ERR-E3", "Date/time of start cannot " +
                "be greater than date/time of end")

        try:
            self._target.setDates(self._startDate,
                                  self._endDate,
                                  moveEntries=1)
        except TimingError, e:
            raise ServiceError("ERR-E2", e.getMsg())

        dateChangeNotificationProblems = ContextManager.get(
            'dateChangeNotificationProblems')

        if dateChangeNotificationProblems:

            warningContent = []
            for problemGroup in dateChangeNotificationProblems.itervalues():
                warningContent.extend(problemGroup)

            return Warning(_('Warning'), [
                _('The start date of your event was changed correctly.'),
                _('However, there were the following problems:'),
                warningContent
            ])

        else:
            return self._params.get('value')
Example #45
0
    def testWithThreads(self):
        "Thread safety"

        t1 = threading.Thread(target=self.thread1)
        t2 = threading.Thread(target=self.thread2)

        t1.start()
        t2.start()

        t1.join()
        t2.join()

        self.assertEquals(ContextManager.get("samevariable").__class__, DummyDict)
Example #46
0
    def testWithThreads(self):
        t1 = threading.Thread(target=self.thread1)
        t2 = threading.Thread(target=self.thread2)

        t1.start()
        t2.start()

        t1.join()
        t2.join()

        self.assertEquals(
            ContextManager.get('samevariable').__class__,
            ContextManager.DummyContext)
Example #47
0
    def requestFinished(self, obj, req):

        sm = SyncManager.getDBInstance()
        cm = ContextManager.get('indico.ext.livesync:actions')
        cm_ids = ContextManager.get('indico.ext.livesync:ids')

        timestamp = int_timestamp(nowutc())

        # if the returned context is a dummy one, there's nothing to do
        if cm.__class__ == DummyDict:
            return

        # Insert the elements from the temporary index
        # into the permanent one (MPT)
        for obj, actions in cm.iteritems():
            objId = cm_ids[obj]
            for action in actions:
                Logger.get('ext.livesync').debug((objId, action))
                # TODO: remove redundant items
            if not sm.objectExcluded(obj):
                sm.add(timestamp,
                       ActionWrapper(timestamp, obj, actions, objId))
Example #48
0
    def requestFinished(self, obj, req):

        sm = SyncManager.getDBInstance()
        cm = ContextManager.get('indico.ext.livesync:actions')
        cm_ids = ContextManager.get('indico.ext.livesync:ids')

        timestamp = int_timestamp(nowutc())

        # if the returned context is a dummy one, there's nothing to do
        if cm.__class__ == DummyDict:
            return

        # Insert the elements from the temporary index
        # into the permanent one (MPT)
        for obj, actions in cm.iteritems():
            objId = cm_ids[obj]
            for action in actions:
                Logger.get('ext.livesync').debug((objId, action))
                # TODO: remove redundant items
            if not sm.objectExcluded(obj):
                sm.add(timestamp, ActionWrapper(timestamp, obj, actions,
                                                objId))
Example #49
0
    def setUp( self ):

        # create a context, for storing autoOps
        ContextManager.create()
        ContextManager.set('autoOps', [])

        a = Avatar()
        a.setId("creator")
        self._conf = ConferenceFacade( a )
        self._conf.setId('a')
        self._conf.setTimezone('UTC')

        self._conf.setDates(datetime(2009, 9, 21, 16, 0 ,0, tzinfo=timezone("UTC")),
                            datetime(2009, 9, 21, 19, 0 ,0, tzinfo=timezone("UTC")))

        self._slot1_sDate = datetime(2009, 9, 21, 17, 0, 0, tzinfo=timezone("UTC"))
        self._slot1_eDate = datetime(2009, 9, 21, 18, 0, 0, tzinfo=timezone("UTC"))
        self._slot2_sDate = datetime(2009, 9, 21, 18, 0, 0, tzinfo=timezone("UTC"))
        self._slot2_eDate = datetime(2009, 9, 21, 19, 0, 0, tzinfo=timezone("UTC"))

        self._slot2_laterDate = datetime(2009, 9, 21, 20, 0, 0, tzinfo=timezone("UTC"))

        self._session1 = Session()
        self._session1.setValues({
            'sDate': self._slot1_sDate,
            'eDate': self._slot1_eDate
            })

        self._conf.addSession(self._session1)

        self._slot1 = self._session1.getSlotById(0)
        self._slot2 = SessionSlot(self._session1)

        self._slot2.setValues({
            'sDate': self._slot2_sDate,
            'eDate': self._slot2_eDate
            });

        self._session1.addSlot(self._slot2)
Example #50
0
    def testNotifyNewContentExpandsSlotDown(self):
        """ When a slot grows down (new content), proper notification is triggered  """

        self.testNewContentExpandsSlotDown()

        ops = ContextManager.get('autoOps')

        self.assert_(len(ops) == 4)

        op1 = ops[0]
        op2 = ops[1]
        op3 = ops[0]
        op4 = ops[1]
Example #51
0
    def testNotifyNewContentExpandsSlotUp(self):
        """ When a slot grows up (new content), proper notification is triggered  """

        #        import rpdb2; rpdb2.start_embedded_debugger_interactive_password()

        self.testNewContentExpandsSlotUp()

        ops = ContextManager.get('autoOps')

        self.assert_(len(ops) == 3)

        op1 = ops[0]
        op2 = ops[1]
Example #52
0
    def testNotifyNewContentExpandsSlotDown(self):
        """ When a slot grows down (new content), proper notification is triggered  """

        self.testNewContentExpandsSlotDown()

        ops = ContextManager.get('autoOps')

        self.assert_(len(ops) == 4)

        op1 = ops[0]
        op2 = ops[1]
        op3 = ops[0]
        op4 = ops[1]
Example #53
0
    def _getAnswer(self):
        ContextManager.set('dateChangeNotificationProblems', {})

        if (self._shiftTimes):
            moveEntries = 1
        else:
            moveEntries = 0

        # first sanity check
        if (self._startDate > self._endDate):
            raise ServiceError("ERR-E3",
                               "Date/time of start cannot "
                               "be greater than date/time of end")

        # catch TimingErrors that can be returned by the algorithm
        try:
            with track_time_changes():
                self._target.setDates(self._startDate, self._endDate, moveEntries=moveEntries)
        except TimingError, e:
            raise TimingNoReportError(e.getMessage(),
                                      title=_("Cannot set event dates"),
                                      explanation=e.getExplanation())
Example #54
0
    def testNotifyNewContentExpandsSlotUp(self):
        """ When a slot grows up (new content), proper notification is triggered  """

#        import rpdb2; rpdb2.start_embedded_debugger_interactive_password()

        self.testNewContentExpandsSlotUp()

        ops = ContextManager.get('autoOps')

        self.assert_(len(ops) == 3)

        op1 = ops[0]
        op2 = ops[1]
Example #55
0
def invokeMethod(method, params, req):

    # create the context
    ContextManager.create()

    DBMgr.getInstance().startRequest()

    # room booking database
    _startRequestSpecific2RH()
    try:
        try:
            retry = 10
            while retry > 0:
                try:
                    DBMgr.getInstance().sync()

                    result = processRequest(method, params, req)

                    _endRequestSpecific2RH( True )
                    DBMgr.getInstance().endRequest(True)
                    break
                except ConflictError:
                    _abortSpecific2RH()
                    DBMgr.getInstance().abort()
                    retry -= 1
                    continue
                except ClientDisconnected:
                    _abortSpecific2RH()
                    DBMgr.getInstance().abort()
                    retry -= 1
                    time.sleep(10 - retry)
                    continue
        except CausedError, e:
            raise e
        except Exception, e:
            raise ProcessError("ERR-P0", "Error processing method.")
Example #56
0
    def _getRequestInfo(self):
        rh = ContextManager.get('currentRH', None)
        info = ['Additional information:']

        try:
            info.append('URL: %s' % request.url)
            info.append('Endpoint: %s' % request.url_rule.endpoint)
            info.append('Method: %s' % request.method)
            if rh:
                info.append('Params: %s' % rh._getTruncatedParams())
            info.append('IP: %s' % request.remote_addr)
            info.append('User Agent: %s' % request.user_agent)
            info.append('Referer: %s' % (request.referrer or 'n/a'))
        except RuntimeError, e:
            info.append('Not available: %s' % e)
Example #57
0
    def getVars(self):
        """Returns a dictionary containing the TPL variables that will
            be passed at the TPL formating time. For this class, it will
            return the configuration user defined variables.
           Classes inheriting from this one will have to take care of adding
            their variables to the ones returned by this method.
        """
        self._rh = ContextManager.get('currentRH', None)

        cfg = Config.getInstance()
        vars = cfg.getTPLVars()

        for paramName in self.__params:
            vars[paramName] = self.__params[paramName]

        return vars
Example #58
0
def _build_folder_api_data(folder):
    avatar = ContextManager.get("currentAW").getUser()
    user = avatar.user if avatar else None
    if not folder.can_view(user):
        return None

    return {
        '_type': 'folder',
        'id': folder.id,
        'title': folder.title,
        'description': folder.description,
        'attachments': [_build_attachment_api_data(attachment)
                        for attachment in folder.attachments
                        if attachment.can_access(user)],
        'default_folder': folder.is_default,
        'is_protected': folder.is_protected
    }
Example #59
0
    def getHTML(self, params=None):
        """Returns the HTML resulting of formating the text contained in
            the corresponding TPL file with the variables returned by the
            getVars method.
            Params:
                params -- additional paramters received from the caller
        """

        self._rh = ContextManager.get('currentRH', None)
        if self.tplId == None:
            self.tplId = self.__class__.__name__[1:]
        self._setTPLFile()
        self.__params = {}
        if params != None:
            self.__params = params

        # include context help info, if it exists
        helpText = None
        if os.path.exists(self.helpFile):
            try:
                fh = open(self.helpFile, "r")
                helpText = fh.read()
                fh.close()
            except exceptions.IOError:
                pass

        vars = self.getVars()

        vars['__rh__'] = self._rh
        vars['self_'] = self

        tempHTML = templateEngine.render(self.tplFile, vars, self)

        if helpText == None:
            return tempHTML
        else:
            try:
                return ContextHelp().merge(self.tplId, tempHTML, helpText)
            except etree.LxmlError, e:
                if tempHTML.strip() == '':
                    raise MaKaCError(
                        _("Template " + str(self.tplId) +
                          " produced empty output, and it has a .wohl file. Error: "
                          + str(e)))
                else:
                    raise
Example #60
0
    def process(self, filteredParams):

        self._filteredParams = filteredParams
        phrase = self._filteredParams.get('p', '')
        if phrase.strip() == '':
            self._noQuery = True

        params = copy.copy(self._filteredParams)

        nEvtRec, nContRec = 0, 0
        numEvtHits, numContHits = 0, 0
        eventResults, contribResults = [], []

        if not self._noQuery:
            if params.get('collections', "") != 'Contributions':
                numEvtHits, evtShortResult, nEvtRec, eventResults = self._getResults(
                    'Events', 25)
                params['evtShortResult'] = evtShortResult

            if params.get('collections', "") != 'Events':
                numContHits, contShortResult, nContRec, contribResults = self._getResults(
                    'Contributions', 25)
                params['contShortResult'] = contShortResult

        params['p'] = cgi.escape(phrase, quote=True)
        params['f'] = cgi.escape(filteredParams.get('f', ''), quote=True)

        params['eventResults'] = eventResults
        params['contribResults'] = contribResults

        params['nEventResult'] = nEvtRec
        params['nContribResult'] = nContRec

        params['numHits'] = numEvtHits + numContHits
        params['page'] = self._page

        params['targetObj'] = self._target

        params['searchingPublicWarning'] = self.isSearchTypeOnlyPublic(
        ) and not self._userLoggedIn
        params['accessWrapper'] = ContextManager().get("currentRH",
                                                       None).getAW()

        return params