Ejemplo n.º 1
0
 def loadSkelton(self, REQUEST, skelton='zch'):
     "Add Page Template PythonScript, DTMLMethod and Image read from skelton directory."
     for entry in os.listdir(os.path.join(package_home(globals()), 'skelton', skelton)):
         if entry[-3:] == '.pt' or entry[-4:]=='.pys' or entry[-5:]=='.dtml' or entry[-4:]=='.gif':
             f=open(os.path.join(package_home(globals()), 'skelton', skelton, entry), 'rb') 
             file=f.read()     
             f.close()     
             try:
                 if entry[-3:] == '.pt':
                     id = entry[:-3]
                     manage_addPageTemplate(self, id, '', file, encoding='utf-8')
                 elif entry[-4:] == '.pys':
                     id = entry[:-4]
                     manage_addPythonScript(self,id)
                     self._getOb(id).write(file)
                 elif entry[-5:] == '.dtml':
                     id = entry[:-5]
                     self.manage_addDTMLMethod(id,'',file)     
                 elif entry[-4:] == '.gif':
                     id = entry[:-4]
                     self.manage_addImage(id,file,content_type='image/gif')
             except:
                 pass
     if REQUEST is not None:
         return REQUEST.RESPONSE.redirect(REQUEST['HTTP_REFERER'])
Ejemplo n.º 2
0
    def __init__(self, path, _prefix=None, max_age_development=60, max_age_production=3600,
                 content_type=None, set_expiry_header=True):
        if _prefix is None:
            _prefix = getConfiguration().softwarehome
        elif type(_prefix) is not type(''):
            _prefix = package_home(_prefix)
        path = os.path.join(_prefix, path)
        self.path = self.original_path = path
        self.set_expiry_header = set_expiry_header
        
        if DevelopmentMode:
            # In development mode, a shorter time is handy
            max_age = max_age_development
        else:
            # A longer time reduces latency in production mode
            max_age = max_age_production
        self.max_age = max_age
        self.cch = 'public,max-age=%d' % max_age

        data = open(path, 'rb').read()
        if content_type is None:
            content_type, __ = my_guess_content_type(path, data)
            
        if content_type:
            self.content_type=content_type
        else:
            raise ValueError, "content_type not set or couldn't be guessed"
            #self.content_type='text/plain'
            
        self.__name__=path[path.rfind('/')+1:]
        self.lmt=float(os.stat(path)[8]) or time.time()
        self.lmh=rfc1123_date(self.lmt)
        self.content_size = os.stat(path)[stat.ST_SIZE]
def install_tsearch(args):
    #Let's try the extension interface, first:
    try:
        ts_file = "extension"
        _dbadminexec(args, "create extension tsearch2")
    except psycopg.ProgrammingError, e:
        if 'syntax error at or near "extension"' in str(e):
            #older version, try the hard way
            ph = package_home(product_globals)
            tsearch_paths = ['/usr/share/postgresql/8.4/contrib/tsearch2.sql',
                             '/usr/share/postgresql/8.3/contrib/tsearch2.sql',
                             '/usr/share/postgresql/8.2/contrib/tsearch2.sql',
                             ph+'/sql/tsearch2.sql']
            for ts_file in tsearch_paths:
                try:
                    ts_schema = open(ts_file,'r').read()
                    break
                except IOError:
                    pass # find first working one

            _dbadminexec(args, ts_schema)
            command = """
                grant all on pg_ts_cfg to public;
                grant all on pg_ts_cfgmap to public;
                grant all on pg_ts_dict to public;
                grant all on pg_ts_parser to public;
                update pg_ts_cfg set locale = (select current_setting('lc_collate')) where ts_name = 'default';
                """
            _dbadminexec(args, command)
        else:
            raise
