def __init__(self, classobj):
        self._class = misc.getCallableByName(classobj)
        self._bases = self._class.__bases__
        self.doc = self._class.__doc__
        self._attrs = {}
        self._methods = {}
        self._properties = {}
        sourcelines = inspect.getsourcelines(self._class)
        startline = sourcelines[1]
        endline = startline + len(sourcelines[0]) - 1
        self.boundaries = (startline, endline)

        self._instance = self._class()
        for prop in self._class.__slots__:
            self._attrs[prop] = getattr(self._instance, prop)

        for member_name in self._class.__dict__:
            member = self._class.__dict__[member_name]
            if type(member) == types.FunctionType:
                self._methods[member_name] = member
            elif type(member) == property:
                self._properties[member_name] = member

        self._module = sys.modules[self._class.__module__]
        self._newimports = []
        self._imports = {}

        moduledict = self._module.__dict__
        for x in moduledict:
            if type(moduledict[x]) == types.ModuleType:
                self._imports[moduledict[x]] = x
            elif callable(moduledict[x]) and (sys.modules[moduledict[x].__module__] != self._module):
                imported = misc.getCallableByName(moduledict[x].__module__ + "." + x)
                self._imports[imported] = x
    def commitChanges(self):
        GenericSchemaEditor.commitChanges(self)
        if len(self._addedProps):
            # we must reload the class module
            oMod = misc.getCallableByName(self._class.__module__)
            reload(oMod)
            from porcupine.oql.command import OqlCommand

            db = offlinedb.getHandle()
            oql_command = OqlCommand()
            rs = oql_command.execute("select * from deep('/') where instanceof('%s')" % self._instance.contentclass)
            try:
                if len(rs):
                    txn = offlinedb.OfflineTransaction()
                    try:
                        for item in rs:
                            for name in self._addedProps:
                                if not hasattr(item, name):
                                    setattr(item, name, self._addedProps[name])
                            db.putItem(item, txn)
                        txn.commit()
                    except Exception, e:
                        txn.abort()
                        raise e
                        sys.exit(2)
            finally:
                offlinedb.close()
def new(self):
    "Displays a generic form for creating a new object"
    context = HttpContext.current()
        
    sCC = context.request.queryString['cc'][0]
    oNewItem = misc.getCallableByName(sCC)()
    
    params = {
        'CC': sCC,
        'URI': context.request.getRootUrl() + '/' + self.id,
        'ICON': oNewItem.__image__,
        'PROPERTIES_TAB': '',
        'EXTRA_TABS': '',
        'SECURITY_TAB': baseitem._getSecurity(self, context.user, True)
    }
    
    # inspect item properties
    sProperties = ''
    for attr_name in oNewItem.__props__:
        attr = getattr(oNewItem, attr_name)
        if isinstance(attr, datatypes.DataType):
            control, tab = baseitem._getControlFromAttribute(oNewItem,
                                                             attr_name,
                                                             attr,
                                                             False,
                                                             True)
            sProperties += control
            params['EXTRA_TABS'] += tab
    
    params['PROPERTIES'] = sProperties
    
    return params
Ejemplo n.º 4
0
    def setParams(self):
        self.response.setHeader('cache-control', 'no-cache')
        self.response.setExpiration(1200)
        
        sCC = self.request.queryString['cc'][0]
        oNewItem = misc.getCallableByName(sCC)()
        
        self.params = {
            'CC': sCC,
            'URI': self.request.getRootUrl() + '/' + self.item.id,
            'ICON': oNewItem.__image__,
            'PROPERTIES_TAB': '',
            'EXTRA_TABS': '',
            'SECURITY_TAB': self.getSecurity(self.item, True)
        }

        # inspect item properties
        sProperties = ''
        for attr_name in oNewItem.__props__:
            attr = getattr(oNewItem, attr_name)
            if isinstance(attr, datatypes.DataType):
                control, tab = \
                    self.getControlFromAttribute(attr_name, attr, False, True)
                sProperties += control
                self.params['EXTRA_TABS'] += tab
        
        self.params['PROPERTIES_TAB'] = \
            '<tab caption="@@PROPERTIES@@">%s</tab>' % sProperties
