Преглед изворни кода

upgrade sdk core:
supported json param;
change the way of include Utils.h;

wb-hx510875 пре 7 година
родитељ
комит
08faebee0d

+ 1 - 1
core/CMakeLists.txt

@@ -59,6 +59,7 @@ set(core_public_header
 	include/alibabacloud/core/SimpleCredentialsProvider.h
 	include/alibabacloud/core/StsAssumeRoleCredentialsProvider.h
 	include/alibabacloud/core/Url.h
+	include/alibabacloud/core/Utils.h
 	)
 
 set(core_public_header_location
@@ -120,7 +121,6 @@ set(core_src
 	src/SimpleCredentialsProvider.cc
 	src/StsAssumeRoleCredentialsProvider.cc
 	src/Url.cc
-	src/Utils.h
 	src/Utils.cc
 	src/location/LocationClient.cc
 	src/location/LocationRequest.cc

+ 13 - 13
core/include/alibabacloud/core/ServiceRequest.h

@@ -17,21 +17,21 @@
 #ifndef CORE_INCLUDE_ALIBABACLOUD_CORE_SERVICEREQUEST_H_
 #define CORE_INCLUDE_ALIBABACLOUD_CORE_SERVICEREQUEST_H_
 
-#include <map>
 #include "CoreExport.h"
 #include "Url.h"
+#include <map>
 #include <string>
 
 namespace AlibabaCloud {
 class ALIBABACLOUD_CORE_EXPORT ServiceRequest {
- public:
+public:
   typedef std::string ParameterNameType;
   typedef std::string ParameterValueType;
   typedef std::map<ParameterNameType, ParameterValueType> ParameterCollection;
 
   virtual ~ServiceRequest();
 
-  const char* content() const;
+  const char *content() const;
   size_t contentSize() const;
   bool hasContent() const;
   ParameterCollection parameters() const;
@@ -44,33 +44,33 @@ class ALIBABACLOUD_CORE_EXPORT ServiceRequest {
   void setConnectTimeout(const long connectTimeout);
   void setReadTimeout(const long readTimeout);
 
- protected:
+protected:
   ServiceRequest(const std::string &product, const std::string &version);
   ServiceRequest(const ServiceRequest &other);
   ServiceRequest(ServiceRequest &&other);
-  ServiceRequest& operator=(const ServiceRequest &other);
-  ServiceRequest& operator=(ServiceRequest &&other);
+  ServiceRequest &operator=(const ServiceRequest &other);
+  ServiceRequest &operator=(ServiceRequest &&other);
 
   void addParameter(const ParameterNameType &name,
-    const ParameterValueType &value);
+                    const ParameterValueType &value);
   ParameterValueType parameter(const ParameterNameType &name) const;
   ParameterValueType coreParameter(const ParameterNameType &name) const;
   void removeParameter(const ParameterNameType &name);
   void setContent(const char *data, size_t size);
   void setParameter(const ParameterNameType &name,
-      const ParameterValueType &value);
+                    const ParameterValueType &value);
 
   void setCoreParameter(const ParameterNameType &name,
-      const ParameterValueType &value);
-
+                        const ParameterValueType &value);
 
   void setParameters(const ParameterCollection &params);
+  void setJsonParameters(const ParameterNameType &name, const ParameterCollection &params);
   void setResourcePath(const std::string &path);
   void setProduct(const std::string &product);
   void setVersion(const std::string &version);
   void setScheme(const std::string scheme);
 
- private:
+private:
   char *content_;
   size_t contentSize_;
   ParameterCollection params_;
@@ -81,6 +81,6 @@ class ALIBABACLOUD_CORE_EXPORT ServiceRequest {
   long connectTimeout_;
   long readTimeout_;
 };
-}  // namespace AlibabaCloud
+} // namespace AlibabaCloud
 
-#endif  // CORE_INCLUDE_ALIBABACLOUD_CORE_SERVICEREQUEST_H_
+#endif // CORE_INCLUDE_ALIBABACLOUD_CORE_SERVICEREQUEST_H_

+ 14 - 9
core/src/Utils.h → core/include/alibabacloud/core/Utils.h

@@ -17,22 +17,27 @@
 #ifndef CORE_SRC_UTILS_H_
 #define CORE_SRC_UTILS_H_
 
-#include <alibabacloud/core/HttpRequest.h>
 #include <alibabacloud/core/HttpMessage.h>
-#include <string>
+#include <alibabacloud/core/HttpRequest.h>
+#include <json/json.h>
 #include <map>
+#include <string>
 
-namespace AlibabaCloud {
+namespace AlibabaCloud
+{
 std::string ComputeContentMD5(const char *data, size_t size);
 std::string GenerateUuid();
 std::string HttpMethodToString(HttpRequest::Method method);
-void StringReplace(std::string &src,
-  const std::string &s1, const std::string &s2);
+void StringReplace(std::string &src, const std::string &s1,
+                   const std::string &s2);
 std::string UrlEncode(const std::string &src);
 std::string UrlDecode(const std::string &src);
-std::string canonicalizedQuery(const std::map <std::string,
-  std::string> &params);
+std::string
+canonicalizedQuery(const std::map<std::string, std::string> &params);
 std::string canonicalizedHeaders(const HttpMessage::HeaderCollection &headers);
 std::string GetEnv(const std::string env);
-}  // namespace AlibabaCloud
-#endif  // CORE_SRC_UTILS_H_
+Json::Value ReadJson(const std::string str);
+std::string MapToJson(const std::map<std::string, std::string> &maps);
+std::map<std::string, std::string> JsonToMap(const std::string &json);
+} // namespace AlibabaCloud
+#endif // CORE_SRC_UTILS_H_

+ 14 - 10
core/src/AsyncCallerContext.cc

@@ -15,27 +15,31 @@
  */
 
 #include <alibabacloud/core/AsyncCallerContext.h>
-#include "Utils.h"
+#include <alibabacloud/core/Utils.h>
 