def setupMetadata(root):
    product = package_home(globals())
    schema = path.join(product, 'schema')

    for setid, xmlfilename, types in metadatasets:
        collection = root.service_metadata.getCollection()
        if not setid in collection.objectIds():
            xmlfile = path.join(schema, xmlfilename)
            definition = open(xmlfile, 'r')
            collection.importSet(definition)


    mapping = root.service_metadata.getTypeMapping()
    default = ''
    tm = (
            {'type': 'Course Date', 'chain': 'silva-content , silva-extra'},
            {'type': 'Review', 'chain': 'silva-content , silva-extra'},
            {'type': 'Course', 'chain': 'silva-content , silva-extra'},
            {'type': 'Course Page Version', 'chain': 'silva-content , silva-extra'},
            {'type': 'Case Study Version', 'chain': 'silva-content , silva-extra'},
            {'type': 'Course Team', 'chain': 'silva-content , silva-extra'},
            {'type': 'Course Tags', 'chain': 'silva-content , silva-extra'},
            {'type': 'Course Facets', 'chain': 'silva-content , silva-extra'},
            {'type': 'Course Subject Version', 'chain': 'silva-content , silva-extra'},
            {'type': 'Anouncement Version', 'chain': 'silva-content , silva-extra'},
            {'type': 'General Page Version', 'chain': 'silva-content , silva-extra'},
        )

    mapping.editMappings(default, tm)
    root.service_metadata.initializeMetadata()
Ejemplo n.º 5
0
 def registerDirectory(self, name, _prefix, subdirs=1, ignore=ignore):
     # This what is actually called to register a
     # file system directory to become a FSDV.
     if not isinstance(_prefix, basestring):
         _prefix = package_home(_prefix)
     filepath = path.join(_prefix, name)
     self.registerDirectoryByPath(filepath, subdirs, ignore=ignore)
Ejemplo n.º 6
0
def load_file(filename):
    import os
    from Globals import package_home
    filename = os.path.sep.join([package_home(globals()), filename])
    data = StringIO(open(filename, 'rb').read())
    data.filename = os.path.basename(filename)
    return data
Ejemplo n.º 7
0
    def createProducts2(self):
        """Add all products to one category.
        """                            
        shop = self.context
                
        id = "category"
        shop.categories.manage_addProduct["easyshop.core"].addCategory(id, title="Category")        
        category = shop.categories.get(id)
        
        wftool = getToolByName(self.context, "portal_workflow")
        wftool.doActionFor(category, "publish")

        for i in range(1, 21):
            title = self.createTitle()
            id = title.lower()
            shop.products.manage_addProduct["easyshop.core"].addProduct(id, title=title)
            product = shop.products.get(id)

            img = os.path.join(package_home(globals()), '../../tests/test_2.jpg')
            img = open(img)
        
            product.setImage(img)

            category.addReference(product, "categories_products")            
            wftool.doActionFor(product, "publish")
            
        self.context.portal_catalog.manage_catalogRebuild()
    def getInputDir(name, templdir=''):
        samples = os.path.join(package_home(globals()), 'input')
        dir = samples
        if templdir:
            dir = os.path.join(dir, templdir)

        return dir
Ejemplo n.º 9
0
 def __init__(self, path, zipfile, _globals=None):
     if _globals:
         import os
         zipfile = os.path.join(package_home(_globals), zipfile)
     
     self._path = path
     self._zipfile = zipfile
Ejemplo n.º 10
0
 def setupPages(self, REQUEST=None):
     """
     Install some default wiki pages to help get a wiki started.
     """
     # copied from ...
     dir = package_home(globals()) + os.sep + 'content' + os.sep + 'basic'
     filenames = os.listdir(dir)
     for filename in filenames:
         if filename[-5:] == '.dtml': pass
         else:
             m = re.search(r'(.+)\.(.+)', filename)
             if m:
                 name, type = m.group(1), m.group(2)
                 if not self.pageWithName(name):
                     text = open(dir + os.sep + filename, 'r').read()
                     # parse optional parents list
                     m = re.match(r'(?si)(^#parents:(.*?)\n)?(.*)', text)
                     if m.group(2): parents = split(strip(m.group(2)), ',')
                     else: parents = []
                     text = m.group(3)
                     # XXX: this will choke if it tries to
                     # create a page with a .png file
                     self.create(name, text=text)
     if REQUEST:
         REQUEST.RESPONSE.redirect(self.pageUrl())
Ejemplo n.º 11
0
    def __init__(self, path, zipfile, _globals=None):
        if _globals:
            import os
            zipfile = os.path.join(package_home(_globals), zipfile)

        self._path = path
        self._zipfile = zipfile
