Exemplo n.º 1
0
def serialization_notifications_callback(channel, method, properties, body):
    obj_data = simplejson.loads(body)
    obj_type = obj_data.get("obj_type")
    domain_model = getattr(domain, obj_type, None)
    if domain_model:
        obj_key = valueKey(obj_data.get("obj_key"))
        session = Session()
        obj = session.query(domain_model).get(obj_key)
        if obj:
            try:
                publish_to_xml(obj)
            except Exception, e:
                notify_serialization_failure(SERIALIZE_FAILURE_TEMPLATE,
                    obj=obj, message=obj_data, error=e
                )
            channel.basic_ack(delivery_tag=method.delivery_tag)
        else:
            log.error("Could not query object of type %s with key %s. "
                "Check database records - Rejecting message.",
                domain_model, obj_key
            )
            #Reject the message
            channel.basic_reject(delivery_tag=method.delivery_tag,
                requeue=False
            )
        session.close()
Exemplo n.º 2
0
 def handle_cancel(self, action, data):
     """Cancelling redirects to the listing."""
     session = Session()
     if not self._next_url:
         self._next_url = url.absoluteURL(self.__parent__, self.request)
     self.request.response.redirect(self._next_url)
     session.close()
Exemplo n.º 3
0
 def handle_cancel(self, action, data):
     """Cancelling redirects to the listing."""
     session = Session()
     if not self._next_url:
         self._next_url = url.absoluteURL(self.__parent__, self.request)
     self.request.response.redirect(self._next_url)
     session.close()
Exemplo n.º 4
0
 def render(self, template=None):
     if template is None:
         template = self.template
     if (not checkPermission(u"bungeni.sitting.Add", self.context)) or \
         (IBusinessSectionLayer.providedBy(self.request)):
         self.edit = False
     else:
         self.edit = True
     session = Session()
     venues = session.query(domain.Venue).all()
     languages = get_all_languages()
     session.close()
     #defaults to english
     self.display_language = 'en'
     if self.request.get('I18N_LANGUAGES'):
         self.display_language = self.request.get('I18N_LANGUAGES')
     #html is hardcoded in here because doing it in the template
     #would have been a colossal pain
     #TODO: FIX THIS
     s = '<div class="dhx_cal_ltext" style="height:90px;">'
     s += '<table>'
     s += '<tr><td>Venue</td><td><select id="select_sitting_venue">'
     for venue in venues:
         s += '<option value="' + str(
             venue.venue_id) + '">' + venue.short_name + '</option>'
     s += '</select></td></tr>'
     s += '<tr><td>Language</td><td><select id="select_sitting_lang">'
     for lang in languages:
         if lang == 'en':
             s += '<option value="' + lang + '" selected>' + lang + '</option>'
         else:
             s += '<option value="' + lang + '">' + lang + '</option>'
     s += '</select></td></tr></table></div>'
     self.sitting_details_form = s
     return template()
Exemplo n.º 5
0
 def render(self, template=None):
     if template is None:
         template = self.template
     if (not checkPermission(u"bungeni.sitting.Add", self.context)) or \
         (IBusinessSectionLayer.providedBy(self.request)):
         self.edit = False
     else:
         self.edit = True
     session = Session()
     venues = session.query(domain.Venue).all()
     languages = get_all_languages()
     session.close()
     self.display_language = get_default_language()
     if self.request.get("I18N_LANGUAGE"):
         self.display_language = self.request.get("I18N_LANGUAGE")
     #html is hardcoded in here because doing it in the template
     #would have been a colossal pain
     #TODO: FIX THIS
     s = '<div class="dhx_cal_ltext" style="height:90px;">' 
     s += '<table>'
     s += '<tr><td>Venue</td><td><select id="select_sitting_venue">'
     for venue in venues:
         s += '<option value="'+str(venue.venue_id)+'">'+venue.short_name+'</option>'
     s += '</select></td></tr>'
     s += '<tr><td>Language</td><td><select id="select_sitting_lang">'
     for lang in languages:
         if lang == 'en':
             s += '<option value="'+lang+'" selected>'+lang+'</option>'
         else:
             s += '<option value="'+lang+'">'+lang+'</option>'
     s += '</select></td></tr></table></div>'
     self.sitting_details_form = s
     return template()
