Exemplo n.º 1
0
    def __init__(self,sfQuery,account,role=roles.MoltenPrivileges.Member,tree=AccountTreeNode(-1,"root",None)):
        '''
	account is the name of the account of the Id of the account.
	To-Do: Feed this object a COntact Id and let it figure-out the account for the contact.
	'''
        expected_class_name = ObjectTypeName._typeName(AccountTreeNode).split('.')[-1]
        got_class_name = ObjectTypeName.typeClassName(tree).split('.')[-1]
        self.__tree__ = tree if (expected_class_name == got_class_name) else None
        self.__role__ = role if (roles.isValidMoltenUserRole(role)) else None
        self.__sfQuery__ = sfQuery
        self.__accountId__ = None
        self.__account__ = None
        if (self.__tree__ is None):
            raise ValueError('Invalid value for tree attribute.')
        if (self.__role__ is None):
            raise ValueError('Invalid value for role attribute.')
        try:
            n = tree.findForwards(Id=account)
            if (n is not None):
                self.__accountId__ = n.Id
            else:
                n = tree.findForwards(Name=account)
                if (n is not None):
                    self.__accountId__ = n.Id
            if (self.__account__ is None) and (self.__accountId__ is not None):
                sf_accounts = SalesForceAccounts(self.sfQuery)
                accounts = sf_accounts.getAccountById(self.accountId)
                if (sf_accounts.contains_sf_objects(accounts)):
                    self.__account__ = accounts[0]
        except Exception as details:
            info_string = _utils.formattedException(details=details)
            print >>sys.stderr, info_string
        if (self.__account__ is None):
            raise ValueError('Invalid value for account attribute, account must be the Id or the Name of the account.')
Exemplo n.º 2
0
def openPickledHashBasedOnFilename(filename, method=PickleMethods.none):
    '''Uses the filename to determine which class should be used to open the database file.  Fails with a list if filename has more than one variation present in the same folder.'''
    def deMungeFileName(fname):
        if (isFilenameMungedAlready(fname)):
            toks = fname.split('_')
            if (len(toks) > 2):
                while (len(toks) > 2):
                    toks[0] = '_'.join(toks[0:2])
                    del toks[1]
            _toks = toks[-1].split('.')
            _fname = '.'.join([toks[:len(toks) - 1][0], _toks[-1]])
            _tag = '_' + _toks[0]
            return (fname, _fname, _tag)
        return (None, None)

    dname = os.path.dirname(filename)
    if (len(dname) == 0):
        dname = os.path.abspath('.')
    _obj = None
    _tag = ''
    fname = os.path.basename(filename)
    fname, _fname, _tag = deMungeFileName(fname)
    toks = fname.split('.')
    if (len(toks) > 1):
        toks[-1] = '.' + toks[-1]
    files = [deMungeFileName(f) for f in os.listdir(dname)]
    files = [f[1] for f in files if (f[0] == fname) and (f[-1] == _tag)]
    if (len(files) == 1):
        if (len(_tag) == 0):
            return openPickledHashBasedOnFilename(os.sep.join(
                [dname, files[0]]),
                                                  method=method)
        i = misc.findInListSafely(__classes_tags, _tag)
        if (i > -1):
            info_string = ''
            toks = ObjectTypeName._typeName(__classes[i]).split('.')
            className = toks[len(toks) - 1:][0]
            try:
                s = '%s(filename,method=method)' % (className)
                _obj = eval(s)
            except TypeError:
                try:
                    s = '%s(filename)' % (className)
                    _obj = eval(s)
                except Exception as details:
                    info_string = str(details)
        else:
            raise ValueError(
                '(%s) :: Cannot figure-out the class name based on "%s", recommend working this out on you own because you seemed to have written some bad code or maybe "%s".'
                % (misc.funcName(), _tag, info_string))
    else:
        raise ValueError(
            '(%s) :: Too %s files (%d) named like "%s" %s for %s, recommend using the class name "%s" and open it yourself.'
            % (misc.funcName(), 'many' if (len(files) > 1) else 'few',
               len(files), str(files), str(toks), filename, _tag))
    return _obj