Ejemplo n.º 12
0
def install_subskin(self, out, skin_name, globals=types_globals):
    homedir = package_home(globals)
    log("Skins are in the %s subdirectory of %s" % (skin_name, homedir))
    skinstool = getToolByName(self, "portal_skins")
    if skin_name not in skinstool.objectIds():
        registerDirectory(skin_name, homedir)
        try:
            addDirectoryViews(skinstool, skin_name, homedir)
        except:
            log("Error adding directory views for " + skin_name)

    for skinName in skinstool.getSkinSelections():
        path = skinstool.getSkinPath(skinName)
        path = [i.strip() for i in path.split(",")]

        # Delete it if it already exists, so it only exists once.
        for skin_dir in SKIN_DIRS:
            if skin_dir in path:
                path.remove(skin_dir)

            try:
                if skin_dir not in path:
                    path.insert(path.index("custom") + 1, skin_dir)
            except ValueError:
                if skin_dir not in path:
                    path.append(skin_dir)

        path = ",".join(path)
        skinstool.addSkinSelection(skinName, path)
Ejemplo n.º 13
0
    def __init__(self,path,_prefix=None):
        if _prefix is None: _prefix=SOFTWARE_HOME
        elif type(_prefix) is not type(''):
            _prefix=package_home(_prefix)
        path = os.path.join(_prefix, path)
        self.path=path
        if Globals.DevelopmentMode:
            # In development mode, a shorter time is handy
            max_age = 60 # One minute
        else:
            # A longer time reduces latency in production mode
            max_age = 3600 # One hour
        self.cch = 'public,max-age=%d' % max_age

        file=open(path, 'rb')
        data=file.read()
        file.close()
        content_type, enc=guess_content_type(path, data)
        if content_type:
            self.content_type=content_type
        else:
            self.content_type='image/%s' % path[path.rfind('.')+1:]
        self.__name__=path[path.rfind('/')+1:]
        self.lmt=float(stat(path)[8]) or time()
        self.lmh=rfc1123_date(self.lmt)
    def getInputDir(name,templdir=''):
        samples=os.path.join(package_home(globals()),'input')
        dir=samples
        if templdir:
            dir=os.path.join(dir,templdir)

        return dir
Ejemplo n.º 15
0
def install_subskin(self, out, skin_name, globals=types_globals):
    homedir=package_home(globals)
    log('Skins are in the %s subdirectory of %s' % (skin_name, homedir))
    skinstool=getToolByName(self, 'portal_skins')
    if skin_name not in skinstool.objectIds():
        registerDirectory(skin_name, homedir)
        try:
            addDirectoryViews(skinstool, skin_name, homedir)
        except:
            log('Error adding directory views for ' + skin_name)

    for skinName in skinstool.getSkinSelections():
        path = skinstool.getSkinPath(skinName) 
        path = [i.strip() for i in  path.split(',')]

        # Delete it if it already exists, so it only exists once.
        for skin_dir in SKIN_DIRS:
            if skin_dir in path:
                path.remove(skin_dir)

            try:
                if skin_dir not in path:
                    path.insert(path.index('custom') +1, skin_dir)
            except ValueError:
                if skin_dir not in path:
                    path.append(skin_dir)  

        path = ','.join(path)
        skinstool.addSkinSelection( skinName, path)
Ejemplo n.º 16
0
def manage_addLocation(self, id, description, title,
        address, url, map_url, roadmap_url,
        max_seats, REQUEST=None):
    """Add a new Location object with id=title, uploading file."""

    ob=Location()
    ob.id = id
    ob.title = title
    ob.description = description
    ob.address = address
    ob.url = url
    ob.map_url = map_url
    ob.roadmap_url = roadmap_url
    ob.max_seats = max_seats
    self._setObject(id, ob)
    ob=self._getOb(id)

    indexfile = open(join(package_home(globals()), 'www','LocationIndex.dtml'))
    content = indexfile.read()
    indexfile.close()

    ob.manage_addDTMLMethod('index_html', title='Default View', file=content)

    if REQUEST is not None:
        return self.manage_main(self, REQUEST, update_menu=1)
