Migrating from C style to C++ style of coding in Lyric Plugin
authorGaganpreet Kaur <gaganpreetx.kaur@intel.com>
Thu, 2 Mar 2017 07:05:01 +0000 (12:35 +0530)
committerTodd Malsbary <todd.malsbary@intel.com>
Thu, 27 Apr 2017 16:55:14 +0000 (16:55 +0000)
Replacing fgets/fputs with fstream equivalents and using std::string
in lyric_plugin, wherever applicable

Change-Id: Iac3a65bc674fcff7576ebc6b8cd45e1bbd4410cd
Signed-off-by: Gaganpreet Kaur <gaganpreetx.kaur@intel.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/17611
Tested-by: jenkins-iotivity <jenkins@iotivity.org>
Reviewed-by: Joseph Morrow <joseph.l.morrow@intel.com>
Reviewed-by: Todd Malsbary <todd.malsbary@intel.com>
(cherry picked from commit 19896e71a673e710dc76cc4c575b12e03e57df34)
Reviewed-on: https://gerrit.iotivity.org/gerrit/19165
Reviewed-by: Uze Choi <uzchoi@samsung.com>
bridging/plugins/lyric_plugin/honeywellHelpers.cpp
bridging/plugins/lyric_plugin/honeywellHelpers.h
bridging/plugins/lyric_plugin/honeywellResource.cpp
bridging/plugins/lyric_plugin/honeywell_objects/honeywell.cpp
bridging/plugins/lyric_plugin/honeywell_objects/honeywell.h
bridging/plugins/lyric_plugin/honeywell_objects/honeywellThermostat.cpp
bridging/plugins/lyric_plugin/honeywell_objects/honeywellThermostat.h

index cb3e214..07e81be 100644 (file)
 #define LOG_TAG "HONEYWELL_HELPERS"
 #endif
 
-MPMResult LoadFileIntoString(const char *filePath, std::string &fileContents)
+MPMResult LoadFileIntoString(const std::string &filePath, std::string &fileContents)
 {
     MPMResult result = MPM_RESULT_OK;
-    if (NULL == filePath)
+    if (filePath.empty())
     {
-        OIC_LOG(ERROR, LOG_TAG, "filePath is NULL.");
-        result = MPM_RESULT_INVALID_PARAMETER;
+        OIC_LOG(ERROR, LOG_TAG, "filePath is empty.");
+        return MPM_RESULT_INVALID_PARAMETER;
     }
 
-    if (MPM_RESULT_OK == result)
+    try
     {
-        try
+        std::ostringstream buffer;
+        std::ifstream inputFile(filePath.c_str());
+        if (!inputFile)
         {
-            std::ostringstream buffer;
-            std::ifstream inputFile(filePath);
-            if (!inputFile)
-            {
-                OIC_LOG_V(ERROR, LOG_TAG, "Couldn't open file %s", filePath);
-                result = MPM_RESULT_FILE_NOT_OPEN;
-            }
-            else
-            {
-                buffer << inputFile.rdbuf();
-                fileContents = buffer.str();
-                OIC_LOG_V(INFO, LOG_TAG, "Read %lu bytes from file", (unsigned long) fileContents.size());
-            }
+            OIC_LOG_V(ERROR, LOG_TAG, "Couldn't open file %s", filePath.c_str());
+            result = MPM_RESULT_FILE_NOT_OPEN;
         }
-        catch (...)
+        else
         {
-            OIC_LOG(ERROR, LOG_TAG, "caught exception.");
-            result = MPM_RESULT_INTERNAL_ERROR;
+            buffer << inputFile.rdbuf();
+            fileContents = buffer.str();
+            OIC_LOG_V(INFO, LOG_TAG, "Read %lu bytes from file", (unsigned long) fileContents.size());
         }
     }
+    catch (...)
+    {
+        OIC_LOG(ERROR, LOG_TAG, "caught exception.");
+        result = MPM_RESULT_INTERNAL_ERROR;
+    }
 
     return result;
 }
 
