<commit_before># -*- coding: utf-8 -*-
##
## $Id: base.py,v 1.39 2009/06/25 15:21:49 jose Exp $
##
## This file is part of CDS Indico.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN.
##
## CDS Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## CDS Indico is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with CDS Indico; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

from MaKaC.conference import Category
from MaKaC.common.PickleJar import DictPickler

import sys, traceback, time, os

from pytz import timezone
from datetime import datetime, date

from MaKaC import conference
from MaKaC.common.timezoneUtils import setAdjustedDate
from MaKaC.common import security

from MaKaC.errors import MaKaCError, htmlScriptError, htmlForbiddenTag, TimingError
from MaKaC.services.interface.rpc.common import ServiceError, ServiceAccessError, HTMLSecurityError, Warning,\
    ResultWithWarning

from MaKaC.webinterface.rh.base import RequestHandlerBase
from MaKaC.webinterface.mail import GenericMailer, GenericNotification

from MaKaC.accessControl import AccessWrapper

from MaKaC.i18n import _

"""
base module for asynchronous server requests
"""

# Just for Python 2.4 compatibility
def parseDateTime(dt, format):
    return datetime(*(time.strptime(dt, format)[0:6]))

class ExpectedParameterException(ServiceError):
    """
    Represents an exception that occurs when a type of parameter was expected
    but another one was obtained
    """

    def __init__(self, paramName, expected, got):
        ServiceError.__init__(self, "ERR-P2","'%s': Expected '%s', got instead '%s'" % (paramName, expected, got))

class EmptyParameterException(ServiceError):
    """
    Thrown when a parameter that should have a value is empty
    """
    def __init__(self, paramName=""):
        ServiceError.__init__(self, "ERR-P3","Expected parameter '%s' is empty"%paramName)

class ParameterManager(object):

    """
    The ParameterManager makes parameter processing a bit easier, by providing
    some default transformations
    """

    def __init__(self, paramList, allowEmpty=False, timezone=None):
        self._paramList = paramList
        self._allowEmpty = allowEmpty
        self._timezone = timezone

    def extract(self, paramName, pType=None, allowEmpty=None, defaultValue=None):
        """
        Extracts a parameter, given a parameter name, and optional type
        """

        # "global" policy applies if allowEmpty not set
        if (allowEmpty == None):
            allowEmpty = self._allowEmpty

        value = self._paramList.get(paramName)

        if (not allowEmpty) and (not value):
            raise EmptyParameterException(paramName)

        if pType == str:
            if value != None:
                value = str(value)
            else:
                value = defaultValue

            if (value == '' or value == None) and not allowEmpty:
                raise EmptyParameterException(paramName)
        elif pType == datetime:
            # format will possibly be accomodated to different standards,
            # in the future

            # both strings and objects are accepted
            if type(value) == str:
                naiveDate = parseDateTime(value,'%Y/%m/%d %H:%M')
            else:
                naiveDate = parseDateTime(value['date']+' '+value['time'][:5], '%Y/%m/%d %H:%M')

            if self._timezone:
                value = timezone(self._timezone).localize(naiveDate).astimezone(timezone('utc'))
            else:
                value = naiveDate
        elif pType == date:
            # format will possibly be accomodated to different standards,
            # in the future
            value = parseDateTime(value,'%Y/%m/%d').date()
        elif pType == int:
            if value == None and allowEmpty:
                value = None
            else:
                value = int(value)
        elif pType == float:
            if value == None and allowEmpty:
                value = None
            else:
                value = float(value)
        elif pType == dict:
            if not (type(value) == dict or (allowEmpty and value == None)):
                raise ExpectedParameterException(paramName, dict, type(value))
        elif pType == list:
            if not (type(value) == list or (allowEmpty and value == None)):
                raise ExpectedParameterException(paramName, list, type(value))

        return value

    def setTimezone(self, tz):
        self._timezone = tz

class ServiceBase(RequestHandlerBase):    
    """
    The ServiceBase class is the basic class for services.
    """    
    
    def __init__(self, params, remoteHost, session):
        """
        Constructor.  Initializes provate variables
        @param req: HTTP Request provided by the previous layer
        """
        self._params = params
        self._requestStarted = False
        self._websession = session
        # Fill in the aw instance with the current information
        self._aw = AccessWrapper()
        self._aw.setIP(remoteHost)
        self._aw.setSession(session)
        self._aw.setUser(session.getUser())<commit_msg>[IMPROVEMENT] ParameterManager - bool type<commit_after># -*- coding: utf-8 -*-
##
## $Id: base.py,v 1.39 2009/06/25 15:21:49 jose Exp $
##
## This file is part of CDS Indico.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN.
##
## CDS Indico is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## CDS Indico is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with CDS Indico; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