Ejemplo n.º 17
0
def installVocabularies(context):
    """creates/imports the atvm vocabs."""
    if isNotPloneRDAProfile(context): return 
    site = context.getSite()
    # Create vocabularies in vocabulary lib
    atvm = getToolByName(site, ATVOCABULARYTOOL)
    vocabmap = {'parroquia': ('SimpleVocabulary', 'SimpleVocabularyTerm'),
         'tipo_establecimiento': ('SimpleVocabulary', 'SimpleVocabularyTerm'),
        }
    for vocabname in vocabmap.keys():
        if not vocabname in atvm.contentIds():
            atvm.invokeFactory(vocabmap[vocabname][0], vocabname)

        if len(atvm[vocabname].contentIds()) < 1:
            if vocabmap[vocabname][0] == "VdexVocabulary":
                vdexpath = os.path.join(
                    package_home(product_globals), 'data', '%s.vdex' % vocabname)
                if not (os.path.exists(vdexpath) and os.path.isfile(vdexpath)):
                    logger.warn('No VDEX import file provided at %s.' % vdexpath)
                    continue
                try:
                    #read data
                    f = open(vdexpath, 'r')
                    data = f.read()
                    f.close()
                except:
                    logger.warn("Problems while reading VDEX import file "+\
                                "provided at %s." % vdexpath)
                    continue
                # this might take some time!
                atvm[vocabname].importXMLBinding(data)
            else:
                pass
Ejemplo n.º 18
0
 def doUninstall(self, context):
     """Remove layers form skins
     @param context: InstallationContext object
     """
     skinsDir = os.path.join(package_home(context.product_globals), self.layers_dir)
     new_layers = [d for d in os.listdir(skinsDir)
                  if ((os.path.isdir(os.path.join(skinsDir, d)))
                      and
                      (d not in ('CVS',)))]
     context.logInfo("Layers %s already removed by CMFQuickInstaller" %
                     ', '.join(["'" + n + "'" for n in new_layers]))
     for skin_name in context.portal_skins.getSkinSelections():
         path = [l.strip() for l in context.portal_skins.getSkinPath(skin_name).split(',')]
         for new_layer in new_layers:
             if new_layer in path:
                 path.remove(new_layer)
                 context.logInfo("Removed '%s' layer from '%s' skin" %
                                 (new_layer, skin_name))
             else:
                 context.logWarning("Didn't find '%s' layer in '%s' skin, skipped" %
                                 (new_layer, skin_name))
             # /if ...
         # /for ...
         path = ', '.join(path)
         context.portal_skins.addSkinSelection(skin_name, path)
     # /for ...
     return
Ejemplo n.º 19
0
 def registerDirectory(self, name, _prefix, subdirs=1, ignore=ignore):
     # This what is actually called to register a
     # file system directory to become a FSDV.
     if not isinstance(_prefix, basestring):
         _prefix = package_home(_prefix)
     filepath = path.join(_prefix, name)
     self.registerDirectoryByPath(filepath, subdirs, ignore=ignore)
def list_doctests():
    home = package_home(GLOBALS)
    filenames = [
        os.path.sep.join([home, 'tests', filename])
        for filename in test_files_in_order
    ]
    return filenames
Ejemplo n.º 21
0
def installVocabularies(context):
    """creates/imports the atvm vocabs."""
    if isNotUWOshSuccessProfile(context):
        return 
    site = context.getSite()
    # Create vocabularies in vocabulary lib
    atvm = getToolByName(site, ATVOCABULARYTOOL)
    vocabmap = { 'UWOshSuccessTestLocations' : ('SimpleVocabulary', 'SimpleVocabularyTerm'),
                 'UWOshSuccessAccommodations' : ('SimpleVocabulary', 'SimpleVocabularyTerm'),
                 'UWOshSuccessAlwaysAllowableAccommodations' : ('SimpleVocabulary', 'SimpleVocabularyTerm'),
                 'UWOshBuildings' : ('SimpleVocabulary', 'SimpleVocabularyTerm'),
                 }

    for vocabname in vocabmap.keys():
        if not vocabname in atvm.contentIds():
            atvm.invokeFactory(vocabmap[vocabname][0], vocabname)

        if len(atvm[vocabname].contentIds()) < 1:
            if vocabmap[vocabname][0] == 'SimpleVocabulary':
                csvpath = os.path.join(package_home(product_globals), 'data', '%s.csv' % vocabname)

                if not (os.path.exists(csvpath) and os.path.isfile(csvpath)):
                    logger.warn('No csv import file provided at %s.' % csvpath)
                    continue
                try:
                    f = open(csvpath, 'r')
                    data = f.read()
                    f.close()
                except:
                    logger.warn("Problems while reading csv import file provided at %s." % csvpath)
                    continue
                atvm[vocabname].importCSV(data)