-MPMResult SaveStringIntoFile(const char *stringData, const char *filePath)
+MPMResult SaveStringIntoFile(const std::string &stringData, const std::string &filePath)
 {
     MPMResult result = MPM_RESULT_OK;
 
-    if ((NULL == stringData) || (NULL == filePath))
+    if ((stringData.empty()) || (filePath.empty()))
     {
-        OIC_LOG(ERROR, LOG_TAG, "stringData or filePath are NULL");
+        OIC_LOG(ERROR, LOG_TAG, "stringData or filePath is empty");
         result = MPM_RESULT_INVALID_PARAMETER;
         goto cleanUp;
     }
 
     try
     {
-        std::ofstream outFile(filePath, std::ofstream::out);
+        std::ofstream outFile(filePath.c_str(), std::ofstream::out);
         if (!outFile)
         {
-            OIC_LOG_V(ERROR, LOG_TAG, "Failed to open file %s for output", filePath);
+            OIC_LOG_V(ERROR, LOG_TAG, "Failed to open file %s for output", filePath.c_str());
             result = MPM_RESULT_FILE_NOT_OPEN;
             goto cleanUp;
         }
@@ -104,7 +101,7 @@ MPMResult SaveStringIntoFile(const char *stringData, const char *filePath)
     return result;
 }
 
-MPMResult CopyFile(const char *sourceFilePath, const char *destFilePath, bool binaryFile)
+MPMResult CopyFile(const std::string &sourceFilePath, const std::string &destFilePath, bool binaryFile)
 {
     MPMResult result = MPM_RESULT_OK;
 
@@ -117,27 +114,27 @@ MPMResult CopyFile(const char *sourceFilePath, const char *destFilePath, bool bi
         inMode |= std::ifstream::binary;
     }
 
-    if ((NULL == sourceFilePath) || (NULL == destFilePath))
+    if ((sourceFilePath.empty()) || (destFilePath.empty()))
     {
-        OIC_LOG(ERROR, LOG_TAG, "sourceFilePath or destFilePath are NULL");
+        OIC_LOG(ERROR, LOG_TAG, "sourceFilePath or destFilePath is empty");
         result = MPM_RESULT_INVALID_PARAMETER;
         goto cleanUp;
     }
 
     try
     {
-        std::ofstream outFile(destFilePath, outMode);
+        std::ofstream outFile(destFilePath.c_str(), outMode);
         if (!outFile)
         {
-            OIC_LOG_V(ERROR, LOG_TAG, "Failed to open file %s for output", destFilePath);
+            OIC_LOG_V(ERROR, LOG_TAG, "Failed to open file %s for output", destFilePath.c_str());
             result = MPM_RESULT_FILE_NOT_OPEN;
             goto cleanUp;
         }
 
-        std::ifstream inFile(sourceFilePath, inMode);
+        std::ifstream inFile(sourceFilePath.c_str(), inMode);
         if (!inFile)
         {
-            OIC_LOG_V(ERROR, LOG_TAG, "Failed to open file %s for input", sourceFilePath);
+            OIC_LOG_V(ERROR, LOG_TAG, "Failed to open file %s for input", sourceFilePath.c_str());
             result = MPM_RESULT_FILE_NOT_OPEN;
             goto cleanUp;
         }
@@ -156,38 +153,21 @@ MPMResult CopyFile(const char *sourceFilePath, const char *destFilePath, bool bi
     return result;
 }
 
-std::string GetTokenPath(const char *fileName)
+std::string GetTokenPath(const std::string &fileName)
 {
-    char *tokenPathVar = NULL;
-    std::string tokenPath = "/";
-    size_t pathLen = 0;
+    std::string tokenPath = "./";
 
-    tokenPathVar = getenv("TOKEN_DIR");
-    if (NULL != tokenPathVar)
+    if (!fileName.empty())
     {
-        // replace default tokenPath with environment variable contents
-        tokenPath = tokenPathVar;
-    }
-
-    if (NULL != fileName)
-    {
-        pathLen = tokenPath.length();
-        if (0 != pathLen)
+        // filename should not begin with a slash
+        if (fileName.at(0) == '/')
         {
-            // path has at least one char; make sure it ends with a slash.
-            if (tokenPath.at(pathLen - 1) != '/')
-            {
-                tokenPath += "/";
-            }
+            tokenPath += fileName.substr(1);
         }
-
-        // filename should not begin with a slash
-        if (fileName[0] == '/')
+        else
         {
-            fileName++;
+            tokenPath += fileName;
         }
-        // append passed filename
-        tokenPath += fileName;
     }
 
     OIC_LOG_V(INFO, LOG_TAG, "Token file path: %s", tokenPath.c_str());
index 985cb70..46a4989 100644 (file)
@@ -33,7 +33,7 @@
 /// @param fileContents - (output) Returned file contents.
 ///
 /// @return MPM_RESULT_OK on success, error code otherwise.
-MPMResult LoadFileIntoString(const char *filePath, std::string &fileContents);
+MPMResult LoadFileIntoString(const std::string &filePath, std::string &fileContents);
 
 /// Saves a string into a text file.
 ///
@@ -41,7 +41,7 @@ MPMResult LoadFileIntoString(const char *filePath, std::string &fileContents);
 /// @param filePath - (input) Path/filename to load.
 ///
 /// @return MPM_RESULT_OK on success, error code otherwise.
-MPMResult SaveStringIntoFile(const char *stringData, const char *filePath);
+MPMResult SaveStringIntoFile(const std::string &stringData, const std::string &filePath);
 
 /// Copies a file.
 ///
@@ -50,7 +50,7 @@ MPMResult SaveStringIntoFile(const char *stringData, const char *filePath);
 /// @param binaryFile - (input) true if source is binary file, false if text file.
 ///
 /// @return MPM_RESULT_OK on success, error code otherwise.
-MPMResult CopyFile(const char *sourceFilePath, const char *destFilePath, bool binaryFile);
+MPMResult CopyFile(const std::string &sourceFilePath, const std::string &destFilePath, bool binaryFile);
 
 /// builds a path string to a given token file of given filename.
 /// Uses the contents of the TOKEN_DIR environment variable as the
@@ -61,7 +61,7 @@ MPMResult CopyFile(const char *sourceFilePath, const char *destFilePath, bool bi
 /// @param fileName - (input) filename only
 ///
 /// @return Full path/filename of token file.
-std::string GetTokenPath(const char *fileName);
+std::string GetTokenPath(const std::string &fileName);
 
 /// Calculates setpoints to achieve a desired target temperature. Honeywell thermostats don't have
 /// a single target temp like Nest. Instead you need to set an upper and lower threshold using
index 249ca78..aaf969c 100644 (file)
@@ -110,7 +110,7 @@ Honeywell::CLIENT_ID_SECRET m_clientId_secret;
 /*******************************************************************************
  * prototypes go here
  ******************************************************************************/
-MPMResult loadAccessToken(const char *filename, Honeywell::ACCESS_TOKEN &token);
+MPMResult loadAccessToken(const std::string &filename, Honeywell::ACCESS_TOKEN &token);
 
 OCEntityHandlerResult resourceEntityHandlerCb(OCEntityHandlerFlag,
                                                  OCEntityHandlerRequest *entityHandlerRequest,
@@ -118,7 +118,7 @@ OCEntityHandlerResult resourceEntityHandlerCb(OCEntityHandlerFlag,
 
 OCEntityHandlerResult processPutRequest(OCRepPayload * payload, LyricThermostatSharedPtr targetThermostat, const std::string uri);
 
-OCRepPayload *getPayload(const char *uri, const THERMOSTAT &data);
+OCRepPayload *getPayload(const std::string uri, const THERMOSTAT &data);
 
 void *accessTokenMonitorThread(void *pointer);
 
@@ -158,50 +158,43 @@ MPMResult pluginCreate(MPMPluginCtx **pluginSpecificCtx)
     ctx->resource_type = DEVICE_TYPE;
     ctx->open = honeywellFopen;
 
-    FILE *fp = fopen("./lyric.cnf", "r");
+    ifstream tokenFile ("./lyric.cnf");
 
-    if (NULL == fp)
+    if (!tokenFile.is_open())
     {
         OIC_LOG(ERROR, LOG_TAG, "error loading lyric.cnf file.");
         return MPM_RESULT_INTERNAL_ERROR;
     }
-    char code[HONEYWELL_REFRESH_TOKEN_BUFSIZE];
-    char str[1024];
-    size_t size = sizeof(str);
-    if (fgets(str, size, fp) == NULL)
+
+    std::string acode;
+
+    if (!getline (tokenFile, acode))
     {
         OIC_LOG(ERROR, LOG_TAG, "Failed to read ./lyric.cnf");
-        fclose(fp);
+        tokenFile.close();
         return MPM_RESULT_INTERNAL_ERROR;
     }
 
-    str[strlen(str) - 1] = '\0';
-    OICStrcpy(code, HONEYWELL_REFRESH_TOKEN_BUFSIZE, str);
-
-    if (fgets(str, size, fp) == NULL)
+    std::string str;
+    if (!getline (tokenFile, str))
     {
         OIC_LOG(ERROR, LOG_TAG, "Failed to read ./lyric.cnf");
-        fclose(fp);
+        tokenFile.close();
         return MPM_RESULT_INTERNAL_ERROR;
     }
+    OICStrcpy(m_clientId_secret.honeywell_clientId, HONEYWELL_CLIENT_ID_BUFFSIZE, str.c_str());
 
-    str[strlen(str) - 1] = '\0';
-    OICStrcpy(m_clientId_secret.honeywell_clientId, HONEYWELL_CLIENT_ID_BUFFSIZE, str);
-    if (fgets(str, size, fp) == NULL)
+    if (!getline (tokenFile, str))
     {
         OIC_LOG(ERROR, LOG_TAG, "Failed to read ./lyric.cnf");
-        fclose(fp);
+        tokenFile.close();
         return MPM_RESULT_INTERNAL_ERROR;
     }
-
-    str[strlen(str) - 1] = '\0';
-    OICStrcpy(m_clientId_secret.honeywell_client_secret, HONEYWELL_CLIENT_AND_SECRET_64_BUFFSIZE, str);
-    fclose(fp);
+    OICStrcpy(m_clientId_secret.honeywell_client_secret, HONEYWELL_CLIENT_AND_SECRET_64_BUFFSIZE, str.c_str());
+    tokenFile.close();
 
     g_honeywell.setClientIdAndSecret(m_clientId_secret);
 
-    std::string acode;
-    acode.assign(code);
     result = (MPMResult) g_honeywell.getAccessToken(acode, m_token);
     if (MPM_RESULT_OK != result)
     {
@@ -342,7 +335,7 @@ OCEntityHandlerResult checkIfOperationIsAllowed(std::string uri, OCMethod operat
  * @param[in] uri           Resource Uri
  * @param[in] data          Thermostat detials to be sent in response.
  */
-OCRepPayload *getPayload(const char *uri, const THERMOSTAT &data)
+OCRepPayload *getPayload(const std::string uri, const THERMOSTAT &data)
 {
     bool result = true;
     std::string modeString;
@@ -362,7 +355,7 @@ OCRepPayload *getPayload(const char *uri, const THERMOSTAT &data)
 
     if (result)
     {
-        result = OCRepPayloadSetUri(payload, uri);
+        result = OCRepPayloadSetUri(payload, uri.c_str());
         if (false == result)
         {
             OIC_LOG(ERROR, LOG_TAG, "OCRepPayloadSetUri failed");
@@ -590,11 +583,11 @@ MPMResult pluginScan(MPMPluginCtx *, MPMPipeMessage *)
     return result;
 }
 
-bool createSecureResources()
+bool isSecureEnvironmentSet()
 {
     char *non_secure_env = getenv("NONSECURE");
 
-    if (non_secure_env != NULL && strcmp(non_secure_env, "true") == 0)
+    if (non_secure_env != NULL && (strcmp(non_secure_env, "true") == 0))
     {
         OIC_LOG(INFO, LOG_TAG, "Creating NON SECURE resources");
         return false;
@@ -603,7 +596,7 @@ bool createSecureResources()
     return true;
 }
 
-void createPayloadForMetadata(MPMResourceList **list , const char *uri, const char * interface)
+void createPayloadForMetadata(MPMResourceList **list , const std::string &uri, const std::string &interface)
 {
     MPMResourceList *tempPtr;
     tempPtr = (MPMResourceList *) OICCalloc(1, sizeof(MPMResourceList));
@@ -614,8 +607,8 @@ void createPayloadForMetadata(MPMResourceList **list , const char *uri, const ch
         return;
     }
     OICStrcpy(tempPtr->rt, MPM_MAX_LENGTH_64, HONEYWELL_THERMOSTAT_RT);
-    OICStrcpy(tempPtr->href, MPM_MAX_URI_LEN, uri);
-    OICStrcpy(tempPtr->interfaces, MPM_MAX_LENGTH_64, interface);
+    OICStrcpy(tempPtr->href, MPM_MAX_URI_LEN, uri.c_str());
+    OICStrcpy(tempPtr->interfaces, MPM_MAX_LENGTH_64, interface.c_str());
     tempPtr->bitmap = BM;
     tempPtr->next = *list;
     *list  = tempPtr;
@@ -632,7 +625,11 @@ void updatePluginSpecificData(THERMOSTAT thermostat, ThermostatDetails *thermost
 MPMResult pluginAdd(MPMPluginCtx *, MPMPipeMessage * message)
 {
     uint8_t resourceProperties = (OC_OBSERVABLE | OC_DISCOVERABLE);
-    if (createSecureResources()) resourceProperties |= OC_SECURE;
+
+    if (isSecureEnvironmentSet())
+    {
+        resourceProperties |= OC_SECURE;
+    }
 
     std::string uri = reinterpret_cast<const char *>(message->payload);
     if(addedThermostats.find(uri) != addedThermostats.end())
@@ -720,7 +717,6 @@ MPMResult pluginRemove(MPMPluginCtx *, MPMPipeMessage * message)
 MPMResult pluginReconnect(MPMPluginCtx *, MPMPipeMessage * message)
 {
     MPMResourceList *list = NULL, *temp = NULL;
-    char *buff = NULL;
     THERMOSTAT thermostat;
     std::vector<LyricThermostatSharedPtr> thermostatsReconnected;
     void *details = NULL;
@@ -730,24 +726,13 @@ MPMResult pluginReconnect(MPMPluginCtx *, MPMPipeMessage * message)
     std::string thermostatMode;
     std::string uri;
 
-    if(message->payloadSize > 0 &&message->payloadSize < SIZE_MAX)
+    if(message->payloadSize <= 0 && message->payload == NULL)
     {
-        buff = (char *) OICCalloc(1, message->payloadSize);
-
-        if (buff ==NULL)
-        {
-            OIC_LOG(ERROR, LOG_TAG, "OICCalloc Failed");
-            return MPM_RESULT_INTERNAL_ERROR;
-        }
-    }
-    else
-    {
-        OIC_LOG(ERROR, LOG_TAG, "Payload size is out of bound");
+        OIC_LOG(ERROR, LOG_TAG, "No payload received, failed to reconnect");
         return MPM_RESULT_INTERNAL_ERROR;
     }
 
-    memcpy(buff, message->payload, message->payloadSize);
-    MPMParseMetaData((uint8_t*)buff, MPM_MAX_METADATA_LEN, &list, &details);
+    MPMParseMetaData(message->payload, MPM_MAX_METADATA_LEN, &list, &details);
 
     ThermostatDetails *thermostatDetails = (ThermostatDetails *)details;
     HoneywellThermostat honeywellThermostat;
@@ -826,7 +811,10 @@ MPMResult pluginReconnect(MPMPluginCtx *, MPMPipeMessage * message)
         goto CLEANUP;
     }
 
-    if (createSecureResources()) resourceProperties |= OC_SECURE;
+    if (isSecureEnvironmentSet())
+    {
+        resourceProperties |= OC_SECURE;
+    }
 
     while(list)
     {
@@ -842,10 +830,6 @@ MPMResult pluginReconnect(MPMPluginCtx *, MPMPipeMessage * message)
     result = MPM_RESULT_OK;
 
     CLEANUP:
-    if (buff != NULL)
-    {
-        OICFree(buff);
-    }
     if (thermostatDetails !=NULL)
     {
         OICFree(thermostatDetails);
index 3fc5bce..e14acb1 100644 (file)
@@ -125,23 +125,23 @@ MPMResult Honeywell::manageMutexes(bool initialize)
     return result;
 }
 
-void Honeywell::dumpResponseString(const char *stringData, const char *fileName)
+void Honeywell::dumpResponseString(const std::string &stringData, const std::string &fileName)
 {
     char logBuffer[MAX_LOG_STRING + 1];
 
-    if ((NULL == stringData) || (0 == strlen(stringData)))
+    if (stringData.empty())
     {
         OIC_LOG_V(ERROR, LOG_TAG, "stringData is NULL or zero len");
         return;
     }
 
-    OICStrcpy(logBuffer, sizeof(logBuffer), stringData);
+    OICStrcpy(logBuffer, sizeof(logBuffer), stringData.c_str());
     // display LENGTH of full response string, but only output the safe/truncated string
-    if ((NULL != fileName) && (0 != strlen(fileName)))
+    if (!fileName.empty())
     {
         if (MPM_RESULT_OK != SaveStringIntoFile(stringData, fileName))
         {
-            OIC_LOG_V(ERROR, LOG_TAG, "Error saving file %s", fileName);
+            OIC_LOG_V(ERROR, LOG_TAG, "Error saving file %s", fileName.c_str());
         }
     }
 }
index 6d5537f..3f4604e 100644 (file)
@@ -133,7 +133,7 @@ public:
     /// @param stringData - (input) String buffer to print.
     /// @param filename - (input optional) If non-null, specifies an output file to store the passed string.
     ///        File output is not truncated like OIC_LOG output is. Use this to capture JSON responses from cloud.
-    void dumpResponseString(const char *stringData, const char *fileName);
+    void dumpResponseString(const std::string &stringData, const std::string &fileName);
 
     /// Sets temperature of selected honeywell thermostat.
     ///
index b990f3d..cd74b89 100644 (file)
@@ -72,9 +72,8 @@ std::string hvacModeToString(const HVAC_MODE &hvacMode)
     return result;
 }
 
-void HoneywellThermostat::buildDeviceUri(const char *baseUri)
+void HoneywellThermostat::buildDeviceUri(const std::string &)
 {
-    (void)baseUri;
     std::string hw_tag = "/honeywell/";
     std::ostringstream uriStream;
 
@@ -219,9 +218,9 @@ THERMOSTAT::THERMOSTAT()
     cloudIndex = 0;
 }
 
-void dump_details(const THERMOSTAT &thermostat, const char *description)
+void dump_details(const THERMOSTAT &thermostat, const std::string &description)
 {
-    if (NULL == description)
+    if (description.empty())
     {
         OIC_LOG_V(INFO, LOG_TAG, "deviceId: %d, heatSetpoint: %f, coolSetpoint: %f, targetTemp: %f",
               thermostat.devInfo.deviceId, thermostat.heatSetpointF, thermostat.coolSetpointF,
@@ -230,7 +229,7 @@ void dump_details(const THERMOSTAT &thermostat, const char *description)
     else
     {
         OIC_LOG_V(INFO, LOG_TAG, "%s - deviceId: %d, heatSetpoint: %f, coolSetpoint: %f, targetTemp: %f",
-              description, thermostat.devInfo.deviceId, thermostat.heatSetpointF,
+              description.c_str(), thermostat.devInfo.deviceId, thermostat.heatSetpointF,
               thermostat.coolSetpointF, thermostat.targetTempF);
     }
     (void)thermostat;
index 4a5c5e7..7957769 100644 (file)
@@ -98,7 +98,7 @@ struct THERMOSTAT
     int cloudIndex;                 // index of device in array returned by server
 };
 
-void dump_details(const THERMOSTAT &thermostat, const char *description);
+void dump_details(const THERMOSTAT &thermostat, const std::string &description);
 
 std::string hvacModeToString(const HVAC_MODE &hvacMode);
 
@@ -148,7 +148,7 @@ public:
         return m_changeableValues;
     }
 
-    void buildDeviceUri(const char *baseUri = NULL);
+    void buildDeviceUri(const std::string &);
 
     std::string getDeviceUri()
     {