from MaKaC.conference import Category
from MaKaC.common.PickleJar import DictPickler

import sys, traceback, time, os

from pytz import timezone
from datetime import datetime, date

from MaKaC import conference
from MaKaC.common.timezoneUtils import setAdjustedDate
from MaKaC.common import security

from MaKaC.errors import MaKaCError, htmlScriptError, htmlForbiddenTag, TimingError
from MaKaC.services.interface.rpc.common import ServiceError, ServiceAccessError, HTMLSecurityError, Warning,\
    ResultWithWarning

from MaKaC.webinterface.rh.base import RequestHandlerBase
from MaKaC.webinterface.mail import GenericMailer, GenericNotification

from MaKaC.accessControl import AccessWrapper

from MaKaC.i18n import _

"""
base module for asynchronous server requests
"""

# Just for Python 2.4 compatibility
def parseDateTime(dt, format):
    return datetime(*(time.strptime(dt, format)[0:6]))

class ExpectedParameterException(ServiceError):
    """
    Represents an exception that occurs when a type of parameter was expected
    but another one was obtained
    """

    def __init__(self, paramName, expected, got):
        ServiceError.__init__(self, "ERR-P2","'%s': Expected '%s', got instead '%s'" % (paramName, expected, got))

class EmptyParameterException(ServiceError):
    """
    Thrown when a parameter that should have a value is empty
    """
    def __init__(self, paramName=""):
        ServiceError.__init__(self, "ERR-P3","Expected parameter '%s' is empty"%paramName)

class ParameterManager(object):

    """
    The ParameterManager makes parameter processing a bit easier, by providing
    some default transformations
    """

    def __init__(self, paramList, allowEmpty=False, timezone=None):
        self._paramList = paramList
        self._allowEmpty = allowEmpty
        self._timezone = timezone

    def extract(self, paramName, pType=None, allowEmpty=None, defaultValue=None):
        """
        Extracts a parameter, given a parameter name, and optional type
        """

        # "global" policy applies if allowEmpty not set
        if (allowEmpty == None):
            allowEmpty = self._allowEmpty

        value = self._paramList.get(paramName)


        if (not allowEmpty) and (value == None):
            raise EmptyParameterException(paramName)

        if pType == str:
            if value != None:
                value = str(value)
            else:
                value = defaultValue

            if (value == '' or value == None) and not allowEmpty:
                raise EmptyParameterException(paramName)
        elif pType == datetime:
            # format will possibly be accomodated to different standards,
            # in the future

            # both strings and objects are accepted
            if type(value) == str:
                naiveDate = parseDateTime(value,'%Y/%m/%d %H:%M')
            else:
                naiveDate = parseDateTime(value['date']+' '+value['time'][:5], '%Y/%m/%d %H:%M')

            if self._timezone:
                value = timezone(self._timezone).localize(naiveDate).astimezone(timezone('utc'))
            else:
                value = naiveDate
        elif pType == date:
            # format will possibly be accomodated to different standards,
            # in the future
            value = parseDateTime(value,'%Y/%m/%d').date()
        elif pType == int:
            if value == None and allowEmpty:
                value = None
            else:
                value = int(value)
        elif pType == float:
            if value == None and allowEmpty:
                value = None
            else:
                value = float(value)
        elif pType == dict:
            if not (type(value) == dict or (allowEmpty and value == None)):
                raise ExpectedParameterException(paramName, dict, type(value))
        elif pType == list:
            if not (type(value) == list or (allowEmpty and value == None)):
                raise ExpectedParameterException(paramName, list, type(value))
        elif pType == bool:
            if not (type(value) == bool or (allowEmpty and value == None)):
                raise ExpectedParameterException(paramName, list, type(value))

        return value

    def setTimezone(self, tz):
        self._timezone = tz

class ServiceBase(RequestHandlerBase):
    """
    The ServiceBase class is the basic class for services.
    """

    def __init__(self, params, remoteHost, session):
        """
        Constructor.  Initializes provate variables
        @param req: HTTP Request provided by the previous layer
        """
        self._params = params
        self._requestStarted = False
        self._websession = session
        # Fill in the aw instance with the current information
        self._aw = AccessWrapper()
        self._aw.setIP(remoteHost)
        self._aw.setSession(session)
        self._aw.setUser(session.getUser())
{'fraction_non_alphanumeric': 0.09195302305350152, 'fraction_numerical': 0.011483253588516746, 'mean_word_length': 2.6623128384835937, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3215783', 'n_tokens_mistral': 3190, 'n_tokens_neox': 2985, 'n_words': 1080}