Ejemplo n.º 22
0
    def Update(self, clean=False, REQUEST=None):
        """ take everything inside the 'tinymce' folder and 
        instanciate in this instance. """

        producthome = package_home(globals())

        try:
            # 1. Create temp dir
            tmpdir = tempfile.mkdtemp()

            # 2. unpack tinymce
            Utils.extract(os.path.join(producthome, TINYMCE_ZIPFILE), tmpdir)

            # 3. unpack language pack (if exists)
            lpackage = os.path.join(producthome, LPACKAGE_ZIPFILE)
            if os.path.isfile(lpackage):
                Utils.extract(lpackage, tmpdir)

            # 4. Unravel into zope
            self._uploadInto(tmpdir, self, clean=clean, create_zope_folder=0)

        finally:
            # 5. Remove the unpacked dir
            if os.path.isdir(tmpdir):
                shutil.rmtree(tmpdir)

        self._updateLastUpdateDate()
        if clean:
            self._updateZipefileUsed()

        if REQUEST is not None:
            url = self.absolute_url() + '/manage_Update'
            url += '?manage_tabs_message=Update+finished'
            REQUEST.RESPONSE.redirect(url)
Ejemplo n.º 23
0
def loadfile(rel_filename):
    """A helper method for loading test data files."""
    home = package_home(product_globals)
    filename = os.path.sep.join([home, rel_filename])
    data = StringIO(open(filename, 'r').read())
    data.filename = os.path.basename(rel_filename)
    return data
Ejemplo n.º 24
0
def load_test_file(filename, globals_):
    """ Load data from a test file """
    home = package_home(globals_)
    filename = os.path.sep.join([home, filename])
    data = StringIO(open(filename, 'rb').read())
    data.filename = os.path.basename(filename)
    return data
Ejemplo n.º 25
0
    def createProducts2(self):
        """Add all products to one category.
        """
        shop = self.context

        id = "category"
        shop.categories.manage_addProduct["EasyShop"].addCategory(
            id, title="Category")
        category = shop.categories.get(id)

        wftool = getToolByName(self.context, "portal_workflow")
        wftool.doActionFor(category, "publish")

        for i in range(1, 21):
            title = self.createTitle()
            id = title.lower()
            shop.products.manage_addProduct["EasyShop"].addProduct(id,
                                                                   title=title)
            product = shop.products.get(id)

            img = os.path.join(package_home(product_globals),
                               'tests/test_2.jpg')
            img = open(img)

            product.setImage(img)

            category.addReference(product, "easyshopcategory_easyshopproduct")
            wftool.doActionFor(product, "publish")

        self.context.portal_catalog.manage_catalogRebuild()
Ejemplo n.º 26
0
def list_skelton(self):
    skelton = []
    for item in os.listdir(os.path.join(package_home(globals()), 'skelton')):
        if item == 'CVS':
            continue
        skelton.append(item)
    return skelton
Ejemplo n.º 27
0
def StaticServeFromFolder(path, _globals=None, cache=True):
    """ Serves static files from the filesystem """

    if _globals:
        _path = os.path.join(package_home(_globals), path)
    else:
        _path = path

    def callback(context, path, REQUEST):
        filepath = os.path.join(_path, *path)
        try:
            fd = open(filepath, 'rb')
        except IOError:
            REQUEST.RESPONSE.setStatus(404)
            return "Not Found"

        try:
            data = fd.read()
            content_type, content_encoding = mimetypes.guess_type(filepath)
            if content_type:
                REQUEST.RESPONSE.setHeader('content-type', content_type)
                if cache:
                    REQUEST.RESPONSE.setHeader('Cache-Control',
                                               'max-age=31556926')
                else:
                    REQUEST.RESPONSE.setHeader('Cache-Control', 'no-cache')
        except KeyError:
            data = "Not Found"
            REQUEST.RESPONSE.setStatus(404)

        fd.close()
        return data

    return CaptureTraverse(callback)