Exemplo n.º 6
0
def serialization_notifications_callback(channel, method, properties, body):
    obj_data = simplejson.loads(body)
    obj_type = obj_data.get("obj_type")
    domain_model = getattr(domain, obj_type, None)
    if domain_model:
        obj_key = valueKey(obj_data.get("obj_key"))
        session = Session()
        obj = session.query(domain_model).get(obj_key)
        if obj:
            try:
                publish_to_xml(obj)
            except Exception, e:
                notify_serialization_failure(SERIALIZE_FAILURE_TEMPLATE,
                                             obj=obj,
                                             message=obj_data,
                                             error=e)
            channel.basic_ack(delivery_tag=method.delivery_tag)
        else:
            log.error(
                "Could not query object of type %s with key %s. "
                "Check database records - Rejecting message.", domain_model,
                obj_key)
            #Reject the message
            channel.basic_reject(delivery_tag=method.delivery_tag,
                                 requeue=False)
        session.close()
Exemplo n.º 7
0
def on_end_request(event):
    """Subscriber to catch end of request processing, and dispatch cleanup 
    tasks as needed. 
    """
    session = Session()
    log.info("""IEndRequestEvent:%s:%s
        closing SqlAlchemy session: %s""" %
             (id(event.request), event.object, session))
    session.close()
Exemplo n.º 8
0
    def handle_add_save(self, action, data):
        """After succesful creation of translation, redirect to the
        view."""
        for key in data.keys():
            if isinstance(data[key], str):
                data[key] = unescape(data[key])
        #url = url.absoluteURL(self.context, self.request)
        #language = get_language_by_name(data["language"])["name"]
        session = Session()
        trusted = removeSecurityProxy(self.context)
        mapper = rdb.orm.object_mapper(trusted)
        pk = getattr(trusted, mapper.primary_key[0].name)

        current_translation = get_translation_for(self.context,
                                                  data["language"])
        if current_translation:
            for translation in current_translation:
                session.delete(translation)

        for form_field in data.keys():
            if form_field == "language":
                continue
            translation = domain.ObjectTranslation()
            translation.object_id = pk
            translation.object_type = trusted.__class__.__name__
            translation.field_name = form_field
            translation.lang = data["language"]
            translation.field_text = data[form_field]
            session.add(translation)
        session.flush()
        session.commit()
        session.close()

        # !+EVENT_DRIVEN_CACHE_INVALIDATION(mr, mar-2011) no translate event
        # invalidate caches for this domain object type
        invalidate_caches_for(trusted.__class__.__name__, "translate")

        #versions = IVersioned(self.context)
        #version = versions.create("'%s' translation added" % language)

        # reset workflow state
        #version.status = None
        #IWorkflowInfo(version).fireTransition("-draft_translation")
        # redefine form context and proceed with edit action
        #self.setUpAdapters(version)
        #handle_edit_action(self, action, data)

        # commit version such that it gets a version id
        #transaction.commit()

        #if not self._next_url:
        #    self._next_url = ( \
        #        "%s/versions/%s" % (url, stringKey(version)) + \
        #        "?portal_status_message=Translation added")

        self._finished_add = True
Exemplo n.º 9
0
 def handle_edit_cancel(self, action, data):
     """Cancelling redirects to the listing."""
     for key in data.keys():
         if isinstance(data[key], str):
             data[key] = unescape(data[key])
     session = Session()
     if not self._next_url:
         self._next_url = url.absoluteURL(self.context, self.request)
     self.request.response.redirect(self._next_url)
     session.close()
Exemplo n.º 10
0
 def handle_edit_cancel(self, action, data):
     """Cancelling redirects to the listing."""
     for key in data.keys():
         if isinstance(data[key], str):
             data[key] = unescape(data[key])
     session = Session()
     if not self._next_url:
         self._next_url = url.absoluteURL(self.context, self.request)
     self.request.response.redirect(self._next_url)
     session.close()
