Example #1
0
def value_str2pywbem(prop, value):
    """
    Used by iname_str2pywbem function for transforming key value
    to a pywbem object.

    @param prop may be None, in that case type will be guessed
    """
    if prop is not None:
        prop_type = prop["type"]
        if _RE_INTEGER_TYPE.match(prop_type) or prop_type == "boolean":
            if value[0] == '"':
                value = value[1:]
            if value[-1] == '"':
                value = value[:-1]
    else:
        prop_type = "string"
        if value.lower() in {"true", "false"}:
            prop_type = "boolean"
        else:
            try:
                int(value)
                prop_type = "uint16"
            except ValueError:
                try:
                    float(value)
                    prop_type = "float"
                except ValueError:
                    pass
    return pywbem.tocimobj(prop_type, value)
Example #2
0
def value_str2pywbem(prop, value):
    """
    Used by iname_str2pywbem function for transforming key value
    to a pywbem object.

    @param prop may be None, in that case type will be guessed
    """
    if prop is not None:
        prop_type = prop['type']
        if (_RE_INTEGER_TYPE.match(prop_type) or prop_type == "boolean"):
            if value[0]  == '"':
                value = value[1:]
            if value[-1] == '"':
                value = value[:-1]
    else:
        prop_type = 'string'
        if value.lower() in {'true', 'false'}:
            prop_type = 'boolean'
        else:
            try:
                int(value)
                prop_type = 'uint16'
            except ValueError:
                try:
                    float(value)
                    prop_type = 'float'
                except ValueError:
                    pass
    return pywbem.tocimobj(prop_type, value)
 def cmpi2pywbem_data(self, cdata, _type=None, is_array=None):
     #TODO check for valid cdata.state
     #TODO error handling
     if (cdata.state & cmpi.CMPI_nullValue) > 0:
         return None
     if _type is None:
         _type, is_array = _cmpi_type2string(cdata.type)
     attr = _type
     if is_array:
         rv = []
         car = cdata.value.array
         if car is None:
             return None
         for i in xrange(0, car.size()):
             adata = car.at(i)
             pdata = self.cmpi2pywbem_data(adata, _type, is_array=False)
             rv.append(pdata)
         return rv
     if cdata.is_null():
         return None
     if attr == 'datetime':
         attr = 'dateTime'
     if attr == 'reference':
         attr = 'ref'
     if attr == 'instance':
         attr = 'inst'
     val = getattr(cdata.value, attr)
     if val is None:
         return None
     if _type == 'string':
         val = str(val)
     if _type == 'boolean':
         val = val == 0 and 'false' or 'true'
     if _type == 'datetime':
         val = self.cmpi2pywbem_datetime(val)
     if _type == 'reference':
         val = self.cmpi2pywbem_instname(val)
     if _type == 'instance':
         val = self.cmpi2pywbem_inst(val)
         return val
     if _type == 'chars':
         _type = 'string'
     return pywbem.tocimobj(_type, val)
 def cmpi2pywbem_value(self, cval, _type, is_array=False):
     ctype = _type
     if _type == 'reference':
         ctype = 'ref' 
     if is_array:
         pval = []
         car = cval.array
         for i in xrange(0, car.size()):
             data = car.at(i)
             ptype = _cmpi2pywbem_typemap[data.type]
             rael = self.cmpi2pywbem_value(data.value, _type)
             pval.append(rael)
     else:
         cval = getattr(cval, ctype)
         if _type == 'string':
             pval = cval.__str__()
         elif _type == 'chars':
             pval = cval.__str__()
         elif ctype == 'ref':
             pval = self.cmpi2pywbem_instname(cval)
         else:
             pval = pywbem.tocimobj(_type, cval)
     return pval