Ejemplo n.º 28
0
def StaticServeFromFolder(path, _globals=None, cache=True):
    """ Serves static files from the filesystem """

    if _globals:
        _path = os.path.join(package_home(_globals), path)
    else:
        _path = path

    def callback(context, path, REQUEST):
        filepath = os.path.join(_path, *path)
        try:
            fd = open(filepath)
        except IOError:
            REQUEST.RESPONSE.setStatus(404)
            return "Not Found"

        try:
            data = fd.read()
            content_type = mimetype_from_filename(filepath)
            if content_type:
                REQUEST.RESPONSE.setHeader('content-type', content_type)
                if cache:
                    REQUEST.RESPONSE.setHeader('Cache-Control', 'max-age=31556926')
                else:
                    REQUEST.RESPONSE.setHeader('Cache-Control', 'no-cache')
        except KeyError:
            data = "Not Found"
            REQUEST.RESPONSE.setStatus(404)

        fd.close()
        return data

    return CaptureTraverse(callback)
Ejemplo n.º 29
0
    def setupDtmlPages(self, REQUEST=None):
        """
        Install the DTML page implementations of some standard views.

        This facilitates easy tweaking and development.
        It doesn't check if dtml is enabled in the wiki, just
        creates the pages with the default page type.
        """
        dir = os.path.join(package_home(globals()), 'skins', 'zwiki')
        filenames = os.listdir(dir)
        for filename in filenames:
            if filename[-5:] != '.dtml':
                pass
            else:
                m = re.search(r'(.+)\.(.+)', filename)
                if m:
                    name, type = m.group(1), m.group(2)
                    if not self.pageWithName(name):
                        text = open(os.path.join(dir, filename), 'r').read()
                        # parse optional parents list
                        m = re.match(r'(?si)(^#parents:(.*?)\n)?(.*)', text)
                        if m.group(2): parents = split(strip(m.group(2)), ',')
                        else: parents = []
                        text = m.group(3)
                        self.create(name, text=text)
        if REQUEST:
            REQUEST.RESPONSE.redirect(self.pageUrl())
Ejemplo n.º 30
0
def ptFile(id, *filename):
    if type(filename[0]) is types.DictType:
        filename = list(filename)
        filename[0] = package_home(filename[0])
    filename = os.path.join(*filename)
    if not os.path.splitext(filename)[1]:
        filename = filename + '.pt'
    return PageTemplateFile(filename, '', __name__=id)
Ejemplo n.º 31
0
 def get_path_from_prefix(self, _prefix):
     if isinstance(_prefix, str):
         path = _prefix
     else:
         if _prefix is None:
             _prefix = sys._getframe(2).f_globals
         path = package_home(_prefix)
     return path
Ejemplo n.º 32
0
 def getMakefile(self, default=1):
     """Return makefile path; meant only for manager consumption.
      'default' if true returns a default value if the field is empty.
     """
     makefile = getattr(self, "_makefile", None)
     if default and not makefile:
         return "%s/printing/Makefile" % package_home(GLOBALS)
     return makefile
Ejemplo n.º 33
0
def getPackageLocation(module):
    """ Return the filesystem location of a module.

    This is a simple wrapper around the global package_home method which
    tricks it into working with just a module name.
    """
    package = getContainingPackage(module)
    return package_home({'__name__' : package})
 def getMakefile(self, default=1):
     """Return makefile path; meant only for manager consumption.
      'default' if true returns a default value if the field is empty.
     """
     makefile = getattr(self, "_makefile", None)
     if default and not makefile:
         return "%s/printing/Makefile" % package_home(GLOBALS)
     return makefile