Exemplo n.º 11
0
    def handle_add_save(self, action, data):
        """After succesful creation of translation, redirect to the
        view."""
        for key in data.keys():
            if isinstance(data[key], str):
                data[key] = unescape(data[key])
        #url = url.absoluteURL(self.context, self.request)
        #language = get_language_by_name(data["language"])["name"]
        session = Session()
        trusted = removeSecurityProxy(self.context)
        mapper = rdb.orm.object_mapper(trusted)
        pk = getattr(trusted, mapper.primary_key[0].name)

        current_translation = get_translation_for(self.context, data["language"])
        if current_translation:
            for translation in current_translation:
                session.delete(translation)

        for form_field in data.keys():
            if form_field == "language":
                continue
            translation = domain.ObjectTranslation()
            translation.object_id = pk
            translation.object_type = trusted.__class__.__name__
            translation.field_name = form_field
            translation.lang = data["language"]
            translation.field_text = data[form_field]
            session.add(translation)
        session.flush()
        session.commit()
        session.close()
        
        # !+EVENT_DRIVEN_CACHE_INVALIDATION(mr, mar-2011) no translate event
        # invalidate caches for this domain object type
        invalidate_caches_for(trusted.__class__.__name__, "translate")

        #versions = IVersioned(self.context)
        #version = versions.create("'%s' translation added" % language)

        # reset workflow state
        #version.status = None
        #IWorkflowInfo(version).fireTransition("-draft_translation")
        # redefine form context and proceed with edit action
        #self.setUpAdapters(version)
        #handle_edit_action(self, action, data)

        # commit version such that it gets a version id
        #transaction.commit()

        #if not self._next_url:
        #    self._next_url = ( \
        #        "%s/versions/%s" % (url, stringKey(version)) + \
        #        "?portal_status_message=Translation added")

        self._finished_add = True
Exemplo n.º 12
0
 def callback(channel, method, properties, body):
     #channel.confirm_delivery()
     notification_utl = component.getUtility(INotificationsUtility)
     exchange = str(mq_utility.get_message_exchange())
     message = simplejson.loads(body)
     domain_class = notification_utl.get_domain(
         message["document_type"])
     session = Session()
     if domain_class and message["document_id"]:
         document = session.query(domain_class).get(message["document_id"])
         if document:
             # first we handle the transition based notifications
             transition_roles = notification_utl.get_transition_based_roles(
                 domain_class, message["destination"]
             )
             transition_principal_ids = get_principal_ids(
                 document, transition_roles)
             if transition_principal_ids:
                 mes = get_message(document, transition_principal_ids)
                 mes["notification_type"] = "onstate"
                 dthandler = lambda obj: obj.isoformat() if isinstance(
                     obj, datetime.datetime) else obj
                 #channel_conf = 
                 channel.basic_publish(
                     exchange=exchange,
                     body=simplejson.dumps(mes, default=dthandler),
                     properties=pika.BasicProperties(
                         content_type="text/plain",
                         delivery_mode=1
                     ),
                     routing_key=""
                 )
                 #if channel_conf:
                 #   log.info("Message published for exchange %r", exchange)
                 #else:
                 #   log.error("Message publication failed for exchange %s and message %s" % (exchange, mes))
             # then we handle the time based notifications
             time_roles = notification_utl.get_time_based_time_and_roles(
                 domain_class, message["destination"]
             )
             for time_string, roles in time_roles.iteritems():
                 time_ntf = domain.TimeBasedNotication()
                 time_ntf.object_id = message["document_id"]
                 time_ntf.object_type = message["document_type"]
                 time_ntf.object_status = message["destination"]
                 time_ntf.time_string = time_string
                 time_ntf.notification_date_time = notification_time(
                     time_string)
                 session.add(time_ntf)
     # we commit manually here as this code is not executed in a zope
     # transaction
     session.commit()
     session.close()
     channel.basic_ack(delivery_tag=method.delivery_tag)