Ejemplo n.º 5
0
 def getInfo(self):
     sLang = self.request.getLang()
     lstChildren = []
     children = self.item.getChildren()
     for child in children:
         obj = {
             'id' : child.id,
             'image': child.__image__,
             'displayName' : child.displayName.value,
             'isCollection': child.isCollection,
             'modified': date.Date(child.modified)
         }
         if hasattr(child, 'size'):
             obj['size'] = child.size
         lstChildren.append(obj)
     
     containment = []
     for contained in self.item.containment:
         image = misc.getCallableByName(contained).__image__
         if not type(image)==str:
             image = ''
         localestring = resources.getResource(contained, sLang)
         containment.append( [localestring, contained, image] )
         
     return {
         'displayName': self.item.displayName.value,
         'path': misc.getFullPath(self.item),
         'parentid': self.item.parentid,
         'iscollection': self.item.isCollection,
         'containment': containment,
         'user_role': objectAccess.getAccess(self.item, self.session.user),
         'contents': lstChildren
     }
Ejemplo n.º 6
0
    def create(self, data):
        # create new item
        oNewItem = misc.getCallableByName(data.pop('CC'))()

        # get user role
        iUserRole = objectAccess.getAccess(self.item, self.session.user)
        if data.has_key('__rolesinherited') and iUserRole == objectAccess.COORDINATOR:
            oNewItem.inheritRoles = data.pop('__rolesinherited')
            if not oNewItem.inheritRoles:
                acl = data.pop('__acl')
                if acl:
                    security = {}
                    for descriptor in acl:
                        security[descriptor['id']] = int(descriptor['role'])
                    oNewItem.security = security

        # set props
        for prop in data:
            oAttr = getattr(oNewItem, prop)
            if isinstance(oAttr, datatypes.File):
                if data[prop]['tempfile']:
                    oAttr.filename = data[prop]['filename']
                    sPath = self.server.temp_folder + '/' + data[prop]['tempfile']
                    oAttr.loadFromFile(sPath)
                    os.remove(sPath)
            elif isinstance(oAttr, datatypes.Date):
                oAttr.value = data[prop].value
            else:
                oAttr.value = data[prop]
                
        txn = self.server.store.getTransaction()
        oNewItem.appendTo(self.item.id, txn)
        txn.commit()
        return True
    def start(self):
        try:
            # read configuration file
            from porcupine.config.settings import settings
            # initialize logging
            log.initialize_logging()
            self.logger.info('Server starting...')
            
            # register request interfaces
            for key, value in settings['requestinterfaces'].items():
                settings['requestinterfaces'][key] = \
                    misc.getCallableByName(value)
            self.logger.info('Succesfullly registered %i request interfaces' % \
                             len(settings['requestinterfaces']))
            
            # register template languages
            for key, value in settings['templatelanguages'].items():
                settings['templatelanguages'][key] = \
                    misc.getCallableByName(value)
            self.logger.info('Succesfullly registered %i template languages' % \
                             len(settings['templatelanguages']))
                        
            # load published directories
            self.logger.info('Loading published directories\' registrations...')
            from porcupine.config import pubdirs

            # open database
            self.logger.info('Opening database...')
            _db.open(misc.getCallableByName(
                     settings['store']['interface']))

            # create session manager
            self.logger.info('Creating session manager...')
            SessionManager.open(misc.getCallableByName(
                            settings['sessionmanager']['interface']),
                            int(settings['sessionmanager']['timeout']))
            
            self.services['_controller'] = self
            # start services
            self.logger.info('Starting services...')
            services.startServices()
            
        except Exception, e:
            self.logger.log(logging.ERROR, e[0], *(), **{'exc_info' : True})
            raise e