Ejemplo n.º 35
0
def getSkinsFolderNames(globals, skins_dir='skins'):
    # Get the content of the skins folder
    skins_path = os.path.join(package_home(globals), skins_dir)
    return [
        filename for filename in os.listdir(skins_path)
        if (not filename.startswith('.') or filename in ('CVS', '{arch}'))
        and os.path.isdir(os.path.join(skins_path, filename))
    ]
Ejemplo n.º 36
0
 def test(self):
     """
     """
     print "================================="
     from Globals import package_home
     product_path = package_home(product_globals)
     print product_path
     print "================================="
Ejemplo n.º 37
0
 def get_path_from_prefix(self, _prefix):
     if isinstance(_prefix, str):
         path = _prefix
     else:
         if _prefix is None:
             _prefix = sys._getframe(2).f_globals
         path = package_home(_prefix)
     return path
Ejemplo n.º 38
0
 def test(self):
     """
     """
     print "================================="
     from Globals import package_home
     product_path = package_home(product_globals)
     print product_path
     print "================================="
Ejemplo n.º 39
0
def getPackageLocation(module):
    """ Return the filesystem location of a module.

    This is a simple wrapper around the global package_home method which
    tricks it into working with just a module name.
    """
    package = getContainingPackage(module)
    return package_home({'__name__': package})
Ejemplo n.º 40
0
 def resource_string(pkg_globals, relative_path):
     from Globals import package_home
     filename = os.path.join(package_home(pkg_globals), relative_path)
     f = open(filename, 'rb')
     try:
         return f.read()
     finally:
         f.close()
def load_file(filename):
    import os
    from StringIO import StringIO
    from Globals import package_home
    filename = os.path.sep.join([package_home(globals()), filename])
    data = StringIO(open(filename, 'rb').read())
    data.filename = os.path.basename(filename)
    return data
    def storeSimilarity(self, object):
        """Calculate and store similarity for the specified object"""
        import os
        from Globals import package_home

        cmd =  os.path.join(INSTANCE_HOME, 'bin', 'zopectl')
        script = os.path.join(package_home(globals()), 'Extensions', 'storeSimilarity.py')
        os.spawnlp(os.P_NOWAIT, cmd, 'zopectl', 'run', script, object.objectId, object.version)
 def importArticleV3(self, container):
     """
         Import article V3 from zexp
     """
     
     article_id = 'articlev3'
     zexp_path = os.path.join(package_home(GLOBALS), 'tests', '%s.zexp' % article_id)
     container._importObjectFromFile(zexp_path, verify = 1, set_owner = 1)
     return getattr(container, article_id)
Ejemplo n.º 44
0
 def getCMFVersion():
     from os.path import join
     from Globals import package_home
     from Products.CMFCore import cmfcore_globals
     path = join(package_home(cmfcore_globals),'version.txt')
     file = open(path, 'r')
     _version = file.read()
     file.close()
     return _version.strip()
Ejemplo n.º 45
0
    def load(self, filename):
        """ Load a file into config """
        name = os.path.join(package_home(globals()), \
                            os.path.basename(filename))
        if not name.endswith('.cfg'):
            name += '.cfg'

        fp = open(name)
        self.parse(fp)
Ejemplo n.º 46
0
def relload(  self ):
    # configuration for Relations
    relations_tool = getToolByName(self,'relations_library')
    xmlpath = os.path.join(package_home(product_globals),'data', 'relations.xml')
    f = open(xmlpath)
    xml = f.read()
    f.close()
    relations_tool.importXML(xml)
    return 'loaded relations'
Ejemplo n.º 47
0
    def afterSetUp(self):
        """
        """
        super(TestPhotoManagement_3, self).afterSetUp()

        img = os.path.join(package_home(product_globals), 'tests/test.jpg')
        img = open(img)

        self.product_1.setImage(img)
        self.logout()
Ejemplo n.º 48
0
def relload(self):
    # configuration for Relations
    relations_tool = getToolByName(self, 'relations_library')
    xmlpath = os.path.join(package_home(product_globals), 'data',
                           'relations.xml')
    f = open(xmlpath)
    xml = f.read()
    f.close()
    relations_tool.importXML(xml)
    return 'loaded relations'