Exemplo n.º 13
0
 def callback(channel, method, properties, body):
     #channel.confirm_delivery()
     notification_utl = component.getUtility(INotificationsUtility)
     exchange = str(mq_utility.get_message_exchange())
     message = simplejson.loads(body)
     domain_class = notification_utl.get_domain(message["document_type"])
     session = Session()
     if domain_class and message["document_id"]:
         document = session.query(domain_class).get(message["document_id"])
         if document:
             # first we handle the transition based notifications
             transition_roles = notification_utl.get_transition_based_roles(
                 domain_class, message["destination"])
             transition_principal_ids = get_principal_ids(
                 document, transition_roles)
             if transition_principal_ids:
                 mes = get_message(document, transition_principal_ids)
                 mes["notification_type"] = "onstate"
                 dthandler = lambda obj: obj.isoformat() if isinstance(
                     obj, datetime.datetime) else obj
                 #channel_conf =
                 channel.basic_publish(exchange=exchange,
                                       body=simplejson.dumps(
                                           mes, default=dthandler),
                                       properties=pika.BasicProperties(
                                           content_type="text/plain",
                                           delivery_mode=1),
                                       routing_key="")
                 #if channel_conf:
                 #   log.info("Message published for exchange %r", exchange)
                 #else:
                 #   log.error("Message publication failed for exchange %s and message %s" % (exchange, mes))
             # then we handle the time based notifications
             time_roles = notification_utl.get_time_based_time_and_roles(
                 domain_class, message["destination"])
             for time_string, roles in time_roles.iteritems():
                 time_ntf = domain.TimeBasedNotication()
                 time_ntf.object_id = message["document_id"]
                 time_ntf.object_type = message["document_type"]
                 time_ntf.object_status = message["destination"]
                 time_ntf.time_string = time_string
                 time_ntf.notification_date_time = notification_time(
                     time_string)
                 session.add(time_ntf)
     # we commit manually here as this code is not executed in a zope
     # transaction
     session.commit()
     session.close()
     channel.basic_ack(delivery_tag=method.delivery_tag)
Exemplo n.º 14
0
    def __call__(self, timestamp=None):
        session = Session()
        if timestamp is None:
            # start the week on the first weekday (e.g. Monday)
            date = utils.datetimedict.fromdate(datetime.date.today())
        else:
            try:
                timestamp = float(timestamp)
            except:
                raise TypeError("Timestamp must be floating-point (got %s)" %
                                timestamp)
            date = utils.datetimedict.fromtimestamp(timestamp)

        if misc.is_ajax_request(self.request):
            rendered = self.render(date, template=self.ajax)
        rendered = self.render(date)
        session.close()
        return rendered
Exemplo n.º 15
0
    def __call__(self, timestamp=None):
        session = Session()
        if timestamp is None:
            # start the week on the first weekday (e.g. Monday)
            date = utils.datetimedict.fromdate(datetime.date.today())
        else:
            try:
                timestamp = float(timestamp)
            except:
                raise TypeError(
                    "Timestamp must be floating-point (got %s)" % timestamp)
            date = utils.datetimedict.fromtimestamp(timestamp)

        if misc.is_ajax_request(self.request):
            rendered = self.render(date, template=self.ajax)
        rendered = self.render(date)
        session.close()
        return rendered
Exemplo n.º 16
0
def serialization_notifications_callback(channel, method, properties, body):
    """Publish an object to XML on receiving AMQP message
    """
    # set up thread local cache
    thread_locals.serialize_cache = {}
    obj_data = simplejson.loads(body)
    obj_type = obj_data.get("obj_type")
    domain_model = getattr(domain, obj_type, None)
    if domain_model:
        obj_key = valueKey(obj_data.get("obj_key"))
        session = Session()
        obj = session.query(domain_model).get(obj_key)
        if obj:
            try:
                publish_to_xml(obj)
            except Exception, e:
                ex_type, ex, tb = sys.exc_info()
                log.warn("Error while publish_to_xml : %r", traceback.format_tb(tb))
                log.warn("Error info type: %s, obj_key: %s, obj: %s", obj_type, obj_key, obj)
                # requeue, usually fails becuase of an object introspection timeout
                # so we simply retry
                channel.basic_reject(delivery_tag=method.delivery_tag,
                    requeue=True
                )
                notify_serialization_failure(SERIALIZE_FAILURE_TEMPLATE,
                    obj=obj, message=obj_data, error=e)
            else:
                # no exceptions so acknowledge the message
                channel.basic_ack(delivery_tag=method.delivery_tag)
        else:
            log.error("Could not query object of type %s with key %s. "
                "Check database records - Rejecting message.",
                domain_model, obj_key
            )
            # reject the message
            channel.basic_reject(delivery_tag=method.delivery_tag,
                requeue=False
            )
        session.close()