Example #5
0
def _get_property_details(prop, inst=None):
    """
    @param prop is either CIMProperty or CIMParameter
    @param inst is either CIMInstance or CIMInstanceName
    @return dictionary describing property
    """
    if not isinstance(prop, (pywbem.CIMProperty, pywbem.CIMParameter)):
        raise TypeError('prop must be either CIMProperty or CIMParameter')
    if (   inst is not None
       and not isinstance(inst, pywbem.CIMInstance)
       and not isinstance(inst, pywbem.CIMInstanceName)):
        raise TypeError('inst must be one of: CIMInstance,'
               ' CIMInstanceName, None')
    value = _get_prop_value(prop, inst)

    res = _get_default_attributes_dict(prop.name,
            is_deprecated = prop.qualifiers.has_key('deprecated'),
            is_required   = prop.qualifiers.has_key('required'),
            is_valuemap   = prop.qualifiers.has_key('valuemap'),
            is_key     = prop.qualifiers.has_key('key'),
            type       = _get_prop_type(prop, inst),
            value_orig = value)

    if prop.is_array:
        res['is_array'] = prop.is_array
        res['array_size'] = prop.array_size

    if value is not None:
        if (   prop.qualifiers.has_key('values')
           and prop.qualifiers.has_key('valuemap')):
            res['value'] = render.mapped_value2str(value, prop.qualifiers)
        elif prop.reference_class is not None:
            res['value'] = value
        else:
            res['value'] = render.val2str(value)

    if prop.qualifiers.has_key('valuemap'):
        res['is_valuemap'] = True
        valmap_quals = prop.qualifiers['valuemap'].value
        values_quals = None
        if prop.qualifiers.has_key('values'):
            values_quals = prop.qualifiers['values'].value
        for ivq, val in enumerate(valmap_quals):
            try:
                pywbem.tocimobj(prop.type, val)
            except Exception:
                # skip valuemap items that aren't valid values
                # such as the numeric ranges for DMTF Reserved and whatnot
                continue
            res['valuemap'].append(val)
            if values_quals and ivq < len(values_quals):
                res['values'][val] = [values_quals[ivq]]
            else:
                res['values'][val] = None

    if isinstance(prop, pywbem.CIMParameter):
        res['out'] = (   prop.qualifiers.has_key('out')
                     and prop.qualifiers['out'].value)
        # consider parameter as input if IN qualifier is missing and
        # it is not an output parameter
        res['in'] = (  (   prop.qualifiers.has_key('in')
                       and prop.qualifiers['in'].value)
                    or (   not prop.qualifiers.has_key
                       and not res['out']))
    return res
Example #6
0
    def invokemethod(self, tt, output):
        path = tt[2]
        method_name = tt[1]['NAME']
        in_params = {}
        for p in tt[3]:
            if p[1] == 'reference':
                in_params[p[0].encode('utf8')] = p[2]
            else:
                in_params[p[0].encode('utf8')] = pywbem.tocimobj(p[1], p[2])

        print 'in_params:', in_params
        rval, out_params = cs.InvokeMethod(method_name, path, 
                in_params)
        print 'rval:', rval
        print 'out_params', out_params

        def paramtype(obj):
            """Return a string to be used as the CIMTYPE for a parameter."""
            if isinstance(obj, pywbem.CIMType):
                return obj.cimtype
            elif type(obj) == bool:
                return 'boolean'
            elif isinstance(obj, StringTypes):
                return 'string'
            elif isinstance(obj, (datetime, timedelta)):
                return 'datetime'
            elif isinstance(obj, (pywbem.CIMClassName, pywbem.CIMInstanceName)):
                return 'reference'
            elif isinstance(obj, (pywbem.CIMClass, pywbem.CIMInstance)):
                return 'string'
            elif isinstance(obj, list):
                return paramtype(obj[0])
            raise TypeError('Unsupported parameter type "%s"' % type(obj))

        def paramvalue(obj):
            """Return a cim_xml node to be used as the value for a
            parameter."""
            if isinstance(obj, (pywbem.CIMType, bool, basestring)):
                return pywbem.VALUE(pywbem.atomic_to_cim_xml(obj))
            if isinstance(obj, (pywbem.CIMClassName, pywbem.CIMInstanceName)):
                return pywbem.VALUE_REFERENCE(obj.tocimxml())
            if isinstance(obj, (pywbem.CIMClass, pywbem.CIMInstance)):
                return pywbem.VALUE(obj.tocimxml().toxml())
            if isinstance(obj, list):
                if isinstance(obj[0], (pywbem.CIMClassName, 
                                       pywbem.CIMInstanceName)):
                    return pywbem.VALUE_REFARRAY([paramvalue(x) for x in obj])
                return pywbem.VALUE_ARRAY([paramvalue(x) for x in obj])
            raise TypeError('Unsupported parameter type "%s"' % type(obj))

        def is_embedded(obj):
            """Determine if an object requires an EmbeddedObject attribute"""
            if isinstance(obj,list) and obj:
                return is_embedded(obj[0])
            elif isinstance(obj, pywbem.CIMClass):
                return 'object'
            elif isinstance(obj, pywbem.CIMInstance):
                return 'instance'
            return None

        plist = [pywbem.PARAMVALUE(x[0], 
                                    paramvalue(x[1]), 
                                    paramtype(x[1]),
                                    embedded_object=is_embedded(x[1]))
                 for x in out_params.items()]
        if rval is not None:
            rxml = pywbem.RETURNVALUE(paramvalue(rval[1]), rval[0])
            output.write(rxml.toxml())
        for p in plist:
            output.write(p.toxml())