def getFiltersList(contextNode):
    filterList = contextNode.getElementsByTagName('filter')
    filters = []
    for filterNode in filterList:
        type = filterNode.getAttribute('type').encode('iso-8859-1')
        filter = [misc.getCallableByName(type), {}]
        for attr in filterNode.attributes.keys():
            filter[1][str(attr)] = filterNode.getAttribute(attr).encode('iso-8859-1')
        filters.append( tuple(filter) )
    return tuple(filters)
 def on_update(cls, item, new_attr, old_attr, trans):
     from porcupine.systemObjects import Composite
     # load objects
     dctObjects = {}
     for i, obj in enumerate(new_attr.value):
         if isinstance(obj, Composite):
             obj._containerid = item._id
         elif isinstance(obj, str):
             obj = _db.getItem(obj, trans)
             new_attr.value[i] = obj
         else:
             raise exceptions.ContainmentError, \
                 'Invalid object type "%s" in composition.' % \
                 obj.__class__.__name__
         dctObjects[obj._id] = obj
     
     # check containment
     compositeClass = misc.getCallableByName(new_attr.compositeClass)
     
     if [obj for obj in dctObjects.values()
             if not isinstance(obj, compositeClass)]:
         raise exceptions.ContainmentError, \
             'Invalid content class "%s" in composition.' % \
             obj.getContentclass()
     
     # get previous value
     if old_attr != None:
         old_ids = set(old_attr.value)
     else:
         old_ids = set()
     
     new_ids = set([obj._id for obj in new_attr.value])
     
     # calculate added composites
     lstAdded = list(new_ids - old_ids)
     for obj_id in lstAdded:
         _db.handle_update(dctObjects[obj_id], None, trans)
         dctObjects[obj_id]._isDeleted = False
         _db.putItem(dctObjects[obj_id], trans)
     
     # calculate constant composites
     lstConstant = list(new_ids & old_ids)
     for obj_id in lstConstant:
         _db.handle_update(dctObjects[obj_id],
                              _db.getItem(obj_id, trans),
                              trans)
         _db.putItem(dctObjects[obj_id], trans)
     
     # calculate removed composites
     lstRemoved = list(old_ids - new_ids)
     for obj_id in lstRemoved:
         composite4removal = _db.getItem(obj_id, trans)
         cls.removeComposite(composite4removal, trans)
     
     new_attr.value = list(new_ids)
def getHandle():
    #open database
    _db.open(misc.getCallableByName(settings['store']['interface']))
    #create in-memory session manager
    SessionManager.open(inMemorySessionManager.SessionManager, 1200)
    oSystemUser = _db.getItem('system')
    context = HttpContext()
    context.session = SessionManager.create(oSystemUser)
    
    currentThread().context = context
    currentThread().trans = None
    return _db
 def __init__(self, identifier, enc, filters, max_age):
     try:
         self.context = misc.getCallableByName(identifier)
         self.type = 2
     except:
         self.context = identifier
         if identifier[-4:] == '.psp':
             self.type = 1
         else:
             self.type = 0
     
     self.encoding = enc
     self.filters = filters
     self.max_age = int(max_age);
 def apply(response, request, registration, args):
     language = request.getLang()
     lst_resources = args['using'].split(',')
     bundles = [misc.getCallableByName( x )
                  for x in lst_resources]
     output = response._getBody()
     tokens = frozenset(re.findall(TOKEN, output, re.DOTALL))
     for token, key in tokens:
         for bundle in bundles:
             res = bundle.getResource(key, language)
             if res != key:
                 break
         output = output.replace(token, res)
     response._body = [output]
Ejemplo n.º 13
0
 def apply(context, registration, **kwargs):
     language = context.request.getLang()
     lst_resources = kwargs['using'].split(',')
     bundles = [misc.getCallableByName(x)
                for x in lst_resources]
     output = context.response._body.getvalue()
     tokens = frozenset(re.findall(I18n._tokens, output, re.DOTALL))
     for token, key in tokens:
         for bundle in bundles:
             res = bundle.getResource(key, language)
             if res != key:
                 break
         output = output.replace(token, res)
     context.response.clear()
     context.response.write(output)
Ejemplo n.º 14
0
 def _getFullName(self, callable):
     module = misc.getCallableByName(callable.__module__)
     if self._imports.has_key(module):
         return self._imports[module] + "." + callable.__name__
     else:
         if module == self._module:
             return callable.__name__
         self._newimports.append(module)
         local_name = callable.__module__.split(".")[-1]
         counter = 2
         while local_name in self._module.__dict__:
             local_name += str(counter)
             counter += 1
         self._imports[module] = local_name
         return local_name + "." + callable.__name__
def startServices():
    for service in settings['services']:
        name = service['name']
        type = service['type']
        service_class = misc.getCallableByName(service['class'])
        
        if type == 'TCPListener':
            address = misc.getAddressFromString(service['address'])
            worker_threads = int(service['worker_threads'])
            services[name] = service_class(name, address, worker_threads)
        elif type == 'ScheduledTask':
            interval = int(service['interval'])
            services[name] = service_class(name, interval)

        # add parameters
        if service.has_key('parameters'):
            services[name].parameters = service['parameters']
            
        # start service
        services[name].start()
