Example #1
0
/**
   _validateKeys method of the NIS provider Test Client
  */
void 
NISTestClient::_validateKeys(CIMObjectPath &cimRef, 
                                 Boolean verboseTest)
{
   // don't have a try here - want it to be caught by caller
   String keyVal;    
   CIMName keyName;
   Array<CIMKeyBinding> keyBindings = cimRef.getKeyBindings();

   if (verboseTest)
      cout << "Retrieved " << keyBindings.size() << " keys" <<endl;

   for (Uint32 j = 0; j < keyBindings.size(); j++)
   {
      keyName = keyBindings[j].getName();
      keyVal = keyBindings[j].getValue();
      if (verboseTest)
         cout << "checking key " << keyName.getString() << endl;
      
          if (keyName.equal("CreationClassName") &&
              !goodCreationClassName(keyVal, verboseTest)) { 
             errorExit ("CreationClassName not PG_NISServerService");
          }
          else if (keyName.equal("Name") &&
                 !goodName(keyVal, verboseTest)) { 
             errorExit ("Name not correct");
          }
          else if (keyName.equal("SystemCreationClassName") &&
                  !goodSystemCreationClassName(keyVal, verboseTest)) { 
             errorExit ("SystemCreationClassName not correct");
          }
          else if (keyName.equal("SystemName") &&
                  !goodSystemName(keyVal, verboseTest)) { 
             errorExit ("SystemName not correct");
          }
   }
}
Example #2
0
void TimingProvider::enumerateInstances(
    const OperationContext & context,
    const CIMObjectPath & classReference,
    const Boolean includeQualifiers,
    const Boolean includeClassOrigin,
    const CIMPropertyList & propertyList,
    InstanceResponseHandler & handler)
{
    cout <<"TimingProvider::enumerateInstances" << endl;
    CIMName cn = classReference.getClassName();

    String className = cn.getString();
    sleep(15);
    // cout << "className = " << className << endl;
    // Create Instances for TimeOne Class
    if (String::equalNoCase(className, "TimeOne"))
    {
        sleep(5);
        // announce operation processing.
        handler.processing();
        for(Uint32 i = 0, n = _instances.size(); i < n; i++)
            // deliver instance
            handler.deliver(_instances[i]);
    }
    // Create Instances for SecondClass
    if (String::equalNoCase(className, "TimeTwo"))
    {
        handler.processing();
        sleep(5);

        for(Uint32 i = 0, n = _instances_2.size(); i < n; i++)
            // deliver instance
            handler.deliver(_instances_2[i]);
    }
    // complete processing the request
    handler.complete();
}
Uint32 benchmarkDefinition::getConfiguration(
                        const CIMName& className,
                        Uint32& numberOfProperties,
                        Uint32& sizeOfPropertyValue,
                        Uint32& numberOfInstances)
{

    String classNameString = className.getString();

    if (!String::equal(classNameString.subString(0, 14), "benchmarkClass"))
    {
       return(CIM_ERR_NOT_SUPPORTED);
    }

    String numberPropertiesString = classNameString.subString(15, 5);
    numberOfProperties = atoi(numberPropertiesString.getCString());
    if (numberOfProperties > MAX_NUMBER_OF_PROPERTIES)
    {
       return(CIM_ERR_NOT_SUPPORTED);
    }

    String sizePropertiesString = classNameString.subString(21, 5);
    sizeOfPropertyValue = atoi(sizePropertiesString.getCString());
    if (sizeOfPropertyValue > MAX_SIZE_OF_PROPERTY_VALUE)
    {
       return(CIM_ERR_NOT_SUPPORTED);
    }

    String numberInstancesString = classNameString.subString(27, 5);
    numberOfInstances = atoi(numberInstancesString.getCString());
    if (numberOfInstances > MAX_NUMBER_OF_INSTANCES)
    {
       return(CIM_ERR_NOT_SUPPORTED);
    }

    return(CIM_ERR_SUCCESS);
}
Example #4
0
void ExceptionsTest::enumerateInstanceNames(
    const OperationContext & context,
    const CIMObjectPath & classReference,
    ObjectPathResponseHandler & handler)
{
    // begin processing the request
    handler.processing();

    cout <<"Calling Exception ExceptionsTest::enumerateInstanceNames 1" << endl;
    CheckExceptionType(EXCEPTION_TYPE);
    CIMName clName = classReference.getClassName();
    String className = clName.getString();
    
    if (className == "FirstClass")
    {
        for(Uint32 i = 0, n = _instances.size(); i < n; i++)
            // deliver reference
            handler.deliver(_instanceNames[i]);
    }   
    else if (className == "SecondClass")
    {
        for(Uint32 i = 0, n = _instances_second.size(); i < n; i++)
            // deliver reference
            handler.deliver(_instanceNames_second[i]);
    }   
    else if (className == "ThirdClass")
    {
        for(Uint32 i = 0, n = _instances_third.size(); i < n; i++)
            // deliver reference
            handler.deliver(_instanceNames_third[i]);

    }
    // complete processing the request
    cout <<"Calling Exception ExceptionsTest::enumerateInstanceNames 2" << endl;
    CheckExceptionType(EXCEPTION_TYPE);
    handler.complete();
}
Example #5
0
void WMIClientRep::deleteClass(
    const CIMNamespaceName& nameSpace,
	const CIMName& className)
{
    CIMException cimException;

	try
	{
		//Initializes the WMI Provider Interface
		WMIClassProvider provider;
   		provider.initialize(TRUE);

		//Performs the WMI call
		provider.deleteClass(
			nameSpace.getString(),
			String::EMPTY,
			String::EMPTY,
			className.getString());

		//terminate the provider
		provider.terminate();
	}
	catch(CIMException&)
	{
		throw;
	}
	catch(Exception& exception)
	{
	   cimException = PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, exception.getMessage());
	   throw cimException;
	}
	catch(...)
	{
		cimException = PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, "deleteClass() failed!");
		throw cimException;
	}
}
void _testAssociators(
    CIMClient& client,
    CIMName assocClass,
    CIMObjectPath instancePath,
    Uint32 numExpectedObjects)
{
    if (verbose)
    {
        cout << "Association Class: " << assocClass.getString() << endl;
        cout << "Object Name: " << instancePath.toString() << endl;
    }

    try
    {
        CIMName resultClass;
        String role;
        String resultRole;

        // Get the CIM instances that are associated with the specified source
        // instance via an instance of the AssocClass
        //

        Array<CIMObject> resultObjects =
            client.associators(providerNamespace, instancePath, assocClass,
                               resultClass, role, resultRole);

        // verify result
        _verifyResult(resultObjects.size(), numExpectedObjects);

        // display result
        _displayResult(resultObjects);
    }
    catch (Exception& e)
    {
        _errorExit(e.getMessage());
    }
}
Example #7
0
void testEnumInstances(CIMClient& client, const char* ns)
{
    Array<CIMInstance> instances;

   instances = client.enumerateInstances(ns,CIM_QUERYCAPCLASS_NAME);

   if(instances.size() != 1) throw Exception("instances.size() incorrect");

   Array<Uint16> providerReturnedVal;
   //Array<Uint16> actualVal(NUM_QUERY_CAPABILITIES);
   Uint32 prop = 0;
   CIMObjectPath path;

   path = instances[0].getPath();
   Array<CIMKeyBinding> keys = path.getKeyBindings();

   //-- make sure we're the right instance
   CIMName keyName;
   String keyValue;

   if (keys.size() != NUM_KEY_PROPERTIES)
       throw Exception("Wrong number of keys");

    keyName = keys[0].getName();
    keyValue = keys[0].getValue();

    if(keyName.getString() != String(PROPERTY_NAME_INSTANCEID) )
        throw Exception("Incorrect Key");
    if(keyValue != String(INSTANCEID_VALUE))
        throw Exception(keyValue);

     prop = instances[0].findProperty(CIMName(PROPERTY_NAME_CQLFEATURES));
     instances[0].getProperty(prop).getValue().get(providerReturnedVal);

     _checkIfReturnedValueIsCorrect(providerReturnedVal);

}
Example #8
0
void AuditLogger::logInvokeMethodOperation(
    const String& userName,
    const String& ipAddr,
    const CIMNamespaceName& nameSpace,
    const CIMObjectPath& objectName,
    const CIMName& methodName,
    const String& moduleName,
    const String& providerName,
    CIMStatusCode statusCode)
{
    // check if SMF is gathering this type of records.
    if (_smf.isRecording(CIM_OPERATION) ||
        (! _isInternalWriterUsed) )
    {
        String cimObjectName =
            CIMObjectPath("", CIMNamespaceName(), objectName.getClassName(),
            objectName.getKeyBindings()).toString();

        _writeCIMOperationRecord(
            INVOKE_METHOD, userName, statusCode,
            ipAddr, methodName.getString(), cimObjectName,
            nameSpace.getString(), providerName,moduleName );
    }
}
Example #9
0
void
OperatingSystemProvider::getInstance(const OperationContext& context,
				     const CIMObjectPath& ref,
				     const Boolean includeQualifiers,
				     const Boolean includeClassOrigin,
				     const CIMPropertyList& propertyList,
				     InstanceResponseHandler &handler)
{
    Array<CIMKeyBinding> keys;
    CIMInstance instance;
    OperatingSystem os;
    CIMName className;
    String csName;
    String name;


    //-- make sure we're working on the right class
    className = ref.getClassName();
    if (!(className.equal (STANDARDOPERATINGSYSTEMCLASS)) &&
        !(className.equal (EXTENDEDOPERATINGSYSTEMCLASS)))
        throw CIMNotSupportedException("OperatingSystemProvider does not support class " + className.getString());

    //-- make sure we're the right instance
    int keyCount;
    CIMName keyName;

    keyCount = 4;
    keys = ref.getKeyBindings();

    if ((unsigned int)keys.size() != (unsigned int)keyCount)
        throw CIMInvalidParameterException("Wrong number of keys");

    // doesn't seem as though this code will handle duplicate keys,
    // but it appears as though the CIMOM strips those out for us.
    // Despite test cases, don't get invoked with 2 keys of the same
    // name.

    if (!os.getCSName(csName))
    {
        throw CIMOperationFailedException("OperatingSystemProvider "
                       "Can't determine name of computer system");
    }

    if (!os.getName(name))
    {
        throw CIMOperationFailedException("OperatingSystemProvider "
                       "Can't determine name of Operating System");
    }

    for (unsigned int ii = 0; ii < keys.size(); ii++)
    {
         keyName = keys[ii].getName();

         if ((keyName.equal ("CSCreationClassName")) &&
       	    String::equalNoCase(keys[ii].getValue(),
                                CSCREATIONCLASSNAME.getString()))
         {
              keyCount--;
         }
         else if ((keyName.equal ("CSName")) &&
  	         String::equalNoCase(keys[ii].getValue(), csName))
         {
              keyCount--;
         }
         else if ((keyName.equal ("CreationClassName")) &&
 	         String::equalNoCase(keys[ii].getValue(),
                                     STANDARDOPERATINGSYSTEMCLASS.getString()))
         {
              keyCount--;
         }
         else if ((keyName.equal ("Name")) &&
 	         String::equalNoCase(keys[ii].getValue(), name))
         {
              keyCount--;
         }
         else
         {
              throw CIMInvalidParameterException("OperatingSystemProvider"
                             " unrecognized key " + keyName.getString());
         }
     }

     if (keyCount)
     {
        throw CIMInvalidParameterException("Wrong keys");
     }

    OSP_DEBUG("losp-> getInstance got the right keys");

    handler.processing();

    //-- fill 'er up...
    instance = _build_instance(ref);
    instance.setPath(ref);

    OSP_DEBUG("losp-> getInstance built an instance");

    handler.deliver(instance);
    handler.complete();

    OSP_DEBUG("losp-> getInstance done");
    return;
}
//
// Function that determines in which namespaces a provider supports a given
// class. This information is needed to properly implement the
// ElementConformsToProfile association.
//
Array<String> findProviderNamespacesForElement(
    const String & moduleName, const String & providerName,
    const CIMName & elementClass, CIMRepository * repository,
    Array<CIMInstance> & providerCapabilitiesInstances)
{
    Array<CIMInstance> capabilities;
    if (providerCapabilitiesInstances.size() == 0)
    {
        Array<CIMName> propList;
        propList.append(PROVIDERCAPABILITIES_PROPERTY_PROVIDERMODULENAME);
        propList.append(PROVIDERCAPABILITIES_PROPERTY_PROVIDERNAME);
        propList.append(PROVIDERCAPABILITIES_PROPERTY_NAMESPACES);
        propList.append(PROVIDERCAPABILITIES_PROPERTY_CLASSNAME);
        capabilities = repository->enumerateInstancesForClass(
            PEGASUS_NAMESPACENAME_INTEROP,
            PEGASUS_CLASSNAME_PROVIDERCAPABILITIES, false, false, false);
    }
    else
    {
        capabilities = providerCapabilitiesInstances;
    }

    for (Uint32 i = 0, n = capabilities.size(); i < n; ++i)
    {
        CIMInstance & currentCapabilities = capabilities[i];
        Uint32 propIndex = currentCapabilities.findProperty(
            PROVIDERCAPABILITIES_PROPERTY_PROVIDERMODULENAME);
        PEGASUS_ASSERT(propIndex != PEG_NOT_FOUND);
        String currentName;
        currentCapabilities.getProperty(propIndex).getValue().get(
            currentName);
        if (currentName == moduleName)
        {
            propIndex = currentCapabilities.findProperty(
                PROVIDERCAPABILITIES_PROPERTY_PROVIDERNAME);
            PEGASUS_ASSERT(propIndex != PEG_NOT_FOUND);
            currentCapabilities.getProperty(propIndex).getValue().get(
                currentName);
            if (currentName == providerName)
            {
                propIndex = currentCapabilities.findProperty(
                    PROVIDERCAPABILITIES_PROPERTY_CLASSNAME);
                PEGASUS_ASSERT(propIndex != PEG_NOT_FOUND);
                currentCapabilities.getProperty(propIndex).getValue().get(
                    currentName);
                if (elementClass.equal(CIMName(currentName)))
                {
                    propIndex = currentCapabilities.findProperty(
                      PROVIDERCAPABILITIES_PROPERTY_NAMESPACES);
                    PEGASUS_ASSERT(propIndex != PEG_NOT_FOUND);
                    Array<String> namespaces;
                    currentCapabilities.getProperty(propIndex).getValue().get(
                        namespaces);
                    return namespaces;
                }
            }
        }
    }

    throw PEGASUS_CIM_EXCEPTION(CIM_ERR_NOT_FOUND,
        "Could not find provider capabilities registered for module " +
        moduleName + ", provider " + providerName + ", and class " +
        elementClass.getString());
}
void CIMOperationResponseEncoder::handleEnqueue(Message* message)
{
    PEG_METHOD_ENTER(TRC_DISPATCHER,
        "CIMOperationResponseEncoder::handleEnqueue()");

    if (!message)
    {
        PEG_METHOD_EXIT();
        return;
    }

    CIMResponseMessage* response = dynamic_cast<CIMResponseMessage*>(message);
    PEGASUS_ASSERT(response);

    response->updateThreadLanguages();

    PEG_TRACE((
        TRC_HTTP,
        Tracer::LEVEL4,
        "CIMOperationResponseEncoder::handleEnque()- "
            "message->getCloseConnect() returned %d",
        message->getCloseConnect()));

    // Handle binary messages up front:
    {
        CIMResponseMessage* msg = dynamic_cast<CIMResponseMessage*>(message);

        if (msg && msg->binaryResponse)
        {
            if (msg->cimException.getCode() == CIM_ERR_SUCCESS)
            {
                Buffer body;
                CIMName name;

                if (BinaryCodec::encodeResponseBody(body, msg, name))
                {
                    sendResponse(msg, name.getString(), true, &body);
                    delete msg;
                    PEG_METHOD_EXIT();
                    return;
                }
            }
        }
    }

    switch (message->getType())
    {
        case CIM_GET_CLASS_RESPONSE_MESSAGE:
            encodeGetClassResponse(
                (CIMGetClassResponseMessage*)message);
            break;

        case CIM_GET_INSTANCE_RESPONSE_MESSAGE:
            encodeGetInstanceResponse(
                (CIMGetInstanceResponseMessage*)message);
            break;

        case CIM_DELETE_CLASS_RESPONSE_MESSAGE:
            encodeDeleteClassResponse(
                (CIMDeleteClassResponseMessage*)message);
            break;

        case CIM_DELETE_INSTANCE_RESPONSE_MESSAGE:
            encodeDeleteInstanceResponse(
                (CIMDeleteInstanceResponseMessage*)message);
            break;

        case CIM_CREATE_CLASS_RESPONSE_MESSAGE:
            encodeCreateClassResponse(
                (CIMCreateClassResponseMessage*)message);
            break;

        case CIM_CREATE_INSTANCE_RESPONSE_MESSAGE:
            encodeCreateInstanceResponse(
                (CIMCreateInstanceResponseMessage*)message);
            break;

        case CIM_MODIFY_CLASS_RESPONSE_MESSAGE:
            encodeModifyClassResponse(
                (CIMModifyClassResponseMessage*)message);
            break;

        case CIM_MODIFY_INSTANCE_RESPONSE_MESSAGE:
            encodeModifyInstanceResponse(
                (CIMModifyInstanceResponseMessage*)message);
            break;

        case CIM_ENUMERATE_CLASSES_RESPONSE_MESSAGE:
            encodeEnumerateClassesResponse(
                (CIMEnumerateClassesResponseMessage*)message);
            break;

        case CIM_ENUMERATE_CLASS_NAMES_RESPONSE_MESSAGE:
            encodeEnumerateClassNamesResponse(
                (CIMEnumerateClassNamesResponseMessage*)message);
            break;

        case CIM_ENUMERATE_INSTANCES_RESPONSE_MESSAGE:
            encodeEnumerateInstancesResponse(
                (CIMEnumerateInstancesResponseMessage*)message);
            break;

        case CIM_ENUMERATE_INSTANCE_NAMES_RESPONSE_MESSAGE:
            encodeEnumerateInstanceNamesResponse(
                (CIMEnumerateInstanceNamesResponseMessage*)message);
            break;

        case CIM_EXEC_QUERY_RESPONSE_MESSAGE:
            encodeExecQueryResponse(
                (CIMExecQueryResponseMessage*)message);
            break;

        case CIM_ASSOCIATORS_RESPONSE_MESSAGE:
            encodeAssociatorsResponse(
                (CIMAssociatorsResponseMessage*)message);
            break;

        case CIM_ASSOCIATOR_NAMES_RESPONSE_MESSAGE:
            encodeAssociatorNamesResponse(
                (CIMAssociatorNamesResponseMessage*)message);
            break;

        case CIM_REFERENCES_RESPONSE_MESSAGE:
            encodeReferencesResponse(
                (CIMReferencesResponseMessage*)message);
            break;

        case CIM_REFERENCE_NAMES_RESPONSE_MESSAGE:
            encodeReferenceNamesResponse(
                (CIMReferenceNamesResponseMessage*)message);
            break;

        case CIM_GET_PROPERTY_RESPONSE_MESSAGE:
            encodeGetPropertyResponse(
                (CIMGetPropertyResponseMessage*)message);
            break;

        case CIM_SET_PROPERTY_RESPONSE_MESSAGE:
            encodeSetPropertyResponse(
                (CIMSetPropertyResponseMessage*)message);
            break;

        case CIM_GET_QUALIFIER_RESPONSE_MESSAGE:
            encodeGetQualifierResponse(
                (CIMGetQualifierResponseMessage*)message);
            break;

        case CIM_SET_QUALIFIER_RESPONSE_MESSAGE:
            encodeSetQualifierResponse(
                (CIMSetQualifierResponseMessage*)message);
            break;

        case CIM_DELETE_QUALIFIER_RESPONSE_MESSAGE:
            encodeDeleteQualifierResponse(
                (CIMDeleteQualifierResponseMessage*)message);
            break;

        case CIM_ENUMERATE_QUALIFIERS_RESPONSE_MESSAGE:
            encodeEnumerateQualifiersResponse(
                (CIMEnumerateQualifiersResponseMessage*)message);
            break;

        case CIM_INVOKE_METHOD_RESPONSE_MESSAGE:
            encodeInvokeMethodResponse(
                (CIMInvokeMethodResponseMessage*)message);
            break;
//EXP_PULL_BEGIN
        case CIM_OPEN_ENUMERATE_INSTANCES_RESPONSE_MESSAGE:
            encodeOpenEnumerateInstancesResponse(
                (CIMOpenEnumerateInstancesResponseMessage*)message);
            break;

        case CIM_OPEN_ENUMERATE_INSTANCE_PATHS_RESPONSE_MESSAGE:
            encodeOpenEnumerateInstancePathsResponse(
                (CIMOpenEnumerateInstancePathsResponseMessage*)message);
            break;

        case CIM_OPEN_REFERENCE_INSTANCES_RESPONSE_MESSAGE:
            encodeOpenReferenceInstancesResponse(
                (CIMOpenReferenceInstancesResponseMessage*)message);
            break;

        case CIM_OPEN_REFERENCE_INSTANCE_PATHS_RESPONSE_MESSAGE:
            encodeOpenReferenceInstancePathsResponse(
                (CIMOpenReferenceInstancePathsResponseMessage*)message);
            break;

        case CIM_OPEN_ASSOCIATOR_INSTANCES_RESPONSE_MESSAGE:
            encodeOpenAssociatorInstancesResponse(
                (CIMOpenAssociatorInstancesResponseMessage*)message);
            break;

        case CIM_OPEN_ASSOCIATOR_INSTANCE_PATHS_RESPONSE_MESSAGE:
            encodeOpenAssociatorInstancePathsResponse(
                (CIMOpenAssociatorInstancePathsResponseMessage*)message);
            break;

        case CIM_PULL_INSTANCE_PATHS_RESPONSE_MESSAGE:
            encodePullInstancePathsResponse(
                (CIMPullInstancePathsResponseMessage*)message);
            break;

        case CIM_PULL_INSTANCES_WITH_PATH_RESPONSE_MESSAGE:
            encodePullInstancesWithPathResponse(
                (CIMPullInstancesWithPathResponseMessage*)message);
            break;

        case CIM_PULL_INSTANCES_RESPONSE_MESSAGE:
            encodePullInstancesResponse(
                (CIMPullInstancesResponseMessage*)message);
            break;

        case CIM_CLOSE_ENUMERATION_RESPONSE_MESSAGE:
            encodeCloseEnumerationResponse(
                (CIMCloseEnumerationResponseMessage*)message);
            break;

        case CIM_ENUMERATION_COUNT_RESPONSE_MESSAGE:
            encodeEnumerationCountResponse(
                (CIMEnumerationCountResponseMessage*)message);
            break;

        case CIM_OPEN_QUERY_INSTANCES_RESPONSE_MESSAGE:
            encodeOpenQueryInstancesResponse(
                (CIMOpenQueryInstancesResponseMessage*)message);
            break;
//EXP_PULL_END
        default:
            // Unexpected message type
            PEGASUS_UNREACHABLE(PEGASUS_ASSERT(0);)
            break;
    }
Example #12
0
/**
    Update the specified property name and value in the planned
    config file.
*/
Boolean ConfigFileHandler::updatePlannedValue(
    const CIMName& name,
    const String& value,
    Boolean unset)
{
    //
    // Remove the old property name and value from the table
    //
    if (_plannedConfig->table.contains(name.getString()))
    {
        if (!_plannedConfig->table.remove(name.getString()))
        {
            return false;
        }
    }

    if (!unset)
    {
        //
        // Store the new property name and value in to the table
        //
        if (!_plannedConfig->table.insert(name.getString(), value))
        {
            return false;
        }
    }

    try
    {
        //
        // Planned file need not exist for off line
        // configuration setting update.
        //
        if (_offLine)
        {
            String pFile = _plannedConfFile->getFileName();

            FILE* fs = Executor::openFile(pFile.getCString(), 'w');

            if (!fs)
            {
                PEG_TRACE((TRC_CONFIG, Tracer::LEVEL1,
                    "Failed to create config file: %s",
                    (const char*)pFile.getCString()));
                throw NoSuchFile(pFile);
            }

            fclose(fs);
        }

        //
        // Store the new property in planned config file.
        //
        _plannedConfFile->save(_plannedConfig);

    }
    catch (Exception& e)
    {
        PEG_TRACE((TRC_CONFIG, Tracer::LEVEL1,
            "Can not save planned configuration: %s",
             (const char*)e.getMessage().getCString()));

        throw;
    }

    //
    // The planned config file would now been created,
    // so set the flag to true.
    //
    _plannedFileExist = true;

    return true;
}
 Str(const CIMName& n) : _cstr(n.getString().getCString()) { }
Example #14
0
void _generateIndication (
    IndicationResponseHandler * handler,
    const CIMName methodName)
{
    if (_enabled)
    {
        CIMInstance indicationInstance;

        if (methodName.equal ("SendTestIndicationSubclass"))
        {
            CIMInstance theIndication (CIMName ("RT_TestIndicationSubclass"));
            indicationInstance = theIndication;
        }
        else
        {
            CIMInstance theIndication (CIMName ("RT_TestIndication"));
            indicationInstance = theIndication;
        }

        CIMObjectPath path;
        if (methodName.equal ("SendTestIndicationUnmatchingNamespace"))
        {
            //
            //  For SendTestIndicationUnmatchingNamespace, generate an
            //  indication instance with namespace that does not match the
            //  subscription instance name included in the operation context
            //  (nor does it match the namespace for which provider has
            //  registered)
            //
            path.setNameSpace ("root/cimv2");
            path.setClassName ("RT_TestIndication");
        }
        else if (methodName.equal ("SendTestIndicationUnmatchingClassName"))
        {
            // the indication class name and object path class must match
            indicationInstance = CIMInstance("CIM_AlertIndication");

            //
            //  For SendTestIndicationUnmatchingClassName, generate an
            //  indication instance with classname that does not match the
            //  subscription instance name included in the operation context
            //  (nor does it match the classname for which provider has
            //  registered)
            //
            path.setNameSpace ("root/SampleProvider");
            path.setClassName ("CIM_AlertIndication");
        }
        else if (methodName.equal ("SendTestIndicationSubclass"))
        {
            //
            //  For SendTestIndicationSubclass, generate an indication instance
            //  of a the RT_TestIndicationSubclass subclass
            //
            path.setNameSpace ("root/SampleProvider");
            path.setClassName ("RT_TestIndicationSubclass");
        }
        else
        {
            path.setNameSpace("root/SampleProvider");
            path.setClassName("RT_TestIndication");
        }

        indicationInstance.setPath(path);

        char buffer[32];
        sprintf(buffer, "%d", _nextUID++);
        indicationInstance.addProperty
            (CIMProperty ("IndicationIdentifier",String(buffer)));

	CIMDateTime currentDateTime = CIMDateTime::getCurrentDateTime ();
	indicationInstance.addProperty
            (CIMProperty ("IndicationTime", currentDateTime));

        //
        //  For SendTestIndicationMissingProperty, leave out the
        //  CorrelatedIndications property
        //
        if (!methodName.equal ("SendTestIndicationMissingProperty"))
        {
	    Array <String> correlatedIndications;
	    indicationInstance.addProperty
                (CIMProperty ("CorrelatedIndications", correlatedIndications));
        }

        if ((methodName.equal ("SendTestIndicationNormal")) ||
            (methodName.equal ("SendTestIndicationSubclass")) ||
            (methodName.equal ("SendTestIndicationMissingProperty")) ||
            (methodName.equal ("SendTestIndicationExtraProperty")) ||
            (methodName.equal ("SendTestIndicationMatchingInstance")) ||
            (methodName.equal ("SendTestIndicationUnmatchingNamespace")) ||
            (methodName.equal ("SendTestIndicationUnmatchingClassName")))
        {
            indicationInstance.addProperty
                (CIMProperty ("MethodName", CIMValue (methodName.getString())));
        }
        else
        {
            indicationInstance.addProperty
                (CIMProperty ("MethodName",
                    CIMValue (String ("generateIndication"))));
        }

        //
        //  For SendTestIndicationExtraProperty, add an extra property,
        //  ExtraProperty, that is not a member of the indication class
        //
        if (methodName.equal ("SendTestIndicationExtraProperty"))
        {
            indicationInstance.addProperty
                (CIMProperty ("ExtraProperty",
                    CIMValue (String ("extraProperty"))));
        }

        CIMIndication cimIndication (indicationInstance);

        //
        //  For SendTestIndicationSubclass,
        //  SendTestIndicationMatchingInstance,
        //  SendTestIndicationUnmatchingNamespace or
        //  SendTestIndicationUnmatchingClassName, include
        //  SubscriptionInstanceNamesContainer in operation context
        //
        if ((methodName.equal ("SendTestIndicationSubclass")) ||
            (methodName.equal ("SendTestIndicationMatchingInstance")) ||
            (methodName.equal ("SendTestIndicationUnmatchingNamespace")) ||
            (methodName.equal ("SendTestIndicationUnmatchingClassName")))
        {
            Array <CIMObjectPath> subscriptionInstanceNames;
            Array <CIMKeyBinding> subscriptionKeyBindings;

            String filterString;
            filterString.append ("CIM_IndicationFilter.CreationClassName=\"CIM_IndicationFilter\",Name=\"PIFilter01\",SystemCreationClassName=\"");
            filterString.append (System::getSystemCreationClassName ());
            filterString.append ("\",SystemName=\"");
            filterString.append (System::getFullyQualifiedHostName ());
            filterString.append ("\"");
            subscriptionKeyBindings.append (CIMKeyBinding ("Filter",
                filterString, CIMKeyBinding::REFERENCE));

            String handlerString;
            handlerString.append ("CIM_IndicationHandlerCIMXML.CreationClassName=\"CIM_IndicationHandlerCIMXML\",Name=\"PIHandler01\",SystemCreationClassName=\"");
            handlerString.append (System::getSystemCreationClassName ());
            handlerString.append ("\",SystemName=\"");
            handlerString.append (System::getFullyQualifiedHostName ());
            handlerString.append ("\"");
            subscriptionKeyBindings.append (CIMKeyBinding ("Handler",
                handlerString, CIMKeyBinding::REFERENCE));

            CIMObjectPath subscriptionPath ("",
                CIMNamespaceName ("root/PG_InterOp"),
                CIMName ("CIM_IndicationSubscription"),
                subscriptionKeyBindings);
            subscriptionInstanceNames.append (subscriptionPath);

	    OperationContext context;
            context.insert (SubscriptionInstanceNamesContainer
                (subscriptionInstanceNames));

            handler->deliver (context, indicationInstance);
        }
        else
        {
	    // deliver an indication without trapOid
            handler->deliver (indicationInstance);
        }

        //
        //  Only deliver extra indication with trapOid for SendTestIndication
        //
        if ((!methodName.equal ("SendTestIndicationNormal")) &&
            (!methodName.equal ("SendTestIndicationSubclass")) &&
            (!methodName.equal ("SendTestIndicationMissingProperty")) &&
            (!methodName.equal ("SendTestIndicationExtraProperty")) &&
            (!methodName.equal ("SendTestIndicationMatchingInstance")) &&
            (!methodName.equal ("SendTestIndicationUnmatchingNamespace")) &&
            (!methodName.equal ("SendTestIndicationUnmatchingClassName")))
        {
	    // deliver another indication with a trapOid which contains in the
	    // operationContext container
	    OperationContext context;

 	    // add trap OID to the context
	    context.insert
                (SnmpTrapOidContainer("1.3.6.1.4.1.900.2.3.9002.9600"));
            handler->deliver (context, indicationInstance);
        }
    }
}
Example #15
0
/*
================================================================================
NAME              : getInstance
DESCRIPTION       : Returns a single instance.
ASSUMPTIONS       : None
PRE-CONDITIONS    :
POST-CONDITIONS   :
NOTES             : LocalOnly, DeepInheritance and propertyList are not
                  : respected by this provider. Localization is not supported
PARAMETERS        :
================================================================================
*/
void BIPTLEpProvider::getInstance(const OperationContext &ctx,
                 const CIMObjectPath           &instanceName,
                 const Boolean includeQualifiers,
                 const Boolean includeClassOrigin,
                 const CIMPropertyList        &propertyList,
                 InstanceResponseHandler &handler)
{	
#ifdef DEBUG
  cout << "BIPTLEpProvider::getInstance(" << instanceName.toString() << ")" 
       << endl;
#endif

  CIMKeyBinding kb;
  CIMName className = instanceName.getClassName();
  CIMNamespaceName nameSpace = instanceName.getNameSpace();
  int i;
  int keysFound;  // this will be used as a bit array
  String sn;      // system name
  String lepName, // LAN Endpoint Name
	 ipeName, // IP Protocol Endpoint Name
	 refCCN,  // Reference's Creation Class Name
	 refName; // Reference's Name

  // Grab the system name
  if (IPInterface::getSystemName(sn) == false)
     sn = String::EMPTY;

  // Validate the classname
  _checkClass(className);

  // Extract the key values
  Array<CIMKeyBinding> kbArray = instanceName.getKeyBindings();

  // Leave immediately if wrong number of keys
  if ( kbArray.size() != NUMKEYS_PG_BINDS_IP_TO_LAN_ENDPOINT )
    throw CIMInvalidParameterException("Wrong number of keys");

  // Validate the keys.
  // Each loop iteration will set a bit in keysFound when a valid
  // key is found. If the expected bits aren't all set when
  // the loop finishes, it's a problem
  for (i=0, keysFound=0; i < NUMKEYS_PG_BINDS_IP_TO_LAN_ENDPOINT; i++)
  {
    kb = kbArray[i];

    CIMName keyName = kb.getName();
    String keyValue = kb.getValue();

    // Antecedent must match
    if (keyName.equal (PROPERTY_ANTECEDENT))
    {
      if (_goodPERefKeys(keyValue, refCCN, refName) &&
	  String::equalNoCase(refCCN, CLASS_CIM_LAN_ENDPOINT.getString()))
      {
        keysFound |= 1;
	lepName = refName;
      }
      else
         throw CIMInvalidParameterException(keyValue+": bad value for key "+
             keyName.getString());
    }

    // Dependent must match
    else if (keyName.equal (PROPERTY_DEPENDENT))
    {
      if (_goodPERefKeys(keyValue, refCCN, refName) &&
	  String::equalNoCase(refCCN, 
              CLASS_CIM_IP_PROTOCOL_ENDPOINT.getString()))
      {
        keysFound |= 2;
	ipeName = refName;
      }
      else
         throw CIMInvalidParameterException(keyValue+": bad value for key "+
             keyName.getString());
    }

    // Key name was not recognized by any of the above tests
    else throw CIMInvalidParameterException(keyName.getString()+ 
        ": Unrecognized key");
		
  } // for

  // We could get here if we didn't get all the keys, which
  // could happen if the right number of keys were supplied,
  // and they all had valid names and values, but there were
  // any duplicates (e.g., two Names, no SystemName)
  if (keysFound != (1<<NUMKEYS_PG_BINDS_IP_TO_LAN_ENDPOINT)-1)
    throw CIMInvalidParameterException("Bad object name");

  // Get the Interface List
  InterfaceList _ifList;
  IPInterface _ipif;

  // Make sure the LAN Endpoint name is embedded in the IP Protocol Endpoint
  // name.  If we can find the request interface and if it's one that
  // binds to a LAN Interface, then we've found the right one, so
  // return it to the client.
  if (ipeName.find(lepName) != PEG_NOT_FOUND &&
      _ifList.findInterface(ipeName, _ipif) &&
      _ipif.bindsToLANInterface())
  {
    /* Notify processing is starting. */
    handler.processing();

    /* Return the instance. */
    handler.deliver(_constructInstance(className, nameSpace, _ipif));

    /* Notify processing is complete. */
    handler.complete();
    return;
  }

  throw CIMObjectNotFoundException(ipeName+": No such IP Interface");

  return; // can never execute, but required to keep compiler happy
}
PEGASUS_NAMESPACE_BEGIN

/*****************************************************************************
 *
 * Implementation of AssociationProvider associators method
 *
 *****************************************************************************/
void InteropProvider::associators(
    const OperationContext & context,
    const CIMObjectPath & objectName,
    const CIMName & associationClass,
    const CIMName & resultClass,
    const String & role,
    const String & resultRole,
    const Boolean includeQualifiers,
    const Boolean includeClassOrigin,
    const CIMPropertyList & propertyList,
    ObjectResponseHandler & handler)
{
    PEG_METHOD_ENTER(TRC_CONTROLPROVIDER,
            "InteropProvider::associators()");
    initProvider();
    PEG_TRACE((TRC_CONTROLPROVIDER, Tracer::LEVEL4,
        "%s associators. objectName= %s, assocClass= %s resultClass= %s "
            "role= %s resultRole %s, includeQualifiers= %s, "
            "includeClassOrigin= %s, PropertyList= %s",
        thisProvider,
        (const char *)objectName.toString().getCString(),
        (const char *)associationClass.getString().getCString(),
        (const char *)resultClass.getString().getCString(),
        (const char *)role.getCString(),
        (const char *)resultRole.getCString(),
                      boolToString(includeQualifiers),
                      boolToString(includeClassOrigin),
        (const char *)propertyListToString(propertyList).getCString()));

    handler.processing();
    String originRole = role;
    String targetRole = resultRole;
    Uint32 numIterations = 1;
    //
    // The localReferences call retrieves instances of the desired association
    // class and sets the originRole and targetRole properties if currently
    // empty.
    //
    if (associationClass.equal(PEGASUS_CLASSNAME_PG_REFERENCEDPROFILE))
    {
        if (originRole.size() == 0 && targetRole.size() == 0)
        {
            originRole = String("Antecedent");
            targetRole = String("Dependent");
            numIterations = 2;
        }
    }
    for (Uint32 i = 0; i < numIterations; ++i)
    {
        Array<CIMInstance> refs = localReferences(
            context,
            objectName,
            associationClass,
            originRole,
            targetRole,
            CIMPropertyList(),
            resultClass);

        if( refs.size() )
        {
            Array<CIMInstance> refObjs = 
                getReferencedInstances(refs,targetRole,context,propertyList);
            ConstArrayIterator<CIMInstance> refsIterator(refObjs);
            for(Uint32 i = 0; i < refsIterator.size(); i++)
            {
                handler.deliver(refsIterator[i]);
            }
        }

        if (numIterations == 2)
        {
            originRole = String("Dependent");
            targetRole = String("Antecedent");
        }
    }
    handler.complete();

    PEG_METHOD_EXIT();
}
void UNIX_AssociatedDeviceMaskingGroup::setScope(CIMName scope)
{
	currentScope = CIMName(scope.getString());
}
Example #18
0
/*
================================================================================
NAME              : _goodPERefKeys
DESCRIPTION       : Checks to see if this is a value reference to a
		  : Protocol Endpoint with good values for SCCN, SN,
		  : and CCN.  If it is, it returns the Name;
                  : otherwise, it returns false.
ASSUMPTIONS       : None
PRE-CONDITIONS    :
POST-CONDITIONS   :
NOTES             :
================================================================================
*/
Boolean BIPTLEpProvider::_goodPERefKeys(const CIMObjectPath &instName,
				     String &rccn,    // CreationClassName
				     String &rname)   // Name
{
#ifdef DEBUG
   cout << "BIPTLEpProvider::_goodPERefKeys(" << instName.toString() << ")" 
        << endl;
#endif

   int keysFound,  // this will be used as a bit array
       i; 

   Array<CIMKeyBinding> kbArray = instName.getKeyBindings();

   if ( kbArray.size() != NUMKEYS_CIM_PROTOCOL_ENDPOINT)
     throw CIMInvalidParameterException("Wrong number of keys in reference");
    
   for (i=0, keysFound=0; i < NUMKEYS_CIM_PROTOCOL_ENDPOINT; i++)
   {
      CIMKeyBinding kb = kbArray[i];  

      CIMName keyName = kb.getName();
      String keyValue = kb.getValue();

      // SystemCreationClassName
      if (keyName.equal (PROPERTY_SYSTEM_CREATION_CLASS_NAME))
      {
	  if (String::equalNoCase(keyValue,
                  CLASS_CIM_UNITARY_COMPUTER_SYSTEM.getString()) ||
		  String::equal(keyValue, String::EMPTY) )
             keysFound |= 1;
	  else
	     return false;  // invalid value for SystemCreationClassName
      }

      // SystemName
      else if (keyName.equal (PROPERTY_SYSTEM_NAME))
      {
	  String sn; // System Name
	  if (IPInterface::getSystemName(sn) == false)
	      sn = String::EMPTY;

	  if (String::equalNoCase(keyValue,sn) ||
		  String::equal(keyValue, String::EMPTY) )
             keysFound |= 2;
	  else
	     return false;  // invalid value for SystemName
      }

      // CreationClassName
      else if (keyName.equal (PROPERTY_CREATION_CLASS_NAME))
      {
	    rccn = keyValue;
            keysFound |= 4;
      }

      // Name must be a valid IP interface, but we will know that later
      // For now, just verify that it's present
      else if (keyName.equal (PROPERTY_NAME))
      {
            rname = keyValue;
            keysFound |= 8;
      }

      // Key name was not recognized by any of the above tests
      else return false;

   } // for
   
  // We could get here if we didn't get all the keys, which
  // could happen if the right number of keys were supplied,
  // and they all had valid names and values, but there were
  // any duplicates (e.g., two Names, no SystemName)
   if (keysFound != (1<<NUMKEYS_CIM_PROTOCOL_ENDPOINT)-1)
      return false;

#ifdef DEBUG
   cout << "BIPTLEpProvider::_goodPERefKeys() - success!" << endl;
#endif

   return true;
}
void UNIX_CIFSShare::setScope(CIMName scope)
{
	currentScope = CIMName(scope.getString());
}
Example #20
0
/*
================================================================================
NAME              : _checkClass
DESCRIPTION       : tests the argument for valid classname,
                  : throws exception if not
ASSUMPTIONS       : None
PRE-CONDITIONS    :
POST-CONDITIONS   :
NOTES             :
================================================================================
*/
void BIPTLEpProvider::_checkClass(CIMName& className)
{
  if (!className.equal (CLASS_PG_BINDS_IP_TO_LAN_ENDPOINT))
    throw CIMNotSupportedException(className.getString()+
        ": Class not supported");
}
void UNIX_AssociatedPrintInterpreter::setScope(CIMName scope)
{
	currentScope = CIMName(scope.getString());
}
void UNIX_BGPAdminDistance::setScope(CIMName scope)
{
	currentScope = CIMName(scope.getString());
}
Example #23
0
// CIMMethodProvider interface
void DynamicIndicationProvider::invokeMethod(
    const OperationContext& context,
    const CIMObjectPath& objectReference,
    const CIMName& methodName,
    const Array<CIMParamValue>& inParameters,
    MethodResultResponseHandler& handler)
{
    PEG_METHOD_ENTER(TRC_CONTROLPROVIDER,
        "DynamicIndicationProvider::invokeMethod");

    Uint32 severity;
    String classname;
    String description;
    char buf[256];

    PEG_TRACE((TRC_CONTROLPROVIDER, Tracer::LEVEL4,"Class %s",
        (const char*)objectReference.toString().getCString()));
    PEG_TRACE((TRC_CONTROLPROVIDER, Tracer::LEVEL4,"Method %s",
        (const char*)methodName.getString().getCString()));

    handler.processing();

    if (String::equal(
            objectReference.getClassName().getString(),
            _DynamicIndicationClassName))
    {
        if (String::equal(methodName.getString(), _DynamicIndicationMethod))
        {
            try
            {
                ((inParameters[0]).getValue()).get(severity);
                ((inParameters[1]).getValue()).get(classname);
                ((inParameters[2]).getValue()).get(description);

                PEG_TRACE((
                    TRC_CONTROLPROVIDER,
                    Tracer::LEVEL4,
                    "severity:!%d!, classname!%s! description!%s!\n",
                    severity,
                    (const char*)classname.getCString(),
                    (const char*)description.getCString()));
            }
            catch (...)
            {
                PEG_METHOD_EXIT();
                throw CIMException(CIM_ERR_INVALID_PARAMETER);
            }
        }
        else
        {
            PEG_METHOD_EXIT();
            throw CIMException(CIM_ERR_METHOD_NOT_FOUND);
        }
    }
    else
    {
        PEG_METHOD_EXIT();
        throw CIMException(CIM_ERR_INVALID_CLASS);
    }

    sendIndication(severity, classname, description);

    unsigned int execStatus = 0;
    CIMValue cimRetValue(execStatus);
    handler.deliver(cimRetValue);
    handler.complete();

    PEG_METHOD_EXIT();
}
Example #24
0
void CIMPropertyRep::resolve(
    DeclContext* declContext,
    const CIMNamespaceName& nameSpace,
    Boolean isInstancePart,
    const CIMConstProperty& inheritedProperty,
    Boolean propagateQualifiers)
{
    PEGASUS_ASSERT(!inheritedProperty.isUninitialized());

    // Check the type:

    if (!inheritedProperty.getValue().typeCompatible(_value))
    {
        if (!(
            (inheritedProperty.getValue().getType() == CIMTYPE_OBJECT) &&
            (_value.getType() == CIMTYPE_STRING) &&
            (_qualifiers.find(PEGASUS_QUALIFIERNAME_EMBEDDEDOBJECT)
                 != PEG_NOT_FOUND) &&
            (inheritedProperty.getValue().isArray() == _value.isArray())
            ) &&
            !(
            (inheritedProperty.getValue().getType() == CIMTYPE_INSTANCE) &&
            (_value.getType() == CIMTYPE_STRING) &&
            (_qualifiers.find(PEGASUS_QUALIFIERNAME_EMBEDDEDINSTANCE)
                 != PEG_NOT_FOUND) &&
            (inheritedProperty.getValue().isArray() == _value.isArray())
            ))
        {
            throw TypeMismatchException();
        }
    }

    // Validate the qualifiers of the property (according to
    // superClass's property with the same name). This method
    // will throw an exception if the validation fails.

    CIMScope scope = CIMScope::PROPERTY;

    if (_value.getType() == CIMTYPE_REFERENCE)
        scope = CIMScope::REFERENCE;

    // Test the reference class name against the inherited property
    if (_value.getType() == CIMTYPE_REFERENCE ||
        _value.getType() == CIMTYPE_INSTANCE)
    {
        CIMName inheritedClassName;
        Array<CIMName> classNames;

        if (_value.getType() == CIMTYPE_INSTANCE)
        {
            Uint32 pos = inheritedProperty.findQualifier(
                             PEGASUS_QUALIFIERNAME_EMBEDDEDINSTANCE);
            if (pos != PEG_NOT_FOUND)
            {
                String qualStr;
                inheritedProperty.getQualifier(pos).getValue().get(qualStr);
                inheritedClassName = qualStr;
            }

            if (_value.isArray())
            {
                Array<CIMInstance> embeddedInstances;
                _value.get(embeddedInstances);
                for (Uint32 i = 0, n = embeddedInstances.size(); i < n; ++i)
                {
                    classNames.append(embeddedInstances[i].getClassName());
                }
            }
            else
            {
                CIMInstance embeddedInst;
                _value.get(embeddedInst);
                classNames.append(embeddedInst.getClassName());
            }
        }
        else
        {
            CIMName referenceClass;
            if (_referenceClassName.isNull())
            {
                CIMObjectPath reference;
                _value.get(reference);
                referenceClass = reference.getClassName();
            }
            else
            {
                referenceClass = _referenceClassName;
            }

            inheritedClassName = inheritedProperty.getReferenceClassName();
            classNames.append(referenceClass);
        }

        // This algorithm is friendly to arrays of embedded instances. It
        // remembers the class names that are found to be subclasses of the
        // inherited class name retrieved from the inherited property. This
        // ensures that any branch in the inheritance hierarchy will only be
        // traversed once. This provides significant optimization given that
        // most elements of an array of embedded instances will probably be of
        // very closely related types.
        Array<CIMName> successTree;
        successTree.append(inheritedClassName);
        for (Uint32 i = 0, n = classNames.size(); i < n; ++i)
        {
            Array<CIMName> traversalHistory;
            CIMName currentName = classNames[i];
            Boolean found = false;
            while (!found && !currentName.isNull())
            {
                for (Uint32 j = 0, m = successTree.size(); j < m; ++j)
                {
                    if (currentName == successTree[j])
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    traversalHistory.append(currentName);
                    CIMClass currentClass = declContext->lookupClass(
                            nameSpace, currentName);
                    if (currentClass.isUninitialized())
                    {
                        throw PEGASUS_CIM_EXCEPTION(
                            CIM_ERR_INVALID_PARAMETER, currentName.getString());
                    }
                    currentName = currentClass.getSuperClassName();
                }
            }

            if (!found)
            {
                throw TypeMismatchException();
            }

            successTree.appendArray(traversalHistory);
        }
    }

    _qualifiers.resolve(
        declContext, nameSpace, scope, isInstancePart,
        inheritedProperty._rep->_qualifiers, propagateQualifiers);

    _classOrigin = inheritedProperty.getClassOrigin();
}
Example #25
0
CIMProperty ObjectNormalizer::processProperty(
    CIMConstProperty& referenceProperty,
    CIMConstProperty& instProperty,
    Boolean includeQualifiers,
    Boolean includeClassOrigin,
    NormalizerContext* context,
    const CIMNamespaceName& nameSpace)
{
    // check name
    if (!referenceProperty.getName().equal(instProperty.getName()))
    {
        MessageLoaderParms message(
            "Common.ObjectNormalizer.INVALID_PROPERTY_NAME",
            "Invalid property name: $0",
            instProperty.getName().getString());

        throw CIMException(CIM_ERR_FAILED, message);
    }

    // check type
    CIMType referencePropType = referenceProperty.getType();
    CIMType instPropType = instProperty.getType();
    if (referencePropType != instPropType)
    {
        MessageLoaderParms message(
            "Common.ObjectNormalizer.INVALID_PROPERTY_TYPE",
            "Invalid property type: $0",
            instProperty.getName().getString());

        throw CIMException(CIM_ERR_FAILED, message);
    }

    // TODO: check array size?

    CIMProperty normalizedProperty(
        referenceProperty.getName(),
        referenceProperty.getValue(),   // default value
        referenceProperty.getArraySize(),
        referenceProperty.getReferenceClassName(),
        CIMName(),
        false);

    // TODO: check override (especially for references)?

    // update value
    if (!instProperty.getValue().isNull())
    {
        normalizedProperty.setValue(instProperty.getValue());
    }

    // update class origin
    if (includeClassOrigin)
    {
        normalizedProperty.setClassOrigin(referenceProperty.getClassOrigin());
    }

    // add qualifiers
    if (includeQualifiers)
    {
        // propagate class property qualifiers
        for (Uint32 i=0, n = referenceProperty.getQualifierCount(); i < n; i++)
        {
            CIMConstQualifier referenceQualifier =
                referenceProperty.getQualifier(i);

            Uint32 pos =
                instProperty.findQualifier(referenceQualifier.getName());

            // update value if qualifier is present in the specified property
            if (pos != PEG_NOT_FOUND)
            {
                CIMConstQualifier cimQualifier = instProperty.getQualifier(pos);

                CIMQualifier normalizedQualifier =
                    _processQualifier(
                        referenceQualifier,
                        cimQualifier);

                normalizedProperty.addQualifier(normalizedQualifier);
            }
            else
            {
                normalizedProperty.addQualifier(referenceQualifier.clone());
            }
        }
    }
#ifdef PEGASUS_SNIA_INTEROP_COMPATIBILITY
    else if (referenceProperty.getType() == CIMTYPE_INSTANCE)
    {
        Uin32 refPos = referenceProperty.findQualifier(
                           PEGASUS_QUALIFIERNAME_EMBEDDEDINSTANCE);
        Uin32 cimPos = instProperty.findQualifier(
                           PEGASUS_QUALIFIERNAME_EMBEDDEDINSTANCE);
        if (refPos != PEG_NOT_FOUND && cimPos == PEG_NOT_FOUND)
        {
            instProperty.addQualifier(refProperty.getQualifier(pos));
        }
    }
#endif

    // Check the type of the embedded instance against the class specified by
    // the EmbeddedInstance qualifier. We can only do this if the context
    // is non-zero.
    if (context != 0)
    {
        if (referenceProperty.getType() == CIMTYPE_INSTANCE)
        {
            Uint32 pos = referenceProperty.findQualifier(
                             PEGASUS_QUALIFIERNAME_EMBEDDEDINSTANCE);

            PEGASUS_ASSERT(pos != PEG_NOT_FOUND);

            String qualClassStr;
            referenceProperty.getQualifier(pos).getValue().get(
                qualClassStr);
            CIMName embedInstClassName(qualClassStr);
            Array<CIMName> embeddedInstSubclasses =
                context->enumerateClassNames(nameSpace, embedInstClassName,
                    true);
            embeddedInstSubclasses.append(embedInstClassName);

            Array<CIMInstance> embeddedInstances;
            if (referenceProperty.isArray())
            {
                instProperty.getValue().get(embeddedInstances);
            }
            else
            {
                CIMInstance embeddedInst;
                instProperty.getValue().get(embeddedInst);
                embeddedInstances.append(embeddedInst);
            }

            Array<CIMClass> embeddedClassDefs;
            for (Uint32 i = 0, n = embeddedInstances.size(); i < n; ++i)
            {
                CIMInstance& currentInstance = embeddedInstances[i];
                CIMName currentClassName = currentInstance.getClassName();
                if (Contains(embeddedInstSubclasses, currentClassName))
                {
                    CIMClass embeddedClassDef;
                    bool found = false;
                    for (Uint32 j = 0, m = embeddedClassDefs.size(); j < m;
                        ++j)
                    {
                        CIMClass& tmpClassDef = embeddedClassDefs[j];
                        if (tmpClassDef.getClassName() == currentClassName)
                        {
                            embeddedClassDef = tmpClassDef;
                            found = true;
                        }
                    }

                    if (!found)
                    {
                        embeddedClassDef = context->getClass(nameSpace,
                            currentClassName);
                        embeddedClassDefs.append(embeddedClassDef);
                    }

                    SharedPtr<NormalizerContext> tmpContext(context->clone());
                    ObjectNormalizer tmpNormalizer(embeddedClassDef,
                        includeQualifiers, includeClassOrigin, nameSpace,
                        tmpContext);
                    if (currentInstance.getPath().getKeyBindings().size()==0)
                    {
                        currentInstance.setPath(
                            currentInstance.buildPath(embeddedClassDef));
                    }
                    embeddedInstances[i] =
                        tmpNormalizer.processInstance(currentInstance);
                }
                else
                {
                    MessageLoaderParms message(
                        "Common.ObjectNormalizer."
                            "INVALID_EMBEDDED_INSTANCE_TYPE",
                        "Found embedded instance of type $0: was expecting "
                            "$1 for property $2",
                        currentClassName.getString(),
                        qualClassStr,
                        instProperty.getName().getString());

                    throw CIMException(CIM_ERR_FAILED, message);
                }
            }

            if (referenceProperty.isArray())
            {
              normalizedProperty.setValue(CIMValue(embeddedInstances));
            }
            else
            {
              normalizedProperty.setValue(CIMValue(embeddedInstances[0]));
            }
        }
    }
    return normalizedProperty;
}
Example #26
0
/**
    ATTN-RK: The DMTF specification for the string form of an
    object path makes it impossible for a parser to distinguish
    between a key values of String type and Reference type.

    Given the ambiguity, this implementation takes a guess at the
    type of a quoted key value.  If the value can be parsed into
    a CIMObjectPath with at least one key binding, the type is
    set to REFERENCE.  Otherwise, the type is set to STRING.
    Note: This algorithm appears to be in line with what the Sun
    WBEM Services implementation does.

    To be totally correct, it would be necessary to retrieve the
    class definition and look up the types of the key properties
    to determine how to interpret the key values.  This is clearly
    too inefficient for internal transformations between
    CIMObjectPaths and String values.
*/
void _parseKeyBindingPairs(
    const String& objectName,
    char*& p,
    Array<CIMKeyBinding>& keyBindings)
{
    // Get the key-value pairs:

    while (*p)
    {
        // Get key part:

        char* equalsign = strchr(p, '=');
        if (!equalsign)
        {
            MessageLoaderParms mlParms(
                "Common.CIMObjectPath.INVALID_KEYVALUEPAIR",
                "$0, reason:\"invalid key-value pair, missing equal sign\"",
                objectName);
            throw MalformedObjectNameException(mlParms);
        }

        *equalsign = 0;

        if (!CIMName::legal(p))
        {
            MessageLoaderParms mlParms(
                "Common.CIMObjectPath.INVALID_KEYNAME",
                "$0, reason:\"invalid key-value pair, invalid key name:$1\"",
                objectName,
                p);
            throw MalformedObjectNameException(mlParms);
        }

        CIMName keyName (p);

        // Get the value part:

        String valueString;
        p = equalsign + 1;
        CIMKeyBinding::Type type;

        if (*p == '"')
        {
            // Could be CIMKeyBinding::STRING or CIMKeyBinding::REFERENCE

            p++;

            Buffer keyValueUTF8(128);

            while (*p && *p != '"')
            {
                if (*p == '\\')
                {
                    p++;

                    if ((*p != '\\') && (*p != '"'))
                    {
                        MessageLoaderParms mlParms(
                            "Common.CIMObjectPath.INVALID_KEYVALUE",
                            "$0, reason:\"invalid key-value pair, "
                                "malformed value\"",
                            objectName);
                        throw MalformedObjectNameException(mlParms);
                    }
                }

                keyValueUTF8.append(*p++);
            }

            if (*p++ != '"')
            {
                MessageLoaderParms mlParms(
                    "Common.CIMObjectPath.INVALID_KEYVALUEPAIR_MISSINGQUOTE",
                    "$0, reason:\"invalid key-value pair, "
                        "missing quote in key value\"",
                    objectName);
                throw MalformedObjectNameException(mlParms);
            }

            // Convert the UTF-8 value to a UTF-16 String

            valueString.assign(
                (const char*)keyValueUTF8.getData(),
                keyValueUTF8.size());

            /*
                Guess at the type of this quoted key value.  If the value
                can be parsed into a CIMObjectPath with at least one key
                binding, the type is assumed to be a REFERENCE.  Otherwise,
                the type is set to STRING.  (See method header for details.)
             */
            type = CIMKeyBinding::STRING;

            /* Performance shortcut will check for
               equal sign instead of doing the full
               CIMObjectPath creation and exception handling
            */
            if (strchr(keyValueUTF8.getData(), '='))
            {
                // found an equal sign, high probability for a reference
                try
                {
                    CIMObjectPath testForPath(valueString);
                    if (testForPath.getKeyBindings().size() > 0)
                    {
                        // We've found a reference value!
                        type = CIMKeyBinding::REFERENCE;
                    }
                }
                catch (const Exception &)
                {
                    // Not a reference value; leave type as STRING
                }
            }
        }
        else if (toupper(*p) == 'T' || toupper(*p) == 'F')
        {
            type = CIMKeyBinding::BOOLEAN;

            char* r = p;
            Uint32 n = 0;

            while (*r && *r != ',')
            {
                *r = toupper(*r);
                r++;
                n++;
            }

            if (!(((strncmp(p, "TRUE", n) == 0) && n == 4) ||
                  ((strncmp(p, "FALSE", n) == 0) && n == 5)))
            {
                MessageLoaderParms mlParms(
                    "Common.CIMObjectPath.INVALID_BOOLVALUE",
                    "$0, reason:\"invalid key-value pair, "
                        "value should be TRUE or FALSE\"",
                    objectName);
                throw MalformedObjectNameException(mlParms);
            }

            valueString.assign(p, n);

            p = p + n;
        }
        else
        {
            type = CIMKeyBinding::NUMERIC;

            char* r = p;
            Uint32 n = 0;

            while (*r && *r != ',')
            {
                r++;
                n++;
            }

            Boolean isComma = false;
            if (*r)
            {
                *r = '\0';
                isComma = true;
            }

            if (*p == '-')
            {
                Sint64 x;
                if (!StringConversion::stringToSignedInteger(p, x))
                {
                    MessageLoaderParms mlParms(
                        "Common.CIMObjectPath.INVALID_NEGATIVNUMBER_VALUE",
                        "$0, reason:\"invalid key-value pair, "
                            "invalid negative number value $1\"",
                        objectName,
                        p);
                    throw MalformedObjectNameException(mlParms);
                }
            }
            else
            {
                Uint64 x;
                if (!StringConversion::stringToUnsignedInteger(p, x))
                {
                    MessageLoaderParms mlParms(
                        "Common.CIMObjectPath.INVALID_NEGATIVNUMBER_VALUE",
                        "$0, reason:\"invalid key-value pair, "
                            "invalid number value $1\"",
                        objectName,
                        p);
                    throw MalformedObjectNameException(mlParms);
                }
            }

            valueString.assign(p, n);

            if (isComma)
            {
                *r = ',';
            }

            p = p + n;
        }

        keyBindings.append(CIMKeyBinding(keyName.getString (), valueString,
            type));

        if (*p)
        {
            if (*p++ != ',')
            {
                MessageLoaderParms mlParms(
                    "Common.CIMObjectPath.INVALID_KEYVALUEPAIR_MISSCOMMA",
                    "$0, reason:\"invalid key-value pair, "
                        "next key-value pair has to start with comma\"",
                    objectName);
                throw MalformedObjectNameException(mlParms);
            }
        }
    }

    _Sort(keyBindings);
}
void UNIX_AccountAuthentication::setScope(CIMName scope)
{
	currentScope = CIMName(scope.getString());
}
/*****************************************************************************
 *
 * Implementation of AssociationProvider associatorNames method
 *
 *****************************************************************************/
void InteropProvider::associatorNames(
    const OperationContext & context,
    const CIMObjectPath & objectName,
    const CIMName & associationClass,
    const CIMName & resultClass,
    const String & role,
    const String & resultRole,
    ObjectPathResponseHandler & handler)
{
    PEG_METHOD_ENTER(TRC_CONTROLPROVIDER,
        "InteropProvider::associatorNames()");
    initProvider();
    PEG_TRACE((TRC_CONTROLPROVIDER, Tracer::LEVEL4,
        "%s associatorNames.objectName= %s, assocClass= %s resultClass= %s "
            "role= %s resultRole = %s",
        thisProvider,
        (const char *)objectName.toString().getCString(),
        (const char *)associationClass.getString().getCString(),
        (const char *)resultClass.getString().getCString(),
        (const char *)role.getCString(),
        (const char *)resultRole.getCString()));

    handler.processing();
    String originRole = role;
    String targetRole = resultRole;
    Uint32 numIterations = 1;
    //
    // The localReferences call retrieves instances of the desired association
    // class and sets the originRole and targetRole properties if currently
    // empty.
    //
    if (associationClass.equal(PEGASUS_CLASSNAME_PG_REFERENCEDPROFILE))
    {
        if (originRole.size() == 0 && targetRole.size() == 0)
        {
            originRole = String("Antecedent");
            targetRole = String("Dependent");
            numIterations = 2;
        }
    }
    for (Uint32 i = 0; i < numIterations; ++i)
    {
        Array<CIMInstance> refs = localReferences(
            context,
            objectName,
            associationClass,
            originRole,
            targetRole,
            CIMPropertyList(),
            resultClass);
        for (Uint32 j = 0, n = refs.size(); j < n; ++j)
        {
            CIMInstance & currentRef = refs[j];
            CIMObjectPath currentTarget = getRequiredValue<CIMObjectPath>(
                currentRef,
                targetRole);
            handler.deliver(currentTarget);
        }
        if (numIterations == 2)
        {
            originRole = String("Dependent");
            targetRole = String("Antecedent");
        }
    }
    handler.complete();
    PEG_METHOD_EXIT();
}
////////////////////////////////////////////////////////////////////////////////
//  Constructor for Next Hop IP Route Info
////////////////////////////////////////////////////////////////////////////////
NextHopIPRouteInfo::NextHopIPRouteInfo(
    CIMClient &client, 
    Boolean enableDebug,
    ostream& outPrintWriter, 
    ostream& errPrintWriter)
{
    _enableDebug = enableDebug;
    Array<CIMInstance> retInstances;

    try
    {
        Boolean deepInheritance = true;
        Boolean localOnly = true;
        Boolean includeQualifiers = false;
        Boolean includeClassOrigin = false;
          
        Array<CIMInstance> cimInstances = client.enumerateInstances(
            NAMESPACE, 
            CLASS_PG_NEXT_HOP_IP_ROUTE,
            deepInheritance,
            localOnly,
            includeQualifiers,
            includeClassOrigin);

        Array<CIMObjectPath> nhiprRefs = client.enumerateInstanceNames(
            NAMESPACE,
            CLASS_CIM_NEXT_HOP_ROUTE);

        for (Uint16 i = 0; i<nhiprRefs.size(); i++)
        {
            CIMName resultClass;
            String role;
            String resultRole;
            CIMObjectPath _nhrRef = nhiprRefs[i];
            _nhrRef.setClassName(CLASS_CIM_NEXT_HOP_ROUTE);

            // Get the association instance of CIM_RouteUsesEndpoint 
            // for each instance of CIM_NextHopRoute class
            Array<CIMObject> localRefs = client.associators(
                NAMESPACE,
                _nhrRef,
                CLASS_PG_ROUTE_USES_ENDPOINT,
                resultClass,
                role,
                resultRole);

            if (localRefs.size() == 1)
            {
                Uint32 index = localRefs[0].findProperty(PROPERTY_IPV4ADDRESS);
                if (index == PEG_NOT_FOUND)
                {
                    index = localRefs[0].findProperty(PROPERTY_IPV6ADDRESS);
                    if (index == PEG_NOT_FOUND)
                    {
                        errPrintWriter << 
                            "Error getting IPv4Address and IPv6Address " <<
                            "property: " << "not found!" << endl; 
                    }
                    else
                    {
                        CIMInstance _cimInstance = cimInstances[i];
                        String _nextHop;
                        localRefs[0].getProperty(index).getValue().get(
                            _nextHop);
                        CIMProperty _nhProperty(
                            PROPERTY_NEXT_HOP,
                             CIMValue(_nextHop));
                        _cimInstance.addProperty(_nhProperty);
                        retInstances.append(_cimInstance);
                    } 
                }
                else
                {
                    CIMInstance _cimInstance = cimInstances[i];
                    String _nextHop;
                    localRefs[0].getProperty(index).getValue().get(_nextHop);
                    CIMProperty _nhProperty(
                        PROPERTY_NEXT_HOP,
                         CIMValue(_nextHop));
                    _cimInstance.addProperty(_nhProperty);
                    retInstances.append(_cimInstance);
                }
            }
            else
            {
                // Get the association instance of CIM_AssociatedNextHop
                // for each instance of CIM_RemoteServiceAccessPoint class
                Array<CIMObject> remoteRefs = client.associators(
                    NAMESPACE,
                    _nhrRef,
                    CLASS_PG_ASSOCIATED_NEXT_HOP,
                    resultClass,
                    role,
                    resultRole);

                if (remoteRefs.size() == 1)
                {
                    Uint32 index = remoteRefs[0].findProperty(
                        PROPERTY_ACCESS_INFO);
                    if (index != PEG_NOT_FOUND)
                    {
                        CIMInstance _cimInstance = cimInstances[i];
                        String _accessInfo;
                        remoteRefs[0].getProperty(index).getValue().get(
                            _accessInfo);
                        Uint32 _sep = _accessInfo.find('/');
                        if (_sep != PEG_NOT_FOUND)
                        {
                            String _nextHop = _accessInfo.subString(0,_sep);
                            CIMProperty _nhProperty(
                                 PROPERTY_NEXT_HOP,
                                 CIMValue(_nextHop));
                            _cimInstance.addProperty(_nhProperty);
                            retInstances.append(_cimInstance);
                        } 
                    }
                    else
                    {
                        errPrintWriter << "Error getting AccessInfo property: "
                            << "not found! " << endl;
                    }
                }
                else
                {
                      outPrintWriter << "Unexpected number of references "
                          << "for this instance of class CIM_NextHopRoute :"
                          << remoteRefs.size() << endl;
                }
            } 
        }

        Uint32 numberInstances = retInstances.size();

        if (_enableDebug)
        {
            outPrintWriter << numberInstances << " instances of " <<
                CLASS_PG_NEXT_HOP_IP_ROUTE.getString() << endl;
        }

        if (numberInstances > 0)
        {
            _gatherProperties(retInstances[0]);
            _outputHeader(outPrintWriter);

            for (Uint32 i = 0; i < numberInstances; i++)
            {
                _gatherProperties(retInstances[i]);
                _outputInstance(outPrintWriter);

            }   // end for looping through instances.
        }
        else
        {
            outPrintWriter << "No instances of class " 
                << CLASS_PG_NEXT_HOP_IP_ROUTE.getString() << endl;
        }

    }  // end try .
    catch(Exception& e)
    {
        errPrintWriter << "Error getting instances of class " <<
            CLASS_PG_NEXT_HOP_IP_ROUTE.getString() << 
            " " << e.getMessage() << endl;
    }

}
/*****************************************************************************
 *
 * Implementation of AssociationProvider references method
 *
 *****************************************************************************/
void InteropProvider::references(
    const OperationContext & context,
    const CIMObjectPath & objectName,
    const CIMName & resultClass,
    const String & role,
    const Boolean includeQualifiers,
    const Boolean includeClassOrigin,
    const CIMPropertyList & propertyList,
    ObjectResponseHandler & handler)
{
    PEG_METHOD_ENTER(TRC_CONTROLPROVIDER,
        "InteropProvider::references()");
    initProvider();
    PEG_TRACE((TRC_CONTROLPROVIDER, Tracer::LEVEL4,
        "%s references. objectName= %s, resultClass= %s role= %s "
            "includeQualifiers= %s, includeClassOrigin= %s, PropertyList= %s",
        thisProvider,
        (const char *)objectName.toString().getCString(),
        (const char *)resultClass.getString().getCString(),
        (const char *)role.getCString(),
                      boolToString(includeQualifiers),
                      boolToString(includeClassOrigin),
        (const char *)propertyListToString(propertyList).getCString()));

    handler.processing();
    String tmpRole = role;
    String tmpTarget;
    Uint32 numIterations = 1;
    //
    // Makes call to internal references method to get result, supplying the
    // role parameter, but obviously not setting a resultRole/target parameter.
    //
    if (resultClass.equal(PEGASUS_CLASSNAME_PG_REFERENCEDPROFILE))
    {
        if (tmpRole.size() == 0)
        {
            tmpRole = String("Antecedent");
            tmpTarget = String("Dependent");
            numIterations = 2;
        }
    }
    for (Uint32 i = 0; i < numIterations; ++i)
    {
        Array<CIMInstance> refs = localReferences(
            context,
            objectName,
            resultClass,
            tmpRole,
            tmpTarget);
        for (Uint32 j = 0, n = refs.size(); j < n; ++j)
        {
            refs[j].filter(includeQualifiers, includeClassOrigin, propertyList);
            handler.deliver((CIMObject)refs[j]);
        }
        if (numIterations == 2)
        {
            tmpRole = String("Dependent");
            tmpTarget = String("Antecedent");
        }
    }
    handler.complete();
    PEG_METHOD_EXIT();
}