Exemplo n.º 3
0
def prettyPrint(item,
                prefix='',
                title='',
                tab_width=4,
                delay_end=False,
                asCSV=False,
                isHorizontal=False,
                csv_callback=None,
                fOut=sys.stdout):
    import types
    from vyperlogix.misc import ReportTheList

    _type_name = ObjectTypeName._typeName(item.__class__)
    ret = []
    try:
        if (isDict(item)):
            tab_width = 4 if (not str(tab_width).isdigit()) else tab_width
            if (asCSV):
                if (isHorizontal):
                    fOut.write('%s\n' % (misc.asCSV(item.keys())))
                    fOut.write('%s\n' % (misc.asCSV(item.values())))
                    fOut.write('\n')
                else:
                    isCallback = ((csv_callback) and (callable(csv_callback)))
                    i = 1
                    for kk, vv in item.iteritems():
                        l = [i, kk, vv]
                        if (isCallback):
                            try:
                                l = csv_callback(l)
                            except:
                                pass
                        fOut.write('%s\n' % (misc.asCSV(l)))
                        i += 1
            else:
                l_keys = [len(kk) for kk, vv in item.iteritems()]
                if (len(l_keys) > 0):
                    max_len = misc.sort(l_keys)[-1]
                    fOut.write('%sBEGIN: %s (%d items)\n' %
                               (prefix, title, len(item)))
                    i = 1
                    for kk, vv in item.iteritems():
                        i_s_len = int(len(kk) / tab_width)
                        i_s_len = 1 if (i_s_len == 0) else i_s_len
                        i_spaces = (int(max_len / tab_width) - i_s_len) - 1
                        if (isinstance(vv, tuple)):
                            vv = list(vv)
                        if (isinstance(vv, list)):
                            fOut.write('(%s' % ('-' * 40))
                            ReportTheList.reportTheList(vv,
                                                        title='%d :: (%s) %s' %
                                                        (i, kk, title),
                                                        fOut=fOut)
                            fOut.write(')%s' % ('-' * 40))
                            fOut.write('\n')
                        elif (isDict(vv)):
                            fOut.write('{%s' % ('-' * 40))
                            prettyPrint(vv,
                                        '\t\t',
                                        title='%d :: (%s) %s' % (i, kk, title),
                                        fOut=fOut)
                            fOut.write('}%s' % ('-' * 40))
                            fOut.write('\n')
                        else:
                            try:
                                fOut.write(
                                    '%s\t\t%d :: %s%s-->%s' %
                                    (prefix, i, kk, '\t' * i_spaces, vv))
                            except:
                                pass
                        i += 1
                    _end_msg = '%sEND! %s from %s' % (prefix, title,
                                                      _type_name)
                    if (not delay_end):
                        fOut.write(_end_msg)
                        fOut.write('\n')
                    else:
                        ret.append(_end_msg)
                        ret.append('')
                else:
                    logging.warning(
                        '(%s) :: Unable to process the object passed to this function due to lack of data.'
                        % (misc.funcName()))
        else:
            logging.warning(
                '(%s) :: Unable to process the object passed to this function because it is of type "%s" and a dictionary object was expected.'
                % (misc.funcName(), _type_name))
    except Exception as details:
        info_string = misc.formattedException(details=details)
        sys.stderr.write(info_string)
    return ret
Exemplo n.º 4
0
    PickleMethods.useMarshal        = 1x
    '''
    def __init__(self, fileName, has_bsddb=False):
        e = PickleMethods.useBsdDbShelf | PickleMethods.use_lzma
        super(PickledLzmaHash2, self).__init__(fileName,
                                               e,
                                               has_bsddb=has_bsddb)


__classes = [
    PickledHash, PickledHash2, PickledFastHash2, PickledFastCompressedHash2,
    PickledFastHash2, PickledLzmaHash2
]
__classes_tags = [
    '_' + _class_tag(n.split('.')[len(n.split('.')) - 1:][0])
    for n in [ObjectTypeName._typeName(cls) for cls in __classes]
]


def isFilenameMungedAlready(fname):
    return (any([fname.find(f) > -1 for f in __classes_tags]))


def getMungedFilenameFor(filename):
    _root = os.path.dirname(filename)
    fname = os.path.splitext(os.path.basename(filename))[0]
    ext = os.path.splitext(filename)[-1]
    _files = [
        os.sep.join([_root, f]) for f in os.listdir(_root)
        if (f.startswith(fname)) and (f.endswith(ext))
    ]