-namespace AlibabaCloud {
+namespace AlibabaCloud
+{
 
-AsyncCallerContext::AsyncCallerContext() :
-  uuid_(GenerateUuid()) {
+AsyncCallerContext::AsyncCallerContext() : uuid_(GenerateUuid())
+{
 }
 
-AsyncCallerContext::AsyncCallerContext(const std::string &uuid) :
-  uuid_(uuid) {
+AsyncCallerContext::AsyncCallerContext(const std::string &uuid) : uuid_(uuid)
+{
 }
 
-AsyncCallerContext::~AsyncCallerContext() {
+AsyncCallerContext::~AsyncCallerContext()
+{
 }
 
-std::string AsyncCallerContext::uuid()const {
+std::string AsyncCallerContext::uuid() const
+{
   return uuid_;
 }
 
-void AsyncCallerContext::setUuid(const std::string &uuid) {
+void AsyncCallerContext::setUuid(const std::string &uuid)
+{
   uuid_ = uuid;
 }
 
-}  // namespace AlibabaCloud
+} // namespace AlibabaCloud

+ 119 - 80
core/src/CommonClient.cc

@@ -23,54 +23,59 @@
 #include <iomanip>
 #include <sstream>
 
-#include "Utils.h"
+#include <alibabacloud/core/Utils.h>
 
-namespace AlibabaCloud {
+namespace AlibabaCloud
+{
 
-namespace {
-  const std::string SERVICE_NAME = "Common";
+namespace
+{
+const std::string SERVICE_NAME = "Common";
 }
 
 CommonClient::CommonClient(const Credentials &credentials,
-  const ClientConfiguration &configuration) :
-  CoreClient(SERVICE_NAME, configuration),
-  credentialsProvider_(
-    std::make_shared<SimpleCredentialsProvider>(credentials)),
-  signer_(std::make_shared<HmacSha1Signer>()) {
+                           const ClientConfiguration &configuration) : CoreClient(SERVICE_NAME, configuration),
+                                                                       credentialsProvider_(
+                                                                           std::make_shared<SimpleCredentialsProvider>(credentials)),
+                                                                       signer_(std::make_shared<HmacSha1Signer>())
+{
 }
 
 CommonClient::CommonClient(
-  const std::shared_ptr<CredentialsProvider>& credentialsProvider,
-  const ClientConfiguration & configuration) :
-  CoreClient(SERVICE_NAME, configuration),
-  credentialsProvider_(credentialsProvider),
-  signer_(std::make_shared<HmacSha1Signer>()) {
+    const std::shared_ptr<CredentialsProvider> &credentialsProvider,
+    const ClientConfiguration &configuration) : CoreClient(SERVICE_NAME, configuration),
+                                                credentialsProvider_(credentialsProvider),
+                                                signer_(std::make_shared<HmacSha1Signer>())
+{
 }
 
-CommonClient::CommonClient(const std::string & accessKeyId,
-  const std::string & accessKeySecret,
-  const ClientConfiguration & configuration) :
-  CoreClient(SERVICE_NAME, configuration),
-  credentialsProvider_(std::make_shared<SimpleCredentialsProvider>(accessKeyId,
-    accessKeySecret)),
-  signer_(std::make_shared<HmacSha1Signer>()) {
+CommonClient::CommonClient(const std::string &accessKeyId,
+                           const std::string &accessKeySecret,
+                           const ClientConfiguration &configuration) : CoreClient(SERVICE_NAME, configuration),
+                                                                       credentialsProvider_(std::make_shared<SimpleCredentialsProvider>(accessKeyId,
+                                                                                                                                        accessKeySecret)),
+                                                                       signer_(std::make_shared<HmacSha1Signer>())
+{
 }
 
-CommonClient::~CommonClient() {
+CommonClient::~CommonClient()
+{
 }
 
 CommonClient::JsonOutcome CommonClient::makeRequest(const std::string &endpoint,
-  const CommonRequest &msg, HttpRequest::Method method)const {
+                                                    const CommonRequest &msg, HttpRequest::Method method) const
+{
   auto outcome = AttemptRequest(endpoint, msg, method);
   if (outcome.isSuccess())
     return JsonOutcome(std::string(outcome.result().body(),
-      outcome.result().bodySize()));
+                                   outcome.result().bodySize()));
   else
     return JsonOutcome(outcome.error());
 }
 
 CommonClient::CommonResponseOutcome CommonClient::commonResponse(
-  const CommonRequest & request) const {
+    const CommonRequest &request) const
+{
   auto outcome = makeRequest(request.domain(), request, request.httpMethod());
   if (outcome.isSuccess())
     return CommonResponseOutcome(CommonResponse(outcome.result()));
@@ -78,9 +83,10 @@ CommonClient::CommonResponseOutcome CommonClient::commonResponse(
     return CommonResponseOutcome(Error(outcome.error()));
 }
 
-void CommonClient::commonResponseAsync(const CommonRequest & request,
-  const CommonResponseAsyncHandler & handler,
-  const std::shared_ptr<const AsyncCallerContext>& context) const {
+void CommonClient::commonResponseAsync(const CommonRequest &request,
+                                       const CommonResponseAsyncHandler &handler,
+                                       const std::shared_ptr<const AsyncCallerContext> &context) const
+{
   auto fn = [this, request, handler, context]() {
     handler(this, request, commonResponse(request), context);
   };
@@ -89,53 +95,63 @@ void CommonClient::commonResponseAsync(const CommonRequest & request,
 }
 
 CommonClient::CommonResponseOutcomeCallable
-CommonClient::commonResponseCallable(const CommonRequest & request) const {
+CommonClient::commonResponseCallable(const CommonRequest &request) const
+{
   auto task = std::make_shared<std::packaged_task<CommonResponseOutcome()>>(
-    [this, request]() {
-    return this->commonResponse(request);
-  });
+      [this, request]() {
+        return this->commonResponse(request);
+      });
 
   asyncExecute(new Runnable([task]() { (*task)(); }));
   return task->get_future();
 }
 
-HttpRequest CommonClient::buildHttpRequest(const std::string & endpoint,
-  const ServiceRequest & msg, HttpRequest::Method method) const {
+HttpRequest CommonClient::buildHttpRequest(const std::string &endpoint,
+                                           const ServiceRequest &msg, HttpRequest::Method method) const
+{
   return buildHttpRequest(endpoint,
-    dynamic_cast<const CommonRequest& >(msg), method);
+                          dynamic_cast<const CommonRequest &>(msg), method);
 }
 
-HttpRequest CommonClient::buildHttpRequest(const std::string & endpoint,
-  const CommonRequest &msg, HttpRequest::Method method) const {
+HttpRequest CommonClient::buildHttpRequest(const std::string &endpoint,
+                                           const CommonRequest &msg, HttpRequest::Method method) const
+{
   if (msg.requestPattern() == CommonRequest::RpcPattern)
     return buildRpcHttpRequest(endpoint, msg, method);
   else
     return buildRoaHttpRequest(endpoint, msg, method);
 }
 
-HttpRequest CommonClient::buildRoaHttpRequest(const std::string & endpoint,
-  const CommonRequest &msg, HttpRequest::Method method) const {
+HttpRequest CommonClient::buildRoaHttpRequest(const std::string &endpoint,
+                                              const CommonRequest &msg, HttpRequest::Method method) const
+{
   const Credentials credentials = credentialsProvider_->getCredentials();
 
   Url url;
-  if (msg.scheme().empty()) {
+  if (msg.scheme().empty())
+  {
     url.setScheme("https");
-  } else {
+  }
+  else
+  {
     url.setScheme(msg.scheme());
   }
   url.setHost(endpoint);
   url.setPath(msg.resourcePath());
 
   auto params = msg.headerParameters();
-  std::map <std::string, std::string> queryParams;
-  for (const auto &p : params) {
+  std::map<std::string, std::string> queryParams;
+  for (const auto &p : params)
+  {
     if (!p.second.empty())
       queryParams[p.first] = p.second;
   }
 
-  if (!queryParams.empty()) {
+  if (!queryParams.empty())
+  {
     std::stringstream queryString;
-    for (const auto &p : queryParams) {
+    for (const auto &p : queryParams)
+    {
       if (p.second.empty())
         queryString << "&" << p.first;
       else
@@ -147,34 +163,46 @@ HttpRequest CommonClient::buildRoaHttpRequest(const std::string & endpoint,
   HttpRequest request(url);
   request.setMethod(method);
 
-  if (msg.connectTimeout() != kInvalidTimeout) {
+  if (msg.connectTimeout() != kInvalidTimeout)
+  {
     request.setConnectTimeout(msg.connectTimeout());
-  } else {
+  }
+  else
+  {
     request.setConnectTimeout(configuration().connectTimeout());
   }
 
-  if (msg.readTimeout() != kInvalidTimeout) {
+  if (msg.readTimeout() != kInvalidTimeout)
+  {
     request.setReadTimeout(msg.readTimeout());
-  } else {
+  }
+  else
+  {
     request.setReadTimeout(configuration().readTimeout());
   }
 
-  if (msg.headerParameter("Accept").empty()) {
+  if (msg.headerParameter("Accept").empty())
+  {
     request.setHeader("Accept", "application/json");
-  } else {
+  }
+  else
+  {
     request.setHeader("Accept", msg.headerParameter("Accept"));
   }
 
   std::stringstream ss;
   ss << msg.contentSize();
   request.setHeader("Content-Length", ss.str());
-  if (msg.headerParameter("Content-Type").empty()) {
+  if (msg.headerParameter("Content-Type").empty())
+  {
     request.setHeader("Content-Type", "application/octet-stream");
-  } else {
+  }
+  else
+  {
     request.setHeader("Content-Type", msg.headerParameter("Content-Type"));
   }
   request.setHeader("Content-MD5",
-    ComputeContentMD5(msg.content(), msg.contentSize()));
+                    ComputeContentMD5(msg.content(), msg.contentSize()));
   request.setBody(msg.content(), msg.contentSize());
 
   std::time_t t = std::time(nullptr);
@@ -189,7 +217,7 @@ HttpRequest CommonClient::buildRoaHttpRequest(const std::string & endpoint,
   request.setHeader("Date", date.str());
   request.setHeader("Host", url.host());
   request.setHeader("x-sdk-client",
-    std::string("CPP/").append(ALIBABACLOUD_VERSION_STR));
+                    std::string("CPP/").append(ALIBABACLOUD_VERSION_STR));
   request.setHeader("x-acs-region-id", configuration().regionId());
   if (!credentials.sessionToken().empty())
     request.setHeader("x-acs-security-token", credentials.sessionToken());
@@ -200,11 +228,11 @@ HttpRequest CommonClient::buildRoaHttpRequest(const std::string & endpoint,
 
   std::stringstream plaintext;
   plaintext << HttpMethodToString(method) << "\n"
-    << request.header("Accept") << "\n"
-    << request.header("Content-MD5") << "\n"
-    << request.header("Content-Type") << "\n"
-    << request.header("Date") << "\n"
-    << canonicalizedHeaders(request.headers());
+            << request.header("Accept") << "\n"
+            << request.header("Content-MD5") << "\n"
+            << request.header("Content-Type") << "\n"
+            << request.header("Date") << "\n"
+            << canonicalizedHeaders(request.headers());
   if (!url.hasQuery())
     plaintext << url.path();
   else
@@ -212,29 +240,34 @@ HttpRequest CommonClient::buildRoaHttpRequest(const std::string & endpoint,
 
   std::stringstream sign;
   sign << "acs "
-    << credentials.accessKeyId()
-    << ":"
-    << signer_->generate(plaintext.str(), credentials.accessKeySecret());
+       << credentials.accessKeyId()
+       << ":"
+       << signer_->generate(plaintext.str(), credentials.accessKeySecret());
   request.setHeader("Authorization", sign.str());
   return request;
 }
 
-HttpRequest CommonClient::buildRpcHttpRequest(const std::string & endpoint,
-  const CommonRequest &msg, HttpRequest::Method method) const {
+HttpRequest CommonClient::buildRpcHttpRequest(const std::string &endpoint,
+                                              const CommonRequest &msg, HttpRequest::Method method) const
+{
   const Credentials credentials = credentialsProvider_->getCredentials();
 
   Url url;
-  if (msg.scheme().empty()) {
+  if (msg.scheme().empty())
+  {
     url.setScheme("https");
-  } else {
+  }
+  else
+  {
     url.setScheme(msg.scheme());
   }
   url.setHost(endpoint);
   url.setPath(msg.resourcePath());
 
   auto params = msg.queryParameters();
-  std::map <std::string, std::string> queryParams;
-  for (const auto &p : params) {
+  std::map<std::string, std::string> queryParams;
+  for (const auto &p : params)
+  {
     if (!p.second.empty())
       queryParams[p.first] = p.second;
   }
@@ -260,13 +293,13 @@ HttpRequest CommonClient::buildRpcHttpRequest(const std::string & endpoint,
 
   std::stringstream plaintext;
   plaintext << HttpMethodToString(method)
-    << "&"
-    << UrlEncode(url.path())
-    << "&"
-    << UrlEncode(canonicalizedQuery(queryParams));
+            << "&"
+            << UrlEncode(url.path())
+            << "&"
+            << UrlEncode(canonicalizedQuery(queryParams));
 
   queryParams["Signature"] = signer_->generate(plaintext.str(),
-    credentials.accessKeySecret() + "&");
+                                               credentials.accessKeySecret() + "&");
 
   std::stringstream queryString;
   for (const auto &p : queryParams)
@@ -274,23 +307,29 @@ HttpRequest CommonClient::buildRpcHttpRequest(const std::string & endpoint,
   url.setQuery(queryString.str().substr(1));
 
   HttpRequest request(url);
-  if (msg.connectTimeout() != kInvalidTimeout) {
+  if (msg.connectTimeout() != kInvalidTimeout)
+  {
     request.setConnectTimeout(msg.connectTimeout());
-  } else {
+  }
+  else
+  {
     request.setConnectTimeout(configuration().connectTimeout());
   }
 
-  if (msg.readTimeout() != kInvalidTimeout) {
+  if (msg.readTimeout() != kInvalidTimeout)
+  {
     request.setReadTimeout(msg.readTimeout());
-  } else {
+  }
+  else
+  {
     request.setReadTimeout(configuration().readTimeout());
   }
 
   request.setMethod(method);
   request.setHeader("Host", url.host());
   request.setHeader("x-sdk-client",
-    std::string("CPP/").append(ALIBABACLOUD_VERSION_STR));
+                    std::string("CPP/").append(ALIBABACLOUD_VERSION_STR));
   return request;
 }
 
-}  // namespace AlibabaCloud
+} // namespace AlibabaCloud

+ 28 - 28
core/src/CoreClient.cc

@@ -14,11 +14,12 @@
  * limitations under the License.
  */
 
-#include <alibabacloud/core/CoreClient.h>
-#include <json/json.h>
-#include <alibabacloud/core/Signer.h>
 #include "CurlHttpClient.h"
 #include "Executor.h"
+#include <alibabacloud/core/Utils.h>
+#include <alibabacloud/core/CoreClient.h>
+#include <alibabacloud/core/Signer.h>
+#include <json/json.h>
 
 /*!
  * \class AlibabaCloud::CoreClient CoreClient.h <alibabacloud/core/CoreClient.h>
@@ -27,33 +28,27 @@
 
 namespace AlibabaCloud {
 
-CoreClient::CoreClient(const std::string & servicename,
-  const ClientConfiguration &configuration) :
-  serviceName_(servicename),
-  configuration_(configuration),
-  httpClient_(new CurlHttpClient) {
+CoreClient::CoreClient(const std::string &servicename,
+                       const ClientConfiguration &configuration)
+    : serviceName_(servicename), configuration_(configuration),
+      httpClient_(new CurlHttpClient) {
   httpClient_->setProxy(configuration.proxy());
 }
 
-CoreClient::~CoreClient() {
-  delete httpClient_;
-}
+CoreClient::~CoreClient() { delete httpClient_; }
 
-ClientConfiguration CoreClient::configuration()const {
-  return configuration_;
-}
+ClientConfiguration CoreClient::configuration() const { return configuration_; }
 
-std::string CoreClient::serviceName()const {
-  return serviceName_;
-}
+std::string CoreClient::serviceName() const { return serviceName_; }
 
-void CoreClient::asyncExecute(Runnable * r)const {
+void CoreClient::asyncExecute(Runnable *r) const {
   Executor::instance()->execute(r);
 }
 
-HttpClient::HttpResponseOutcome CoreClient::AttemptRequest(
-  const std::string & endpoint,
-  const ServiceRequest & request, HttpRequest::Method method) const {
+HttpClient::HttpResponseOutcome
+CoreClient::AttemptRequest(const std::string &endpoint,
+                           const ServiceRequest &request,
+                           HttpRequest::Method method) const {
   auto r = buildHttpRequest(endpoint, request, method);
   auto outcome = httpClient_->makeRequest(r);
   if (!outcome.isSuccess())
@@ -64,13 +59,17 @@ HttpClient::HttpResponseOutcome CoreClient::AttemptRequest(
     return outcome;
 }
 
-Error CoreClient::buildCoreError(const HttpResponse &response)const {
+Error CoreClient::buildCoreError(const HttpResponse &response) const {
   Json::Reader reader;
   Json::Value value;
-  if (!reader.parse(std::string(response.body(), response.bodySize()), value)) {
-    if (response.bodySize() > 0) {
+  if (!reader.parse(std::string(response.body(), response.bodySize()), value))
+  {
+    if (response.bodySize() > 0)
+    {
       return Error("InvalidResponse", response.body());
-    } else {
+    }
+    else
+    {
       return Error("InvalidResponse", "body is empty");
     }
   }
@@ -80,14 +79,15 @@ Error CoreClient::buildCoreError(const HttpResponse &response)const {
   error.setErrorMessage(value["Message"].asString());
   error.setHost(value["HostId"].asString());
   error.setRequestId(value["RequestId"].asString());
-  if (value["Code"].asString().empty() || value["Message"].asString().empty()) {
+  if (value["Code"].asString().empty() || value["Message"].asString().empty())
+  {
     error.setDetail(std::string(response.body()));
   }
   return error;
 }
 
-bool CoreClient::hasResponseError(const HttpResponse &response)const {
+bool CoreClient::hasResponseError(const HttpResponse &response) const {
   return response.statusCode() < 200 || response.statusCode() > 299;
 }
 
-}  // namespace AlibabaCloud
+} // namespace AlibabaCloud

+ 1 - 1
core/src/CurlHttpClient.cc

@@ -15,7 +15,7 @@
  */
 
 #include "CurlHttpClient.h"
-#include "Utils.h"
+#include <alibabacloud/core/Utils.h>
 #include <cassert>
 #include <sstream>
 #include <string>

+ 134 - 109
core/src/EndpointProvider.cc

@@ -1,38 +1,42 @@
 /*
-* Copyright 1999-2019 Alibaba Cloud All rights reserved.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*      http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
+ * Copyright 1999-2019 Alibaba Cloud All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 
+#include <algorithm>
 #include <alibabacloud/core/EndpointProvider.h>
-#include <json/json.h>
 #include <iomanip>
+#include <json/json.h>
 #include <sstream>
-#include <algorithm>
+
 #ifndef WIN32
 #include "LocalEndpoints.h"
+#include <alibabacloud/core/Utils.h>
 #else
 #include "LocalEndpointsForWindows.h"
 #endif
 
-namespace AlibabaCloud {
+namespace AlibabaCloud
+{
 
-namespace {
+namespace
+{
 #if defined(WIN32) && defined(_MSC_VER)
-#  define strcasecmp _stricmp
-#  define strncasecmp _strnicmp
+#define strcasecmp _stricmp
+#define strncasecmp _strnicmp
 #else
-#  include <strings.h>
+#include <strings.h>
 #endif
 
 bool local_endpoints_loaded = false;
@@ -42,7 +46,8 @@ typedef std::string endpointType;
 typedef std::string mappingType;
 typedef std::vector<regionType> regionsType;
 typedef std::map<productType, endpointType> regionalType;
-typedef struct {
+typedef struct
+{
   regionsType regions;
   regionalType regional;
 } productInfoType;
@@ -51,172 +56,192 @@ static std::vector<regionType> allRegions;
 static std::vector<productType> allProductsInLocalEndpoints;
 static std::map<productType, productInfoType> allLocalEndpoints;
 
-static void LoadLocalEndpoints() {
+static void LoadLocalEndpoints()
+{
   Json::Reader reader;
   Json::Value value;
-
-  if (local_endpoints_loaded) {
+  if (local_endpoints_loaded)
+  {
     return;
   }
 
 #ifdef WIN32
   std::string LOCAL_ENDPOINTS_CONFIG = WIN_LOCAL_ENDPOINTS_CONFIG_1 +
-    WIN_LOCAL_ENDPOINTS_CONFIG_2 + WIN_LOCAL_ENDPOINTS_CONFIG_3;
+                                       WIN_LOCAL_ENDPOINTS_CONFIG_2 +
+                                       WIN_LOCAL_ENDPOINTS_CONFIG_3;
 #endif
 
-  if (!reader.parse(LOCAL_ENDPOINTS_CONFIG, value)){
-    return;
-  }
-
-  auto regions = value["regions"];
-  for (const auto &region : regions) {
-    allRegions.push_back(region.asString());
-  }
-
-  auto products = value["products"];
-  for (const auto &product : products) {
-    allProductsInLocalEndpoints.push_back(product.asString());
-  }
-
-  auto endpoints = value["endpoints"];
-  for (auto &product : allProductsInLocalEndpoints ) {
-    auto endpoint_per_product = endpoints[product];
-    productInfoType p;
+  try
+  {
+    if (!reader.parse(LOCAL_ENDPOINTS_CONFIG, value))
+    {
+      return;
+    }
+    
+    auto regions = value["regions"];
+    for (const auto &region : regions)
+    {
+      allRegions.push_back(region.asString());
+    }
 
-    auto regions = endpoint_per_product["regions"];
-    auto regional = endpoint_per_product["regional"];
+    auto products = value["products"];
+    for (const auto &product : products)
+    {
+      allProductsInLocalEndpoints.push_back(product.asString());
+    }
 
-    for (auto & r : regions) {
-      const std::string region = r.asString();
-      p.regions.push_back(region);
-      p.regional[region] = endpoint_per_product["regional"][region].asString();
+    auto endpoints = value["endpoints"];
+    for (auto &product : allProductsInLocalEndpoints)
+    {
+      auto endpoint_per_product = endpoints[product];
+      productInfoType p;
+
+      auto regions = endpoint_per_product["regions"];
+      auto regional = endpoint_per_product["regional"];
+
+      for (auto &r : regions)
+      {
+        const std::string region = r.asString();
+        p.regions.push_back(region);
+        p.regional[region] =
+            endpoint_per_product["regional"][region].asString();
+      }
+      allLocalEndpoints[product] = p;
     }
-    allLocalEndpoints[product] = p;
+    local_endpoints_loaded = true;
+  }
+  catch (JSONCPP_STRING errs)
+  {
+    return;
   }
-  local_endpoints_loaded = true;
 }
 
-}  // namespace
+} // namespace
 
 EndpointProvider::EndpointProvider(
-  const std::shared_ptr<Location::LocationClient>& locationClient,
-  const std::string regionId,
-  const std::string product,
-  const std::string serviceCode, int durationSeconds) :
-  LocationClient(locationClient),
-  regionId_(regionId),
-  product_(product),
-  serviceCode_(serviceCode),
-  durationSeconds_(durationSeconds),
-  cachedMutex_(),
-  cachedEndpoint_(),
-  expiry_() {
+    const std::shared_ptr<Location::LocationClient> &locationClient,
+    const std::string regionId, const std::string product,
+    const std::string serviceCode, int durationSeconds)
+    : LocationClient(locationClient), regionId_(regionId), product_(product),
+      serviceCode_(serviceCode), durationSeconds_(durationSeconds),
+      cachedMutex_(), cachedEndpoint_(), expiry_()
+{
   transform(product_.begin(), product_.end(), product_.begin(), ::tolower);
   loadLocalProductsInfo();
 }
 
-EndpointProvider::EndpointProvider(
-    const Credentials& credentials,
-    const ClientConfiguration &configuration,
-    const std::string &regionId,
-    const std::string &product,
-    const std::string &serviceCode,
-    int durationSeconds) :
-  LocationClient(credentials, configuration),
-  regionId_(regionId),
-  product_(product),
-  serviceCode_(serviceCode),
-  durationSeconds_(durationSeconds),
-  cachedMutex_(),
-  cachedEndpoint_(),
-  expiry_() {
+EndpointProvider::EndpointProvider(const Credentials &credentials,
+                                   const ClientConfiguration &configuration,
+                                   const std::string &regionId,
+                                   const std::string &product,
+                                   const std::string &serviceCode,
+                                   int durationSeconds)
+    : LocationClient(credentials, configuration), regionId_(regionId),
+      product_(product), serviceCode_(serviceCode),
+      durationSeconds_(durationSeconds), cachedMutex_(), cachedEndpoint_(),
+      expiry_()
+{
   transform(product_.begin(), product_.end(), product_.begin(), ::tolower);
   loadLocalProductsInfo();
 }
 
-EndpointProvider::~EndpointProvider() {
-}
+EndpointProvider::~EndpointProvider() {}
 
-
-bool EndpointProvider::loadLocalProductsInfo() {
+bool EndpointProvider::loadLocalProductsInfo()
+{
   LoadLocalEndpoints();
   return true;
 }
 
-std::string EndpointProvider::localEndpoint(
-  const std::string regionId, const std::string product) {
+std::string EndpointProvider::localEndpoint(const std::string regionId,
+                                            const std::string product)
+{
 
-  if (!local_endpoints_loaded) {
+  if (!local_endpoints_loaded)
+  {
     // impossible
     return std::string();
   }
 
   std::vector<regionType>::iterator allRegionsit;
   allRegionsit = std::find(allRegions.begin(), allRegions.end(), regionId);
-  if (allRegionsit == allRegions.end()) {
+  if (allRegionsit == allRegions.end())
+  {
     return std::string();
   }
 
   std::vector<productType>::iterator allProductsInLocalEndpointsit;
-  allProductsInLocalEndpointsit = std::find(allProductsInLocalEndpoints.begin(), allProductsInLocalEndpoints.end(), product);
-  if (allProductsInLocalEndpointsit == allProductsInLocalEndpoints.end()) {
+  allProductsInLocalEndpointsit =
+      std::find(allProductsInLocalEndpoints.begin(),
+                allProductsInLocalEndpoints.end(), product);
+  if (allProductsInLocalEndpointsit == allProductsInLocalEndpoints.end())
+  {
     return std::string();
   }
 
   std::vector<regionType> vec = allLocalEndpoints[product].regions;
   std::vector<regionType>::iterator it;
   it = std::find(vec.begin(), vec.end(), regionId);
-  if (it == vec.end()) {
+  if (it == vec.end())
+  {
     return std::string();
   }
   return allLocalEndpoints[product].regional[regionId];
 }
 
-
-bool EndpointProvider::checkExpiry()const {
+bool EndpointProvider::checkExpiry() const
+{
   auto now = std::chrono::system_clock::now();
   auto diff =
-  std::chrono::duration_cast<std::chrono::seconds>(now - expiry_).count();
+      std::chrono::duration_cast<std::chrono::seconds>(now - expiry_).count();
   return (diff > 0 - 60);
 }
 
-EndpointProvider::EndpointOutcome EndpointProvider::getEndpoint() {
+EndpointProvider::EndpointOutcome EndpointProvider::getEndpoint()
+{
   // 1st priority: user specified via configuration
-  if (!configuration().endpoint().empty()) {
+  if (!configuration().endpoint().empty())
+  {
     return EndpointOutcome(configuration().endpoint());
   }
 
   // 2nd priority: local configuration
   std::string endpoint = localEndpoint(regionId_, product_);
-  if (!endpoint.empty()) {
+  if (!endpoint.empty())
+  {
     return EndpointOutcome(endpoint);
   }
 
   // service code is mandatory for location service.
-  if (serviceCode_.empty()) {
+  if (serviceCode_.empty())
+  {
     return EndpointOutcome(
-      Error("InvalidRegionId",
-        "Product[" + product_ + "] at region[" +
-        regionId_ + "] does not exist."));
+        Error("InvalidRegionId", "Product[" + product_ + "] at region[" +
+                                     regionId_ + "] does not exist."));
   }
 
   // 3rd priority: request from location service
   EndpointOutcome outcome = loadRemoteEndpoint();
-  if (outcome.isSuccess()) {
+  if (outcome.isSuccess())
+  {
     return outcome;
   }
 
-  if (outcome.error().errorCode() == "Illegal Parameter") {
-    return EndpointOutcome(Error("InvalidProduct",
-      "Prodcut[" + serviceCode_ + "] does not exist."));
+  if (outcome.error().errorCode() == "Illegal Parameter")
+  {
+    return EndpointOutcome(Error("InvalidProduct", "Prodcut[" + serviceCode_ +
+                                                       "] does not exist."));
   }
   return outcome;
 }
 
-EndpointProvider::EndpointOutcome EndpointProvider::loadRemoteEndpoint() {
-  if (checkExpiry()) {
+EndpointProvider::EndpointOutcome EndpointProvider::loadRemoteEndpoint()
+{
+  if (checkExpiry())
+  {
     std::lock_guard<std::mutex> locker(cachedMutex_);
-    if (checkExpiry()) {
+    if (checkExpiry())
+    {
       Location::Model::DescribeEndpointsRequest request;
       request.setId(regionId_);
       request.setServiceCode(serviceCode_);
@@ -236,4 +261,4 @@ EndpointProvider::EndpointOutcome EndpointProvider::loadRemoteEndpoint() {
   return EndpointOutcome(cachedEndpoint_);
 }
 
-}  // namespace AlibabaCloud
+} // namespace AlibabaCloud

+ 29 - 28
core/src/InstanceProfileCredentialsProvider.cc

@@ -14,58 +14,59 @@
  * limitations under the License.
  */
 
-#include <alibabacloud/core/InstanceProfileCredentialsProvider.h>
-#include <json/json.h>
 #include "EcsMetadataFetcher.h"
+#include <alibabacloud/core/Utils.h>
+#include <alibabacloud/core/InstanceProfileCredentialsProvider.h>
 #include <chrono>
 #include <iomanip>
+#include <json/json.h>
 #include <mutex>
 #include <sstream>
 
-
-namespace AlibabaCloud {
+namespace AlibabaCloud
+{
 
 InstanceProfileCredentialsProvider::InstanceProfileCredentialsProvider(
-  const std::string & roleName, int durationSeconds):
-  CredentialsProvider(),
-  EcsMetadataFetcher(),
-  durationSeconds_(durationSeconds),
-  cachedMutex_(),
-  cachedCredentials_("", ""),
-  expiry_() {
+    const std::string &roleName, int durationSeconds)
+    : CredentialsProvider(), EcsMetadataFetcher(),
+      durationSeconds_(durationSeconds), cachedMutex_(),
+      cachedCredentials_("", ""), expiry_()
+{
   setRoleName(roleName);
 }
 
-InstanceProfileCredentialsProvider::~InstanceProfileCredentialsProvider() {
-}
+InstanceProfileCredentialsProvider::~InstanceProfileCredentialsProvider() {}
 
-Credentials InstanceProfileCredentialsProvider::getCredentials() {
+Credentials InstanceProfileCredentialsProvider::getCredentials()
+{
   loadCredentials();
   std::lock_guard<std::mutex> locker(cachedMutex_);
   return cachedCredentials_;
 }
 
-bool InstanceProfileCredentialsProvider::checkExpiry()const {
+bool InstanceProfileCredentialsProvider::checkExpiry() const
+{
   auto now = std::chrono::system_clock::now();
   auto diff =
-  std::chrono::duration_cast<std::chrono::seconds>(now - expiry_).count();
+      std::chrono::duration_cast<std::chrono::seconds>(now - expiry_).count();
 
   return (diff > 0 - 60);
 }
 
-void InstanceProfileCredentialsProvider::loadCredentials() {
-  if (checkExpiry()) {
+void InstanceProfileCredentialsProvider::loadCredentials()
+{
+  if (checkExpiry())
+  {
     std::lock_guard<std::mutex> locker(cachedMutex_);
-    if (checkExpiry()) {
+    if (checkExpiry())
+    {
       auto outcome = getMetadata();
       Json::Value value;
       Json::Reader reader;
-      if (reader.parse(outcome, value)) {
-        if (value["Code"].empty()
-          &&value["AccessKeyId"].empty()
-          &&value["AccessKeySecret"].empty()
-          &&value["SecurityToken"].empty()
-          &&value["Expiration"].empty()) {
+      if (reader.parse(outcome, value))
+      {
+        if (value["Code"].empty() && value["AccessKeyId"].empty() && value["AccessKeySecret"].empty() && value["SecurityToken"].empty() && value["Expiration"].empty())
+        {
           cachedCredentials_ = Credentials("", "");
           return;
         }
@@ -77,8 +78,8 @@ void InstanceProfileCredentialsProvider::loadCredentials() {
         auto expiration = value["Expiration"].asString();
 
         cachedCredentials_ = Credentials(accessKeyId,
-          accessKeySecret,
-          securityToken);
+                                         accessKeySecret,
+                                         securityToken);
 
         std::tm tm = {};
 #if defined(__GNUG__) && __GNUC__ < 5
@@ -93,4 +94,4 @@ void InstanceProfileCredentialsProvider::loadCredentials() {
   }
 }
 
-}  // namespace AlibabaCloud
+} // namespace AlibabaCloud

+ 1 - 1
core/src/RoaServiceClient.cc

@@ -20,7 +20,7 @@
 #include <algorithm>
 #include <iomanip>
 #include <sstream>
-#include "Utils.h"
+#include <alibabacloud/core/Utils.h>
 
 namespace AlibabaCloud {
 

+ 9 - 7
core/src/RoaServiceRequest.cc

@@ -18,16 +18,18 @@
 #include <algorithm>
 #include <iomanip>
 #include <sstream>
-#include "Utils.h"
+#include <alibabacloud/core/Utils.h>
 
-namespace AlibabaCloud {
+namespace AlibabaCloud
+{
 
-RoaServiceRequest::RoaServiceRequest(const std::string & product,
-  const std::string & version) :
-  ServiceRequest(product, version) {
+RoaServiceRequest::RoaServiceRequest(const std::string &product,
+                                     const std::string &version) : ServiceRequest(product, version)
+{
 }
 
-RoaServiceRequest::~RoaServiceRequest() {
+RoaServiceRequest::~RoaServiceRequest()
+{
 }
 
-}  // namespace AlibabaCloud
+} // namespace AlibabaCloud

+ 1 - 1
core/src/RpcServiceClient.cc

@@ -20,7 +20,7 @@
 #include <algorithm>
 #include <iomanip>
 #include <sstream>
-#include "Utils.h"
+#include <alibabacloud/core/Utils.h>
 
 namespace AlibabaCloud {
 

+ 95 - 58
core/src/ServiceRequest.cc

@@ -16,41 +16,46 @@
 
 #include <alibabacloud/core/ServiceRequest.h>
 #include <alibabacloud/core/AlibabaCloud.h>
+#include <alibabacloud/core/Utils.h>
 
-namespace AlibabaCloud {
+namespace AlibabaCloud
+{
 
 ServiceRequest::ServiceRequest(const std::string &product,
-  const std::string &version) :
-  content_(nullptr),
-  contentSize_(0),
-  params_(),
-  product_(product),
-  resourcePath_("/"),
-  version_(version),
-  scheme_("https"),
-  connectTimeout_(kInvalidTimeout),
-  readTimeout_(kInvalidTimeout) {
-}
-
-ServiceRequest::ServiceRequest(const ServiceRequest &other) :
-  content_(nullptr),
-  contentSize_(other.contentSize_),
-  params_(other.params_),
-  product_(other.product_),
-  resourcePath_(other.resourcePath_),
-  version_(other.version_),
-  scheme_(other.scheme_),
-  connectTimeout_(other.connectTimeout_),
-  readTimeout_(other.readTimeout_) {
+                               const std::string &version) : content_(nullptr),
+                                                             contentSize_(0),
+                                                             params_(),
+                                                             product_(product),
+                                                             resourcePath_("/"),
+                                                             version_(version),
+                                                             scheme_("https"),
+                                                             connectTimeout_(kInvalidTimeout),
+                                                             readTimeout_(kInvalidTimeout)
+{
+}
+
+ServiceRequest::ServiceRequest(const ServiceRequest &other) : content_(nullptr),
+                                                              contentSize_(other.contentSize_),
+                                                              params_(other.params_),
+                                                              product_(other.product_),
+                                                              resourcePath_(other.resourcePath_),
+                                                              version_(other.version_),
+                                                              scheme_(other.scheme_),
+                                                              connectTimeout_(other.connectTimeout_),
+                                                              readTimeout_(other.readTimeout_)
+{
   setContent(other.content_, other.contentSize_);
 }
 
-ServiceRequest::ServiceRequest(ServiceRequest &&other) {
+ServiceRequest::ServiceRequest(ServiceRequest &&other)
+{
   *this = std::move(other);
 }
 
-ServiceRequest& ServiceRequest::operator=(const ServiceRequest &other) {
-  if (this != &other) {
+ServiceRequest &ServiceRequest::operator=(const ServiceRequest &other)
+{
+  if (this != &other)
+  {
     content_ = nullptr;
     contentSize_ = 0;
     params_ = other.params_;
@@ -61,130 +66,162 @@ ServiceRequest& ServiceRequest::operator=(const ServiceRequest &other) {
   return *this;
 }
 
-ServiceRequest& ServiceRequest::operator=(ServiceRequest &&other) {
+ServiceRequest &ServiceRequest::operator=(ServiceRequest &&other)
+{
   if (this != &other)
     *this = std::move(other);
   return *this;
 }
 
-ServiceRequest::~ServiceRequest() {
+ServiceRequest::~ServiceRequest()
+{
   if (content_)
     delete content_;
 }
 
-const char * ServiceRequest::content() const {
+const char *ServiceRequest::content() const
+{
   return content_;
 }
 
-size_t ServiceRequest::contentSize() const {
+size_t ServiceRequest::contentSize() const
+{
   return contentSize_;
 }
 
-bool ServiceRequest::hasContent() const {
+bool ServiceRequest::hasContent() const
+{
   return (contentSize_ != 0);
 }
 
-void ServiceRequest::setContent(const char * data, size_t size) {
+void ServiceRequest::setContent(const char *data, size_t size)
+{
   if (content_)
     delete content_;
   content_ = nullptr;
   contentSize_ = 0;
-  if (size) {
+  if (size)
+  {
     contentSize_ = size;
     content_ = new char[size];
     std::copy(data, data + size, content_);
   }
 }
 
-void ServiceRequest::addParameter(const ParameterNameType & name,
-  const ParameterValueType & value) {
+void ServiceRequest::addParameter(const ParameterNameType &name,
+                                  const ParameterValueType &value)
+{
   setParameter(name, value);
 }
 
 ServiceRequest::ParameterValueType ServiceRequest::parameter(
-  const ParameterNameType &name)const {
+    const ParameterNameType &name) const
+{
   ParameterCollection::const_iterator it = params_.find(name);
-  if (it == params_.end()) {
+  if (it == params_.end())
+  {
     return ParameterValueType("");
   }
   return it->second;
 }
 
-
 ServiceRequest::ParameterValueType ServiceRequest::coreParameter(
-  const ParameterNameType &name)const {
+    const ParameterNameType &name) const
+{
   return parameter(name);
 }
 
-ServiceRequest::ParameterCollection ServiceRequest::parameters() const {
+ServiceRequest::ParameterCollection ServiceRequest::parameters() const
+{
   return params_;
 }
 
-void ServiceRequest::removeParameter(const ParameterNameType & name) {
+void ServiceRequest::removeParameter(const ParameterNameType &name)
+{
   params_.erase(name);
 }
 
 void ServiceRequest::setParameter(const ParameterNameType &name,
-  const ParameterValueType &value) {
+                                  const ParameterValueType &value)
+{
   params_[name] = value;
 }
 
-void ServiceRequest::setCoreParameter(const ParameterNameType &name,
-  const ParameterValueType &value) {
+void ServiceRequest::setCoreParameter(const ParameterNameType &name, const ParameterValueType &value)
+{
   setParameter(name, value);
 }
 
+void ServiceRequest::setParameters(const ParameterCollection &params)
+{
+  params_ = params;
+}
 
-void ServiceRequest::setParameters(const ParameterCollection & params) {
+void ServiceRequest::setJsonParameters(const ParameterNameType &name, const ParameterCollection &params)
+{
+  params_ = params;
   params_ = params;
+  setCoreParameter(name, AlibabaCloud::MapToJson(params));
 }
 
-std::string ServiceRequest::version()const {
+std::string ServiceRequest::version() const
+{
   return version_;
 }
 
-void ServiceRequest::setVersion(const std::string &version) {
+void ServiceRequest::setVersion(const std::string &version)
+{
   version_ = version;
 }
 
-std::string ServiceRequest::product() const {
+std::string ServiceRequest::product() const
+{
   return product_;
 }
 
-void ServiceRequest::setProduct(const std::string & product) {
+void ServiceRequest::setProduct(const std::string &product)
+{
   product_ = product;
 }
 
-std::string ServiceRequest::resourcePath() const {
+std::string ServiceRequest::resourcePath() const
+{
   return resourcePath_;
 }
 
-void ServiceRequest::setResourcePath(const std::string & path) {
+void ServiceRequest::setResourcePath(const std::string &path)
+{
   resourcePath_ = path;
 }
 
-void ServiceRequest::setScheme(const std::string scheme) {
+void ServiceRequest::setScheme(const std::string scheme)
+{
   scheme_ = scheme;
 }
 
-std::string ServiceRequest::scheme() const {
+std::string ServiceRequest::scheme() const
+{
   return scheme_;
 }
 
-long ServiceRequest::connectTimeout() const{
+long ServiceRequest::connectTimeout() const
+{
   return connectTimeout_;
 }
 
-long ServiceRequest::readTimeout() const{
+long ServiceRequest::readTimeout() const
+{
   return readTimeout_;
 }
 
-void ServiceRequest::setConnectTimeout(const long connectTimeout) {
+void ServiceRequest::setConnectTimeout(const long connectTimeout)
+{
   connectTimeout_ = connectTimeout;
 }
 
-void ServiceRequest::setReadTimeout(const long readTimeout) {
+void ServiceRequest::setReadTimeout(const long readTimeout)
+{
   readTimeout_ = readTimeout;
 }
 
-}  // namespace AlibabaCloud
+} // namespace AlibabaCloud

+ 135 - 34
core/src/Utils.cc

@@ -14,10 +14,11 @@
  * limitations under the License.
  */
 
-#include "Utils.h"
-#include <sstream>
 #include <algorithm>
+#include <sstream>
 #include <stdlib.h>
+#include <alibabacloud/core/Utils.h>
+
 #ifdef _WIN32
 #include <Windows.h>
 #else
@@ -26,15 +27,17 @@
 #include <uuid/uuid.h>
 #endif
 #include <curl/curl.h>
+#include <json/json.h>
 
-std::string AlibabaCloud::GenerateUuid() {
+std::string AlibabaCloud::GenerateUuid()
+{
 #ifdef _WIN32
   char *data;
   UUID uuidhandle;
   UuidCreate(&uuidhandle);
-  UuidToString(&uuidhandle, reinterpret_cast<RPC_CSTR*>(&data));
+  UuidToString(&uuidhandle, reinterpret_cast<RPC_CSTR *>(&data));
   std::string uuid(data);
-  RpcStringFree(reinterpret_cast<RPC_CSTR*>(&data));
+  RpcStringFree(reinterpret_cast<RPC_CSTR *>(&data));
   return uuid;
 #else
   uuid_t uu;
@@ -45,7 +48,8 @@ std::string AlibabaCloud::GenerateUuid() {
 #endif
 }
 
-std::string AlibabaCloud::UrlEncode(const std::string & src) {
+std::string AlibabaCloud::UrlEncode(const std::string &src)
+{
   CURL *curl = curl_easy_init();
   char *output = curl_easy_escape(curl, src.c_str(), src.size());
   std::string result(output);
@@ -54,7 +58,8 @@ std::string AlibabaCloud::UrlEncode(const std::string & src) {
   return result;
 }
 
-std::string AlibabaCloud::UrlDecode(const std::string & src) {
+std::string AlibabaCloud::UrlDecode(const std::string &src)
+{
   CURL *curl = curl_easy_init();
   int outlength = 0;
   char *output = curl_easy_unescape(curl, src.c_str(), src.size(), &outlength);
@@ -64,7 +69,8 @@ std::string AlibabaCloud::UrlDecode(const std::string & src) {
   return result;
 }
 
-std::string AlibabaCloud::ComputeContentMD5(const char * data, size_t size) {
+std::string AlibabaCloud::ComputeContentMD5(const char *data, size_t size)
+{
 #ifdef _WIN32
   HCRYPTPROV hProv = 0;
   HCRYPTHASH hHash = 0;
@@ -73,7 +79,7 @@ std::string AlibabaCloud::ComputeContentMD5(const char * data, size_t size) {
 
   CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
   CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash);
-  CryptHashData(hHash, (BYTE*)(data), size, 0);
+  CryptHashData(hHash, (BYTE *)(data), size, 0);
   CryptGetHashParam(hHash, HP_HASHVAL, pbHash, &dwDataLen, 0);
 
   CryptDestroyHash(hHash);
@@ -81,36 +87,41 @@ std::string AlibabaCloud::ComputeContentMD5(const char * data, size_t size) {
 
   DWORD dlen = 0;
   CryptBinaryToString(pbHash, dwDataLen,
-    CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, NULL, &dlen);
-  char* dest = new char[dlen];
-  CryptBinaryToString(pbHash,
-    dwDataLen, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, dest, &dlen);
+                      CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, NULL, &dlen);
+  char *dest = new char[dlen];
+  CryptBinaryToString(pbHash, dwDataLen,
+                      CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, dest, &dlen);
 
   std::string ret = std::string(dest, dlen);
   delete dest;
   return ret;
 #else
   unsigned char md[MD5_DIGEST_LENGTH];
-  MD5(reinterpret_cast<const unsigned char*>(data), size, (unsigned char*)&md);
+  MD5(reinterpret_cast<const unsigned char *>(data), size,
+      (unsigned char *)&md);
 
   char encodedData[100];
-  EVP_EncodeBlock(reinterpret_cast<unsigned char*>(encodedData),
-    md, MD5_DIGEST_LENGTH);
+  EVP_EncodeBlock(reinterpret_cast<unsigned char *>(encodedData), md,
+                  MD5_DIGEST_LENGTH);
   return encodedData;
 #endif
 }
 
-void AlibabaCloud::StringReplace(std::string & src,
-  const std::string & s1, const std::string & s2) {
+void AlibabaCloud::StringReplace(std::string &src, const std::string &s1,
+                                 const std::string &s2)
+{
   std::string::size_type pos = 0;
-  while ((pos = src.find(s1, pos)) != std::string::npos) {
+  while ((pos = src.find(s1, pos)) != std::string::npos)
+  {
     src.replace(pos, s1.length(), s2);
     pos += s2.length();
   }
 }
 
-std::string AlibabaCloud::HttpMethodToString(HttpRequest::Method method) {
-  switch (method) {
+std::string AlibabaCloud::HttpMethodToString(HttpRequest::Method method)
+{
+  switch (method)
+  {
   case HttpRequest::Method::Head:
     return "HEAD";
     break;
@@ -142,13 +153,15 @@ std::string AlibabaCloud::HttpMethodToString(HttpRequest::Method method) {
   }
 }
 
-std::string AlibabaCloud::canonicalizedQuery(const std::map<std::string,
-  std::string>& params) {
+std::string AlibabaCloud::canonicalizedQuery(
+    const std::map<std::string, std::string> &params)
+{
   if (params.empty())
     return std::string();
 
   std::stringstream ss;
-  for (const auto &p : params) {
+  for (const auto &p : params)
+  {
     std::string key = UrlEncode(p.first);
     StringReplace(key, "+", "%20");
     StringReplace(key, "*", "%2A");
@@ -163,9 +176,11 @@ std::string AlibabaCloud::canonicalizedQuery(const std::map<std::string,
 }
 
 std::string AlibabaCloud::canonicalizedHeaders(
-  const HttpMessage::HeaderCollection &headers) {
-  std::map <std::string, std::string> materials;
-  for (const auto &p : headers) {
+    const HttpMessage::HeaderCollection &headers)
+{
+  std::map<std::string, std::string> materials;
+  for (const auto &p : headers)
+  {
     std::string key = p.first;
     std::transform(key.begin(), key.end(), key.begin(), ::tolower);
     if (key.find("x-acs-") != 0)
@@ -188,25 +203,111 @@ std::string AlibabaCloud::canonicalizedHeaders(
   return ss.str();
 }
 
-std::string AlibabaCloud::GetEnv(const std::string env) {
+Json::Value AlibabaCloud::ReadJson(const std::string str)
+{
+  Json::CharReaderBuilder builder;
+  Json::CharReader *reader = builder.newCharReader();
+  Json::Value *val;
+  Json::Value value;
+  JSONCPP_STRING *errs;
+  reader->parse(str.data(), str.data() + str.size(), val, errs);
+  if (errs == NULL)
+  {
+    value = *val;
+    return value;
+  }
+  throw errs;
+}
+
+std::string AlibabaCloud::GetEnv(const std::string env)
+{
 #ifdef _WIN32
-  char* buf = nullptr;
+  char *buf = nullptr;
   size_t sz = 0;
-  if (_dupenv_s(&buf, &sz, env.c_str()) == 0 && buf != nullptr) {
+  if (_dupenv_s(&buf, &sz, env.c_str()) == 0 && buf != nullptr)
+  {
     std::string var(buf);
     free(buf);
     return var;
-  } else {
-    if (buf) {
+  }
+  else
+  {
+    if (buf)
+    {
       free(buf);
     }
     return std::string();
   }
 #else
-  char* var = getenv(env.c_str());
-  if (var) {
+  char *var = getenv(env.c_str());
+  if (var)
+  {
     return std::string(var);
   }
   return std::string();
 #endif
 }
+
+std::string AlibabaCloud::MapToJson(const std::map<std::string, std::string> &maps)
+{
+  Json::Value jsonObject;
+  for (std::map<std::string, std::string>::const_iterator iter = maps.begin(); iter != maps.end(); ++iter)
+  {
+    jsonObject[iter->first] = iter->second;
+  }
+  return jsonObject.toStyledString();
+}
+
+std::map<std::string, std::string> AlibabaCloud::JsonToMap(const std::string &json)
+{
+  Json::Reader reader;
+  Json::Value value;
+  std::map<std::string, std::string> maps;
+
+  if (json.length() > 0)
+  {
+    if (reader.parse(json, value))
+    {
+      Json::Value::Members members = value.getMemberNames();
+      for (Json::Value::Members::iterator it = members.begin(); it != members.end(); it++)
+      {
+        Json::ValueType vt = value[*it].type();
+        switch (vt)
+        {
+        case Json::stringValue:
+        {
+          maps.insert(std::pair<std::string, std::string>(*it, value[*it].asString()));
+          break;
+        }
+        case Json::intValue:
+        {
+          int inttmp = value[*it].asInt();
+          maps.insert(std::pair<std::string, std::string>(*it, std::to_string(inttmp)));
+          break;
+        }
+        case Json::arrayValue:
+        {
+          std::string strid;
+          for (unsigned int i = 0; i < value[*it].size(); i++)
+          {
+            strid += value[*it][i].asString();
+            strid += ",";
+          }
+          if (!strid.empty())
+          {
+            strid = strid.substr(0, strid.size() - 1);
+          }
+          maps.insert(std::pair<std::string, std::string>(*it, strid));
+          break;
+        }
+        default:
+        {
+          break;
+        }
+        }
+      }
+    }
+  }
+
+  return maps;
+}

+ 8 - 11
core/src/location/model/DescribeEndpointsResult.cc

@@ -14,18 +14,17 @@
  * limitations under the License.
  */
 
+#include <alibabacloud/core/Utils.h>
 #include <alibabacloud/core/location/model/DescribeEndpointsResult.h>
 #include <json/json.h>
 
 using namespace AlibabaCloud::Location;
 using namespace AlibabaCloud::Location::Model;
 
-DescribeEndpointsResult::DescribeEndpointsResult() :
-  ServiceResult() {
-}
+DescribeEndpointsResult::DescribeEndpointsResult() : ServiceResult() {}
 
-DescribeEndpointsResult::DescribeEndpointsResult(const std::string &payload) :
-  ServiceResult() {
+DescribeEndpointsResult::DescribeEndpointsResult(const std::string &payload)
+    : ServiceResult() {
   parse(payload);
 }
 
@@ -56,19 +55,17 @@ void DescribeEndpointsResult::parse(const std::string &payload) {
 }
 
 std::vector<DescribeEndpointsResult::Endpoint>
-  DescribeEndpointsResult::endpoints()const {
+DescribeEndpointsResult::endpoints() const {
   return endpoints_;
 }
 
 void DescribeEndpointsResult::setEndpoints(
-  const std::vector<Endpoint> & endpoints) {
+    const std::vector<Endpoint> &endpoints) {
   endpoints_ = endpoints;
 }
 
-bool DescribeEndpointsResult::success()const {
-  return success_;
-}
+bool DescribeEndpointsResult::success() const { return success_; }
 
-void DescribeEndpointsResult::setSuccess(const bool & success) {
+void DescribeEndpointsResult::setSuccess(const bool &success) {
   success_ = success;
 }

+ 29 - 30
core/src/sts/model/AssumeRoleResult.cc

@@ -1,50 +1,49 @@
 /*
-* Copyright 1999-2019 Alibaba Cloud All rights reserved.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*      http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
+ * Copyright 1999-2019 Alibaba Cloud All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <alibabacloud/core/Utils.h>
 #include <alibabacloud/core/sts/model/AssumeRoleResult.h>
 #include <json/json.h>
 
 using namespace AlibabaCloud::Sts;
 using namespace AlibabaCloud::Sts::Model;
 
-AssumeRoleResult::AssumeRoleResult() :
-  ServiceResult(),
-  assumedRoleUser_(),
-  credentials_() {
-}
+AssumeRoleResult::AssumeRoleResult()
+    : ServiceResult(), assumedRoleUser_(), credentials_() {}
 
-AssumeRoleResult::AssumeRoleResult(const std::string & payload) :
-  ServiceResult(),
-  assumedRoleUser_(),
-  credentials_() {
+AssumeRoleResult::AssumeRoleResult(const std::string &payload)
+    : ServiceResult(), assumedRoleUser_(), credentials_()
+{
   parse(payload);
 }
 
-AssumeRoleResult::~AssumeRoleResult() {
-}
+AssumeRoleResult::~AssumeRoleResult() {}
 
-AssumeRoleResult::AssumedRoleUser AssumeRoleResult::assumedRoleUser() const {
+AssumeRoleResult::AssumedRoleUser AssumeRoleResult::assumedRoleUser() const
+{
   return assumedRoleUser_;
 }
 
-AssumeRoleResult::Credentials AssumeRoleResult::credentials() const {
+AssumeRoleResult::Credentials AssumeRoleResult::credentials() const
+{
   return credentials_;
 }
 
-void AssumeRoleResult::parse(const std::string & payload) {
+void AssumeRoleResult::parse(const std::string &payload)
+{
   Json::Reader reader;
   Json::Value value;
   reader.parse(payload, value);
@@ -53,7 +52,7 @@ void AssumeRoleResult::parse(const std::string & payload) {
 
   auto assumedRoleUserNode = value["AssumedRoleUser"];
   assumedRoleUser_.assumedRoleId =
-  assumedRoleUserNode["AssumedRoleId"].asString();
+      assumedRoleUserNode["AssumedRoleId"].asString();
   assumedRoleUser_.arn = assumedRoleUserNode["Arn"].asString();
 
   auto credentialsNode = value["Credentials"];

+ 25 - 38
core/src/sts/model/GetCallerIdentityResult.cc

@@ -1,19 +1,20 @@
 /*
-* Copyright 1999-2019 Alibaba Cloud All rights reserved.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*      http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
+ * Copyright 1999-2019 Alibaba Cloud All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <alibabacloud/core/Utils.h>
 #include <alibabacloud/core/sts/model/GetCallerIdentityResult.h>
 #include <json/json.h>
 
@@ -21,37 +22,23 @@ using namespace AlibabaCloud;
 using namespace AlibabaCloud::Sts;
 using namespace AlibabaCloud::Sts::Model;
 
-GetCallerIdentityResult::GetCallerIdentityResult() :
-  ServiceResult(),
-  accountId_(),
-  arn_(),
-  userId_() {
-}
+GetCallerIdentityResult::GetCallerIdentityResult()
+    : ServiceResult(), accountId_(), arn_(), userId_() {}
 
-GetCallerIdentityResult::GetCallerIdentityResult(const std::string & payload) :
-  ServiceResult(),
-  accountId_(),
-  arn_(),
-  userId_() {
+GetCallerIdentityResult::GetCallerIdentityResult(const std::string &payload)
+    : ServiceResult(), accountId_(), arn_(), userId_() {
   parse(payload);
 }
 
-GetCallerIdentityResult::~GetCallerIdentityResult() {
-}
+GetCallerIdentityResult::~GetCallerIdentityResult() {}
 
-std::string GetCallerIdentityResult::accountId() {
-  return accountId_;
-}
+std::string GetCallerIdentityResult::accountId() { return accountId_; }
 
-std::string GetCallerIdentityResult::arn() const {
-  return arn_;
-}
+std::string GetCallerIdentityResult::arn() const { return arn_; }
 
-std::string GetCallerIdentityResult::userId() const {
-  return userId_;
-}
+std::string GetCallerIdentityResult::userId() const { return userId_; }
 
-void GetCallerIdentityResult::parse(const std::string & payload) {
+void GetCallerIdentityResult::parse(const std::string &payload) {
   Json::Reader reader;
   Json::Value value;
   reader.parse(payload, value);