Ejemplo n.º 49
0
    def storeSimilarity(self, object):
        """Calculate and store similarity for the specified object"""
        import os
        from Globals import package_home

        cmd = os.path.join(INSTANCE_HOME, 'bin', 'zopectl')
        script = os.path.join(package_home(globals()), 'Extensions',
                              'storeSimilarity.py')
        os.spawnlp(os.P_NOWAIT, cmd, 'zopectl', 'run', script, object.objectId,
                   object.version)
    def importArticleV3(self, container):
        """
            Import article V3 from zexp
        """

        article_id = 'articlev3'
        zexp_path = os.path.join(package_home(GLOBALS), 'tests',
                                 '%s.zexp' % article_id)
        container._importObjectFromFile(zexp_path, verify=1, set_owner=1)
        return getattr(container, article_id)
Ejemplo n.º 51
0
def installRelations(context):
    """imports the relations.xml file"""
    site = context.getSite()
    relations_tool = getToolByName(site, 'relations_library')
    xmlpath = os.path.join(package_home(product_globals), 'data',
                           'relations.xml')
    f = open(xmlpath)
    xml = f.read()
    f.close()
    relations_tool.importXML(xml)
Ejemplo n.º 52
0
class PeterbePageTemplate(ZopePageTemplate):
    """ Page Templates just for Peterbecom """
    meta_type = PETERBEPAGETEMPLATE_METATYPE
    

    manage_options = ZopePageTemplate.manage_options[:2] + \
        ({'label':'Misc', 'action':'PageTemplateMisc'},) + \
        ZopePageTemplate.manage_options[2:]
        
    _default_content_fn = os.path.join(package_home(globals()),
                                       'zpt','default.zpt')
Ejemplo n.º 53
0
def EmailPageTemplateFile(filename, _prefix):
    if _prefix:
        if isinstance(_prefix, str):
            filename = os.path.join(_prefix, filename)
        else:
            filename = os.path.join(package_home(_prefix), filename)
    f = open(filename)
    content = f.read()
    f.close()
    id = os.path.basename(filename)
    return EmailPageTemplate(id, content)
Ejemplo n.º 54
0
    def test_a_html(self):
        file_path = os.path.join(package_home(globals()),
                                 'static_serve/a.html')
        fd = open(file_path)
        read_data = fd.read()
        fd.close()

        url = 'http://localhost/portal/info/contact/test_static_serve/a.html'
        self.browser.go(url)
        server_data = self.browser.get_html()

        self.assertEqual(read_data, server_data)
Ejemplo n.º 55
0
def listFsWikis(self):
    """
    list the wiki templates available in the filesystem
    """
    try:
        list = os.listdir(package_home(globals()) + os.sep + 'content')
        # likewise for Subversion
        if '.svn' in list: list.remove('.svn')
        if 'tracker' in list: list.remove('tracker')  #XXX temp
        return list
    except OSError:
        return []
Ejemplo n.º 56
0
    def afterSetUp(self):
        """
        """
        super(TestImageManagement_4, self).afterSetUp()

        img = os.path.join(package_home(globals()), 'test.jpg')
        img = open(img)

        self.product_1.setImage(img)
        self.product_1.invokeFactory("EasyShopImage", id="image_1")
        self.product_1.invokeFactory("EasyShopImage", id="image_2")

        self.logout()
Ejemplo n.º 57
0
    def afterSetUp(self):
        """
        """
        super(TestPhotoManagement_4, self).afterSetUp()

        img = os.path.join(package_home(product_globals), 'tests/test.jpg')
        img = open(img)

        self.product_1.setImage(img)
        self.product_1.invokeFactory("Photo", id="photo_1")
        self.product_1.invokeFactory("Photo", id="photo_2")

        self.logout()
Ejemplo n.º 58
0
def customizeFrontPage(self, portal):
    # FIXME: currently disabled until we have better text to go here
    try:
        portal.manage_delObjects('index_html')
    except AttributeError:
        pass
    portal.invokeFactory('Document', 'index_html')
    frontpage = portal.index_html
    frontpage.title = 'Welcome to Rhaptos'
    path = os.path.join(package_home(product_globals), 'www/index_html')
    f = open(path)
    content = f.read()
    f.close()
    frontpage.edit('html',content)