fix code style

1. add .clang-format code style file.
2. format code of core.

use `clang-format -i -style=file ./core/*/*.cc ./core/*/*.h` command to format
This commit is contained in:
wb-hx510875
2020-07-01 16:06:18 +08:00
committed by page
parent e065d50def
commit a57f6ec422
39 changed files with 7959 additions and 8262 deletions

137
.clang-format Normal file
View File

@@ -0,0 +1,137 @@
---
Language: Cpp
# BasedOnStyle: LLVM
AccessModifierOffset: -2
AlignAfterOpenBracket: Align
AlignConsecutiveMacros: false
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Right
AlignOperands: true
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: true
AllowAllConstructorInitializersOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: MultiLine
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DeriveLineEnding: true
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
SortPriority: 0
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
SortPriority: 0
- Regex: '.*'
Priority: 1
SortPriority: 0
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentCaseLabels: false
IndentGotoLabels: true
IndentPPDirectives: None
IndentWidth: 2
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInConditionalStatement: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
SpaceBeforeSquareBrackets: false
Standard: Latest
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 8
UseCRLF: false
UseTab: Never
...

View File

@@ -14,10 +14,10 @@
* limitations under the License.
*/
#include <alibabacloud/core/AlibabaCloud.h>
#include "Executor.h"
#include <alibabacloud/core/AlibabaCloud.h>
static AlibabaCloud::Executor * executor = nullptr;
static AlibabaCloud::Executor *executor = nullptr;
void AlibabaCloud::InitializeSdk() {
if (IsSdkInitialized())
@@ -27,9 +27,7 @@ void AlibabaCloud::InitializeSdk() {
executor->start();
}
bool AlibabaCloud::IsSdkInitialized() {
return executor != nullptr;
}
bool AlibabaCloud::IsSdkInitialized() { return executor != nullptr; }
void AlibabaCloud::ShutdownSdk() {
if (!IsSdkInitialized())

View File

@@ -17,29 +17,16 @@
#include <alibabacloud/core/AsyncCallerContext.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
{
return uuid_;
}
std::string AsyncCallerContext::uuid() const { return uuid_; }
void AsyncCallerContext::setUuid(const std::string &uuid)
{
uuid_ = uuid;
}
void AsyncCallerContext::setUuid(const std::string &uuid) { uuid_ = uuid; }
} // namespace AlibabaCloud

View File

@@ -14,36 +14,26 @@
* limitations under the License.
*/
#include <alibabacloud/core/ClientConfiguration.h>
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/ClientConfiguration.h>
namespace AlibabaCloud {
ClientConfiguration::ClientConfiguration(const std::string &regionId,
const NetworkProxy &proxy):
regionId_(regionId),
proxy_(proxy),
endpoint_(),
connectTimeout_(kDefaultConnectTimeout),
readTimeout_(kDefaultReadTimeout) {
}
const NetworkProxy &proxy)
: regionId_(regionId), proxy_(proxy), endpoint_(),
connectTimeout_(kDefaultConnectTimeout),
readTimeout_(kDefaultReadTimeout) {}
ClientConfiguration::~ClientConfiguration() {
}
ClientConfiguration::~ClientConfiguration() {}
std::string ClientConfiguration::endpoint() const {
return endpoint_;
}
std::string ClientConfiguration::endpoint() const { return endpoint_; }
NetworkProxy ClientConfiguration::proxy()const {
return proxy_;
}
NetworkProxy ClientConfiguration::proxy() const { return proxy_; }
std::string ClientConfiguration::regionId()const {
return regionId_;
}
std::string ClientConfiguration::regionId() const { return regionId_; }
void ClientConfiguration::setEndpoint(const std::string & endpoint) {
void ClientConfiguration::setEndpoint(const std::string &endpoint) {
endpoint_ = endpoint;
}
@@ -55,13 +45,9 @@ void ClientConfiguration::setRegionId(const std::string &regionId) {
regionId_ = regionId;
}
long ClientConfiguration::connectTimeout() const {
return connectTimeout_;
}
long ClientConfiguration::connectTimeout() const { return connectTimeout_; }
long ClientConfiguration::readTimeout() const {
return readTimeout_;
}
long ClientConfiguration::readTimeout() const { return readTimeout_; }
void ClientConfiguration::setConnectTimeout(const long connectTimeout) {
connectTimeout_ = connectTimeout;
@@ -72,11 +58,11 @@ void ClientConfiguration::setReadTimeout(const long readTimeout) {
}
bool ClientConfiguration::rejectUnauthorized() const {
return rejectUnauthorized_;
return rejectUnauthorized_;
}
void ClientConfiguration::setRejectUnauthorized(const bool rejectUnauthorized) {
rejectUnauthorized_ = rejectUnauthorized;
rejectUnauthorized_ = rejectUnauthorized;
}
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -1,81 +1,73 @@
/*
* 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/AlibabaCloud.h>
#include <alibabacloud/core/CommonClient.h>
#include <alibabacloud/core/location/LocationClient.h>
#include <alibabacloud/core/SimpleCredentialsProvider.h>
#include <alibabacloud/core/location/LocationClient.h>
#include <ctime>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <alibabacloud/core/Utils.h>
namespace AlibabaCloud
{
namespace AlibabaCloud {
namespace
{
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 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>())
{
}
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
{
CommonClient::JsonOutcome
CommonClient::makeRequest(const std::string &endpoint, 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()));
return JsonOutcome(
std::string(outcome.result().body(), outcome.result().bodySize()));
else
return JsonOutcome(outcome.error());
}
CommonClient::CommonResponseOutcome CommonClient::commonResponse(
const CommonRequest &request) const
{
CommonClient::CommonResponseOutcome
CommonClient::commonResponse(const CommonRequest &request) const {
auto outcome = makeRequest(request.domain(), request, request.httpMethod());
if (outcome.isSuccess())
return CommonResponseOutcome(CommonResponse(outcome.result()));
@@ -83,10 +75,9 @@ 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);
};
@@ -95,45 +86,40 @@ 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
{
return buildHttpRequest(endpoint,
dynamic_cast<const CommonRequest &>(msg), method);
const ServiceRequest &msg,
HttpRequest::Method method) const {
return buildHttpRequest(endpoint, dynamic_cast<const CommonRequest &>(msg),
method);
}
HttpRequest CommonClient::buildHttpRequest(const std::string &endpoint,
const CommonRequest &msg, HttpRequest::Method method) const
{
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);
@@ -141,17 +127,14 @@ HttpRequest CommonClient::buildRoaHttpRequest(const std::string &endpoint,
auto params = msg.headerParameters();
std::map<std::string, std::string> queryParams;
for (const auto &p : params)
{
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
@@ -163,42 +146,30 @@ 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",
@@ -239,26 +210,22 @@ HttpRequest CommonClient::buildRoaHttpRequest(const std::string &endpoint,
plaintext << url.path() << "?" << url.query();
std::stringstream sign;
sign << "acs "
<< credentials.accessKeyId()
<< ":"
sign << "acs " << 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);
@@ -266,8 +233,7 @@ HttpRequest CommonClient::buildRpcHttpRequest(const std::string &endpoint,
auto params = msg.queryParameters();
std::map<std::string, std::string> queryParams;
for (const auto &p : params)
{
for (const auto &p : params) {
if (!p.second.empty())
queryParams[p.first] = p.second;
}
@@ -294,21 +260,17 @@ HttpRequest CommonClient::buildRpcHttpRequest(const std::string &endpoint,
std::string bodyParamString;
auto signParams = queryParams;
auto bodyParams = msg.bodyParameters();
for (const auto &p : bodyParams)
{
for (const auto &p : bodyParams) {
bodyParamString += "&";
bodyParamString += (p.first + "=" + UrlEncode(p.second));
signParams[p.first] = p.second;
}
std::stringstream plaintext;
plaintext << HttpMethodToString(method)
<< "&"
<< UrlEncode(url.path())
<< "&"
plaintext << HttpMethodToString(method) << "&" << UrlEncode(url.path()) << "&"
<< UrlEncode(canonicalizedQuery(signParams));
queryParams["Signature"] = signer_->generate(plaintext.str(),
credentials.accessKeySecret() + "&");
queryParams["Signature"] =
signer_->generate(plaintext.str(), credentials.accessKeySecret() + "&");
std::stringstream queryString;
for (const auto &p : queryParams)
@@ -316,21 +278,15 @@ 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());
}
@@ -339,8 +295,7 @@ HttpRequest CommonClient::buildRpcHttpRequest(const std::string &endpoint,
request.setHeader("x-sdk-client",
std::string("CPP/").append(ALIBABACLOUD_VERSION_STR));
if (!bodyParamString.empty())
{
if (!bodyParamString.empty()) {
request.setBody(bodyParamString.c_str() + 1, bodyParamString.size() - 1);
}
return request;

View File

@@ -1,41 +1,32 @@
/*
* 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/CommonRequest.h>
namespace AlibabaCloud {
CommonRequest::CommonRequest(RequestPattern pattern):
ServiceRequest("", ""),
domain_(),
queryParams_(),
httpMethod_(HttpRequest::Get),
requestPattern_(pattern) {
}
CommonRequest::CommonRequest(RequestPattern pattern)
: ServiceRequest("", ""), domain_(), queryParams_(),
httpMethod_(HttpRequest::Get), requestPattern_(pattern) {}
CommonRequest::~CommonRequest() {
}
CommonRequest::~CommonRequest() {}
std::string CommonRequest::domain()const {
return domain_;
}
std::string CommonRequest::domain() const { return domain_; }
void CommonRequest::setDomain(const std::string &domain) {
domain_ = domain;
}
void CommonRequest::setDomain(const std::string &domain) { domain_ = domain; }
CommonRequest::RequestPattern CommonRequest::requestPattern() const {
return requestPattern_;
@@ -49,12 +40,10 @@ void CommonRequest::setHttpMethod(HttpRequest::Method method) {
httpMethod_ = method;
}
HttpRequest::Method CommonRequest::httpMethod() const {
return httpMethod_;
}
HttpRequest::Method CommonRequest::httpMethod() const { return httpMethod_; }
CommonRequest::ParameterValueType CommonRequest::queryParameter(
const ParameterNameType &name) const {
CommonRequest::ParameterValueType
CommonRequest::queryParameter(const ParameterNameType &name) const {
ParameterCollection::const_iterator it = queryParams_.find(name);
if (it == queryParams_.end()) {
return ParameterValueType("");
@@ -62,19 +51,18 @@ CommonRequest::ParameterValueType CommonRequest::queryParameter(
return it->second;
}
CommonRequest::ParameterCollection CommonRequest::queryParameters() const {
return queryParams_;
}
void CommonRequest::setQueryParameter(const ParameterNameType &name,
const ParameterValueType &value) {
const ParameterValueType &value) {
queryParams_[name] = value;
}
CommonRequest::ParameterValueType CommonRequest::headerParameter(
const ParameterNameType &name) const {
const ParameterCollection::const_iterator it = headerParams_.find(name);
CommonRequest::ParameterValueType
CommonRequest::headerParameter(const ParameterNameType &name) const {
const ParameterCollection::const_iterator it = headerParams_.find(name);
if (it == headerParams_.end()) {
return ParameterValueType("");
}
@@ -86,8 +74,8 @@ CommonRequest::ParameterCollection CommonRequest::headerParameters() const {
}
void CommonRequest::setHeaderParameter(const ParameterNameType &name,
const ParameterValueType &value) {
const ParameterValueType &value) {
headerParams_[name] = value;
}
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -1,36 +1,30 @@
/*
* 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/CommonResponse.h>
namespace AlibabaCloud {
CommonResponse::CommonResponse() :
payload_() {
}
CommonResponse::CommonResponse() : payload_() {}
CommonResponse::CommonResponse(const std::string &payload) :
payload_(payload) {
}
CommonResponse::CommonResponse(const std::string &payload)
: payload_(payload) {}
CommonResponse::~CommonResponse() {
}
CommonResponse::~CommonResponse() {}
std::string CommonResponse::payload() const {
return payload_;
}
std::string CommonResponse::payload() const { return payload_; }
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -16,9 +16,9 @@
#include "CurlHttpClient.h"
#include "Executor.h"
#include <alibabacloud/core/Utils.h>
#include <alibabacloud/core/CoreClient.h>
#include <alibabacloud/core/Signer.h>
#include <alibabacloud/core/Utils.h>
#include <json/json.h>
/*!
@@ -63,14 +63,10 @@ CoreClient::AttemptRequest(const std::string &endpoint,
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,8 +76,7 @@ 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;

27
core/src/Credentials.cc Executable file → Normal file
View File

@@ -19,23 +19,16 @@
namespace AlibabaCloud {
Credentials::Credentials(const std::string &accessKeyId,
const std::string &accessKeySecret,
const std::string &sessionToken) :
accessKeyId_(accessKeyId),
accessKeySecret_(accessKeySecret),
sessionToken_(sessionToken) {
}
const std::string &accessKeySecret,
const std::string &sessionToken)
: accessKeyId_(accessKeyId), accessKeySecret_(accessKeySecret),
sessionToken_(sessionToken) {}
Credentials::~Credentials() {
}
Credentials::~Credentials() {}
std::string Credentials::accessKeyId() const {
return accessKeyId_;
}
std::string Credentials::accessKeyId() const { return accessKeyId_; }
std::string Credentials::accessKeySecret() const {
return accessKeySecret_;
}
std::string Credentials::accessKeySecret() const { return accessKeySecret_; }
void Credentials::setAccessKeyId(const std::string &accessKeyId) {
accessKeyId_ = accessKeyId;
@@ -49,8 +42,6 @@ void Credentials::setSessionToken(const std::string &sessionToken) {
sessionToken_ = sessionToken;
}
std::string Credentials::sessionToken() const {
return sessionToken_;
}
std::string Credentials::sessionToken() const { return sessionToken_; }
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -18,9 +18,9 @@
#include <alibabacloud/core/Utils.h>
#include <cassert>
#include <sstream>
#include <string.h>
#include <string>
#include <vector>
#include <string.h>
namespace AlibabaCloud {
@@ -52,13 +52,13 @@ static size_t readCallback(void *ptr, size_t size, size_t nmemb, void *stream) {
}
size_t recvBody(char *ptr, size_t size, size_t nmemb, void *userdata) {
std::ostringstream &out = *static_cast<std::ostringstream*>(userdata);
out << std::string(ptr, nmemb*size);
std::ostringstream &out = *static_cast<std::ostringstream *>(userdata);
out << std::string(ptr, nmemb * size);
return nmemb * size;
}
size_t recvHeaders(char *buffer, size_t size, size_t nitems, void *userdata) {
HttpResponse *response = static_cast<HttpResponse*>(userdata);
HttpResponse *response = static_cast<HttpResponse *>(userdata);
std::string line(buffer);
auto pos = line.find(':');
if (pos != line.npos) {
@@ -98,16 +98,12 @@ void setCUrlProxy(CURL *curlHandle, const NetworkProxy &proxy) {
curl_easy_setopt(curlHandle, CURLOPT_PROXYUSERPWD, out.str().c_str());
}
}
} // namespace
} // namespace
CurlHttpClient::CurlHttpClient() :
HttpClient(),
curlHandle_(curl_easy_init()) {
}
CurlHttpClient::CurlHttpClient()
: HttpClient(), curlHandle_(curl_easy_init()) {}
CurlHttpClient::~CurlHttpClient() {
curl_easy_cleanup(curlHandle_);
}
CurlHttpClient::~CurlHttpClient() { curl_easy_cleanup(curlHandle_); }
HttpClient::HttpResponseOutcome
CurlHttpClient::makeRequest(const HttpRequest &request) {
@@ -119,46 +115,43 @@ CurlHttpClient::makeRequest(const HttpRequest &request) {
std::string url = request.url().toString();
switch (request.method()) {
case HttpRequest::Method::Get:
case HttpRequest::Method::Get:
break;
case HttpRequest::Method::Post: {
if (request.bodySize() > 0) {
curl_easy_setopt(curlHandle_, CURLOPT_POSTFIELDS, request.body());
} else {
curl_easy_setopt(curlHandle_, CURLOPT_POSTFIELDS, "");
}
case HttpRequest::Method::Post: {
if (request.bodySize() > 0) {
curl_easy_setopt(curlHandle_, CURLOPT_POSTFIELDS, request.body());
} else {
curl_easy_setopt(curlHandle_, CURLOPT_POSTFIELDS, "");
}
break;
} break;
case HttpRequest::Method::Put: {
uploadContext* ctx = (uploadContext *)malloc(sizeof(uploadContext));
// this is impossible, as the size is 24 Bytes
if (ctx == nullptr) {
return HttpResponseOutcome(
case HttpRequest::Method::Put: {
uploadContext *ctx = (uploadContext *)malloc(sizeof(uploadContext));
// this is impossible, as the size is 24 Bytes
if (ctx == nullptr) {
return HttpResponseOutcome(
Error("MemoryAllocateError",
"There is not enough memory for http transfer."));
}
ctx->data = request.body();
ctx->pos = request.body();
ctx->last = ctx->pos + request.bodySize();
curl_easy_setopt(curlHandle_, CURLOPT_READFUNCTION, readCallback);
curl_easy_setopt(curlHandle_, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(curlHandle_, CURLOPT_READDATA, ctx);
"There is not enough memory for http transfer."));
}
break;
ctx->data = request.body();
ctx->pos = request.body();
ctx->last = ctx->pos + request.bodySize();
case HttpRequest::Method::Delete: {
curl_easy_setopt(curlHandle_, CURLOPT_CUSTOMREQUEST, "DELETE");
if (request.bodySize() > 0) {
curl_easy_setopt(curlHandle_, CURLOPT_POSTFIELDS, request.body());
} else {
curl_easy_setopt(curlHandle_, CURLOPT_POSTFIELDS, "");
}
curl_easy_setopt(curlHandle_, CURLOPT_READFUNCTION, readCallback);
curl_easy_setopt(curlHandle_, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(curlHandle_, CURLOPT_READDATA, ctx);
} break;
case HttpRequest::Method::Delete: {
curl_easy_setopt(curlHandle_, CURLOPT_CUSTOMREQUEST, "DELETE");
if (request.bodySize() > 0) {
curl_easy_setopt(curlHandle_, CURLOPT_POSTFIELDS, request.body());
} else {
curl_easy_setopt(curlHandle_, CURLOPT_POSTFIELDS, "");
}
break;
} break;
default:
default:
break;
}
@@ -200,33 +193,34 @@ CurlHttpClient::makeRequest(const HttpRequest &request) {
CURLcode res = curl_easy_perform(curlHandle_);
switch (res) {
case CURLE_OK: {
long response_code;
curl_easy_getinfo(curlHandle_, CURLINFO_RESPONSE_CODE, &response_code);
response.setStatusCode(response_code);
response.setBody(out.str().c_str(), out.str().length());
return HttpResponseOutcome(response);
}
case CURLE_SSL_CONNECT_ERROR:
return HttpResponseOutcome(
case CURLE_OK: {
long response_code;
curl_easy_getinfo(curlHandle_, CURLINFO_RESPONSE_CODE, &response_code);
response.setStatusCode(response_code);
response.setBody(out.str().c_str(), out.str().length());
return HttpResponseOutcome(response);
}
case CURLE_SSL_CONNECT_ERROR:
return HttpResponseOutcome(
Error("SSLConnectError",
"A problem occurred somewhere in the SSL/TLS handshake."));
case CURLE_OPERATION_TIMEDOUT:
return HttpResponseOutcome(
"A problem occurred somewhere in the SSL/TLS handshake."));
case CURLE_OPERATION_TIMEDOUT:
return HttpResponseOutcome(
Error("OperationTimeoutError",
"Timeout (connectTimeout: " +
std::to_string(connect_timeout) + "ms, readTimeout: " +
std::to_string(read_timeout) + "ms) when connect or read data: " +
HttpMethodToString(request.method()) + " " + request.url().toString()));
"Timeout (connectTimeout: " + std::to_string(connect_timeout) +
"ms, readTimeout: " + std::to_string(read_timeout) +
"ms) when connect or read data: " +
HttpMethodToString(request.method()) + " " +
request.url().toString()));
default: {
return HttpResponseOutcome(
Error("NetworkError",
"Failed to connect to host or proxy: " +
HttpMethodToString(request.method()) + " " + request.url().toString()));
}
default: {
return HttpResponseOutcome(
Error("NetworkError", "Failed to connect to host or proxy: " +
HttpMethodToString(request.method()) + " " +
request.url().toString()));
}
}
curl_slist_free_all(list);
}
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -22,15 +22,15 @@
namespace AlibabaCloud {
class CurlHttpClient : public HttpClient {
public:
public:
CurlHttpClient();
~CurlHttpClient();
HttpResponseOutcome makeRequest(const HttpRequest &request) override;
private:
private:
CURL *curlHandle_;
};
} // namespace AlibabaCloud
} // namespace AlibabaCloud
#endif // CORE_SRC_CURLHTTPCLIENT_H_
#endif // CORE_SRC_CURLHTTPCLIENT_H_

View File

@@ -1,38 +1,34 @@
/*
* 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/Url.h>
#include <sstream>
#include <memory>
#include "EcsMetadataFetcher.h"
#include "CurlHttpClient.h"
#include <alibabacloud/core/Url.h>
#include <memory>
#include <sstream>
namespace AlibabaCloud {
EcsMetadataFetcher::EcsMetadataFetcher() {
}
EcsMetadataFetcher::EcsMetadataFetcher() {}
EcsMetadataFetcher::~EcsMetadataFetcher() {
}
EcsMetadataFetcher::~EcsMetadataFetcher() {}
std::string EcsMetadataFetcher::roleName()const {
return roleName_;
}
std::string EcsMetadataFetcher::roleName() const { return roleName_; }
void EcsMetadataFetcher::setRoleName(const std::string & roleName) {
void EcsMetadataFetcher::setRoleName(const std::string &roleName) {
roleName_ = roleName;
}
@@ -41,7 +37,7 @@ std::string EcsMetadataFetcher::getMetadata() {
}
std::string EcsMetadataFetcher::getMetadata(const std::string host,
const std::string in_path) {
const std::string in_path) {
std::stringstream path;
path << in_path << roleName_;
@@ -61,4 +57,4 @@ std::string EcsMetadataFetcher::getMetadata(const std::string host,
return outcome.error().errorCode();
}
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -1,18 +1,18 @@
/*
* 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.
*/
#ifndef CORE_SRC_ECSMETADATAFETCHER_H_
#define CORE_SRC_ECSMETADATAFETCHER_H_
@@ -20,26 +20,26 @@
#include <string>
namespace {
const int DEFAULT_TIMEOUT_IN_MILLISECONDS = 5000;
const char* const METADATA_SERVICE_HOST = "100.100.100.200";
const char* const URL_IN_ECS_METADATA =
"/latest/meta-data/ram/security-credentials/";
}
const int DEFAULT_TIMEOUT_IN_MILLISECONDS = 5000;
const char *const METADATA_SERVICE_HOST = "100.100.100.200";
const char *const URL_IN_ECS_METADATA =
"/latest/meta-data/ram/security-credentials/";
} // namespace
namespace AlibabaCloud {
class EcsMetadataFetcher {
public:
public:
EcsMetadataFetcher();
~EcsMetadataFetcher();
std::string roleName()const;
void setRoleName(const std::string & roleName);
std::string roleName() const;
void setRoleName(const std::string &roleName);
std::string getMetadata(const std::string host, const std::string path);
virtual std::string getMetadata();
private:
private:
std::string roleName_;
};
} // namespace AlibabaCloud
} // namespace AlibabaCloud
#endif // CORE_SRC_ECSMETADATAFETCHER_H_
#endif // CORE_SRC_ECSMETADATAFETCHER_H_

View File

@@ -16,12 +16,12 @@
#include <algorithm>
#include <alibabacloud/core/EndpointProvider.h>
#include <condition_variable>
#include <iomanip>
#include <json/json.h>
#include <mutex>
#include <sstream>
#include <thread>
#include <mutex>
#include <condition_variable>
#ifndef WIN32
#include "LocalEndpoints.h"
@@ -30,11 +30,9 @@
#include "LocalEndpointsForWindows.h"
#endif
namespace AlibabaCloud
{
namespace AlibabaCloud {
namespace
{
namespace {
#if defined(WIN32) && defined(_MSC_VER)
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
@@ -52,8 +50,7 @@ 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;
@@ -62,14 +59,12 @@ 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;
std::unique_lock<std::mutex> lock(mutex);
if (local_endpoints_loaded)
{
if (local_endpoints_loaded) {
return;
}
@@ -79,42 +74,38 @@ static void LoadLocalEndpoints()
WIN_LOCAL_ENDPOINTS_CONFIG_3;
#endif
if (!reader.parse(LOCAL_ENDPOINTS_CONFIG, value))
{
if (!reader.parse(LOCAL_ENDPOINTS_CONFIG, value)) {
return;
}
cv.wait(lock, [] { return !local_endpoints_loading; });// continue if loading completed
cv.wait(lock, [] {
return !local_endpoints_loading;
}); // continue if loading completed
local_endpoints_loading = true;
auto regions = value["regions"];
for (const auto &region : regions)
{
for (const auto &region : regions) {
allRegions.push_back(region.asString());
}
auto products = value["products"];
for (const auto &product : products)
{
for (const auto &product : products) {
allProductsInLocalEndpoints.push_back(product.asString());
}
auto endpoints = value["endpoints"];
for (auto &product : allProductsInLocalEndpoints)
{
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)
{
for (auto &r : regions) {
const std::string region = r.asString();
p.regions.push_back(region);
p.regional[region] =
endpoint_per_product["regional"][region].asString();
p.regional[region] = endpoint_per_product["regional"][region].asString();
}
allLocalEndpoints[product] = p;
}
@@ -133,8 +124,7 @@ EndpointProvider::EndpointProvider(
const std::string serviceCode, int durationSeconds)
: LocationClient(locationClient), regionId_(regionId), product_(product),
serviceCode_(serviceCode), durationSeconds_(durationSeconds),
cachedMutex_(), cachedEndpoint_(), expiry_()
{
cachedMutex_(), cachedEndpoint_(), expiry_() {
transform(product_.begin(), product_.end(), product_.begin(), ::tolower);
loadLocalProductsInfo();
}
@@ -148,34 +138,29 @@ EndpointProvider::EndpointProvider(const Credentials &credentials,
: LocationClient(credentials, configuration), regionId_(regionId),
product_(product), serviceCode_(serviceCode),
durationSeconds_(durationSeconds), cachedMutex_(), cachedEndpoint_(),
expiry_()
{
expiry_() {
transform(product_.begin(), product_.end(), product_.begin(), ::tolower);
loadLocalProductsInfo();
}
EndpointProvider::~EndpointProvider() {}
bool EndpointProvider::loadLocalProductsInfo()
{
bool EndpointProvider::loadLocalProductsInfo() {
LoadLocalEndpoints();
return true;
}
std::string EndpointProvider::localEndpoint(const std::string regionId,
const std::string product)
{
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();
}
@@ -183,47 +168,40 @@ std::string EndpointProvider::localEndpoint(const std::string regionId,
allProductsInLocalEndpointsit =
std::find(allProductsInLocalEndpoints.begin(),
allProductsInLocalEndpoints.end(), product);
if (allProductsInLocalEndpointsit == allProductsInLocalEndpoints.end())
{
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();
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."));
@@ -231,26 +209,21 @@ EndpointProvider::EndpointOutcome EndpointProvider::getEndpoint()
// 3rd priority: request from location service
EndpointOutcome outcome = loadRemoteEndpoint();
if (outcome.isSuccess())
{
if (outcome.isSuccess()) {
return outcome;
}
if (outcome.error().errorCode() == "Illegal Parameter")
{
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_);

View File

@@ -18,23 +18,18 @@
namespace AlibabaCloud {
Error::Error(std::string code, const std::string message) :
errorCode_(code),
message_(message),
host_(),
requestId_(),
detail_() {
}
Error::Error(std::string code, const std::string message)
: errorCode_(code), message_(message), host_(), requestId_(), detail_() {}
std::string Error::errorCode()const { return errorCode_; }
std::string Error::errorCode() const { return errorCode_; }
std::string Error::errorMessage() const { return message_; }
std::string Error::host() const { return host_; }
std::string Error::requestId() const { return requestId_; }
std::string Error::detail() const { return detail_; }
void Error::setErrorCode(const std::string &code) { errorCode_ = code; }
void Error::setErrorMessage(const std::string& message) { message_ = message; }
void Error::setHost(const std::string& host) { host_ = host; }
void Error::setRequestId(const std::string& request) { requestId_ = request; }
void Error::setDetail(const std::string& detail) { detail_ = detail; }
void Error::setErrorMessage(const std::string &message) { message_ = message; }
void Error::setHost(const std::string &host) { host_ = host; }
void Error::setRequestId(const std::string &request) { requestId_ = request; }
void Error::setDetail(const std::string &detail) { detail_ = detail; }
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -1,18 +1,18 @@
/*
* 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 "Executor.h"
#include <alibabacloud/core/Runnable.h>
@@ -21,12 +21,9 @@ namespace AlibabaCloud {
Executor *Executor::self_ = nullptr;
Executor::Executor() :
cvMutex_(),
shutdown_(true),
tasksQueue_(),
tasksQueueMutex_(),
thread_() {
Executor::Executor()
: cvMutex_(), shutdown_(true), tasksQueue_(), tasksQueueMutex_(),
thread_() {
self_ = this;
}
@@ -35,9 +32,7 @@ Executor::~Executor() {
shutdown();
}
Executor * Executor::instance() {
return self_;
}
Executor *Executor::instance() { return self_; }
bool Executor::start() {
if (!isShutdown())
@@ -73,11 +68,9 @@ bool Executor::start() {
return true;
}
bool Executor::isShutdown()const {
return shutdown_;
}
bool Executor::isShutdown() const { return shutdown_; }
void Executor::execute(Runnable* task) {
void Executor::execute(Runnable *task) {
if (isShutdown())
return;
@@ -111,4 +104,4 @@ void Executor::shutdown() {
thread_.join();
}
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -1,52 +1,52 @@
/*
* 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.
*/
#ifndef CORE_SRC_EXECUTOR_H_
#define CORE_SRC_EXECUTOR_H_
#include <atomic>
#include <condition_variable>
#include <queue>
#include <vector>
#include <thread>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
namespace AlibabaCloud {
class Runnable;
class Executor {
public:
public:
Executor();
~Executor();
static Executor * instance();
void execute(Runnable* task);
bool isShutdown()const;
static Executor *instance();
void execute(Runnable *task);
bool isShutdown() const;
bool start();
void shutdown();
void wakeUp();
private:
private:
static Executor *self_;
std::atomic<bool> shutdown_;
std::queue<Runnable*> tasksQueue_;
std::queue<Runnable *> tasksQueue_;
std::mutex tasksQueueMutex_;
std::thread thread_;
std::condition_variable cv_;
std::mutex cvMutex_;
};
} // namespace AlibabaCloud
} // namespace AlibabaCloud
#endif // CORE_SRC_EXECUTOR_H_
#endif // CORE_SRC_EXECUTOR_H_

View File

@@ -16,23 +16,20 @@
#include <alibabacloud/core/HmacSha1Signer.h>
#ifdef _WIN32
#include <windows.h>
#include <wincrypt.h>
#include <windows.h>
#else
#include <openssl/hmac.h>
#endif
namespace AlibabaCloud {
HmacSha1Signer::HmacSha1Signer() :
Signer(HmacSha1, "HMAC-SHA1", "1.0") {
}
HmacSha1Signer::HmacSha1Signer() : Signer(HmacSha1, "HMAC-SHA1", "1.0") {}
HmacSha1Signer::~HmacSha1Signer() {
}
HmacSha1Signer::~HmacSha1Signer() {}
std::string HmacSha1Signer::generate(const std::string & src,
const std::string & secret) const {
std::string HmacSha1Signer::generate(const std::string &src,
const std::string &secret) const {
if (src.empty())
return std::string();
@@ -41,10 +38,10 @@ std::string HmacSha1Signer::generate(const std::string & src,
BLOBHEADER hdr;
DWORD dwKeySize;
BYTE rgbKeyData[];
}my_blob;
} my_blob;
DWORD kbLen = sizeof(my_blob) + secret.size();
my_blob * kb = (my_blob *)LocalAlloc(LPTR, kbLen);
my_blob *kb = (my_blob *)LocalAlloc(LPTR, kbLen);
kb->hdr.bType = PLAINTEXTKEYBLOB;
kb->hdr.bVersion = CUR_BLOB_VERSION;
kb->hdr.reserved = 0;
@@ -61,12 +58,12 @@ std::string HmacSha1Signer::generate(const std::string & src,
ZeroMemory(&HmacInfo, sizeof(HmacInfo));
HmacInfo.HashAlgid = CALG_SHA1;
CryptAcquireContext(&hProv, NULL,
MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_NEWKEYSET);
CryptImportKey(hProv, (BYTE*)kb, kbLen, 0, CRYPT_IPSEC_HMAC_KEY, &hKey);
CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT | CRYPT_NEWKEYSET);
CryptImportKey(hProv, (BYTE *)kb, kbLen, 0, CRYPT_IPSEC_HMAC_KEY, &hKey);
CryptCreateHash(hProv, CALG_HMAC, hKey, 0, &hHmacHash);
CryptSetHashParam(hHmacHash, HP_HMAC_INFO, (BYTE*)&HmacInfo, 0);
CryptHashData(hHmacHash, (BYTE*)(src.c_str()), src.size(), 0);
CryptSetHashParam(hHmacHash, HP_HMAC_INFO, (BYTE *)&HmacInfo, 0);
CryptHashData(hHmacHash, (BYTE *)(src.c_str()), src.size(), 0);
CryptGetHashParam(hHmacHash, HP_HASHVAL, pbHash, &dwDataLen, 0);
LocalFree(kb);
@@ -75,11 +72,11 @@ std::string HmacSha1Signer::generate(const std::string & src,
CryptReleaseContext(hProv, 0);
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);
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);
std::string ret = std::string(dest, dlen);
delete dest;
@@ -89,14 +86,14 @@ std::string HmacSha1Signer::generate(const std::string & src,
unsigned int mdLen = EVP_MAX_BLOCK_LENGTH;
if (HMAC(EVP_sha1(), secret.c_str(), secret.size(),
reinterpret_cast<const unsigned char*>(src.c_str()), src.size(),
md, &mdLen) == nullptr)
reinterpret_cast<const unsigned char *>(src.c_str()), src.size(), md,
&mdLen) == nullptr)
return std::string();
char encodedData[100];
EVP_EncodeBlock(reinterpret_cast<unsigned char*>(encodedData), md, mdLen);
EVP_EncodeBlock(reinterpret_cast<unsigned char *>(encodedData), md, mdLen);
return encodedData;
#endif
}
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -16,32 +16,23 @@
#include <alibabacloud/core/HttpClient.h>
#include <cassert>
#include <vector>
#include <sstream>
#include <vector>
namespace AlibabaCloud {
HttpClient::HttpClient() :
proxy_() {
}
HttpClient::HttpClient() : proxy_() {}
HttpClient::~HttpClient() {
}
HttpClient::~HttpClient() {}
NetworkProxy HttpClient::proxy()const {
return proxy_;
}
NetworkProxy HttpClient::proxy() const { return proxy_; }
void HttpClient::setProxy(const NetworkProxy &proxy) {
proxy_ = proxy;
}
void HttpClient::setProxy(const NetworkProxy &proxy) { proxy_ = proxy; }
bool HttpClient::rejectUnauthorized()const{
return rejectUnauthorized_;
}
bool HttpClient::rejectUnauthorized() const { return rejectUnauthorized_; }
void HttpClient::setRejectUnauthorized(const bool &rejectUnauthorized) {
rejectUnauthorized_ = rejectUnauthorized;
rejectUnauthorized_ = rejectUnauthorized;
}
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -14,54 +14,44 @@
* limitations under the License.
*/
#include <alibabacloud/core/HttpMessage.h>
#include <algorithm>
#include <alibabacloud/core/HttpMessage.h>
namespace AlibabaCloud {
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
std::string KnownHeaderMapper[] {
"Accept",
"Accept-Charset",
"Accept-Encoding",
"Accept-Language",
"Authorization",
"Connection",
"Content-Length",
"Content-MD5",
"Content-Type",
"Date",
"Host",
"Server",
"User-Agent"
};
} // namespace
std::string KnownHeaderMapper[]{"Accept",
"Accept-Charset",
"Accept-Encoding",
"Accept-Language",
"Authorization",
"Connection",
"Content-Length",
"Content-MD5",
"Content-Type",
"Date",
"Host",
"Server",
"User-Agent"};
} // namespace
HttpMessage::HttpMessage() :
body_(nullptr),
bodySize_(0),
headers_() {
}
HttpMessage::HttpMessage() : body_(nullptr), bodySize_(0), headers_() {}
HttpMessage::HttpMessage(const HttpMessage &other) :
body_(nullptr),
bodySize_(other.bodySize_),
headers_(other.headers_) {
HttpMessage::HttpMessage(const HttpMessage &other)
: body_(nullptr), bodySize_(other.bodySize_), headers_(other.headers_) {
setBody(other.body_, other.bodySize_);
}
HttpMessage::HttpMessage(HttpMessage &&other) {
*this = std::move(other);
}
HttpMessage::HttpMessage(HttpMessage &&other) { *this = std::move(other); }
HttpMessage& HttpMessage::operator=(const HttpMessage &other) {
HttpMessage &HttpMessage::operator=(const HttpMessage &other) {
if (this != &other) {
body_ = nullptr;
bodySize_ = 0;
@@ -71,23 +61,23 @@ HttpMessage& HttpMessage::operator=(const HttpMessage &other) {
return *this;
}
HttpMessage& HttpMessage::operator=(HttpMessage &&other) {
HttpMessage &HttpMessage::operator=(HttpMessage &&other) {
if (this != &other)
*this = std::move(other);
return *this;
}
void HttpMessage::addHeader(const HeaderNameType & name,
const HeaderValueType & value) {
void HttpMessage::addHeader(const HeaderNameType &name,
const HeaderValueType &value) {
setHeader(name, value);
}
void HttpMessage::addHeader(KnownHeader header, const HeaderValueType & value) {
void HttpMessage::addHeader(KnownHeader header, const HeaderValueType &value) {
setHeader(header, value);
}
HttpMessage::HeaderValueType HttpMessage::header(
const HeaderNameType & name) const {
HttpMessage::HeaderValueType
HttpMessage::header(const HeaderNameType &name) const {
auto it = headers_.find(name);
if (it != headers_.end())
return it->second;
@@ -95,11 +85,9 @@ HttpMessage::HeaderValueType HttpMessage::header(
return std::string();
}
HttpMessage::HeaderCollection HttpMessage::headers() const {
return headers_;
}
HttpMessage::HeaderCollection HttpMessage::headers() const { return headers_; }
void HttpMessage::removeHeader(const HeaderNameType & name) {
void HttpMessage::removeHeader(const HeaderNameType &name) {
headers_.erase(name);
}
@@ -107,33 +95,24 @@ void HttpMessage::removeHeader(KnownHeader header) {
removeHeader(KnownHeaderMapper[header]);
}
void HttpMessage::setHeader(const HeaderNameType & name,
const HeaderValueType & value) {
void HttpMessage::setHeader(const HeaderNameType &name,
const HeaderValueType &value) {
headers_[name] = value;
}
void HttpMessage::setHeader(KnownHeader header,
const std::string & value) {
void HttpMessage::setHeader(KnownHeader header, const std::string &value) {
setHeader(KnownHeaderMapper[header], value);
}
HttpMessage::~HttpMessage() {
setBody(nullptr, 0);
}
HttpMessage::~HttpMessage() { setBody(nullptr, 0); }
const char* HttpMessage::body()const {
return body_;
}
const char *HttpMessage::body() const { return body_; }
size_t HttpMessage::bodySize()const {
return bodySize_;
}
size_t HttpMessage::bodySize() const { return bodySize_; }
bool HttpMessage::hasBody() const {
return (bodySize_ != 0);
}
bool HttpMessage::hasBody() const { return (bodySize_ != 0); }
HttpMessage::HeaderValueType HttpMessage::header(KnownHeader header)const {
HttpMessage::HeaderValueType HttpMessage::header(KnownHeader header) const {
return this->header(KnownHeaderMapper[header]);
}
@@ -150,9 +129,9 @@ void HttpMessage::setBody(const char *data, size_t size) {
}
}
bool HttpMessage::nocaseLess::operator()(const std::string & s1,
const std::string & s2) const {
bool HttpMessage::nocaseLess::operator()(const std::string &s1,
const std::string &s2) const {
return strcasecmp(s1.c_str(), s2.c_str()) < 0;
}
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -14,46 +14,29 @@
* limitations under the License.
*/
#include <alibabacloud/core/HttpRequest.h>
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/HttpRequest.h>
namespace AlibabaCloud {
HttpRequest::HttpRequest(const Url &url, Method method) :
HttpMessage(),
url_(url),
method_(method),
connectTimeout_(kDefaultConnectTimeout),
readTimeout_(kDefaultReadTimeout) {
}
HttpRequest::HttpRequest(const Url &url, Method method)
: HttpMessage(), url_(url), method_(method),
connectTimeout_(kDefaultConnectTimeout),
readTimeout_(kDefaultReadTimeout) {}
HttpRequest::~HttpRequest() {
}
HttpRequest::~HttpRequest() {}
HttpRequest::Method HttpRequest::method() const {
return method_;
}
HttpRequest::Method HttpRequest::method() const { return method_; }
void HttpRequest::setMethod(Method method) { method_ = method; }
void HttpRequest::setMethod(Method method) {
method_ = method;
}
void HttpRequest::setUrl(const Url &url) { url_ = url; }
void HttpRequest::setUrl(const Url &url) {
url_ = url;
}
Url HttpRequest::url() const { return url_; }
Url HttpRequest::url()const {
return url_;
}
long HttpRequest::connectTimeout() const { return connectTimeout_; }
long HttpRequest::connectTimeout() const {
return connectTimeout_;
}
long HttpRequest::readTimeout() const {
return readTimeout_;
}
long HttpRequest::readTimeout() const { return readTimeout_; }
void HttpRequest::setConnectTimeout(const long connectTimeout) {
connectTimeout_ = connectTimeout;
@@ -63,4 +46,4 @@ void HttpRequest::setReadTimeout(const long readTimeout) {
readTimeout_ = readTimeout;
}
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -17,36 +17,23 @@
#include <alibabacloud/core/HttpResponse.h>
namespace {
#define INVALID_STATUS_CODE -1
}
#define INVALID_STATUS_CODE -1
} // namespace
namespace AlibabaCloud {
HttpResponse::HttpResponse() :
HttpMessage(),
request_(),
statusCode_(INVALID_STATUS_CODE) {
}
HttpResponse::HttpResponse()
: HttpMessage(), request_(), statusCode_(INVALID_STATUS_CODE) {}
HttpResponse::HttpResponse(const HttpRequest & request) :
HttpMessage(),
request_(request),
statusCode_(INVALID_STATUS_CODE) {
}
HttpResponse::HttpResponse(const HttpRequest &request)
: HttpMessage(), request_(request), statusCode_(INVALID_STATUS_CODE) {}
HttpResponse::~HttpResponse() {
}
HttpResponse::~HttpResponse() {}
HttpRequest HttpResponse::request() const {
return request_;
}
HttpRequest HttpResponse::request() const { return request_; }
void HttpResponse::setStatusCode(int code) {
statusCode_ = code;
}
void HttpResponse::setStatusCode(int code) { statusCode_ = code; }
int HttpResponse::statusCode() const {
return statusCode_;
}
int HttpResponse::statusCode() const { return statusCode_; }
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -18,11 +18,9 @@
namespace AlibabaCloud {
InstanceProfileCredentials::InstanceProfileCredentials() :
BasicSessionCredentials(Credentials::InstanceProfile) {
}
InstanceProfileCredentials::InstanceProfileCredentials()
: BasicSessionCredentials(Credentials::InstanceProfile) {}
InstanceProfileCredentials::~InstanceProfileCredentials() {
}
InstanceProfileCredentials::~InstanceProfileCredentials() {}
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -15,37 +15,33 @@
*/
#include "EcsMetadataFetcher.h"
#include <alibabacloud/core/Utils.h>
#include <alibabacloud/core/InstanceProfileCredentialsProvider.h>
#include <alibabacloud/core/Utils.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_()
{
cachedCredentials_("", ""), expiry_() {
setRoleName(roleName);
}
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();
@@ -53,20 +49,17 @@ bool InstanceProfileCredentialsProvider::checkExpiry() const
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,9 +70,8 @@ void InstanceProfileCredentialsProvider::loadCredentials()
auto securityToken = value["SecurityToken"].asString();
auto expiration = value["Expiration"].asString();
cachedCredentials_ = Credentials(accessKeyId,
accessKeySecret,
securityToken);
cachedCredentials_ =
Credentials(accessKeyId, accessKeySecret, securityToken);
std::tm tm = {};
#if defined(__GNUG__) && __GNUC__ < 5

File diff suppressed because it is too large Load Diff

7014
core/src/LocalEndpointsForWindows.h Executable file → Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -18,32 +18,19 @@
namespace AlibabaCloud {
NetworkProxy::NetworkProxy(Type type,
const std::string &hostName,
uint16_t port,
const std::string &user,
const std::string &password)
: hostName_(hostName),
password_(password),
port_(port),
type_(type),
user_(user) {
}
NetworkProxy::NetworkProxy(Type type, const std::string &hostName,
uint16_t port, const std::string &user,
const std::string &password)
: hostName_(hostName), password_(password), port_(port), type_(type),
user_(user) {}
NetworkProxy::~NetworkProxy() {
}
NetworkProxy::~NetworkProxy() {}
std::string NetworkProxy::hostName() const {
return hostName_;
}
std::string NetworkProxy::hostName() const { return hostName_; }
std::string NetworkProxy::password() const {
return password_;
}
std::string NetworkProxy::password() const { return password_; }
uint16_t NetworkProxy::port() const {
return port_;
}
uint16_t NetworkProxy::port() const { return port_; }
void NetworkProxy::setHostName(const std::string &hostName) {
hostName_ = hostName;
@@ -53,24 +40,14 @@ void NetworkProxy::setPassword(const std::string &password) {
password_ = password;
}
void NetworkProxy::setPort(uint16_t port) {
port_ = port;
}
void NetworkProxy::setPort(uint16_t port) { port_ = port; }
void NetworkProxy::setType(NetworkProxy::Type type) {
type_ = type;
}
void NetworkProxy::setType(NetworkProxy::Type type) { type_ = type; }
void NetworkProxy::setUser(const std::string &user) {
user_ = user;
}
void NetworkProxy::setUser(const std::string &user) { user_ = user; }
NetworkProxy::Type NetworkProxy::type() const {
return type_;
}
NetworkProxy::Type NetworkProxy::type() const { return type_; }
std::string NetworkProxy::user() const {
return user_;
}
std::string NetworkProxy::user() const { return user_; }
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -14,51 +14,53 @@
* limitations under the License.
*/
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/RoaServiceClient.h>
#include <alibabacloud/core/HmacSha1Signer.h>
#include <algorithm>
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/HmacSha1Signer.h>
#include <alibabacloud/core/RoaServiceClient.h>
#include <alibabacloud/core/Utils.h>
#include <iomanip>
#include <sstream>
#include <alibabacloud/core/Utils.h>
namespace AlibabaCloud {
RoaServiceClient::RoaServiceClient(const std::string & servicename,
const std::shared_ptr<CredentialsProvider> &credentialsProvider,
const ClientConfiguration &configuration,
const std::shared_ptr<Signer> &signer) :
CoreClient(servicename, configuration),
credentialsProvider_(credentialsProvider),
signer_(signer) {
}
RoaServiceClient::RoaServiceClient(
const std::string &servicename,
const std::shared_ptr<CredentialsProvider> &credentialsProvider,
const ClientConfiguration &configuration,
const std::shared_ptr<Signer> &signer)
: CoreClient(servicename, configuration),
credentialsProvider_(credentialsProvider), signer_(signer) {}
RoaServiceClient::~RoaServiceClient() {
}
RoaServiceClient::~RoaServiceClient() {}
RoaServiceClient::JsonOutcome RoaServiceClient::makeRequest(
const std::string &endpoint,
const RoaServiceRequest &request, HttpRequest::Method method) const
{
if(method == HttpRequest::Method::Get){
RoaServiceClient::JsonOutcome
RoaServiceClient::makeRequest(const std::string &endpoint,
const RoaServiceRequest &request,
HttpRequest::Method method) const {
if (method == HttpRequest::Method::Get) {
method = request.method();
}
auto outcome = AttemptRequest(endpoint, request, method);
if (outcome.isSuccess())
return JsonOutcome(std::string(outcome.result().body(),
outcome.result().bodySize()));
return JsonOutcome(
std::string(outcome.result().body(), outcome.result().bodySize()));
else
return JsonOutcome(outcome.error());
}
HttpRequest RoaServiceClient::buildHttpRequest(const std::string & endpoint,
const ServiceRequest &msg, HttpRequest::Method method)const {
HttpRequest
RoaServiceClient::buildHttpRequest(const std::string &endpoint,
const ServiceRequest &msg,
HttpRequest::Method method) const {
return buildHttpRequest(endpoint,
dynamic_cast<const RoaServiceRequest& >(msg), method);
dynamic_cast<const RoaServiceRequest &>(msg), method);
}
HttpRequest RoaServiceClient::buildHttpRequest(const std::string & endpoint,
const RoaServiceRequest &msg, HttpRequest::Method method) const {
HttpRequest
RoaServiceClient::buildHttpRequest(const std::string &endpoint,
const RoaServiceRequest &msg,
HttpRequest::Method method) const {
const Credentials credentials = credentialsProvider_->getCredentials();
Url url;
@@ -71,7 +73,7 @@ HttpRequest RoaServiceClient::buildHttpRequest(const std::string & endpoint,
url.setPath(msg.resourcePath());
auto params = msg.parameters();
std::map <std::string, std::string> queryParams;
std::map<std::string, std::string> queryParams;
for (const auto &p : params) {
if (!p.second.empty())
queryParams[p.first] = p.second;
@@ -102,10 +104,10 @@ HttpRequest RoaServiceClient::buildHttpRequest(const std::string & endpoint,
request.setReadTimeout(configuration().readTimeout());
}
for(const auto &h : msg.headers()){
if(!h.second.empty()){
request.setHeader(h.first, h.second);
}
for (const auto &h : msg.headers()) {
if (!h.second.empty()) {
request.setHeader(h.first, h.second);
}
}
if (msg.parameter("Accept").empty()) {
@@ -124,7 +126,7 @@ HttpRequest RoaServiceClient::buildHttpRequest(const std::string & endpoint,
request.setHeader("Content-Type", msg.parameter("Content-Type"));
}
request.setHeader("Content-MD5",
ComputeContentMD5(msg.content(), msg.contentSize()));
ComputeContentMD5(msg.content(), msg.contentSize()));
request.setBody(msg.content(), msg.contentSize());
}
@@ -140,7 +142,7 @@ HttpRequest RoaServiceClient::buildHttpRequest(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());
@@ -151,23 +153,21 @@ HttpRequest RoaServiceClient::buildHttpRequest(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
plaintext << url.path() << "?" << url.query();
std::stringstream sign;
sign << "acs "
<< credentials.accessKeyId()
<< ":"
<< signer_->generate(plaintext.str(), credentials.accessKeySecret());
sign << "acs " << credentials.accessKeyId() << ":"
<< signer_->generate(plaintext.str(), credentials.accessKeySecret());
request.setHeader("Authorization", sign.str());
return request;
}
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -14,22 +14,18 @@
* limitations under the License.
*/
#include <alibabacloud/core/RoaServiceRequest.h>
#include <algorithm>
#include <alibabacloud/core/RoaServiceRequest.h>
#include <alibabacloud/core/Utils.h>
#include <iomanip>
#include <sstream>
#include <alibabacloud/core/Utils.h>
namespace AlibabaCloud
{
namespace AlibabaCloud {
RoaServiceRequest::RoaServiceRequest(const std::string &product,
const std::string &version) : ServiceRequest(product, version)
{
}
const std::string &version)
: ServiceRequest(product, version) {}
RoaServiceRequest::~RoaServiceRequest()
{
}
RoaServiceRequest::~RoaServiceRequest() {}
} // namespace AlibabaCloud

View File

@@ -14,61 +14,59 @@
* limitations under the License.
*/
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/RpcServiceClient.h>
#include <alibabacloud/core/HmacSha1Signer.h>
#include <algorithm>
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/HmacSha1Signer.h>
#include <alibabacloud/core/RpcServiceClient.h>
#include <alibabacloud/core/Utils.h>
#include <iomanip>
#include <sstream>
#include <alibabacloud/core/Utils.h>
namespace AlibabaCloud {
RpcServiceClient::RpcServiceClient(const std::string & servicename,
const std::shared_ptr<CredentialsProvider> &credentialsProvider,
const ClientConfiguration &configuration,
const std::shared_ptr<Signer> &signer) :
CoreClient(servicename, configuration),
credentialsProvider_(credentialsProvider),
signer_(signer) {
}
RpcServiceClient::RpcServiceClient(
const std::string &servicename,
const std::shared_ptr<CredentialsProvider> &credentialsProvider,
const ClientConfiguration &configuration,
const std::shared_ptr<Signer> &signer)
: CoreClient(servicename, configuration),
credentialsProvider_(credentialsProvider), signer_(signer) {}
RpcServiceClient::~RpcServiceClient() {
}
RpcServiceClient::~RpcServiceClient() {}
RpcServiceClient::JsonOutcome RpcServiceClient::makeRequest(
const std::string &endpoint,
const RpcServiceRequest &request, HttpRequest::Method method) const
{
if (method == HttpRequest::Method::Get)
{
RpcServiceClient::JsonOutcome
RpcServiceClient::makeRequest(const std::string &endpoint,
const RpcServiceRequest &request,
HttpRequest::Method method) const {
if (method == HttpRequest::Method::Get) {
method = request.method();
}
auto outcome = AttemptRequest(endpoint, request, method);
if (outcome.isSuccess())
return JsonOutcome(std::string(outcome.result().body(),
outcome.result().bodySize()));
return JsonOutcome(
std::string(outcome.result().body(), outcome.result().bodySize()));
else
return JsonOutcome(outcome.error());
}
HttpRequest RpcServiceClient::buildHttpRequest(const std::string & endpoint,
const ServiceRequest &msg, HttpRequest::Method method)const {
HttpRequest
RpcServiceClient::buildHttpRequest(const std::string &endpoint,
const ServiceRequest &msg,
HttpRequest::Method method) const {
return buildHttpRequest(endpoint,
dynamic_cast<const RpcServiceRequest& >(msg), method);
dynamic_cast<const RpcServiceRequest &>(msg), method);
}
HttpRequest RpcServiceClient::buildHttpRequest(const std::string & endpoint,
const RpcServiceRequest &msg, HttpRequest::Method method) const {
HttpRequest
RpcServiceClient::buildHttpRequest(const std::string &endpoint,
const RpcServiceRequest &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);
@@ -77,8 +75,7 @@ HttpRequest RpcServiceClient::buildHttpRequest(const std::string & endpoint,
std::map<std::string, std::string> signParams;
auto params = msg.parameters();
for (const auto &p : params)
{
for (const auto &p : params) {
if (!p.second.empty())
signParams[p.first] = p.second;
}
@@ -103,25 +100,20 @@ HttpRequest RpcServiceClient::buildHttpRequest(const std::string & endpoint,
signParams["Version"] = msg.version();
std::map<std::string, std::string> query;
for (const auto &p : signParams)
{
for (const auto &p : signParams) {
query[p.first] = p.second;
}
auto body_params = msg.bodyParameters();
for (const auto &p : body_params)
{
for (const auto &p : body_params) {
signParams[p.first] = p.second;
}
std::stringstream plaintext;
plaintext << HttpMethodToString(method)
<< "&"
<< UrlEncode(url.path())
<< "&"
plaintext << HttpMethodToString(method) << "&" << UrlEncode(url.path()) << "&"
<< UrlEncode(canonicalizedQuery(signParams));
query["Signature"] = signer_->generate(plaintext.str(),
credentials.accessKeySecret() + "&");
query["Signature"] =
signer_->generate(plaintext.str(), credentials.accessKeySecret() + "&");
std::stringstream queryString;
for (const auto &p : query)
@@ -129,29 +121,21 @@ HttpRequest RpcServiceClient::buildHttpRequest(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());
}
for (const auto &h : msg.headers())
{
if (!h.second.empty())
{
for (const auto &h : msg.headers()) {
if (!h.second.empty()) {
request.setHeader(h.first, h.second);
}
}
if (msg.readTimeout() != kInvalidTimeout)
{
if (msg.readTimeout() != kInvalidTimeout) {
request.setReadTimeout(msg.readTimeout());
}
else
{
} else {
request.setReadTimeout(configuration().readTimeout());
}
@@ -162,11 +146,11 @@ HttpRequest RpcServiceClient::buildHttpRequest(const std::string & endpoint,
std::stringstream tmp;
for (const auto &p : body_params)
tmp << "&" << p.first << "=" << UrlEncode(p.second);
if(tmp.str().length() > 0){
if (tmp.str().length() > 0) {
std::string body = tmp.str().substr(1);
request.setBody(body.c_str(), body.length());
}
return request;
}
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -18,21 +18,21 @@
namespace AlibabaCloud {
RpcServiceRequest::RpcServiceRequest(const std::string & product,
const std::string & version, const std::string & action) :
ServiceRequest(product, version) {
RpcServiceRequest::RpcServiceRequest(const std::string &product,
const std::string &version,
const std::string &action)
: ServiceRequest(product, version) {
setActionName(action);
}
RpcServiceRequest::~RpcServiceRequest() {
}
RpcServiceRequest::~RpcServiceRequest() {}
std::string RpcServiceRequest::actionName()const {
std::string RpcServiceRequest::actionName() const {
return parameter("Action");
}
void RpcServiceRequest::setActionName(const std::string & name) {
void RpcServiceRequest::setActionName(const std::string &name) {
setParameter("Action", name);
}
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -1,29 +1,25 @@
/*
* 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/Runnable.h>
namespace AlibabaCloud {
Runnable::Runnable(const std::function<void()> f) :
f_(f) {
}
Runnable::Runnable(const std::function<void()> f) : f_(f) {}
void Runnable::run() const {
f_();
}
void Runnable::run() const { f_(); }
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -14,49 +14,34 @@
* limitations under the License.
*/
#include <alibabacloud/core/ServiceRequest.h>
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/ServiceRequest.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),
method_(HttpRequest::Method::Get)
{
}
const std::string &version)
: content_(nullptr), contentSize_(0), params_(), product_(product),
resourcePath_("/"), version_(version), scheme_("https"),
connectTimeout_(kInvalidTimeout), readTimeout_(kInvalidTimeout),
method_(HttpRequest::Method::Get) {}
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_)
{
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_;
@@ -67,42 +52,29 @@ 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
{
return content_;
}
const char *ServiceRequest::content() const { return content_; }
size_t ServiceRequest::contentSize() const
{
return contentSize_;
}
size_t ServiceRequest::contentSize() const { return contentSize_; }
bool ServiceRequest::hasContent() const
{
return (contentSize_ != 0);
}
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_);
@@ -110,160 +82,119 @@ void ServiceRequest::setContent(const char *data, size_t size)
}
void ServiceRequest::addParameter(const ParameterNameType &name,
const ParameterValueType &value)
{
const ParameterValueType &value) {
setParameter(name, value);
}
ServiceRequest::ParameterValueType ServiceRequest::parameter(
const ParameterNameType &name) const
{
ServiceRequest::ParameterValueType
ServiceRequest::parameter(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
{
ServiceRequest::ParameterValueType
ServiceRequest::coreParameter(const ParameterNameType &name) const {
return parameter(name);
}
ServiceRequest::ParameterCollection ServiceRequest::parameters() const
{
ServiceRequest::ParameterCollection ServiceRequest::parameters() const {
return params_;
}
ServiceRequest::ParameterCollection ServiceRequest::bodyParameters() const
{
ServiceRequest::ParameterCollection ServiceRequest::bodyParameters() const {
return body_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::setBodyParameter(const ParameterNameType &name, const ParameterValueType &value)
{
void ServiceRequest::setBodyParameter(const ParameterNameType &name,
const ParameterValueType &value) {
body_params_[name] = value;
}
void ServiceRequest::setParameters(const ParameterCollection &params)
{
void ServiceRequest::setParameters(const ParameterCollection &params) {
params_ = params;
}
void ServiceRequest::setJsonParameters(const ParameterNameType &name, const ParameterCollection &params)
{
void ServiceRequest::setJsonParameters(const ParameterNameType &name,
const ParameterCollection &params) {
params_ = params;
params_ = params;
setParameter(name, AlibabaCloud::MapToJson(params));
}
std::string ServiceRequest::version() const
{
return version_;
}
std::string ServiceRequest::version() const { return version_; }
HttpRequest::Method ServiceRequest::method() const
{
return method_;
}
HttpRequest::Method ServiceRequest::method() const { return method_; }
void ServiceRequest::setVersion(const std::string &version)
{
void ServiceRequest::setVersion(const std::string &version) {
version_ = version;
}
std::string ServiceRequest::product() const
{
return product_;
}
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
{
return resourcePath_;
}
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)
{
scheme_ = scheme;
}
void ServiceRequest::setScheme(const std::string scheme) { scheme_ = scheme; }
std::string ServiceRequest::scheme() const
{
return scheme_;
}
std::string ServiceRequest::scheme() const { return scheme_; }
long ServiceRequest::connectTimeout() const
{
return connectTimeout_;
}
long ServiceRequest::connectTimeout() const { return connectTimeout_; }
long ServiceRequest::readTimeout() const
{
return readTimeout_;
}
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;
}
void ServiceRequest::setMethod(const HttpRequest::Method method)
{
void ServiceRequest::setMethod(const HttpRequest::Method method) {
method_ = method;
}
void ServiceRequest::setHeader(const ServiceRequest::ParameterNameType &name,
const ServiceRequest::ParameterValueType &value)
{
void ServiceRequest::setHeader(
const ServiceRequest::ParameterNameType &name,
const ServiceRequest::ParameterValueType &value) {
headers_[name] = value;
}
ServiceRequest::ParameterValueType ServiceRequest::getHeader(const ServiceRequest::ParameterNameType &name)
{
ServiceRequest::ParameterValueType
ServiceRequest::getHeader(const ServiceRequest::ParameterNameType &name) {
return headers_[name];
}
void ServiceRequest::removeHeader(const ServiceRequest::ParameterNameType &name)
{
void ServiceRequest::removeHeader(
const ServiceRequest::ParameterNameType &name) {
headers_.erase(name);
}
ServiceRequest::ParameterCollection ServiceRequest::headers() const
{
ServiceRequest::ParameterCollection ServiceRequest::headers() const {
return headers_;
}

View File

@@ -18,19 +18,14 @@
namespace AlibabaCloud {
ServiceResult::ServiceResult() :
requestId_() {
}
ServiceResult::ServiceResult() : requestId_() {}
ServiceResult::~ServiceResult() {
}
ServiceResult::~ServiceResult() {}
std::string ServiceResult::requestId() const {
return requestId_;
}
std::string ServiceResult::requestId() const { return requestId_; }
void ServiceResult::setRequestId(const std::string & requestId) {
void ServiceResult::setRequestId(const std::string &requestId) {
requestId_ = requestId;
}
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -18,26 +18,15 @@
namespace AlibabaCloud {
Signer::Signer(Type type, const std::string & name,
const std::string & version) :
type_(type),
name_(name),
version_(version) {
}
Signer::Signer(Type type, const std::string &name, const std::string &version)
: type_(type), name_(name), version_(version) {}
Signer::~Signer() {
}
Signer::~Signer() {}
std::string Signer::name() const {
return name_;
}
std::string Signer::name() const { return name_; }
Signer::Type Signer::type() const {
return type_;
}
Signer::Type Signer::type() const { return type_; }
std::string Signer::version() const {
return version_;
}
std::string Signer::version() const { return version_; }
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -19,22 +19,15 @@
namespace AlibabaCloud {
SimpleCredentialsProvider::SimpleCredentialsProvider(
const Credentials &credentials):
CredentialsProvider(),
credentials_(credentials) {
}
const Credentials &credentials)
: CredentialsProvider(), credentials_(credentials) {}
SimpleCredentialsProvider::SimpleCredentialsProvider(
const std::string & accessKeyId, const std::string & accessKeySecret) :
CredentialsProvider(),
credentials_(accessKeyId, accessKeySecret) {
}
const std::string &accessKeyId, const std::string &accessKeySecret)
: CredentialsProvider(), credentials_(accessKeyId, accessKeySecret) {}
SimpleCredentialsProvider::~SimpleCredentialsProvider() {
}
SimpleCredentialsProvider::~SimpleCredentialsProvider() {}
Credentials SimpleCredentialsProvider::getCredentials() {
return credentials_;
}
Credentials SimpleCredentialsProvider::getCredentials() { return credentials_; }
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -1,18 +1,18 @@
/*
* 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/StsAssumeRoleCredentialsProvider.h>
#include <iomanip>
@@ -21,25 +21,15 @@
namespace AlibabaCloud {
StsAssumeRoleCredentialsProvider::StsAssumeRoleCredentialsProvider(
const Credentials &credentials,
const ClientConfiguration &configuration,
const std::string & roleArn,
const std::string & roleSessionName,
const std::string & policy,
int durationSeconds):
CredentialsProvider(),
StsClient(credentials, configuration),
roleArn_(roleArn),
roleSessionName_(roleSessionName),
policy_(policy),
durationSeconds_(durationSeconds),
cachedMutex_(),
cachedCredentials_("", ""),
expiry_() {
}
const Credentials &credentials, const ClientConfiguration &configuration,
const std::string &roleArn, const std::string &roleSessionName,
const std::string &policy, int durationSeconds)
: CredentialsProvider(), StsClient(credentials, configuration),
roleArn_(roleArn), roleSessionName_(roleSessionName), policy_(policy),
durationSeconds_(durationSeconds), cachedMutex_(),
cachedCredentials_("", ""), expiry_() {}
StsAssumeRoleCredentialsProvider::~StsAssumeRoleCredentialsProvider() {
}
StsAssumeRoleCredentialsProvider::~StsAssumeRoleCredentialsProvider() {}
Credentials StsAssumeRoleCredentialsProvider::getCredentials() {
loadCredentials();
@@ -47,10 +37,10 @@ Credentials StsAssumeRoleCredentialsProvider::getCredentials() {
return cachedCredentials_;
}
bool StsAssumeRoleCredentialsProvider::checkExpiry()const {
bool StsAssumeRoleCredentialsProvider::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);
}
@@ -69,8 +59,8 @@ void StsAssumeRoleCredentialsProvider::loadCredentials() {
if (assumeRoleOutcome.isSuccess()) {
const auto stsCredentials = assumeRoleOutcome.result().credentials();
cachedCredentials_ = Credentials(stsCredentials.accessKeyId,
stsCredentials.accessKeySecret,
stsCredentials.securityToken);
stsCredentials.accessKeySecret,
stsCredentials.securityToken);
std::tm tm = {};
#if defined(__GNUG__) && __GNUC__ < 5
@@ -85,4 +75,4 @@ void StsAssumeRoleCredentialsProvider::loadCredentials() {
}
}
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -14,46 +14,33 @@
* limitations under the License.
*/
#include <alibabacloud/core/Url.h>
#include <algorithm>
#include <alibabacloud/core/Url.h>
#include <sstream>
namespace AlibabaCloud {
namespace {
#define INVALID_PORT -1
}
} // namespace
Url::Url(const std::string & url) :
scheme_(),
userName_(),
password_(),
host_(),
path_(),
port_(INVALID_PORT),
query_(),
fragment_() {
Url::Url(const std::string &url)
: scheme_(), userName_(), password_(), host_(), path_(),
port_(INVALID_PORT), query_(), fragment_() {
if (!url.empty())
fromString(url);
}
Url::~Url() {
}
Url::~Url() {}
bool Url::operator==(const Url &url) const {
return scheme_ == url.scheme_
&& userName_ == url.userName_
&& password_ == url.password_
&& host_ == url.host_
&& path_ == url.path_
&& port_ == url.port_
&& query_ == url.query_
&& fragment_ == url.fragment_;
return scheme_ == url.scheme_ && userName_ == url.userName_ &&
password_ == url.password_ && host_ == url.host_ &&
path_ == url.path_ && port_ == url.port_ && query_ == url.query_ &&
fragment_ == url.fragment_;
}
bool Url::operator!=(const Url &url) const {
return !(*this == url);
}
bool Url::operator!=(const Url &url) const { return !(*this == url); }
std::string Url::authority() const {
if (!isValid())
@@ -80,11 +67,9 @@ void Url::clear() {
fragment_.clear();
}
std::string Url::fragment() const {
return fragment_;
}
std::string Url::fragment() const { return fragment_; }
void Url::fromString(const std::string & url) {
void Url::fromString(const std::string &url) {
clear();
if (url.empty())
return;
@@ -128,27 +113,16 @@ void Url::fromString(const std::string & url) {
setFragment(fragment);
}
bool Url::hasFragment() const {
return !fragment_.empty();
}
bool Url::hasFragment() const { return !fragment_.empty(); }
bool Url::hasQuery() const {
return !query_.empty();
}
bool Url::hasQuery() const { return !query_.empty(); }
std::string Url::host() const {
return host_;
}
std::string Url::host() const { return host_; }
bool Url::isEmpty() const {
return scheme_.empty()
&& userName_.empty()
&& password_.empty()
&& host_.empty()
&& path_.empty()
&& (port_ == INVALID_PORT)
&& query_.empty()
&& fragment_.empty();
return scheme_.empty() && userName_.empty() && password_.empty() &&
host_.empty() && path_.empty() && (port_ == INVALID_PORT) &&
query_.empty() && fragment_.empty();
}
bool Url::isValid() const {
@@ -164,27 +138,17 @@ bool Url::isValid() const {
return valid;
}
int Url::port() const {
return port_;
}
int Url::port() const { return port_; }
std::string Url::password() const {
return password_;
}
std::string Url::password() const { return password_; }
std::string Url::path() const {
return path_;
}
std::string Url::path() const { return path_; }
std::string Url::query() const {
return query_;
}
std::string Url::query() const { return query_; }
std::string Url::scheme() const {
return scheme_;
}
std::string Url::scheme() const { return scheme_; }
void Url::setAuthority(const std::string & authority) {
void Url::setAuthority(const std::string &authority) {
if (authority.empty()) {
setUserInfo("");
setHost("");
@@ -213,14 +177,12 @@ void Url::setAuthority(const std::string & authority) {
setUserInfo(userinfo);
setHost(host);
setPort(!port.empty() ? atoi(port.c_str()): INVALID_PORT);
setPort(!port.empty() ? atoi(port.c_str()) : INVALID_PORT);
}
void Url::setFragment(const std::string & fragment) {
fragment_ = fragment;
}
void Url::setFragment(const std::string &fragment) { fragment_ = fragment; }
void Url::setHost(const std::string & host) {
void Url::setHost(const std::string &host) {
if (host.empty()) {
host_.clear();
return;
@@ -229,23 +191,15 @@ void Url::setHost(const std::string & host) {
std::transform(host_.begin(), host_.end(), host_.begin(), ::tolower);
}
void Url::setPassword(const std::string & password) {
password_ = password;
}
void Url::setPassword(const std::string &password) { password_ = password; }
void Url::setPath(const std::string & path) {
path_ = path;
}
void Url::setPath(const std::string &path) { path_ = path; }
void Url::setPort(int port) {
port_ = port;
}
void Url::setPort(int port) { port_ = port; }
void Url::setQuery(const std::string & query) {
query_ = query;
}
void Url::setQuery(const std::string &query) { query_ = query; }
void Url::setScheme(const std::string & scheme) {
void Url::setScheme(const std::string &scheme) {
if (scheme.empty()) {
scheme_.clear();
return;
@@ -254,7 +208,7 @@ void Url::setScheme(const std::string & scheme) {
std::transform(scheme_.begin(), scheme_.end(), scheme_.begin(), ::tolower);
}
void Url::setUserInfo(const std::string & userInfo) {
void Url::setUserInfo(const std::string &userInfo) {
if (userInfo.empty()) {
userName_.clear();
password_.clear();
@@ -270,9 +224,7 @@ void Url::setUserInfo(const std::string & userInfo) {
}
}
void Url::setUserName(const std::string & userName) {
userName_ = userName;
}
void Url::setUserName(const std::string &userName) { userName_ = userName; }
std::string Url::toString() const {
if (!isValid())
@@ -306,8 +258,6 @@ std::string Url::userInfo() const {
return out.str();
}
std::string Url::userName() const {
return userName_;
}
std::string Url::userName() const { return userName_; }
} // namespace AlibabaCloud
} // namespace AlibabaCloud

View File

@@ -15,9 +15,9 @@
*/
#include <algorithm>
#include <alibabacloud/core/Utils.h>
#include <sstream>
#include <stdlib.h>
#include <alibabacloud/core/Utils.h>
#ifdef _WIN32
#include <Windows.h>
@@ -29,8 +29,7 @@
#include <curl/curl.h>
#include <json/json.h>
std::string AlibabaCloud::GenerateUuid()
{
std::string AlibabaCloud::GenerateUuid() {
#ifdef _WIN32
char *data;
UUID uuidhandle;
@@ -48,8 +47,7 @@ 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);
@@ -58,8 +56,7 @@ 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);
@@ -69,8 +66,7 @@ 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;
@@ -108,20 +104,16 @@ std::string AlibabaCloud::ComputeContentMD5(const char *data, size_t size)
}
void AlibabaCloud::StringReplace(std::string &src, const std::string &s1,
const std::string &s2)
{
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;
@@ -154,14 +146,12 @@ std::string AlibabaCloud::HttpMethodToString(HttpRequest::Method method)
}
std::string AlibabaCloud::canonicalizedQuery(
const std::map<std::string, std::string> &params)
{
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");
@@ -176,11 +166,9 @@ std::string AlibabaCloud::canonicalizedQuery(
}
std::string AlibabaCloud::canonicalizedHeaders(
const HttpMessage::HeaderCollection &headers)
{
const HttpMessage::HeaderCollection &headers) {
std::map<std::string, std::string> materials;
for (const auto &p : headers)
{
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)
@@ -203,91 +191,78 @@ std::string AlibabaCloud::canonicalizedHeaders(
return ss.str();
}
std::string AlibabaCloud::GetEnv(const std::string env)
{
std::string AlibabaCloud::GetEnv(const std::string env) {
#ifdef _WIN32
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)
{
if (var) {
return std::string(var);
}
return std::string();
#endif
}
std::string AlibabaCloud::MapToJson(const std::map<std::string, std::string> &maps)
{
std::string
AlibabaCloud::MapToJson(const std::map<std::string, std::string> &maps) {
Json::Value jsonObject;
Json::FastWriter writer;
for (std::map<std::string, std::string>::const_iterator iter = maps.begin(); iter != maps.end(); ++iter)
{
Json::FastWriter writer;
for (std::map<std::string, std::string>::const_iterator iter = maps.begin();
iter != maps.end(); ++iter) {
jsonObject[iter->first] = iter->second;
}
std::string unformat_str = writer.write(jsonObject);
return unformat_str.substr(0, unformat_str.length() - 1);
}
std::map<std::string, std::string> AlibabaCloud::JsonToMap(const std::string &json)
{
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))
{
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++)
{
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()));
switch (vt) {
case Json::stringValue: {
maps.insert(
std::pair<std::string, std::string>(*it, value[*it].asString()));
break;
}
case Json::intValue:
{
case Json::intValue: {
int inttmp = value[*it].asInt();
maps.insert(std::pair<std::string, std::string>(*it, std::to_string(inttmp)));
maps.insert(
std::pair<std::string, std::string>(*it, std::to_string(inttmp)));
break;
}
case Json::arrayValue:
{
case Json::arrayValue: {
std::string strid;
for (unsigned int i = 0; i < value[*it].size(); i++)
{
for (unsigned int i = 0; i < value[*it].size(); i++) {
strid += value[*it][i].asString();
strid += ",";
}
if (!strid.empty())
{
if (!strid.empty()) {
strid = strid.substr(0, strid.size() - 1);
}
maps.insert(std::pair<std::string, std::string>(*it, strid));
break;
}
default:
{
default: {
break;
}
}