Example #7
0
 def process_simple_value(val):
     """@return value as a cim object"""
     return pywbem.tocimobj(param["type"], val)
Example #8
0
def _get_property_details(prop, inst=None):
    """
    @param prop is either CIMProperty or CIMParameter
    @param inst is either CIMInstance or CIMInstanceName
    @return dictionary describing property
    """
    if not isinstance(prop, (pywbem.CIMProperty, pywbem.CIMParameter)):
        raise TypeError('prop must be either CIMProperty or CIMParameter')
    if (inst is not None and not isinstance(inst, pywbem.CIMInstance)
            and not isinstance(inst, pywbem.CIMInstanceName)):
        raise TypeError('inst must be one of: CIMInstance,'
                        ' CIMInstanceName, None')
    value = _get_prop_value(prop, inst)

    res = _get_default_attributes_dict(
        prop.name,
        is_deprecated=prop.qualifiers.has_key('deprecated'),
        is_required=prop.qualifiers.has_key('required'),
        is_valuemap=prop.qualifiers.has_key('valuemap'),
        is_key=prop.qualifiers.has_key('key'),
        type=_get_prop_type(prop, inst),
        value_orig=value)

    if prop.is_array:
        res['is_array'] = prop.is_array
        res['array_size'] = prop.array_size

    if value is not None:
        if (prop.qualifiers.has_key('values')
                and prop.qualifiers.has_key('valuemap')):
            res['value'] = yawn_render.mapped_value2str(value, prop.qualifiers)
        elif prop.reference_class is not None:
            res['value'] = value
        else:
            res['value'] = yawn_render.val2str(value)

    if prop.qualifiers.has_key('valuemap'):
        res['is_valuemap'] = True
        valmap_quals = prop.qualifiers['valuemap'].value
        values_quals = None
        if prop.qualifiers.has_key('values'):
            values_quals = prop.qualifiers['values'].value
        for ivq, val in enumerate(valmap_quals):
            try:
                pywbem.tocimobj(prop.type, val)
            except Exception:
                # skip valuemap items that aren't valid values
                # such as the numeric ranges for DMTF Reserved and whatnot
                continue
            res['valuemap'].append(val)
            if values_quals and ivq < len(values_quals):
                res['values'][val] = [values_quals[ivq]]
            else:
                res['values'][val] = None

    if isinstance(prop, pywbem.CIMParameter):
        res['out'] = (prop.qualifiers.has_key('out')
                      and prop.qualifiers['out'].value)
        # consider parameter as input if IN qualifier is missing and
        # it is not an output parameter
        res['in'] = ((prop.qualifiers.has_key('in')
                      and prop.qualifiers['in'].value)
                     or (not prop.qualifiers.has_key and not res['out']))
    return res