Ejemplo n.º 16
0
def open():
    global db_handle, object_cache
    db_handle = misc.getCallableByName(
                     settings['store']['interface'])()
Ejemplo n.º 17
0
def _recover():
    global db_handle
    db_handle = misc.getCallableByName(
        settings['store']['interface'])._recover()
Ejemplo n.º 18
0
           or imp.is_frozen("__main__")) # tools/freeze

if main_is_frozen():
    sys.path.insert(0, '')

from porcupine.db import _db
from porcupine.utils import misc

answer = raw_input('''WARNING: Please ensure that Porcupine Server is stopped!
All objects will be erased!
Are you sure you want to initialize the database(Y/N)?''')

if (answer == 'Y'):
    try:
        from porcupine.config.settings import settings
        _db.open(misc.getCallableByName(settings['store']['interface']))
    except Exception, e:
        sys.exit(e[0])

    import porcupine.systemObjects
    import org.innoscript.desktop.schema.common
    import org.innoscript.desktop.schema.security

    # truncate database
    sys.stdout.write('Deleting existing database...')
    _db.db_handle._truncate()
    sys.stdout.write('[OK]\n')

    sOwner = 'SYSTEM'
    ftime = time.time()
Ejemplo n.º 19
0
def h_66(params, variables, forObject):
    className = evaluateStack(params[0][:], variables, forObject)
    return isinstance(forObject, misc.getCallableByName(className))
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Lesser General Public License for more details.
#    You should have received a copy of the GNU Lesser General Public License
#    along with Porcupine; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#===============================================================================
"Server request interfaces"

from porcupine.config.settings import settings
from porcupine.utils import misc
from porcupine import serverExceptions

requestInterfaces = {}

try:
    ris = settings.requestinterfaces.options
except AttributeError:
    raise serverExceptions.ConfigurationError, 'The configuration file either has no [requestinterfaces] section or the aforementioned section is blank'

for ri in ris:
    sInterface = getattr(settings.requestinterfaces, ri)
    try:
        requestInterfaces[ri.upper()] = misc.getCallableByName(sInterface)
    except AttributeError:
        raise serverExceptions.ConfigurationError, 'Invalid request interface "%s"' % sInterface
    except ImportError:
        raise serverExceptions.ConfigurationError, 'Invalid request interface "%s"' % sInterface

del ris    
from porcupine.config.settings import settings
from porcupine.utils import misc
from porcupine import serverExceptions

try:
    sm_class = settings.sessionmanager.interface
except AttributeError:
    raise serverExceptions.ConfigurationError, \
        (('interface', 'sessionmanager'),)

try:
    timeout = int(settings.sessionmanager.timeout)
except AttributeError:
    # default timeout set to 20 minutes
    timeout = 1200
except ValueError:
    raise serverExceptions.ConfigurationError, \
        'Invalid value for session manager timeout: %s' % \
        settings.sessionmanager.timeout

try:
    sm_class = misc.getCallableByName(sm_class)
except AttributeError:
    raise serverExceptions.ConfigurationError, \
        'Invalid session manager interface "%s"' % \
        settings.sessionmanager.interface
except ImportError:
    raise serverExceptions.ConfigurationError, \
        'Invalid session manager interface "%s"' % \
        settings.sessionmanager.interface
#    the Free Software Foundation; either version 2.1 of the License, or
#    (at your option) any later version.
#    Porcupine 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 Lesser General Public License for more details.
#    You should have received a copy of the GNU Lesser General Public License
#    along with Porcupine; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#===============================================================================
"Server database parameters"

from porcupine import serverExceptions
from porcupine.config.settings import settings
from porcupine.utils import misc

try:
    db_class = settings.store.interface
except AttributeError:
    raise serverExceptions.ConfigurationError, (('interface', 'store'),)

try:
    db_class = misc.getCallableByName(db_class)
except AttributeError:
    raise serverExceptions.ConfigurationError, 'Invalid store interface "%s"' % settings.store.interface
except ImportError:
    raise serverExceptions.ConfigurationError, 'Invalid store interface "%s"' % settings.store.interface
    
params = settings.storeparameters.toDict()