code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeBusinessCardRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeBusinessCardRequest;
RecognizeBusinessCardRequest::RecognizeBusinessCardRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeBusinessCard")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeBusinessCardRequest::~RecognizeBusinessCardRequest()
{}
int RecognizeBusinessCardRequest::getImageType()const
{
return imageType_;
}
void RecognizeBusinessCardRequest::setImageType(int imageType)
{
imageType_ = imageType;
setBodyParameter("ImageType", std::to_string(imageType));
}
std::string RecognizeBusinessCardRequest::getImageURL()const
{
return imageURL_;
}
void RecognizeBusinessCardRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setBodyParameter("ImageURL", imageURL);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeBusinessCardRequest.cc
|
C++
|
apache-2.0
| 1,480
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeBusinessCardResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeBusinessCardResult::RecognizeBusinessCardResult() :
ServiceResult()
{}
RecognizeBusinessCardResult::RecognizeBusinessCardResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeBusinessCardResult::~RecognizeBusinessCardResult()
{}
void RecognizeBusinessCardResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
if(!dataNode["Name"].isNull())
data_.name = dataNode["Name"].asString();
auto allCompanies = dataNode["Companies"]["Company"];
for (auto value : allCompanies)
data_.companies.push_back(value.asString());
auto allDepartments = dataNode["Departments"]["Department"];
for (auto value : allDepartments)
data_.departments.push_back(value.asString());
auto allTitles = dataNode["Titles"]["Title"];
for (auto value : allTitles)
data_.titles.push_back(value.asString());
auto allCellPhoneNumbers = dataNode["CellPhoneNumbers"]["CellPhoneNumber"];
for (auto value : allCellPhoneNumbers)
data_.cellPhoneNumbers.push_back(value.asString());
auto allOfficePhoneNumbers = dataNode["OfficePhoneNumbers"]["OfficePhoneNumber"];
for (auto value : allOfficePhoneNumbers)
data_.officePhoneNumbers.push_back(value.asString());
auto allAddresses = dataNode["Addresses"]["Address"];
for (auto value : allAddresses)
data_.addresses.push_back(value.asString());
auto allEmails = dataNode["Emails"]["Email"];
for (auto value : allEmails)
data_.emails.push_back(value.asString());
}
RecognizeBusinessCardResult::Data RecognizeBusinessCardResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeBusinessCardResult.cc
|
C++
|
apache-2.0
| 2,496
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeBusinessLicenseRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeBusinessLicenseRequest;
RecognizeBusinessLicenseRequest::RecognizeBusinessLicenseRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeBusinessLicense")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeBusinessLicenseRequest::~RecognizeBusinessLicenseRequest()
{}
int RecognizeBusinessLicenseRequest::getImageType()const
{
return imageType_;
}
void RecognizeBusinessLicenseRequest::setImageType(int imageType)
{
imageType_ = imageType;
setBodyParameter("ImageType", std::to_string(imageType));
}
std::string RecognizeBusinessLicenseRequest::getImageURL()const
{
return imageURL_;
}
void RecognizeBusinessLicenseRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setBodyParameter("ImageURL", imageURL);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeBusinessLicenseRequest.cc
|
C++
|
apache-2.0
| 1,513
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeBusinessLicenseResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeBusinessLicenseResult::RecognizeBusinessLicenseResult() :
ServiceResult()
{}
RecognizeBusinessLicenseResult::RecognizeBusinessLicenseResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeBusinessLicenseResult::~RecognizeBusinessLicenseResult()
{}
void RecognizeBusinessLicenseResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
if(!dataNode["Angle"].isNull())
data_.angle = std::stof(dataNode["Angle"].asString());
if(!dataNode["RegisterNumber"].isNull())
data_.registerNumber = dataNode["RegisterNumber"].asString();
if(!dataNode["Name"].isNull())
data_.name = dataNode["Name"].asString();
if(!dataNode["Type"].isNull())
data_.type = dataNode["Type"].asString();
if(!dataNode["LegalPerson"].isNull())
data_.legalPerson = dataNode["LegalPerson"].asString();
if(!dataNode["EstablishDate"].isNull())
data_.establishDate = dataNode["EstablishDate"].asString();
if(!dataNode["ValidPeriod"].isNull())
data_.validPeriod = dataNode["ValidPeriod"].asString();
if(!dataNode["Address"].isNull())
data_.address = dataNode["Address"].asString();
if(!dataNode["Capital"].isNull())
data_.capital = dataNode["Capital"].asString();
if(!dataNode["Business"].isNull())
data_.business = dataNode["Business"].asString();
auto emblemNode = dataNode["Emblem"];
if(!emblemNode["Top"].isNull())
data_.emblem.top = std::stoi(emblemNode["Top"].asString());
if(!emblemNode["Left"].isNull())
data_.emblem.left = std::stoi(emblemNode["Left"].asString());
if(!emblemNode["Height"].isNull())
data_.emblem.height = std::stoi(emblemNode["Height"].asString());
if(!emblemNode["Width"].isNull())
data_.emblem.width = std::stoi(emblemNode["Width"].asString());
auto titleNode = dataNode["Title"];
if(!titleNode["Top"].isNull())
data_.title.top = std::stoi(titleNode["Top"].asString());
if(!titleNode["Left"].isNull())
data_.title.left = std::stoi(titleNode["Left"].asString());
if(!titleNode["Height"].isNull())
data_.title.height = std::stoi(titleNode["Height"].asString());
if(!titleNode["Width"].isNull())
data_.title.width = std::stoi(titleNode["Width"].asString());
auto stampNode = dataNode["Stamp"];
if(!stampNode["Top"].isNull())
data_.stamp.top = std::stoi(stampNode["Top"].asString());
if(!stampNode["Left"].isNull())
data_.stamp.left = std::stoi(stampNode["Left"].asString());
if(!stampNode["Height"].isNull())
data_.stamp.height = std::stoi(stampNode["Height"].asString());
if(!stampNode["Width"].isNull())
data_.stamp.width = std::stoi(stampNode["Width"].asString());
auto qRCodeNode = dataNode["QRCode"];
if(!qRCodeNode["Top"].isNull())
data_.qRCode.top = std::stoi(qRCodeNode["Top"].asString());
if(!qRCodeNode["Left"].isNull())
data_.qRCode.left = std::stoi(qRCodeNode["Left"].asString());
if(!qRCodeNode["Height"].isNull())
data_.qRCode.height = std::stoi(qRCodeNode["Height"].asString());
if(!qRCodeNode["Width"].isNull())
data_.qRCode.width = std::stoi(qRCodeNode["Width"].asString());
}
RecognizeBusinessLicenseResult::Data RecognizeBusinessLicenseResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeBusinessLicenseResult.cc
|
C++
|
apache-2.0
| 4,042
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeCharacterRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeCharacterRequest;
RecognizeCharacterRequest::RecognizeCharacterRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeCharacter")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeCharacterRequest::~RecognizeCharacterRequest()
{}
int RecognizeCharacterRequest::getImageType()const
{
return imageType_;
}
void RecognizeCharacterRequest::setImageType(int imageType)
{
imageType_ = imageType;
setBodyParameter("ImageType", std::to_string(imageType));
}
bool RecognizeCharacterRequest::getOutputProbability()const
{
return outputProbability_;
}
void RecognizeCharacterRequest::setOutputProbability(bool outputProbability)
{
outputProbability_ = outputProbability;
setBodyParameter("OutputProbability", outputProbability ? "true" : "false");
}
std::string RecognizeCharacterRequest::getImageURL()const
{
return imageURL_;
}
void RecognizeCharacterRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setBodyParameter("ImageURL", imageURL);
}
int RecognizeCharacterRequest::getMinHeight()const
{
return minHeight_;
}
void RecognizeCharacterRequest::setMinHeight(int minHeight)
{
minHeight_ = minHeight;
setBodyParameter("MinHeight", std::to_string(minHeight));
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeCharacterRequest.cc
|
C++
|
apache-2.0
| 1,988
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeCharacterResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeCharacterResult::RecognizeCharacterResult() :
ServiceResult()
{}
RecognizeCharacterResult::RecognizeCharacterResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeCharacterResult::~RecognizeCharacterResult()
{}
void RecognizeCharacterResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
auto allResultsNode = dataNode["Results"];
for (auto dataNodeResultsResult : allResultsNode)
{
Data::Result resultObject;
if(!dataNodeResultsResult["Probability"].isNull())
resultObject.probability = std::stof(dataNodeResultsResult["Probability"].asString());
if(!dataNodeResultsResult["Text"].isNull())
resultObject.text = dataNodeResultsResult["Text"].asString();
auto textRectanglesNode = dataNodeResultsResult["TextRectangles"];
if(!textRectanglesNode["Angle"].isNull())
resultObject.textRectangles.angle = std::stoi(textRectanglesNode["Angle"].asString());
if(!textRectanglesNode["Left"].isNull())
resultObject.textRectangles.left = std::stoi(textRectanglesNode["Left"].asString());
if(!textRectanglesNode["Top"].isNull())
resultObject.textRectangles.top = std::stoi(textRectanglesNode["Top"].asString());
if(!textRectanglesNode["Width"].isNull())
resultObject.textRectangles.width = std::stoi(textRectanglesNode["Width"].asString());
if(!textRectanglesNode["Height"].isNull())
resultObject.textRectangles.height = std::stoi(textRectanglesNode["Height"].asString());
data_.results.push_back(resultObject);
}
}
RecognizeCharacterResult::Data RecognizeCharacterResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeCharacterResult.cc
|
C++
|
apache-2.0
| 2,517
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeChinapassportRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeChinapassportRequest;
RecognizeChinapassportRequest::RecognizeChinapassportRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeChinapassport")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeChinapassportRequest::~RecognizeChinapassportRequest()
{}
std::string RecognizeChinapassportRequest::getImageURL()const
{
return imageURL_;
}
void RecognizeChinapassportRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setBodyParameter("ImageURL", imageURL);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeChinapassportRequest.cc
|
C++
|
apache-2.0
| 1,247
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeChinapassportResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeChinapassportResult::RecognizeChinapassportResult() :
ServiceResult()
{}
RecognizeChinapassportResult::RecognizeChinapassportResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeChinapassportResult::~RecognizeChinapassportResult()
{}
void RecognizeChinapassportResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
if(!dataNode["Authority"].isNull())
data_.authority = dataNode["Authority"].asString();
if(!dataNode["BirthDate"].isNull())
data_.birthDate = dataNode["BirthDate"].asString();
if(!dataNode["BirthDay"].isNull())
data_.birthDay = dataNode["BirthDay"].asString();
if(!dataNode["BirthPlace"].isNull())
data_.birthPlace = dataNode["BirthPlace"].asString();
if(!dataNode["BirthPlaceRaw"].isNull())
data_.birthPlaceRaw = dataNode["BirthPlaceRaw"].asString();
if(!dataNode["Country"].isNull())
data_.country = dataNode["Country"].asString();
if(!dataNode["ExpiryDate"].isNull())
data_.expiryDate = dataNode["ExpiryDate"].asString();
if(!dataNode["ExpiryDay"].isNull())
data_.expiryDay = dataNode["ExpiryDay"].asString();
if(!dataNode["IssueDate"].isNull())
data_.issueDate = dataNode["IssueDate"].asString();
if(!dataNode["IssuePlace"].isNull())
data_.issuePlace = dataNode["IssuePlace"].asString();
if(!dataNode["IssuePlaceRaw"].isNull())
data_.issuePlaceRaw = dataNode["IssuePlaceRaw"].asString();
if(!dataNode["LineZero"].isNull())
data_.lineZero = dataNode["LineZero"].asString();
if(!dataNode["LineOne"].isNull())
data_.lineOne = dataNode["LineOne"].asString();
if(!dataNode["Name"].isNull())
data_.name = dataNode["Name"].asString();
if(!dataNode["NameChinese"].isNull())
data_.nameChinese = dataNode["NameChinese"].asString();
if(!dataNode["NameChineseRaw"].isNull())
data_.nameChineseRaw = dataNode["NameChineseRaw"].asString();
if(!dataNode["PassportNo"].isNull())
data_.passportNo = dataNode["PassportNo"].asString();
if(!dataNode["PersonId"].isNull())
data_.personId = dataNode["PersonId"].asString();
if(!dataNode["Sex"].isNull())
data_.sex = dataNode["Sex"].asString();
if(!dataNode["SourceCountry"].isNull())
data_.sourceCountry = dataNode["SourceCountry"].asString();
if(!dataNode["Success"].isNull())
data_.success = dataNode["Success"].asString() == "true";
if(!dataNode["Type"].isNull())
data_.type = dataNode["Type"].asString();
}
RecognizeChinapassportResult::Data RecognizeChinapassportResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeChinapassportResult.cc
|
C++
|
apache-2.0
| 3,405
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeDriverLicenseRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeDriverLicenseRequest;
RecognizeDriverLicenseRequest::RecognizeDriverLicenseRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeDriverLicense")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeDriverLicenseRequest::~RecognizeDriverLicenseRequest()
{}
int RecognizeDriverLicenseRequest::getImageType()const
{
return imageType_;
}
void RecognizeDriverLicenseRequest::setImageType(int imageType)
{
imageType_ = imageType;
setBodyParameter("ImageType", std::to_string(imageType));
}
std::string RecognizeDriverLicenseRequest::getSide()const
{
return side_;
}
void RecognizeDriverLicenseRequest::setSide(const std::string& side)
{
side_ = side;
setBodyParameter("Side", side);
}
std::string RecognizeDriverLicenseRequest::getImageURL()const
{
return imageURL_;
}
void RecognizeDriverLicenseRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setBodyParameter("ImageURL", imageURL);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeDriverLicenseRequest.cc
|
C++
|
apache-2.0
| 1,729
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeDriverLicenseResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeDriverLicenseResult::RecognizeDriverLicenseResult() :
ServiceResult()
{}
RecognizeDriverLicenseResult::RecognizeDriverLicenseResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeDriverLicenseResult::~RecognizeDriverLicenseResult()
{}
void RecognizeDriverLicenseResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
auto faceResultNode = dataNode["FaceResult"];
if(!faceResultNode["Name"].isNull())
data_.faceResult.name = faceResultNode["Name"].asString();
if(!faceResultNode["LicenseNumber"].isNull())
data_.faceResult.licenseNumber = faceResultNode["LicenseNumber"].asString();
if(!faceResultNode["VehicleType"].isNull())
data_.faceResult.vehicleType = faceResultNode["VehicleType"].asString();
if(!faceResultNode["StartDate"].isNull())
data_.faceResult.startDate = faceResultNode["StartDate"].asString();
if(!faceResultNode["EndDate"].isNull())
data_.faceResult.endDate = faceResultNode["EndDate"].asString();
if(!faceResultNode["IssueDate"].isNull())
data_.faceResult.issueDate = faceResultNode["IssueDate"].asString();
if(!faceResultNode["Address"].isNull())
data_.faceResult.address = faceResultNode["Address"].asString();
if(!faceResultNode["Gender"].isNull())
data_.faceResult.gender = faceResultNode["Gender"].asString();
auto backResultNode = dataNode["BackResult"];
if(!backResultNode["ArchiveNumber"].isNull())
data_.backResult.archiveNumber = backResultNode["ArchiveNumber"].asString();
}
RecognizeDriverLicenseResult::Data RecognizeDriverLicenseResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeDriverLicenseResult.cc
|
C++
|
apache-2.0
| 2,513
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeDrivingLicenseRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeDrivingLicenseRequest;
RecognizeDrivingLicenseRequest::RecognizeDrivingLicenseRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeDrivingLicense")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeDrivingLicenseRequest::~RecognizeDrivingLicenseRequest()
{}
int RecognizeDrivingLicenseRequest::getImageType()const
{
return imageType_;
}
void RecognizeDrivingLicenseRequest::setImageType(int imageType)
{
imageType_ = imageType;
setBodyParameter("ImageType", std::to_string(imageType));
}
std::string RecognizeDrivingLicenseRequest::getSide()const
{
return side_;
}
void RecognizeDrivingLicenseRequest::setSide(const std::string& side)
{
side_ = side;
setBodyParameter("Side", side);
}
std::string RecognizeDrivingLicenseRequest::getImageURL()const
{
return imageURL_;
}
void RecognizeDrivingLicenseRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setBodyParameter("ImageURL", imageURL);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeDrivingLicenseRequest.cc
|
C++
|
apache-2.0
| 1,715
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeDrivingLicenseResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeDrivingLicenseResult::RecognizeDrivingLicenseResult() :
ServiceResult()
{}
RecognizeDrivingLicenseResult::RecognizeDrivingLicenseResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeDrivingLicenseResult::~RecognizeDrivingLicenseResult()
{}
void RecognizeDrivingLicenseResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
auto faceResultNode = dataNode["FaceResult"];
if(!faceResultNode["PlateNumber"].isNull())
data_.faceResult.plateNumber = faceResultNode["PlateNumber"].asString();
if(!faceResultNode["VehicleType"].isNull())
data_.faceResult.vehicleType = faceResultNode["VehicleType"].asString();
if(!faceResultNode["Owner"].isNull())
data_.faceResult.owner = faceResultNode["Owner"].asString();
if(!faceResultNode["UseCharacter"].isNull())
data_.faceResult.useCharacter = faceResultNode["UseCharacter"].asString();
if(!faceResultNode["Address"].isNull())
data_.faceResult.address = faceResultNode["Address"].asString();
if(!faceResultNode["Model"].isNull())
data_.faceResult.model = faceResultNode["Model"].asString();
if(!faceResultNode["Vin"].isNull())
data_.faceResult.vin = faceResultNode["Vin"].asString();
if(!faceResultNode["EngineNumber"].isNull())
data_.faceResult.engineNumber = faceResultNode["EngineNumber"].asString();
if(!faceResultNode["RegisterDate"].isNull())
data_.faceResult.registerDate = faceResultNode["RegisterDate"].asString();
if(!faceResultNode["IssueDate"].isNull())
data_.faceResult.issueDate = faceResultNode["IssueDate"].asString();
auto backResultNode = dataNode["BackResult"];
if(!backResultNode["ApprovedPassengerCapacity"].isNull())
data_.backResult.approvedPassengerCapacity = backResultNode["ApprovedPassengerCapacity"].asString();
if(!backResultNode["ApprovedLoad"].isNull())
data_.backResult.approvedLoad = backResultNode["ApprovedLoad"].asString();
if(!backResultNode["FileNumber"].isNull())
data_.backResult.fileNumber = backResultNode["FileNumber"].asString();
if(!backResultNode["GrossMass"].isNull())
data_.backResult.grossMass = backResultNode["GrossMass"].asString();
if(!backResultNode["EnergyType"].isNull())
data_.backResult.energyType = backResultNode["EnergyType"].asString();
if(!backResultNode["InspectionRecord"].isNull())
data_.backResult.inspectionRecord = backResultNode["InspectionRecord"].asString();
if(!backResultNode["OverallDimension"].isNull())
data_.backResult.overallDimension = backResultNode["OverallDimension"].asString();
if(!backResultNode["TractionMass"].isNull())
data_.backResult.tractionMass = backResultNode["TractionMass"].asString();
if(!backResultNode["UnladenMass"].isNull())
data_.backResult.unladenMass = backResultNode["UnladenMass"].asString();
if(!backResultNode["PlateNumber"].isNull())
data_.backResult.plateNumber = backResultNode["PlateNumber"].asString();
}
RecognizeDrivingLicenseResult::Data RecognizeDrivingLicenseResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeDrivingLicenseResult.cc
|
C++
|
apache-2.0
| 3,900
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeIdentityCardRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeIdentityCardRequest;
RecognizeIdentityCardRequest::RecognizeIdentityCardRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeIdentityCard")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeIdentityCardRequest::~RecognizeIdentityCardRequest()
{}
int RecognizeIdentityCardRequest::getImageType()const
{
return imageType_;
}
void RecognizeIdentityCardRequest::setImageType(int imageType)
{
imageType_ = imageType;
setBodyParameter("ImageType", std::to_string(imageType));
}
std::string RecognizeIdentityCardRequest::getSide()const
{
return side_;
}
void RecognizeIdentityCardRequest::setSide(const std::string& side)
{
side_ = side;
setBodyParameter("Side", side);
}
std::string RecognizeIdentityCardRequest::getImageURL()const
{
return imageURL_;
}
void RecognizeIdentityCardRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setBodyParameter("ImageURL", imageURL);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeIdentityCardRequest.cc
|
C++
|
apache-2.0
| 1,689
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeIdentityCardResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeIdentityCardResult::RecognizeIdentityCardResult() :
ServiceResult()
{}
RecognizeIdentityCardResult::RecognizeIdentityCardResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeIdentityCardResult::~RecognizeIdentityCardResult()
{}
void RecognizeIdentityCardResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
auto frontResultNode = dataNode["FrontResult"];
if(!frontResultNode["Address"].isNull())
data_.frontResult.address = frontResultNode["Address"].asString();
if(!frontResultNode["Name"].isNull())
data_.frontResult.name = frontResultNode["Name"].asString();
if(!frontResultNode["Nationality"].isNull())
data_.frontResult.nationality = frontResultNode["Nationality"].asString();
if(!frontResultNode["IDNumber"].isNull())
data_.frontResult.iDNumber = frontResultNode["IDNumber"].asString();
if(!frontResultNode["Gender"].isNull())
data_.frontResult.gender = frontResultNode["Gender"].asString();
if(!frontResultNode["BirthDate"].isNull())
data_.frontResult.birthDate = frontResultNode["BirthDate"].asString();
auto allCardAreasNode = frontResultNode["CardAreas"];
for (auto frontResultNodeCardAreasCardArea : allCardAreasNode)
{
Data::FrontResult::CardArea cardAreaObject;
if(!frontResultNodeCardAreasCardArea["X"].isNull())
cardAreaObject.x = std::stof(frontResultNodeCardAreasCardArea["X"].asString());
if(!frontResultNodeCardAreasCardArea["Y"].isNull())
cardAreaObject.y = std::stof(frontResultNodeCardAreasCardArea["Y"].asString());
data_.frontResult.cardAreas.push_back(cardAreaObject);
}
auto allFaceRectVerticesNode = frontResultNode["FaceRectVertices"];
for (auto frontResultNodeFaceRectVerticesFaceRectVertice : allFaceRectVerticesNode)
{
Data::FrontResult::FaceRectVertice faceRectVerticeObject;
if(!frontResultNodeFaceRectVerticesFaceRectVertice["X"].isNull())
faceRectVerticeObject.x = std::stof(frontResultNodeFaceRectVerticesFaceRectVertice["X"].asString());
if(!frontResultNodeFaceRectVerticesFaceRectVertice["Y"].isNull())
faceRectVerticeObject.y = std::stof(frontResultNodeFaceRectVerticesFaceRectVertice["Y"].asString());
data_.frontResult.faceRectVertices.push_back(faceRectVerticeObject);
}
auto faceRectangleNode = frontResultNode["FaceRectangle"];
if(!faceRectangleNode["Angle"].isNull())
data_.frontResult.faceRectangle.angle = std::stof(faceRectangleNode["Angle"].asString());
auto centerNode = faceRectangleNode["Center"];
if(!centerNode["X"].isNull())
data_.frontResult.faceRectangle.center.x = std::stof(centerNode["X"].asString());
if(!centerNode["Y"].isNull())
data_.frontResult.faceRectangle.center.y = std::stof(centerNode["Y"].asString());
auto sizeNode = faceRectangleNode["Size"];
if(!sizeNode["Height"].isNull())
data_.frontResult.faceRectangle.size.height = std::stof(sizeNode["Height"].asString());
if(!sizeNode["Width"].isNull())
data_.frontResult.faceRectangle.size.width = std::stof(sizeNode["Width"].asString());
auto backResultNode = dataNode["BackResult"];
if(!backResultNode["StartDate"].isNull())
data_.backResult.startDate = backResultNode["StartDate"].asString();
if(!backResultNode["EndDate"].isNull())
data_.backResult.endDate = backResultNode["EndDate"].asString();
if(!backResultNode["Issue"].isNull())
data_.backResult.issue = backResultNode["Issue"].asString();
}
RecognizeIdentityCardResult::Data RecognizeIdentityCardResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeIdentityCardResult.cc
|
C++
|
apache-2.0
| 4,382
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeLicensePlateRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeLicensePlateRequest;
RecognizeLicensePlateRequest::RecognizeLicensePlateRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeLicensePlate")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeLicensePlateRequest::~RecognizeLicensePlateRequest()
{}
int RecognizeLicensePlateRequest::getImageType()const
{
return imageType_;
}
void RecognizeLicensePlateRequest::setImageType(int imageType)
{
imageType_ = imageType;
setBodyParameter("ImageType", std::to_string(imageType));
}
std::string RecognizeLicensePlateRequest::getImageURL()const
{
return imageURL_;
}
void RecognizeLicensePlateRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setBodyParameter("ImageURL", imageURL);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeLicensePlateRequest.cc
|
C++
|
apache-2.0
| 1,480
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeLicensePlateResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeLicensePlateResult::RecognizeLicensePlateResult() :
ServiceResult()
{}
RecognizeLicensePlateResult::RecognizeLicensePlateResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeLicensePlateResult::~RecognizeLicensePlateResult()
{}
void RecognizeLicensePlateResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
auto allPlatesNode = dataNode["Plates"];
for (auto dataNodePlatesPlate : allPlatesNode)
{
Data::Plate plateObject;
if(!dataNodePlatesPlate["Confidence"].isNull())
plateObject.confidence = std::stof(dataNodePlatesPlate["Confidence"].asString());
if(!dataNodePlatesPlate["PlateNumber"].isNull())
plateObject.plateNumber = dataNodePlatesPlate["PlateNumber"].asString();
if(!dataNodePlatesPlate["PlateType"].isNull())
plateObject.plateType = dataNodePlatesPlate["PlateType"].asString();
if(!dataNodePlatesPlate["PlateTypeConfidence"].isNull())
plateObject.plateTypeConfidence = std::stof(dataNodePlatesPlate["PlateTypeConfidence"].asString());
auto roiNode = value["Roi"];
if(!roiNode["H"].isNull())
plateObject.roi.h = std::stoi(roiNode["H"].asString());
if(!roiNode["W"].isNull())
plateObject.roi.w = std::stoi(roiNode["W"].asString());
if(!roiNode["X"].isNull())
plateObject.roi.x = std::stoi(roiNode["X"].asString());
if(!roiNode["Y"].isNull())
plateObject.roi.y = std::stoi(roiNode["Y"].asString());
data_.plates.push_back(plateObject);
}
}
RecognizeLicensePlateResult::Data RecognizeLicensePlateResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeLicensePlateResult.cc
|
C++
|
apache-2.0
| 2,479
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizePassportMRZRequest.h>
using AlibabaCloud::Ocr::Model::RecognizePassportMRZRequest;
RecognizePassportMRZRequest::RecognizePassportMRZRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizePassportMRZ")
{
setMethod(HttpRequest::Method::Post);
}
RecognizePassportMRZRequest::~RecognizePassportMRZRequest()
{}
std::string RecognizePassportMRZRequest::getImageURL()const
{
return imageURL_;
}
void RecognizePassportMRZRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setBodyParameter("ImageURL", imageURL);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizePassportMRZRequest.cc
|
C++
|
apache-2.0
| 1,229
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizePassportMRZResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizePassportMRZResult::RecognizePassportMRZResult() :
ServiceResult()
{}
RecognizePassportMRZResult::RecognizePassportMRZResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizePassportMRZResult::~RecognizePassportMRZResult()
{}
void RecognizePassportMRZResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
auto allRegionsNode = dataNode["Regions"]["Region"];
for (auto dataNodeRegionsRegion : allRegionsNode)
{
Data::Region regionObject;
if(!dataNodeRegionsRegion["Name"].isNull())
regionObject.name = dataNodeRegionsRegion["Name"].asString();
if(!dataNodeRegionsRegion["RecognitionScore"].isNull())
regionObject.recognitionScore = std::stof(dataNodeRegionsRegion["RecognitionScore"].asString());
if(!dataNodeRegionsRegion["Content"].isNull())
regionObject.content = dataNodeRegionsRegion["Content"].asString();
if(!dataNodeRegionsRegion["DetectionScore"].isNull())
regionObject.detectionScore = std::stof(dataNodeRegionsRegion["DetectionScore"].asString());
auto allBandBoxes = value["BandBoxes"]["BandBox"];
for (auto value : allBandBoxes)
regionObject.bandBoxes.push_back(value.asString());
data_.regions.push_back(regionObject);
}
}
RecognizePassportMRZResult::Data RecognizePassportMRZResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizePassportMRZResult.cc
|
C++
|
apache-2.0
| 2,243
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizePoiNameRequest.h>
using AlibabaCloud::Ocr::Model::RecognizePoiNameRequest;
RecognizePoiNameRequest::RecognizePoiNameRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizePoiName")
{
setMethod(HttpRequest::Method::Post);
}
RecognizePoiNameRequest::~RecognizePoiNameRequest()
{}
std::string RecognizePoiNameRequest::getImageURL()const
{
return imageURL_;
}
void RecognizePoiNameRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setBodyParameter("ImageURL", imageURL);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizePoiNameRequest.cc
|
C++
|
apache-2.0
| 1,193
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizePoiNameResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizePoiNameResult::RecognizePoiNameResult() :
ServiceResult()
{}
RecognizePoiNameResult::RecognizePoiNameResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizePoiNameResult::~RecognizePoiNameResult()
{}
void RecognizePoiNameResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
auto allSignboardsNode = dataNode["Signboards"]["SignboardsItem"];
for (auto dataNodeSignboardsSignboardsItem : allSignboardsNode)
{
Data::SignboardsItem signboardsItemObject;
auto allTextsNode = dataNodeSignboardsSignboardsItem["Texts"]["TextsItem"];
for (auto dataNodeSignboardsSignboardsItemTextsTextsItem : allTextsNode)
{
Data::SignboardsItem::TextsItem textsObject;
if(!dataNodeSignboardsSignboardsItemTextsTextsItem["Label"].isNull())
textsObject.label = dataNodeSignboardsSignboardsItemTextsTextsItem["Label"].asString();
if(!dataNodeSignboardsSignboardsItemTextsTextsItem["Score"].isNull())
textsObject.score = std::stof(dataNodeSignboardsSignboardsItemTextsTextsItem["Score"].asString());
if(!dataNodeSignboardsSignboardsItemTextsTextsItem["Tag"].isNull())
textsObject.tag = dataNodeSignboardsSignboardsItemTextsTextsItem["Tag"].asString();
if(!dataNodeSignboardsSignboardsItemTextsTextsItem["Type"].isNull())
textsObject.type = dataNodeSignboardsSignboardsItemTextsTextsItem["Type"].asString();
auto allPoints = value["Points"]["Points"];
for (auto value : allPoints)
textsObject.points.push_back(value.asString());
signboardsItemObject.texts.push_back(textsObject);
}
data_.signboards.push_back(signboardsItemObject);
}
auto summaryNode = dataNode["Summary"];
if(!summaryNode["Brand"].isNull())
data_.summary.brand = summaryNode["Brand"].asString();
if(!summaryNode["Score"].isNull())
data_.summary.score = std::stof(summaryNode["Score"].asString());
}
RecognizePoiNameResult::Data RecognizePoiNameResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizePoiNameResult.cc
|
C++
|
apache-2.0
| 2,869
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeQrCodeRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeQrCodeRequest;
RecognizeQrCodeRequest::RecognizeQrCodeRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeQrCode")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeQrCodeRequest::~RecognizeQrCodeRequest()
{}
std::vector<RecognizeQrCodeRequest::Tasks> RecognizeQrCodeRequest::getTasks()const
{
return tasks_;
}
void RecognizeQrCodeRequest::setTasks(const std::vector<Tasks>& tasks)
{
tasks_ = tasks;
for(int dep1 = 0; dep1!= tasks.size(); dep1++) {
auto tasksObj = tasks.at(dep1);
std::string tasksObjStr = "Tasks." + std::to_string(dep1 + 1);
setParameter(tasksObjStr + ".ImageURL", tasksObj.imageURL);
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeQrCodeRequest.cc
|
C++
|
apache-2.0
| 1,364
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeQrCodeResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeQrCodeResult::RecognizeQrCodeResult() :
ServiceResult()
{}
RecognizeQrCodeResult::RecognizeQrCodeResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeQrCodeResult::~RecognizeQrCodeResult()
{}
void RecognizeQrCodeResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
auto allElementsNode = dataNode["Elements"]["Element"];
for (auto dataNodeElementsElement : allElementsNode)
{
Data::Element elementObject;
if(!dataNodeElementsElement["TaskId"].isNull())
elementObject.taskId = dataNodeElementsElement["TaskId"].asString();
if(!dataNodeElementsElement["ImageURL"].isNull())
elementObject.imageURL = dataNodeElementsElement["ImageURL"].asString();
auto allResultsNode = dataNodeElementsElement["Results"]["Result"];
for (auto dataNodeElementsElementResultsResult : allResultsNode)
{
Data::Element::Result resultsObject;
if(!dataNodeElementsElementResultsResult["Label"].isNull())
resultsObject.label = dataNodeElementsElementResultsResult["Label"].asString();
if(!dataNodeElementsElementResultsResult["Suggestion"].isNull())
resultsObject.suggestion = dataNodeElementsElementResultsResult["Suggestion"].asString();
if(!dataNodeElementsElementResultsResult["Rate"].isNull())
resultsObject.rate = std::stof(dataNodeElementsElementResultsResult["Rate"].asString());
auto allQrCodesData = value["QrCodesData"]["QrCodeData"];
for (auto value : allQrCodesData)
resultsObject.qrCodesData.push_back(value.asString());
elementObject.results.push_back(resultsObject);
}
data_.elements.push_back(elementObject);
}
}
RecognizeQrCodeResult::Data RecognizeQrCodeResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeQrCodeResult.cc
|
C++
|
apache-2.0
| 2,627
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeStampRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeStampRequest;
RecognizeStampRequest::RecognizeStampRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeStamp")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeStampRequest::~RecognizeStampRequest()
{}
int RecognizeStampRequest::getImageType()const
{
return imageType_;
}
void RecognizeStampRequest::setImageType(int imageType)
{
imageType_ = imageType;
setBodyParameter("ImageType", std::to_string(imageType));
}
std::string RecognizeStampRequest::getImageURL()const
{
return imageURL_;
}
void RecognizeStampRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setBodyParameter("ImageURL", imageURL);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeStampRequest.cc
|
C++
|
apache-2.0
| 1,403
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeStampResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeStampResult::RecognizeStampResult() :
ServiceResult()
{}
RecognizeStampResult::RecognizeStampResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeStampResult::~RecognizeStampResult()
{}
void RecognizeStampResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
auto allResultsNode = dataNode["Results"]["ResultsItem"];
for (auto dataNodeResultsResultsItem : allResultsNode)
{
Data::ResultsItem resultsItemObject;
auto allGeneralTextNode = dataNodeResultsResultsItem["GeneralText"]["GeneralTextItem"];
for (auto dataNodeResultsResultsItemGeneralTextGeneralTextItem : allGeneralTextNode)
{
Data::ResultsItem::GeneralTextItem generalTextObject;
if(!dataNodeResultsResultsItemGeneralTextGeneralTextItem["Content"].isNull())
generalTextObject.content = dataNodeResultsResultsItemGeneralTextGeneralTextItem["Content"].asString();
if(!dataNodeResultsResultsItemGeneralTextGeneralTextItem["Confidence"].isNull())
generalTextObject.confidence = std::stof(dataNodeResultsResultsItemGeneralTextGeneralTextItem["Confidence"].asString());
resultsItemObject.generalText.push_back(generalTextObject);
}
auto roiNode = value["Roi"];
if(!roiNode["Left"].isNull())
resultsItemObject.roi.left = std::stoi(roiNode["Left"].asString());
if(!roiNode["Top"].isNull())
resultsItemObject.roi.top = std::stoi(roiNode["Top"].asString());
if(!roiNode["Width"].isNull())
resultsItemObject.roi.width = std::stoi(roiNode["Width"].asString());
if(!roiNode["Height"].isNull())
resultsItemObject.roi.height = std::stoi(roiNode["Height"].asString());
auto textNode = value["Text"];
if(!textNode["Content"].isNull())
resultsItemObject.text.content = textNode["Content"].asString();
if(!textNode["Confidence"].isNull())
resultsItemObject.text.confidence = std::stof(textNode["Confidence"].asString());
data_.results.push_back(resultsItemObject);
}
}
RecognizeStampResult::Data RecognizeStampResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeStampResult.cc
|
C++
|
apache-2.0
| 2,938
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeTableRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeTableRequest;
RecognizeTableRequest::RecognizeTableRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeTable")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeTableRequest::~RecognizeTableRequest()
{}
int RecognizeTableRequest::getImageType()const
{
return imageType_;
}
void RecognizeTableRequest::setImageType(int imageType)
{
imageType_ = imageType;
setBodyParameter("ImageType", std::to_string(imageType));
}
bool RecognizeTableRequest::getUseFinanceModel()const
{
return useFinanceModel_;
}
void RecognizeTableRequest::setUseFinanceModel(bool useFinanceModel)
{
useFinanceModel_ = useFinanceModel;
setBodyParameter("UseFinanceModel", useFinanceModel ? "true" : "false");
}
bool RecognizeTableRequest::getSkipDetection()const
{
return skipDetection_;
}
void RecognizeTableRequest::setSkipDetection(bool skipDetection)
{
skipDetection_ = skipDetection;
setBodyParameter("SkipDetection", skipDetection ? "true" : "false");
}
std::string RecognizeTableRequest::getImageURL()const
{
return imageURL_;
}
void RecognizeTableRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setBodyParameter("ImageURL", imageURL);
}
std::string RecognizeTableRequest::getOutputFormat()const
{
return outputFormat_;
}
void RecognizeTableRequest::setOutputFormat(const std::string& outputFormat)
{
outputFormat_ = outputFormat;
setBodyParameter("OutputFormat", outputFormat);
}
bool RecognizeTableRequest::getAssureDirection()const
{
return assureDirection_;
}
void RecognizeTableRequest::setAssureDirection(bool assureDirection)
{
assureDirection_ = assureDirection;
setBodyParameter("AssureDirection", assureDirection ? "true" : "false");
}
bool RecognizeTableRequest::getHasLine()const
{
return hasLine_;
}
void RecognizeTableRequest::setHasLine(bool hasLine)
{
hasLine_ = hasLine;
setBodyParameter("HasLine", hasLine ? "true" : "false");
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeTableRequest.cc
|
C++
|
apache-2.0
| 2,706
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeTableResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeTableResult::RecognizeTableResult() :
ServiceResult()
{}
RecognizeTableResult::RecognizeTableResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeTableResult::~RecognizeTableResult()
{}
void RecognizeTableResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
if(!dataNode["FileContent"].isNull())
data_.fileContent = dataNode["FileContent"].asString();
auto allTablesNode = dataNode["Tables"]["Table"];
for (auto dataNodeTablesTable : allTablesNode)
{
Data::Table tableObject;
auto allTableRowsNode = dataNodeTablesTable["TableRows"]["TableRow"];
for (auto dataNodeTablesTableTableRowsTableRow : allTableRowsNode)
{
Data::Table::TableRow tableRowsObject;
auto allTableColumnsNode = dataNodeTablesTableTableRowsTableRow["TableColumns"]["TableColumn"];
for (auto dataNodeTablesTableTableRowsTableRowTableColumnsTableColumn : allTableColumnsNode)
{
Data::Table::TableRow::TableColumn tableColumnsObject;
if(!dataNodeTablesTableTableRowsTableRowTableColumnsTableColumn["StartColumn"].isNull())
tableColumnsObject.startColumn = std::stoi(dataNodeTablesTableTableRowsTableRowTableColumnsTableColumn["StartColumn"].asString());
if(!dataNodeTablesTableTableRowsTableRowTableColumnsTableColumn["StartRow"].isNull())
tableColumnsObject.startRow = std::stoi(dataNodeTablesTableTableRowsTableRowTableColumnsTableColumn["StartRow"].asString());
if(!dataNodeTablesTableTableRowsTableRowTableColumnsTableColumn["EndColumn"].isNull())
tableColumnsObject.endColumn = std::stoi(dataNodeTablesTableTableRowsTableRowTableColumnsTableColumn["EndColumn"].asString());
if(!dataNodeTablesTableTableRowsTableRowTableColumnsTableColumn["EndRow"].isNull())
tableColumnsObject.endRow = std::stoi(dataNodeTablesTableTableRowsTableRowTableColumnsTableColumn["EndRow"].asString());
if(!dataNodeTablesTableTableRowsTableRowTableColumnsTableColumn["Height"].isNull())
tableColumnsObject.height = std::stoi(dataNodeTablesTableTableRowsTableRowTableColumnsTableColumn["Height"].asString());
if(!dataNodeTablesTableTableRowsTableRowTableColumnsTableColumn["Width"].isNull())
tableColumnsObject.width = std::stoi(dataNodeTablesTableTableRowsTableRowTableColumnsTableColumn["Width"].asString());
auto allTexts = value["Texts"]["Text"];
for (auto value : allTexts)
tableColumnsObject.texts.push_back(value.asString());
tableRowsObject.tableColumns.push_back(tableColumnsObject);
}
tableObject.tableRows.push_back(tableRowsObject);
}
auto allHead = value["Head"]["Head"];
for (auto value : allHead)
tableObject.head.push_back(value.asString());
auto allTail = value["Tail"]["Tail"];
for (auto value : allTail)
tableObject.tail.push_back(value.asString());
data_.tables.push_back(tableObject);
}
}
RecognizeTableResult::Data RecognizeTableResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeTableResult.cc
|
C++
|
apache-2.0
| 3,841
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeTakeoutOrderRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeTakeoutOrderRequest;
RecognizeTakeoutOrderRequest::RecognizeTakeoutOrderRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeTakeoutOrder")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeTakeoutOrderRequest::~RecognizeTakeoutOrderRequest()
{}
std::string RecognizeTakeoutOrderRequest::getImageURL()const
{
return imageURL_;
}
void RecognizeTakeoutOrderRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setBodyParameter("ImageURL", imageURL);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeTakeoutOrderRequest.cc
|
C++
|
apache-2.0
| 1,238
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeTakeoutOrderResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeTakeoutOrderResult::RecognizeTakeoutOrderResult() :
ServiceResult()
{}
RecognizeTakeoutOrderResult::RecognizeTakeoutOrderResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeTakeoutOrderResult::~RecognizeTakeoutOrderResult()
{}
void RecognizeTakeoutOrderResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
auto allElementsNode = dataNode["Elements"]["Element"];
for (auto dataNodeElementsElement : allElementsNode)
{
Data::Element elementObject;
if(!dataNodeElementsElement["Score"].isNull())
elementObject.score = std::stof(dataNodeElementsElement["Score"].asString());
if(!dataNodeElementsElement["Name"].isNull())
elementObject.name = dataNodeElementsElement["Name"].asString();
if(!dataNodeElementsElement["Value"].isNull())
elementObject.value = dataNodeElementsElement["Value"].asString();
auto allBoxes = value["Boxes"]["Box"];
for (auto value : allBoxes)
elementObject.boxes.push_back(value.asString());
data_.elements.push_back(elementObject);
}
}
RecognizeTakeoutOrderResult::Data RecognizeTakeoutOrderResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeTakeoutOrderResult.cc
|
C++
|
apache-2.0
| 2,068
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeTaxiInvoiceRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeTaxiInvoiceRequest;
RecognizeTaxiInvoiceRequest::RecognizeTaxiInvoiceRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeTaxiInvoice")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeTaxiInvoiceRequest::~RecognizeTaxiInvoiceRequest()
{}
int RecognizeTaxiInvoiceRequest::getImageType()const
{
return imageType_;
}
void RecognizeTaxiInvoiceRequest::setImageType(int imageType)
{
imageType_ = imageType;
setBodyParameter("ImageType", std::to_string(imageType));
}
std::string RecognizeTaxiInvoiceRequest::getImageURL()const
{
return imageURL_;
}
void RecognizeTaxiInvoiceRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setBodyParameter("ImageURL", imageURL);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeTaxiInvoiceRequest.cc
|
C++
|
apache-2.0
| 1,469
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeTaxiInvoiceResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeTaxiInvoiceResult::RecognizeTaxiInvoiceResult() :
ServiceResult()
{}
RecognizeTaxiInvoiceResult::RecognizeTaxiInvoiceResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeTaxiInvoiceResult::~RecognizeTaxiInvoiceResult()
{}
void RecognizeTaxiInvoiceResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
auto allInvoicesNode = dataNode["Invoices"]["Invoice"];
for (auto dataNodeInvoicesInvoice : allInvoicesNode)
{
Data::Invoice invoiceObject;
if(!dataNodeInvoicesInvoice["RotateType"].isNull())
invoiceObject.rotateType = std::stoi(dataNodeInvoicesInvoice["RotateType"].asString());
auto allItemsNode = dataNodeInvoicesInvoice["Items"]["Item"];
for (auto dataNodeInvoicesInvoiceItemsItem : allItemsNode)
{
Data::Invoice::Item itemsObject;
if(!dataNodeInvoicesInvoiceItemsItem["Text"].isNull())
itemsObject.text = dataNodeInvoicesInvoiceItemsItem["Text"].asString();
auto itemRoiNode = value["ItemRoi"];
if(!itemRoiNode["Angle"].isNull())
itemsObject.itemRoi.angle = std::stof(itemRoiNode["Angle"].asString());
auto centerNode = itemRoiNode["Center"];
if(!centerNode["X"].isNull())
itemsObject.itemRoi.center.x = std::stof(centerNode["X"].asString());
if(!centerNode["Y"].isNull())
itemsObject.itemRoi.center.y = std::stof(centerNode["Y"].asString());
auto sizeNode = itemRoiNode["Size"];
if(!sizeNode["H"].isNull())
itemsObject.itemRoi.size.h = std::stof(sizeNode["H"].asString());
if(!sizeNode["W"].isNull())
itemsObject.itemRoi.size.w = std::stof(sizeNode["W"].asString());
invoiceObject.items.push_back(itemsObject);
}
auto invoiceRoiNode = value["InvoiceRoi"];
if(!invoiceRoiNode["H"].isNull())
invoiceObject.invoiceRoi.h = std::stof(invoiceRoiNode["H"].asString());
if(!invoiceRoiNode["W"].isNull())
invoiceObject.invoiceRoi.w = std::stof(invoiceRoiNode["W"].asString());
if(!invoiceRoiNode["X"].isNull())
invoiceObject.invoiceRoi.x = std::stof(invoiceRoiNode["X"].asString());
if(!invoiceRoiNode["Y"].isNull())
invoiceObject.invoiceRoi.y = std::stof(invoiceRoiNode["Y"].asString());
data_.invoices.push_back(invoiceObject);
}
}
RecognizeTaxiInvoiceResult::Data RecognizeTaxiInvoiceResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeTaxiInvoiceResult.cc
|
C++
|
apache-2.0
| 3,208
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeTrainTicketRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeTrainTicketRequest;
RecognizeTrainTicketRequest::RecognizeTrainTicketRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeTrainTicket")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeTrainTicketRequest::~RecognizeTrainTicketRequest()
{}
int RecognizeTrainTicketRequest::getImageType()const
{
return imageType_;
}
void RecognizeTrainTicketRequest::setImageType(int imageType)
{
imageType_ = imageType;
setBodyParameter("ImageType", std::to_string(imageType));
}
std::string RecognizeTrainTicketRequest::getImageURL()const
{
return imageURL_;
}
void RecognizeTrainTicketRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setBodyParameter("ImageURL", imageURL);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeTrainTicketRequest.cc
|
C++
|
apache-2.0
| 1,469
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeTrainTicketResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeTrainTicketResult::RecognizeTrainTicketResult() :
ServiceResult()
{}
RecognizeTrainTicketResult::RecognizeTrainTicketResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeTrainTicketResult::~RecognizeTrainTicketResult()
{}
void RecognizeTrainTicketResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
if(!dataNode["Date"].isNull())
data_.date = dataNode["Date"].asString();
if(!dataNode["Destination"].isNull())
data_.destination = dataNode["Destination"].asString();
if(!dataNode["Level"].isNull())
data_.level = dataNode["Level"].asString();
if(!dataNode["Number"].isNull())
data_.number = dataNode["Number"].asString();
if(!dataNode["Name"].isNull())
data_.name = dataNode["Name"].asString();
if(!dataNode["DepartureStation"].isNull())
data_.departureStation = dataNode["DepartureStation"].asString();
if(!dataNode["Seat"].isNull())
data_.seat = dataNode["Seat"].asString();
if(!dataNode["Price"].isNull())
data_.price = std::stof(dataNode["Price"].asString());
}
RecognizeTrainTicketResult::Data RecognizeTrainTicketResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeTrainTicketResult.cc
|
C++
|
apache-2.0
| 2,067
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeVATInvoiceRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeVATInvoiceRequest;
RecognizeVATInvoiceRequest::RecognizeVATInvoiceRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeVATInvoice")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeVATInvoiceRequest::~RecognizeVATInvoiceRequest()
{}
std::string RecognizeVATInvoiceRequest::getFileType()const
{
return fileType_;
}
void RecognizeVATInvoiceRequest::setFileType(const std::string& fileType)
{
fileType_ = fileType;
setBodyParameter("FileType", fileType);
}
std::string RecognizeVATInvoiceRequest::getFileURL()const
{
return fileURL_;
}
void RecognizeVATInvoiceRequest::setFileURL(const std::string& fileURL)
{
fileURL_ = fileURL;
setBodyParameter("FileURL", fileURL);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeVATInvoiceRequest.cc
|
C++
|
apache-2.0
| 1,449
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeVATInvoiceResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeVATInvoiceResult::RecognizeVATInvoiceResult() :
ServiceResult()
{}
RecognizeVATInvoiceResult::RecognizeVATInvoiceResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeVATInvoiceResult::~RecognizeVATInvoiceResult()
{}
void RecognizeVATInvoiceResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
auto contentNode = dataNode["Content"];
if(!contentNode["InvoiceCode"].isNull())
data_.content.invoiceCode = contentNode["InvoiceCode"].asString();
if(!contentNode["InvoiceNo"].isNull())
data_.content.invoiceNo = contentNode["InvoiceNo"].asString();
if(!contentNode["InvoiceDate"].isNull())
data_.content.invoiceDate = contentNode["InvoiceDate"].asString();
if(!contentNode["AntiFakeCode"].isNull())
data_.content.antiFakeCode = contentNode["AntiFakeCode"].asString();
if(!contentNode["PayerName"].isNull())
data_.content.payerName = contentNode["PayerName"].asString();
if(!contentNode["PayerRegisterNo"].isNull())
data_.content.payerRegisterNo = contentNode["PayerRegisterNo"].asString();
if(!contentNode["PayerAddress"].isNull())
data_.content.payerAddress = contentNode["PayerAddress"].asString();
if(!contentNode["PayerBankName"].isNull())
data_.content.payerBankName = contentNode["PayerBankName"].asString();
if(!contentNode["WithoutTaxAmount"].isNull())
data_.content.withoutTaxAmount = contentNode["WithoutTaxAmount"].asString();
if(!contentNode["TaxAmount"].isNull())
data_.content.taxAmount = contentNode["TaxAmount"].asString();
if(!contentNode["SumAmount"].isNull())
data_.content.sumAmount = contentNode["SumAmount"].asString();
if(!contentNode["InvoiceAmount"].isNull())
data_.content.invoiceAmount = contentNode["InvoiceAmount"].asString();
if(!contentNode["PayeeName"].isNull())
data_.content.payeeName = contentNode["PayeeName"].asString();
if(!contentNode["PayeeRegisterNo"].isNull())
data_.content.payeeRegisterNo = contentNode["PayeeRegisterNo"].asString();
if(!contentNode["PayeeAddress"].isNull())
data_.content.payeeAddress = contentNode["PayeeAddress"].asString();
if(!contentNode["PayeeBankName"].isNull())
data_.content.payeeBankName = contentNode["PayeeBankName"].asString();
if(!contentNode["Payee"].isNull())
data_.content.payee = contentNode["Payee"].asString();
if(!contentNode["Checker"].isNull())
data_.content.checker = contentNode["Checker"].asString();
if(!contentNode["Clerk"].isNull())
data_.content.clerk = contentNode["Clerk"].asString();
auto boxNode = dataNode["Box"];
auto allInvoiceCodes = boxNode["InvoiceCodes"]["InvoiceCode"];
for (auto value : allInvoiceCodes)
data_.box.invoiceCodes.push_back(value.asString());
auto allInvoiceNoes = boxNode["InvoiceNoes"]["InvoiceNo"];
for (auto value : allInvoiceNoes)
data_.box.invoiceNoes.push_back(value.asString());
auto allInvoiceDates = boxNode["InvoiceDates"]["InvoiceDate"];
for (auto value : allInvoiceDates)
data_.box.invoiceDates.push_back(value.asString());
auto allInvoiceFakeCodes = boxNode["InvoiceFakeCodes"]["InvoiceFakeCode"];
for (auto value : allInvoiceFakeCodes)
data_.box.invoiceFakeCodes.push_back(value.asString());
auto allPayerNames = boxNode["PayerNames"]["PayerName"];
for (auto value : allPayerNames)
data_.box.payerNames.push_back(value.asString());
auto allPayerRegisterNoes = boxNode["PayerRegisterNoes"]["PayerRegisterNo"];
for (auto value : allPayerRegisterNoes)
data_.box.payerRegisterNoes.push_back(value.asString());
auto allPayerAddresses = boxNode["PayerAddresses"]["PayerAddress"];
for (auto value : allPayerAddresses)
data_.box.payerAddresses.push_back(value.asString());
auto allPayerBankNames = boxNode["PayerBankNames"]["PayerBankNames"];
for (auto value : allPayerBankNames)
data_.box.payerBankNames.push_back(value.asString());
auto allWithoutTaxAmounts = boxNode["WithoutTaxAmounts"]["WithoutTaxAmount"];
for (auto value : allWithoutTaxAmounts)
data_.box.withoutTaxAmounts.push_back(value.asString());
auto allTaxAmounts = boxNode["TaxAmounts"]["TaxAmount"];
for (auto value : allTaxAmounts)
data_.box.taxAmounts.push_back(value.asString());
auto allSumAmounts = boxNode["SumAmounts"]["SumAmount"];
for (auto value : allSumAmounts)
data_.box.sumAmounts.push_back(value.asString());
auto allInvoiceAmounts = boxNode["InvoiceAmounts"]["InvoiceAmount"];
for (auto value : allInvoiceAmounts)
data_.box.invoiceAmounts.push_back(value.asString());
auto allPayeeNames = boxNode["PayeeNames"]["PayeeName"];
for (auto value : allPayeeNames)
data_.box.payeeNames.push_back(value.asString());
auto allPayeeRegisterNoes = boxNode["PayeeRegisterNoes"]["PayeeRegisterNo"];
for (auto value : allPayeeRegisterNoes)
data_.box.payeeRegisterNoes.push_back(value.asString());
auto allPayeeAddresses = boxNode["PayeeAddresses"]["PayeeAddress"];
for (auto value : allPayeeAddresses)
data_.box.payeeAddresses.push_back(value.asString());
auto allPayeeBankNames = boxNode["PayeeBankNames"]["PayeeBankName"];
for (auto value : allPayeeBankNames)
data_.box.payeeBankNames.push_back(value.asString());
auto allPayees = boxNode["Payees"]["Payee"];
for (auto value : allPayees)
data_.box.payees.push_back(value.asString());
auto allCheckers = boxNode["Checkers"]["Checker"];
for (auto value : allCheckers)
data_.box.checkers.push_back(value.asString());
auto allClerks = boxNode["Clerks"]["Clerk"];
for (auto value : allClerks)
data_.box.clerks.push_back(value.asString());
}
RecognizeVATInvoiceResult::Data RecognizeVATInvoiceResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeVATInvoiceResult.cc
|
C++
|
apache-2.0
| 6,539
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeVINCodeRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeVINCodeRequest;
RecognizeVINCodeRequest::RecognizeVINCodeRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeVINCode")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeVINCodeRequest::~RecognizeVINCodeRequest()
{}
int RecognizeVINCodeRequest::getImageType()const
{
return imageType_;
}
void RecognizeVINCodeRequest::setImageType(int imageType)
{
imageType_ = imageType;
setParameter("ImageType", std::to_string(imageType));
}
std::string RecognizeVINCodeRequest::getImageURL()const
{
return imageURL_;
}
void RecognizeVINCodeRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setParameter("ImageURL", imageURL);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeVINCodeRequest.cc
|
C++
|
apache-2.0
| 1,417
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeVINCodeResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeVINCodeResult::RecognizeVINCodeResult() :
ServiceResult()
{}
RecognizeVINCodeResult::RecognizeVINCodeResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeVINCodeResult::~RecognizeVINCodeResult()
{}
void RecognizeVINCodeResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
if(!dataNode["VinCode"].isNull())
data_.vinCode = dataNode["VinCode"].asString();
}
RecognizeVINCodeResult::Data RecognizeVINCodeResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeVINCodeResult.cc
|
C++
|
apache-2.0
| 1,424
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeVerificationcodeRequest.h>
using AlibabaCloud::Ocr::Model::RecognizeVerificationcodeRequest;
RecognizeVerificationcodeRequest::RecognizeVerificationcodeRequest() :
RpcServiceRequest("ocr", "2019-12-30", "RecognizeVerificationcode")
{
setMethod(HttpRequest::Method::Post);
}
RecognizeVerificationcodeRequest::~RecognizeVerificationcodeRequest()
{}
std::string RecognizeVerificationcodeRequest::getImageURL()const
{
return imageURL_;
}
void RecognizeVerificationcodeRequest::setImageURL(const std::string& imageURL)
{
imageURL_ = imageURL;
setBodyParameter("ImageURL", imageURL);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeVerificationcodeRequest.cc
|
C++
|
apache-2.0
| 1,274
|
/*
* Copyright 2009-2017 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/ocr/model/RecognizeVerificationcodeResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
RecognizeVerificationcodeResult::RecognizeVerificationcodeResult() :
ServiceResult()
{}
RecognizeVerificationcodeResult::RecognizeVerificationcodeResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecognizeVerificationcodeResult::~RecognizeVerificationcodeResult()
{}
void RecognizeVerificationcodeResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
if(!dataNode["Content"].isNull())
data_.content = dataNode["Content"].asString();
}
RecognizeVerificationcodeResult::Data RecognizeVerificationcodeResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/RecognizeVerificationcodeResult.cc
|
C++
|
apache-2.0
| 1,514
|
/*
* Copyright 2009-2017 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/ocr/model/TrimDocumentRequest.h>
using AlibabaCloud::Ocr::Model::TrimDocumentRequest;
TrimDocumentRequest::TrimDocumentRequest() :
RpcServiceRequest("ocr", "2019-12-30", "TrimDocument")
{
setMethod(HttpRequest::Method::Post);
}
TrimDocumentRequest::~TrimDocumentRequest()
{}
std::string TrimDocumentRequest::getFileType()const
{
return fileType_;
}
void TrimDocumentRequest::setFileType(const std::string& fileType)
{
fileType_ = fileType;
setBodyParameter("FileType", fileType);
}
bool TrimDocumentRequest::getAsync()const
{
return async_;
}
void TrimDocumentRequest::setAsync(bool async)
{
async_ = async;
setBodyParameter("Async", async ? "true" : "false");
}
std::string TrimDocumentRequest::getFileURL()const
{
return fileURL_;
}
void TrimDocumentRequest::setFileURL(const std::string& fileURL)
{
fileURL_ = fileURL;
setBodyParameter("FileURL", fileURL);
}
std::string TrimDocumentRequest::getOutputType()const
{
return outputType_;
}
void TrimDocumentRequest::setOutputType(const std::string& outputType)
{
outputType_ = outputType;
setBodyParameter("OutputType", outputType);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/TrimDocumentRequest.cc
|
C++
|
apache-2.0
| 1,808
|
/*
* Copyright 2009-2017 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/ocr/model/TrimDocumentResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ocr;
using namespace AlibabaCloud::Ocr::Model;
TrimDocumentResult::TrimDocumentResult() :
ServiceResult()
{}
TrimDocumentResult::TrimDocumentResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
TrimDocumentResult::~TrimDocumentResult()
{}
void TrimDocumentResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
if(!dataNode["Content"].isNull())
data_.content = dataNode["Content"].asString();
}
TrimDocumentResult::Data TrimDocumentResult::getData()const
{
return data_;
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/ocr/src/model/TrimDocumentResult.cc
|
C++
|
apache-2.0
| 1,384
|
cmake_minimum_required(VERSION 2.8.2)
set(CMAKE_CXX_STANDARD 11)
include(CTest)
if (CMAKE_VERSION VERSION_LESS 3.2)
set(UPDATE_DISCONNECTED_IF_AVAILABLE "")
else()
set(UPDATE_DISCONNECTED_IF_AVAILABLE "UPDATE_DISCONNECTED 1")
endif()
include(DownloadProject.cmake)
download_project(PROJ googletest
PREFIX CMAKE_SOURCE_DIR/test/googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG master
${UPDATE_DISCONNECTED_IF_AVAILABLE}
)
# Prevent GoogleTest from overriding our compiler/linker options
# when building with Visual Studio
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR})
# When using CMake 2.8.11 or later, header path dependencies
# are automatically added to the gtest and gmock targets.
# For earlier CMake versions, we have to explicitly add the
# required directories to the header search path ourselves.
if (CMAKE_VERSION VERSION_LESS 2.8.11)
include_directories("${gtest_SOURCE_DIR}/include"
"${gmock_SOURCE_DIR}/include")
endif()
include_directories("../../core/include/")
add_executable(core_ut
alibabacloud_ut.cc
asynccallercontext_ut.cc
coreclient_ut.cc
clientconfiguration_ut.cc
commonclient_ut.cc
commonrequest_ut.cc
commonresponse_ut.cc
credentials_ut.cc
curlhttpclient_ut.cc
ecsmetadatafetcher_ut.cc
endpointprovider_ut.cc
error_ut.cc
executor_ut.cc
httprequest_ut.cc
httpresponse_ut.cc
httpmessage_ut.cc
hmacsha1signer_ut.cc
networkproxy_ut.cc
roaserviceclient_ut.cc
roaservicerequest_ut.cc
rpcserviceclient_ut.cc
rpcservicerequest_ut.cc
runnable_ut.cc
serviceresult_ut.cc
servicerequest_ut.cc
simplecredentialsprovider_ut.cc
url_ut.cc
utils_ut.cc
instanceprofilecredentialsprovider_ut.cc
locationclient_ut.cc
location_model_describeendpoints_request_ut.cc
location_model_describeendpoints_result_ut.cc
stsclient_ut.cc
stsassumerolecredentialsprovider_ut.cc
sts_model_assumerole_request_ut.cc
sts_model_assumerole_result_ut.cc
sts_model_getcalleridentity_request_ut.cc
sts_model_getcalleridentity_result_ut.cc
timeout_ut.cc
)
set_target_properties(core_ut
PROPERTIES
OUTPUT_NAME ${TARGET_OUTPUT_NAME_PREFIX}core_ut
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
target_link_libraries(core_ut core gtest gmock_main)
add_test(NAME core_ut COMMAND core_ut)
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/CMakeLists.txt
|
CMake
|
apache-2.0
| 2,507
|
# Distributed under the OSI-approved MIT License. See accompanying
# file LICENSE or https://github.com/Crascit/DownloadProject for details.
cmake_minimum_required(VERSION 2.8.2)
project(${DL_ARGS_PROJ}-download NONE)
include(ExternalProject)
ExternalProject_Add(${DL_ARGS_PROJ}-download
${DL_ARGS_UNPARSED_ARGUMENTS}
SOURCE_DIR "${DL_ARGS_SOURCE_DIR}"
BINARY_DIR "${DL_ARGS_BINARY_DIR}"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
)
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/DownloadProject.CMakeLists.cmake.in
|
CMake
|
apache-2.0
| 644
|
# Distributed under the OSI-approved MIT License. See accompanying
# file LICENSE or https://github.com/Crascit/DownloadProject for details.
#
# MODULE: DownloadProject
#
# PROVIDES:
# download_project( PROJ projectName
# [PREFIX prefixDir]
# [DOWNLOAD_DIR downloadDir]
# [SOURCE_DIR srcDir]
# [BINARY_DIR binDir]
# [QUIET]
# ...
# )
#
# Provides the ability to download and unpack a tarball, zip file, git repository,
# etc. at configure time (i.e. when the cmake command is run). How the downloaded
# and unpacked contents are used is up to the caller, but the motivating case is
# to download source code which can then be included directly in the build with
# add_subdirectory() after the call to download_project(). Source and build
# directories are set up with this in mind.
#
# The PROJ argument is required. The projectName value will be used to construct
# the following variables upon exit (obviously replace projectName with its actual
# value):
#
# projectName_SOURCE_DIR
# projectName_BINARY_DIR
#
# The SOURCE_DIR and BINARY_DIR arguments are optional and would not typically
# need to be provided. They can be specified if you want the downloaded source
# and build directories to be located in a specific place. The contents of
# projectName_SOURCE_DIR and projectName_BINARY_DIR will be populated with the
# locations used whether you provide SOURCE_DIR/BINARY_DIR or not.
#
# The DOWNLOAD_DIR argument does not normally need to be set. It controls the
# location of the temporary CMake build used to perform the download.
#
# The PREFIX argument can be provided to change the base location of the default
# values of DOWNLOAD_DIR, SOURCE_DIR and BINARY_DIR. If all of those three arguments
# are provided, then PREFIX will have no effect. The default value for PREFIX is
# CMAKE_BINARY_DIR.
#
# The QUIET option can be given if you do not want to show the output associated
# with downloading the specified project.
#
# In addition to the above, any other options are passed through unmodified to
# ExternalProject_Add() to perform the actual download, patch and update steps.
# The following ExternalProject_Add() options are explicitly prohibited (they
# are reserved for use by the download_project() command):
#
# CONFIGURE_COMMAND
# BUILD_COMMAND
# INSTALL_COMMAND
# TEST_COMMAND
#
# Only those ExternalProject_Add() arguments which relate to downloading, patching
# and updating of the project sources are intended to be used. Also note that at
# least one set of download-related arguments are required.
#
# If using CMake 3.2 or later, the UPDATE_DISCONNECTED option can be used to
# prevent a check at the remote end for changes every time CMake is run
# after the first successful download. See the documentation of the ExternalProject
# module for more information. It is likely you will want to use this option if it
# is available to you. Note, however, that the ExternalProject implementation contains
# bugs which result in incorrect handling of the UPDATE_DISCONNECTED option when
# using the URL download method or when specifying a SOURCE_DIR with no download
# method. Fixes for these have been created, the last of which is scheduled for
# inclusion in CMake 3.8.0. Details can be found here:
#
# https://gitlab.kitware.com/cmake/cmake/commit/bdca68388bd57f8302d3c1d83d691034b7ffa70c
# https://gitlab.kitware.com/cmake/cmake/issues/16428
#
# If you experience build errors related to the update step, consider avoiding
# the use of UPDATE_DISCONNECTED.
#
# EXAMPLE USAGE:
#
# include(DownloadProject)
# download_project(PROJ googletest
# GIT_REPOSITORY https://github.com/google/googletest.git
# GIT_TAG master
# UPDATE_DISCONNECTED 1
# QUIET
# )
#
# add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR})
#
#========================================================================================
set(_DownloadProjectDir "${CMAKE_CURRENT_LIST_DIR}")
include(CMakeParseArguments)
function(download_project)
set(options QUIET)
set(oneValueArgs
PROJ
PREFIX
DOWNLOAD_DIR
SOURCE_DIR
BINARY_DIR
# Prevent the following from being passed through
CONFIGURE_COMMAND
BUILD_COMMAND
INSTALL_COMMAND
TEST_COMMAND
)
set(multiValueArgs "")
cmake_parse_arguments(DL_ARGS "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
# Hide output if requested
if (DL_ARGS_QUIET)
set(OUTPUT_QUIET "OUTPUT_QUIET")
else()
unset(OUTPUT_QUIET)
message(STATUS "Downloading/updating ${DL_ARGS_PROJ}")
endif()
# Set up where we will put our temporary CMakeLists.txt file and also
# the base point below which the default source and binary dirs will be.
# The prefix must always be an absolute path.
if (NOT DL_ARGS_PREFIX)
set(DL_ARGS_PREFIX "${CMAKE_BINARY_DIR}")
else()
get_filename_component(DL_ARGS_PREFIX "${DL_ARGS_PREFIX}" ABSOLUTE
BASE_DIR "${CMAKE_CURRENT_BINARY_DIR}")
endif()
if (NOT DL_ARGS_DOWNLOAD_DIR)
set(DL_ARGS_DOWNLOAD_DIR "${DL_ARGS_PREFIX}/${DL_ARGS_PROJ}-download")
endif()
# Ensure the caller can know where to find the source and build directories
if (NOT DL_ARGS_SOURCE_DIR)
set(DL_ARGS_SOURCE_DIR "${DL_ARGS_PREFIX}/${DL_ARGS_PROJ}-src")
endif()
if (NOT DL_ARGS_BINARY_DIR)
set(DL_ARGS_BINARY_DIR "${DL_ARGS_PREFIX}/${DL_ARGS_PROJ}-build")
endif()
set(${DL_ARGS_PROJ}_SOURCE_DIR "${DL_ARGS_SOURCE_DIR}" PARENT_SCOPE)
set(${DL_ARGS_PROJ}_BINARY_DIR "${DL_ARGS_BINARY_DIR}" PARENT_SCOPE)
# The way that CLion manages multiple configurations, it causes a copy of
# the CMakeCache.txt to be copied across due to it not expecting there to
# be a project within a project. This causes the hard-coded paths in the
# cache to be copied and builds to fail. To mitigate this, we simply
# remove the cache if it exists before we configure the new project. It
# is safe to do so because it will be re-generated. Since this is only
# executed at the configure step, it should not cause additional builds or
# downloads.
file(REMOVE "${DL_ARGS_DOWNLOAD_DIR}/CMakeCache.txt")
# Create and build a separate CMake project to carry out the download.
# If we've already previously done these steps, they will not cause
# anything to be updated, so extra rebuilds of the project won't occur.
# Make sure to pass through CMAKE_MAKE_PROGRAM in case the main project
# has this set to something not findable on the PATH.
configure_file("${_DownloadProjectDir}/DownloadProject.CMakeLists.cmake.in"
"${DL_ARGS_DOWNLOAD_DIR}/CMakeLists.txt")
execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}"
-D "CMAKE_MAKE_PROGRAM:FILE=${CMAKE_MAKE_PROGRAM}"
.
RESULT_VARIABLE result
${OUTPUT_QUIET}
WORKING_DIRECTORY "${DL_ARGS_DOWNLOAD_DIR}"
)
if(result)
message(FATAL_ERROR "CMake step for ${DL_ARGS_PROJ} failed: ${result}")
endif()
execute_process(COMMAND ${CMAKE_COMMAND} --build .
RESULT_VARIABLE result
${OUTPUT_QUIET}
WORKING_DIRECTORY "${DL_ARGS_DOWNLOAD_DIR}"
)
if(result)
message(FATAL_ERROR "Build step for ${DL_ARGS_PROJ} failed: ${result}")
endif()
endfunction()
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/DownloadProject.cmake
|
CMake
|
apache-2.0
| 8,043
|
#include "gtest/gtest.h"
#include "alibabacloud/core/AlibabaCloud.h"
using namespace std;
using namespace AlibabaCloud;
TEST(AlibabaCloudTest, basic) {
InitializeSdk();
EXPECT_TRUE(IsSdkInitialized() == true);
InitializeSdk();
EXPECT_TRUE(IsSdkInitialized() == true);
ShutdownSdk();
EXPECT_TRUE(IsSdkInitialized() == false);
ShutdownSdk();
EXPECT_TRUE(IsSdkInitialized() == false);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/alibabacloud_ut.cc
|
C++
|
apache-2.0
| 404
|
#include "gtest/gtest.h"
#include "alibabacloud/core/AsyncCallerContext.h"
using namespace std;
using namespace AlibabaCloud;
TEST(AsyncCallerContext, basic) {
const std::string sys_generated_uuid = "643ce9ff-32b5-444c-814a-153b87a6aca8";
const std::string init_uuid = "init_uuid_for_test";
const std::string new_uuid = "new_uuid_for_test";
AsyncCallerContext context(init_uuid);
EXPECT_TRUE(context.uuid() == init_uuid);
context.setUuid(new_uuid);
EXPECT_TRUE(context.uuid() == new_uuid);
AsyncCallerContext context_from_GenerateUuid = AsyncCallerContext();
EXPECT_TRUE(context_from_GenerateUuid.uuid().length() == sys_generated_uuid.length());
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/asynccallercontext_ut.cc
|
C++
|
apache-2.0
| 669
|
#include "gtest/gtest.h"
#include "alibabacloud/core/ClientConfiguration.h"
#include "alibabacloud/core/AlibabaCloud.h"
using namespace std;
using namespace AlibabaCloud;
TEST(ClientConfiguration, basic) {
const std::string regionId = "cn-shanghai";
const std::string regionId_new = "cn-beijing";
const std::string endpoint = "ep-cn-shanghai";
const std::string hostname = "hostname";
const std::string user = "user";
const std::string password = "password";
uint16_t port = 12345;
const NetworkProxy proxy(NetworkProxy::Http, hostname, port, user, password);
ClientConfiguration config(regionId);
EXPECT_TRUE(config.regionId() == regionId);
config.setEndpoint(endpoint);
config.setProxy(proxy);
config.setRegionId(regionId_new);
EXPECT_TRUE(config.endpoint() == endpoint);
EXPECT_TRUE(config.regionId() == regionId_new);
EXPECT_TRUE(config.proxy().hostName() == hostname);
EXPECT_TRUE(config.proxy().port() == port);
EXPECT_TRUE(config.proxy().user() == user);
EXPECT_TRUE(config.proxy().password() == password);
EXPECT_TRUE(config.connectTimeout() == kDefaultConnectTimeout);
EXPECT_TRUE(config.readTimeout() == kDefaultReadTimeout);
config.setConnectTimeout(1222);
config.setReadTimeout(23333);
EXPECT_TRUE(config.connectTimeout() == 1222);
EXPECT_TRUE(config.readTimeout() == 23333);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/clientconfiguration_ut.cc
|
C++
|
apache-2.0
| 1,347
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/Utils.h"
#include "alibabacloud/core/Config.h"
#include "alibabacloud/core/AlibabaCloud.h"
#include "alibabacloud/core/CommonClient.h"
#include "alibabacloud/core/CommonResponse.h"
#include "alibabacloud/core/CommonRequest.h"
#include "alibabacloud/core/SimpleCredentialsProvider.h"
using namespace std;
using namespace AlibabaCloud;
namespace AlibabaCloud {
class TestCommonClient : public CommonClient {
public:
TestCommonClient(const Credentials &credentials, const ClientConfiguration &configuration):
CommonClient(credentials, configuration)
{}
using CommonClient::buildHttpRequest;
using CommonClient::buildRoaHttpRequest;
using CommonClient::buildRpcHttpRequest;
using CommonClient::makeRequest;
using CommonClient::asyncExecute;
using CommonClient::commonResponseAsync;
};
}
static int nbr = 0;
static void task() {
nbr |= 0x01;
}
namespace {
TEST(CommonClient, basic) {
InitializeSdk();
const ClientConfiguration cfg;
std::string key = "accessKeyId";
std::string secret = "accessSecret";
std::string token = "sessionToken";
const Credentials credentials(key, secret, token);
const CommonClient cc1(credentials, cfg);
CommonClient cc2(std::make_shared<SimpleCredentialsProvider>(credentials), cfg);
CommonClient cc3(key, secret, cfg);
CommonClient cc4(key, secret, cfg);
CommonRequest cr;
cr.setContent("test-content", 12);
CommonClient::CommonResponseOutcome out1 = cc1.commonResponse(cr);
EXPECT_TRUE(out1.error().errorCode() == "NetworkError");
EXPECT_TRUE(out1.error().errorMessage().find("Failed to connect to host or proxy: GET ") == 0);
EXPECT_TRUE(out1.result().payload() == "");
CommonClient::CommonResponseOutcome out2 = cc2.commonResponse(cr);
EXPECT_TRUE(out2.error().errorCode() == "NetworkError");
EXPECT_TRUE(out2.error().errorMessage().find("Failed to connect to host or proxy: GET ") == 0);
EXPECT_TRUE(out2.result().payload() == "");
CommonClient::CommonResponseOutcome out3 = cc3.commonResponse(cr);
EXPECT_TRUE(out3.error().errorCode() == "NetworkError");
EXPECT_TRUE(out3.error().errorMessage().find("Failed to connect to host or proxy: GET ") == 0);
EXPECT_TRUE(out3.result().payload() == "");
cr.setRequestPattern(CommonRequest::RequestPattern::RoaPattern);
CommonClient::CommonResponseOutcome out4 = cc4.commonResponse(cr);
EXPECT_TRUE(out4.error().errorCode() == "NetworkError");
EXPECT_TRUE(out4.error().errorMessage().find("Failed to connect to host or proxy: GET ") == 0);
EXPECT_TRUE(out4.result().payload() == "");
/*
https://cn-hangzhou/?
AccessKeyId=accessKeyId
&Format=JSON
&RegionId=cn-hangzhou
&SecurityToken=sessionToken
&Signature=tWGagYMK93km44TOY%2FY60snVYWE%3D
&SignatureMethod=HMAC-SHA1
&SignatureNonce=ef27311a-5151-40a0-974f-2b808a8a683e
&SignatureVersion=1.0
&Timestamp=2019-01-02T08%3A56%3A26Z
&Version=
*/
cr.setRequestPattern(CommonRequest::RequestPattern::RpcPattern);
TestCommonClient* client = new TestCommonClient(credentials, cfg);
HttpRequest r = client->buildHttpRequest("cn-hangzhou", cr, HttpRequest::Method::Post);
EXPECT_TRUE(r.method() == HttpRequest::Method::Post);
EXPECT_TRUE(r.url().scheme() == "https");
EXPECT_TRUE(r.url().userName() == "");
EXPECT_TRUE(r.url().password() == "");
EXPECT_TRUE(r.url().host() == "cn-hangzhou");
EXPECT_TRUE(r.url().port() == -1);
EXPECT_TRUE(r.url().fragment() == "");
EXPECT_TRUE(r.url().query().find("AccessKeyId=") != string::npos);
EXPECT_TRUE(r.url().query().find("Format=") != string::npos);
EXPECT_TRUE(r.url().query().find("RegionId=") != string::npos);
EXPECT_TRUE(r.url().query().find("SecurityToken=") != string::npos);
EXPECT_TRUE(r.url().query().find("Signature=") != string::npos);
EXPECT_TRUE(r.url().query().find("SignatureMethod=") != string::npos);
EXPECT_TRUE(r.url().query().find("SignatureNonce=") != string::npos);
EXPECT_TRUE(r.url().query().find("SignatureVersion=") != string::npos);
EXPECT_TRUE(r.url().query().find("Timestamp=") != string::npos);
EXPECT_TRUE(r.url().query().find("Version=") != string::npos);
cr.setQueryParameter("query_k1", "query_v1");
cr.setHeaderParameter("header_k1", "header_v1");
cr.setScheme("");
cr.setHeaderParameter("Accept", "");
HttpRequest rr = client->buildRoaHttpRequest("cn-shanghai", cr, HttpRequest::Method::Get);
EXPECT_TRUE(rr.method() == HttpRequest::Method::Get);
EXPECT_TRUE(rr.header("Accept") == "application/json");
EXPECT_TRUE(rr.url().toString() == "https://cn-shanghai/?header_k1=header_v1");
EXPECT_TRUE(rr.header("Host") == "cn-shanghai");
// Wed, 09 Jan 2019 06:32:41 GMT
string date = "Wed, 09 Jan 2019 06:32:41 GMT";
EXPECT_TRUE(rr.header("Date").length() == date.length());
string signature_nonce = "fb62c51d-f735-4ec7-870d-c6ce03368214";
EXPECT_TRUE(rr.header("x-acs-signature-nonce").length() == signature_nonce.length());
EXPECT_TRUE(rr.header("x-acs-signature-method") == "HMAC-SHA1");
EXPECT_TRUE(rr.header("x-acs-signature-version") == "1.0");
EXPECT_TRUE(rr.header("x-acs-version") == "");
EXPECT_TRUE(rr.header("x-sdk-client") == string("CPP/").append(ALIBABACLOUD_VERSION_STR));
EXPECT_TRUE(rr.header("x-acs-region-id") == "cn-hangzhou");
// acs accessKeyId:JZD81jGWLp1F3ZIkaLp1yuEZmKc=
EXPECT_TRUE(rr.header("Authorization").find("acs accessKeyId:") != string::npos);
EXPECT_TRUE(rr.header("unknown-header") == "");
cr.setScheme("http");
cr.setHeaderParameter("Accept", "test-accept");
cr.setHeaderParameter("Content-Type", "test-content-type");
rr = client->buildRoaHttpRequest("cn-shanghai", cr, HttpRequest::Method::Get);
EXPECT_TRUE(rr.url().toString() == "http://cn-shanghai/?Accept=test-accept&Content-Type=test-content-type&header_k1=header_v1");
EXPECT_TRUE(rr.header("Accept") == "test-accept");
EXPECT_TRUE(rr.header("Content-Type") == "test-content-type");
HttpRequest rrr = client->buildRpcHttpRequest("cn-hangzhou", cr, HttpRequest::Method::Post);
EXPECT_TRUE(client->serviceName() == "Common");
EXPECT_TRUE(rrr.url().scheme() == "http");
cr.setScheme("");
rrr = client->buildRpcHttpRequest("cn-hangzhou", cr, HttpRequest::Method::Post);
EXPECT_TRUE(rrr.url().scheme() == "https");
std::function<void()> func(task);
Runnable* rf = new Runnable(func);
EXPECT_TRUE(nbr == 0);
client->asyncExecute(rf);
usleep(10000);
EXPECT_EQ(nbr, 1);
ShutdownSdk();
}
TEST(CommonClient, bodyParam) {
const ClientConfiguration cfg;
std::string key = "accessKeyId";
std::string secret = "accessSecret";
std::string token = "sessionToken";
const Credentials credentials(key, secret, token);
CommonRequest cr;
cr.setBodyParameter("TestBodyParamKey", "TestBodyParamValue");
TestCommonClient* client = new TestCommonClient(credentials, cfg);
HttpRequest r = client->buildRpcHttpRequest("cn-hangzhou", cr, HttpRequest::Method::Post);
const char *s = "TestBodyParamKey=TestBodyParamValue";
EXPECT_EQ(*r.body(), *s);
}
TEST(CommonClient, abnormal) {
InitializeSdk();
ClientConfiguration configuration("cn-hangzhou");
CommonClient client("key", "secret", configuration);
CommonRequest req;
req.setScheme("http");
req.setDomain("aliyun.com");
auto out = client.commonResponse(req);
EXPECT_TRUE(out.error().errorCode() == "InvalidResponse");
EXPECT_TRUE(out.result().payload().empty());
/*
1: =====================<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
1: <html>
1: <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1: <title>301 Moved Permanently</title></head>
1: <body bgcolor="white">
1: <h1>301 Moved Permanently</h1>
1: <p>The requested resource has been assigned a new permanent URI.</p>
1: <hr/>Powered by Tengine/Aserver</body>
1: </html>
*/
EXPECT_FALSE(out.error().errorMessage().empty());
ShutdownSdk();
}
void cb(const CommonClient *client,
const CommonRequest &req,
const CommonClient::CommonResponseOutcome& out,
const std::shared_ptr<const AsyncCallerContext>& contex) {
EXPECT_FALSE(out.error().errorCode().empty());
}
TEST(CommonClient, async) {
InitializeSdk();
const ClientConfiguration cfg;
std::string key = "accessKeyId";
std::string secret = "accessSecret";
std::string token = "sessionToken";
const Credentials credentials(key, secret, token);
const CommonClient cc1(credentials, cfg);
CommonRequest cr;
cr.setContent("test-content", 12);
TestCommonClient::CommonResponseAsyncHandler handler(cb);
const AsyncCallerContext context;
cc1.commonResponseAsync(cr, handler, std::make_shared<const AsyncCallerContext>(context));
ShutdownSdk();
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/commonclient_ut.cc
|
C++
|
apache-2.0
| 9,100
|
#include "gtest/gtest.h"
#include "alibabacloud/core/CommonRequest.h"
using namespace std;
using namespace AlibabaCloud;
TEST(CommonRequest, basic) {
CommonRequest cr;
cr.setDomain("testDomain");
cr.setHeaderParameter("name1", "value1");
cr.setHttpMethod(HttpRequest::Method::Get);
cr.setQueryParameter("name2", "value2");
cr.setRequestPattern(CommonRequest::RequestPattern::RpcPattern);
EXPECT_TRUE(cr.domain() == "testDomain");
EXPECT_TRUE(cr.httpMethod() == HttpRequest::Method::Get);
EXPECT_TRUE(cr.requestPattern() == CommonRequest::RequestPattern::RpcPattern);
EXPECT_TRUE(cr.headerParameter("name1") == "value1");
EXPECT_TRUE(cr.queryParameter("name2") == "value2");
EXPECT_TRUE(cr.queryParameters()["name2"] == "value2");
EXPECT_TRUE(cr.headerParameters()["name1"] == "value1");
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/commonrequest_ut.cc
|
C++
|
apache-2.0
| 818
|
#include "gtest/gtest.h"
#include "alibabacloud/core/CommonResponse.h"
using namespace std;
using namespace AlibabaCloud;
TEST(CommonResponse, basic) {
CommonResponse cres("test_payload_");
EXPECT_TRUE(cres.payload() == "test_payload_");
CommonResponse cres1;
EXPECT_TRUE(cres1.payload() == "");
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/commonresponse_ut.cc
|
C++
|
apache-2.0
| 310
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/CoreClient.h"
using namespace std;
using namespace AlibabaCloud;
namespace AlibabaCloud {
class TestCoreClient : public CoreClient {
public:
TestCoreClient(const std::string & servicename, const ClientConfiguration &configuration):
CoreClient(servicename, configuration)
{}
using CoreClient::buildCoreError;
using CoreClient::hasResponseError;
HttpRequest buildHttpRequest(const std::string & endpoint, const ServiceRequest &msg, HttpRequest::Method method)const {
Url url;
url.setScheme("abc");
url.setUserName("username");
HttpRequest req(url, HttpRequest::Method::Post);
return req;
}
};
}
TEST(CoreClient, basic) {
ClientConfiguration configuration;
TestCoreClient client("test-service", configuration);
HttpResponse res;
Error e1 = client.buildCoreError(res);
EXPECT_TRUE(e1.errorCode() == ("InvalidResponse"));
EXPECT_TRUE(e1.errorMessage() == ("body is empty"));
string body = "{\"Code\":\"any-error-code\",\"Message\":\"any-error-message\",\"HostId\":\"any-host-id\",\"RequestId\":\"any-request-id\"}";
res.setBody(body.c_str(), body.size());
Error e2 = client.buildCoreError(res);
EXPECT_TRUE(e2.errorCode() == ("any-error-code"));
EXPECT_TRUE(e2.errorMessage() == ("any-error-message"));
EXPECT_TRUE(e2.host() == ("any-host-id"));
EXPECT_TRUE(e2.requestId() == ("any-request-id"));
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/coreclient_ut.cc
|
C++
|
apache-2.0
| 1,511
|
#include "gtest/gtest.h"
#include "alibabacloud/core/Credentials.h"
using namespace std;
using namespace AlibabaCloud;
TEST(CredentialsTest, basic) {
const string access_key = "accessKeyId";
const string access_secret = "accessKeySecret";
const string session_token = "sessionToken";
const string new_access_key = "new_accessKeyId";
const string new_access_secret = "new_accessKeySecret";
const string new_session_token = "new_sessionToken";
Credentials credentials(access_key, access_secret, session_token);
EXPECT_TRUE(credentials.accessKeyId() == access_key);
EXPECT_TRUE(credentials.accessKeySecret() == access_secret);
EXPECT_TRUE(credentials.sessionToken() == session_token);
credentials.setAccessKeyId(new_access_key);
credentials.setAccessKeySecret(new_access_secret);
credentials.setSessionToken(new_session_token);
EXPECT_TRUE(credentials.accessKeyId() == new_access_key);
EXPECT_TRUE(credentials.accessKeySecret() == new_access_secret);
EXPECT_TRUE(credentials.sessionToken() == new_session_token);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/credentials_ut.cc
|
C++
|
apache-2.0
| 1,050
|
#include <iostream>
#include <stdio.h>
#include "utils.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "alibabacloud/core/Url.h"
#include "alibabacloud/core/HttpRequest.h"
#include "alibabacloud/core/HttpClient.h"
#include "../src/CurlHttpClient.h"
using namespace std;
using ::testing::_;
using ::testing::NiceMock;
using ::testing::DefaultValue;
using namespace AlibabaCloud;
using namespace std;
class mockCurlHttpClient : public CurlHttpClient {
public:
MOCK_METHOD1(makeRequest, HttpResponseOutcome (const HttpRequest &request));
};
TEST(CurlHttpClient, connectTimeout) {
CurlHttpClient client;
HttpRequest request;
Url url;
url.setScheme("http");
url.setHost("192.168.100.100");
request.setMethod(HttpRequest::Method::Get);
request.setUrl(url);
request.setConnectTimeout(100);
request.setReadTimeout(1000);
request.setHeader("Content-Type", "text/html");
HttpClient::HttpResponseOutcome out = client.makeRequest(request);
string errmsg = "Timeout (connectTimeout: 100ms, readTimeout: 1000ms) when connect or read data: GET http://192.168.100.100/";
EXPECT_TRUE(out.error().errorCode() == "OperationTimeoutError");
EXPECT_TRUE(out.error().errorMessage() == errmsg);
}
TEST(CurlHttpClient, defaultTimeout) {
CurlHttpClient client;
HttpRequest request;
Url url;
url.setScheme("http");
url.setHost("192.168.100.100");
request.setMethod(HttpRequest::Method::Get);
request.setUrl(url);
request.setHeader("Content-Type", "text/html");
HttpClient::HttpResponseOutcome out = client.makeRequest(request);
string errmsg = "Timeout (connectTimeout: 5000ms, readTimeout: 10000ms) when connect or read data: GET http://192.168.100.100/";
EXPECT_TRUE(out.error().errorCode() == "OperationTimeoutError");
EXPECT_TRUE(out.error().errorMessage() == errmsg);
}
TEST(CurlHttpClient, readTimeout) {
CurlHttpClient client;
HttpRequest request;
Url url;
url.setScheme("http");
url.setHost("127.0.0.1");
url.setPort(8021);
url.setPath("/readTimeoutTest");
url.setQuery("timeout=500");
request.setMethod(HttpRequest::Method::Get);
request.setUrl(url);
request.setConnectTimeout(233);
request.setReadTimeout(500);
request.setHeader("Content-Type", "text/html");
HttpClient::HttpResponseOutcome out = client.makeRequest(request);
string errmsg = "Timeout (connectTimeout: 233ms, readTimeout: 500ms) when connect or read data: GET http://127.0.0.1:8021/readTimeoutTest?timeout=500";
EXPECT_TRUE(out.error().errorCode() == "OperationTimeoutError");
EXPECT_TRUE(out.error().errorMessage() == errmsg);
}
TEST(CurlHttpClient, http_get) {
CurlHttpClient client;
HttpRequest request;
Url url;
url.setHost("127.0.0.1");
url.setPort(8021);
url.setPath("/anypath");
url.setQuery("k1=v1&k2=v2");
request.setMethod(HttpRequest::Method::Get);
request.setUrl(url);
request.setHeader("Content-Type", "text/html");
HttpClient::HttpResponseOutcome out = client.makeRequest(request);
EXPECT_TRUE(std::string(out.result().body()) == "{\"k1\":\"v1\",\"k2\":\"v2\"}");
}
TEST(CurlHttpClient, http_post) {
CurlHttpClient client;
HttpRequest request;
std::string test_body = "any-body";
Url url;
url.setHost("127.0.0.1");
url.setPort(8021);
url.setPath("/anypath");
url.setQuery("k1=v1&k2=v2");
request.setMethod(HttpRequest::Method::Post);
request.setUrl(url);
request.setHeader("Content-Type", "text/html");
request.setBody(test_body.c_str(), test_body.size());
HttpClient::HttpResponseOutcome out = client.makeRequest(request);
EXPECT_TRUE(std::string(out.result().body()) == "POST: " + test_body);
}
TEST(CurlHttpClient, http_put) {
CurlHttpClient client;
HttpRequest request;
std::string test_body = "any-body";
Url url;
url.setHost("127.0.0.1");
url.setPort(8021);
url.setPath("/anypath");
url.setQuery("k1=v1&k2=v2");
request.setMethod(HttpRequest::Method::Put);
request.setUrl(url);
request.setHeader("Content-Type", "text/html");
request.setBody(test_body.c_str(), test_body.size());
HttpClient::HttpResponseOutcome out = client.makeRequest(request);
EXPECT_TRUE(std::string(out.result().body()) == "PUT: " + test_body);
}
TEST(CurlHttpClient, http_delete) {
CurlHttpClient client;
HttpRequest request;
std::string test_body = "any-body";
Url url;
url.setHost("127.0.0.1");
url.setPort(8021);
url.setPath("/anypath");
url.setQuery("k1=v1&k2=v2");
request.setMethod(HttpRequest::Method::Delete);
request.setUrl(url);
request.setHeader("Content-Type", "text/html");
request.setBody(test_body.c_str(), test_body.size());
HttpClient::HttpResponseOutcome out = client.makeRequest(request);
EXPECT_TRUE(std::string(out.result().body()) == "DELETE: " + test_body);
}
TEST(CurlHttpClient, netWorkError) {
CurlHttpClient client;
HttpRequest request;
HttpClient::HttpResponseOutcome out = client.makeRequest(request);
EXPECT_TRUE(out.error().errorCode() == "NetworkError");
EXPECT_TRUE(out.error().errorMessage().find("Failed to connect to host or proxy: GET ") == 0);
}
TEST(CurlHttpClient, netWorkErrorWithHttpProxy) {
const std::string hostname = "hostname";
const std::string user = "user";
const std::string password = "password";
uint16_t port = 12345;
const NetworkProxy proxy(NetworkProxy::Http, hostname, port, user, password);
CurlHttpClient client;
client.setProxy(proxy);
HttpRequest request;
HttpClient::HttpResponseOutcome out = client.makeRequest(request);
EXPECT_TRUE(out.error().errorCode() == "NetworkError");
EXPECT_TRUE(out.error().errorMessage().find("Failed to connect to host or proxy: GET ") == 0);
}
TEST(CurlHttpClient, netWorkErrorWithSocks5Proxy) {
const std::string hostname = "hostname";
const std::string user = "user";
const std::string password = "password";
uint16_t port = 12345;
const NetworkProxy proxy(NetworkProxy::Socks5, hostname, port, user, password);
CurlHttpClient client;
client.setProxy(proxy);
HttpRequest request;
HttpClient::HttpResponseOutcome out = client.makeRequest(request);
EXPECT_TRUE(out.error().errorCode() == "NetworkError");
EXPECT_TRUE(out.error().errorMessage().find("Failed to connect to host or proxy: GET ") == 0);
}
TEST(CurlHttpClient, mock) {
CurlHttpClient client;
HttpRequest request;
string body = "1234567";
HttpResponse response(request);
response.setStatusCode(200);
response.setBody(body.c_str(), body.size());
NiceMock<mockCurlHttpClient> mclient;
HttpClient::HttpResponseOutcome res = HttpClient::HttpResponseOutcome(response);
HttpClient::HttpResponseOutcome out1;
out1.error().setErrorCode("111");
out1.error().setErrorMessage("this is a mock test");
DefaultValue<HttpClient::HttpResponseOutcome>::Set(res);
HttpRequest req;
EXPECT_CALL(mclient, makeRequest(_));
HttpClient::HttpResponseOutcome o = mclient.makeRequest(request);
EXPECT_TRUE(res.result().body() == body);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/curlhttpclient_ut.cc
|
C++
|
apache-2.0
| 6,945
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "alibabacloud/core/Url.h"
#include "alibabacloud/core/HttpRequest.h"
#include "alibabacloud/core/HttpClient.h"
#include "../src/EcsMetadataFetcher.h"
using namespace std;
using namespace AlibabaCloud;
namespace {
TEST(EcsMetadataFetcher, basic) {
EcsMetadataFetcher fetcher;
fetcher.setRoleName("test-role-name");
EXPECT_TRUE(fetcher.roleName() == "test-role-name");
}
TEST(EcsMetadataFetcher, mock) {
HttpRequest request;
string body = "1234567";
HttpResponse response(request);
response.setStatusCode(200);
response.setBody(body.c_str(), body.size());
EcsMetadataFetcher fetcher;
string out = fetcher.getMetadata("a", "b");
EXPECT_TRUE(out == "NetworkError");
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/ecsmetadatafetcher_ut.cc
|
C++
|
apache-2.0
| 822
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "utils.h"
#include "alibabacloud/core/EndpointProvider.h"
using namespace std;
using namespace AlibabaCloud;
using namespace AlibabaCloud::Location;
using ::testing::_;
using ::testing::DefaultValue;
class mockEndpointProvider: public EndpointProvider {
public:
mockEndpointProvider(
const Credentials &credentials,
const ClientConfiguration &configuration,
const std::string ®ionId,
const std::string &product,
const std::string &serviceCode = std::string(),
int durationSeconds = 3600
):
EndpointProvider(credentials, configuration, regionId, product, serviceCode, durationSeconds) {}
MOCK_CONST_METHOD1(describeEndpoints, LocationClient::DescribeEndpointsOutcome(const Model::DescribeEndpointsRequest &request));
};
TEST(EndpointProvider, basic_function) {
const Credentials sub_user_credentials("key", "secret");
ClientConfiguration config; // default is cn-hangzhou
// user specified has 1st priority, even it is a wrong configuration
config.setEndpoint("test-endpoint");
mockEndpointProvider p0(sub_user_credentials, config, config.regionId(), "non-exist-product", "");
EndpointProvider::EndpointOutcome out0 = p0.getEndpoint();
EXPECT_TRUE(out0.result() == "test-endpoint");
config.setEndpoint(""); // set endpoint to empty
// invalid product
mockEndpointProvider p1(sub_user_credentials, config, config.regionId(), "non-exist-Product", "");
EndpointProvider::EndpointOutcome out1 = p1.getEndpoint();
EXPECT_TRUE(out1.error().errorCode() == "InvalidRegionId");
EXPECT_TRUE(out1.error().errorMessage() == "Product[non-exist-product] at region[cn-hangzhou] does not exist.");
mockEndpointProvider p2(sub_user_credentials, config, "non-exist-region", "ecs", "");
EndpointProvider::EndpointOutcome out2 = p2.getEndpoint();
EXPECT_TRUE(out2.error().errorCode() == "InvalidRegionId");
EXPECT_TRUE(out2.error().errorMessage() == "Product[ecs] at region[non-exist-region] does not exist.");
// local_endpoints can provide the endpoint
mockEndpointProvider p3(sub_user_credentials, config, config.regionId(), "ecs", "");
EndpointProvider::EndpointOutcome out3 = p3.getEndpoint();
EXPECT_TRUE(out3.result() == "ecs-cn-hangzhou.aliyuncs.com");
// aegis has global_endpoint
mockEndpointProvider p4(sub_user_credentials, config, config.regionId(), "aegis", "");
EndpointProvider::EndpointOutcome out4 = p4.getEndpoint();
EXPECT_TRUE(out4.result() == "aegis.cn-hangzhou.aliyuncs.com");
// aegis has global_endpoint
mockEndpointProvider p5(sub_user_credentials, config, config.regionId(), "Aegis", "");
EndpointProvider::EndpointOutcome out5 = p5.getEndpoint();
EXPECT_TRUE(out5.result() == "aegis.cn-hangzhou.aliyuncs.com");
mockEndpointProvider p6(sub_user_credentials, config, "cn-shanghai", "ensdisk", "");
EndpointProvider::EndpointOutcome out6 = p6.getEndpoint();
EXPECT_TRUE(out6.error().errorCode() == "InvalidRegionId");
EXPECT_TRUE(out6.error().errorMessage() == "Product[ensdisk] at region[cn-shanghai] does not exist.");
}
TEST(EndpointProvider, mock_remote) {
const Credentials sub_user_credentials("key", "secret");
ClientConfiguration config; // default is cn-hangzhou
// config.setEndpoint("test-endpoint");
mockEndpointProvider provider(sub_user_credentials, config, config.regionId(), "fake-ecs", "fake-ecs");
Model::DescribeEndpointsRequest request;
const string payload = "{\"RequestId\":\"test-request-id\",\"Success\":true,\"Endpoints\":{\"Endpoint\":[{\"Endpoint\":\"test-ep\",\"Id\":\"test-id\",\"Namespace\":\"test-namespace\",\"SerivceCode\":\"test-service-code\",\"Type\":\"test-type\",\"Protocols\":{\"Protocols\":[\"a\",\"b\"]}}]}}";
Location::Model::DescribeEndpointsResult res(payload);
LocationClient::DescribeEndpointsOutcome xout(res);
DefaultValue<LocationClient::DescribeEndpointsOutcome>::Set(xout);
EXPECT_CALL(provider, describeEndpoints(_));
EndpointProvider::EndpointOutcome out = provider.getEndpoint();
EXPECT_TRUE(out.error().errorCode().empty());
EXPECT_TRUE(out.result() == "test-ep");
}
TEST(EndpointProvider, mock_remote_error) {
const Credentials sub_user_credentials("key", "secret");
ClientConfiguration config; // default is cn-hangzhou
mockEndpointProvider provider(sub_user_credentials, config, config.regionId(), "fake-ecs", "fake-ecs");
LocationClient::DescribeEndpointsOutcome xout(Error("any-error-code", "any-error-message"));
DefaultValue<LocationClient::DescribeEndpointsOutcome>::Set(xout);
EXPECT_CALL(provider, describeEndpoints(_));
EndpointProvider::EndpointOutcome out = provider.getEndpoint();
EXPECT_TRUE(out.error().errorCode() == "any-error-code");
}
TEST(EndpointProvider, serial_02) {
utUtils utils;
string key = utils.get_env("ENV_AccessKeyId");
string secret = utils.get_env("ENV_AccessKeySecret");
Credentials credentials(key, secret);
ClientConfiguration configuration("cn-hangzhou");
EndpointProvider ep(credentials, configuration, "cn-hangzhou", "arms", "arms");
EndpointProvider::EndpointOutcome out = ep.getEndpoint();
EXPECT_EQ("arms.cn-hangzhou.aliyuncs.com", out.result());
EndpointProvider p1(credentials, configuration, "cn-shanghai", "fake-ecs", "fake-ecs");
EndpointProvider::EndpointOutcome out1 = p1.getEndpoint();
EXPECT_EQ("InvalidProduct", out1.error().errorCode());
EXPECT_EQ("Prodcut[fake-ecs] does not exist.", out1.error().errorMessage());
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/endpointprovider_ut.cc
|
C++
|
apache-2.0
| 5,538
|
#include "gtest/gtest.h"
#include "alibabacloud/core/Error.h"
using namespace std;
using namespace AlibabaCloud;
TEST(Error, basic) {
const std::string error_code = "errorCode";
const std::string error_message = "errorMessage";
const std::string host = "Host";
const std::string request_id = "requestId";
Error error(error_code, error_message);
EXPECT_TRUE(error.errorCode() == error_code);
EXPECT_TRUE(error.errorMessage() == error_message);
EXPECT_TRUE(error.host() == "");
EXPECT_TRUE(error.requestId() == "");
error.setHost(host);
error.setRequestId(request_id);
EXPECT_TRUE(error.errorCode() == error_code);
EXPECT_TRUE(error.errorMessage() == error_message);
EXPECT_TRUE(error.host() == host);
EXPECT_TRUE(error.requestId() == request_id);
const string code1 = "invalid regionId";
const string message1 = "invalid regionId cn-xxxx";
error.setErrorCode(code1);
error.setErrorMessage(message1);
EXPECT_TRUE(error.errorCode() == code1);
EXPECT_TRUE(error.errorMessage() == message1);
const string detail = "any error detail";
error.setDetail(detail);
EXPECT_TRUE(error.detail() == detail);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/error_ut.cc
|
C++
|
apache-2.0
| 1,150
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/Runnable.h"
#include "../src/Executor.h"
using namespace std;
using namespace AlibabaCloud;
namespace {
static unsigned int nbr = 0;
static void f0() {
usleep(3000);
nbr |= 0x01;
}
static void f1() {
usleep(3000);
nbr |= 0x02;
}
static void f2() {
usleep(3000);
nbr |= 0x04;
}
// there should be no exception
TEST(Executor, basic) {
std::function<void()> func0(f0);
std::function<void()> func1(f1);
std::function<void()> func2(f2);
Runnable* rf0 = new Runnable(func0);
Runnable* rf1 = new Runnable(func1);
Runnable* rf2 = new Runnable(func2);
Executor* e = new Executor;
EXPECT_TRUE(e->isShutdown() == true);
// thread created to execute tasks
e->start();
// before
EXPECT_TRUE(nbr == 0);
// push tasks to queue
e->instance()->execute(rf0);
e->instance()->execute(rf1);
e->instance()->execute(rf2);
// shutdown removes tasks in queue
e->shutdown();
// there is no time for task executing
// maybe some tasks executed as the async reason
// EXPECT_EQ(nbr, 0x07);
rf0 = new Runnable(func0);
rf1 = new Runnable(func1);
rf2 = new Runnable(func2);
nbr = 0;
e->execute(rf0);
usleep(5000);
// executor not started, nbr no changed
EXPECT_TRUE(nbr == 0);
e->start();
// there should be no more thread created
e->start();
e->instance()->execute(rf0);
e->execute(rf1);
e->execute(rf2);
usleep(20000);
// EXPECT_EQ(nbr, 0x07);
e->shutdown();
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/executor_ut.cc
|
C++
|
apache-2.0
| 1,611
|
#include "gtest/gtest.h"
#include "alibabacloud/core/HmacSha1Signer.h"
#include <openssl/hmac.h>
using namespace std;
using namespace AlibabaCloud;
namespace {
TEST(HmacSha1Signer, assign) {
HmacSha1Signer sig;
string sign = sig.generate("GET&%2F&AccessKeyId%3Dtestid%26Action%3DDescribeRegions"
"%26Format%3DXML%26RegionId%3Dregion1%26SignatureMethod%3DHMAC-SHA1"
"%26SignatureNonce%3DNwDAxvLU6tFE0DVb%26SignatureVersion%3D1.0"
"%26TimeStamp%3D2012-12-26T10%253A33%253A56Z%26Version%3D2013-01-10",
"testsecret&");
EXPECT_TRUE("axE3FUHgDyfm9/+Iep0HpZXrRwE=" == sign);
EXPECT_TRUE(sig.type() == HmacSha1Signer::HmacSha1);
EXPECT_TRUE(sig.name() == "HMAC-SHA1");
EXPECT_TRUE(sig.version() == "1.0");
}
TEST(HmacSha1Signer, edge_from_empty_string) {
HmacSha1Signer sign;
EXPECT_TRUE(sign.generate("", "") == "");
}
TEST(HmacSha1Signer, unicode) {
HmacSha1Signer sig;
string sign = sig.generate("GET&%2F&AccessKeyId%3Dtestid%26Action%3DDescribeRegions"
"%26TestUnicode%3DDescribeRegions啊啊啊"
"%26Format%3DXML%26RegionId%3Dregion1%26SignatureMethod%3DHMAC-SHA1"
"%26SignatureNonce%3DNwDAxvLU6tFE0DVb%26SignatureVersion%3D1.0"
"%26TimeStamp%3D2012-12-26T10%253A33%253A56Z%26Version%3D2013-01-10",
"testsecret&");
EXPECT_TRUE("VJ1a5YBLy+shtBK/l97MCMq+mzs=" == sign);
}
TEST(HmacSha1Signer, specialQuery) {
HmacSha1Signer sig;
string sign = sig.generate("GET&%2F&AccessKeyId%3Dtestid%26Action%3DDescribeRegions"
"%26TestUnicode%3DDescri&beRegions"
"%26Format%3DXML%26RegionId%3Dregion1%26SignatureMethod%3DHMAC-SHA1"
"%26SignatureNonce%3DNwDAxvLU6tFE0DVb%26SignatureVersion%3D1.0"
"%26TimeStamp%3D2012-12-26T10%253A33%253A56Z%26Version%3D2013-01-10",
"testsecret&");
EXPECT_TRUE("3PuleV7r01lLr4wwvWNCOuLKV5A=" == sign);
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/hmacsha1signer_ut.cc
|
C++
|
apache-2.0
| 1,909
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/HttpRequest.h"
using namespace std;
using namespace AlibabaCloud;
TEST(HttpMessage, perRequest) {
const std::string data = "Thu, 19 Oct 2017 04:38:27 GMT";
HttpRequest req;
req.setHeader("accept", "application/xml");
EXPECT_TRUE(req.header("accept") == "application/xml");
req.setHeader("Accept", "application/json");
EXPECT_TRUE(req.header("accept") == "application/json");
EXPECT_TRUE(req.headers().size() == 1);
req.setHeader("Date", data);
EXPECT_TRUE(req.headers().size() == 2);
EXPECT_TRUE(req.header(HttpMessage::KnownHeader::Date) == data);
req.addHeader("header1", "value1");
EXPECT_TRUE(req.header("header1") == "value1");
EXPECT_TRUE(req.headers().size() == 3);
req.addHeader(HttpMessage::KnownHeader::ContentMD5, "testmd5sume");
EXPECT_TRUE(req.header(HttpMessage::KnownHeader::ContentMD5) == "testmd5sume");
EXPECT_TRUE(req.headers().size() == 4);
req.removeHeader("header1");
EXPECT_TRUE(req.header("header1") == "");
EXPECT_TRUE(req.headers().size() == 3);
req.removeHeader(HttpMessage::KnownHeader::ContentMD5);
EXPECT_TRUE(req.header(HttpMessage::KnownHeader::ContentMD5) == "");
EXPECT_TRUE(req.headers().size() == 2);
string body = "this is a test body";
req.setBody(body.c_str(), body.size());
EXPECT_TRUE(req.bodySize() == body.size());
EXPECT_TRUE(req.hasBody());
EXPECT_TRUE(req.body() != nullptr);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/httpmessage_ut.cc
|
C++
|
apache-2.0
| 1,472
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/HttpRequest.h"
using namespace std;
using namespace AlibabaCloud;
TEST(HttpRequest, basic) {
const string src = "abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1";
Url url;
url.setScheme("abc");
url.setUserName("username");
url.setPassword("password");
url.setHost("example.com");
url.setPath("/path/data");
url.setPort(123);
url.setQuery("key=value&key2=value2");
url.setFragment("fragid1");
HttpRequest req(url, HttpRequest::Method::Post);
EXPECT_TRUE(req.method() == HttpRequest::Method::Post);
req.setMethod(HttpRequest::Method::Get);
EXPECT_TRUE(req.method() == HttpRequest::Method::Get);
req.setUrl(url);
Url rUrl = req.url();
EXPECT_TRUE(rUrl.toString() == src);
EXPECT_TRUE(req.connectTimeout() == 5000);
EXPECT_TRUE(req.readTimeout() == 10000);
req.setConnectTimeout(12345);
req.setReadTimeout(3335);
EXPECT_TRUE(req.connectTimeout() == 12345);
EXPECT_TRUE(req.readTimeout() == 3335);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/httprequest_ut.cc
|
C++
|
apache-2.0
| 1,071
|
#include "gtest/gtest.h"
#include "alibabacloud/core/HttpResponse.h"
using namespace std;
using namespace AlibabaCloud;
TEST(HttpResponse, basic) {
HttpResponse r;
r.setStatusCode(202);
EXPECT_TRUE(r.statusCode() == 202);
Url url;
url.setHost("example.com");
HttpRequest req(url, HttpRequest::Method::Post);
HttpResponse res(req);
EXPECT_TRUE(res.request().url().host() == "example.com");
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/httpresponse_ut.cc
|
C++
|
apache-2.0
| 411
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "alibabacloud/core/InstanceProfileCredentialsProvider.h"
using namespace std;
using namespace AlibabaCloud;
using ::testing::_;
using ::testing::DefaultValue;
class mockInstanceProfileCredentialsProvider: public InstanceProfileCredentialsProvider {
public:
mockInstanceProfileCredentialsProvider(const std::string &roleName, int durationSeconds):
InstanceProfileCredentialsProvider(roleName, durationSeconds) {}
MOCK_METHOD0(getMetadata, std::string());
};
TEST(InstanceProfileCredentialsProvider, basic) {
mockInstanceProfileCredentialsProvider p("test-role-name", 1800);
DefaultValue<std::string>::Set("{\"Code\":\"test-code\",\"AccessKeyId\":\"any-key\",\"AccessKeySecret\":\"any-secret\",\"SecurityToken\":\"any-token\",\"Expiration\":3233}");
EXPECT_CALL(p, getMetadata());
Credentials credentials = p.getCredentials();
EXPECT_TRUE(credentials.accessKeyId() == "any-key");
EXPECT_TRUE(credentials.accessKeySecret() == "any-secret");
EXPECT_TRUE(credentials.sessionToken() == "any-token");
}
TEST(InstanceProfileCredentialsProvider, empty) {
mockInstanceProfileCredentialsProvider p("test-role-name", 1800);
DefaultValue<std::string>::Set("{}");
EXPECT_CALL(p, getMetadata());
Credentials credentials = p.getCredentials();
EXPECT_TRUE(credentials.accessKeyId().empty());
EXPECT_TRUE(credentials.accessKeySecret().empty());
EXPECT_TRUE(credentials.sessionToken().empty());
}
TEST(InstanceProfileCredentialsProvider, empty_1) {
mockInstanceProfileCredentialsProvider p("test-role-name", 1800);
DefaultValue<std::string>::Set("");
EXPECT_CALL(p, getMetadata());
Credentials credentials = p.getCredentials();
EXPECT_TRUE(credentials.accessKeyId().empty());
EXPECT_TRUE(credentials.accessKeySecret().empty());
EXPECT_TRUE(credentials.sessionToken().empty());
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/instanceprofilecredentialsprovider_ut.cc
|
C++
|
apache-2.0
| 1,920
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/location/model/DescribeEndpointsRequest.h"
using namespace std;
using namespace AlibabaCloud;
TEST(DescribeEndpointsRequest, basic) {
Location::Model::DescribeEndpointsRequest req;
req.setServiceCode("test-sc");
req.setId("test-id");
req.setType("test-type");
EXPECT_TRUE(req.serviceCode() == "test-sc");
EXPECT_TRUE(req.id() == "test-id");
EXPECT_TRUE(req.type() == "test-type");
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/location_model_describeendpoints_request_ut.cc
|
C++
|
apache-2.0
| 494
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/location/model/DescribeEndpointsResult.h"
using namespace std;
using namespace AlibabaCloud;
TEST(DescribeEndpointsResult, basic) {
const string payload = "{\"RequestId\":\"test-request-id\",\"Success\":true,\"Endpoints\":{\"Endpoint\":[{\"Endpoint\":\"test-ep\",\"Id\":\"test-id\",\"Namespace\":\"test-namespace\",\"SerivceCode\":\"test-service-code\",\"Type\":\"test-type\",\"Protocols\":{\"Protocols\":[\"a\",\"b\"]}}]}}";
Location::Model::DescribeEndpointsResult res(payload);
EXPECT_TRUE(res.success());
EXPECT_TRUE(res.endpoints().size() == 1);
EXPECT_TRUE(res.endpoints()[0].endpoint == "test-ep");
EXPECT_TRUE(res.endpoints()[0].id == "test-id");
EXPECT_TRUE(res.endpoints()[0].namespace_ == "test-namespace");
EXPECT_TRUE(res.endpoints()[0].serivceCode == "test-service-code");
EXPECT_TRUE(res.endpoints()[0].type == "test-type");
EXPECT_TRUE(res.endpoints()[0].protocols.size() == 2);
EXPECT_TRUE(res.endpoints()[0].protocols[0] == "a");
EXPECT_TRUE(res.endpoints()[0].protocols[1] == "b");
}
TEST(DescribeEndpointsResult, set) {
Location::Model::DescribeEndpointsResult res;
res.setSuccess(true);
EXPECT_TRUE(res.success());
res.setSuccess(false);
EXPECT_TRUE(res.success() == false);
std::vector<std::string> protocols;
protocols.push_back("p1");
protocols.push_back("p2");
Location::Model::DescribeEndpointsResult::Endpoint ep;
ep.endpoint = "ep";
ep.id = "id";
ep.namespace_ = "ns";
ep.serivceCode = "sc";
ep.type = "t";
ep.protocols = protocols;
std::vector<Location::Model::DescribeEndpointsResult::Endpoint> endpoints_;
endpoints_.push_back(ep);
res.setEndpoints(endpoints_);
res.setSuccess(true);
EXPECT_TRUE(res.success());
EXPECT_TRUE(res.endpoints().size() == 1);
EXPECT_TRUE(res.endpoints()[0].endpoint == "ep");
EXPECT_TRUE(res.endpoints()[0].id == "id");
EXPECT_TRUE(res.endpoints()[0].namespace_ == "ns");
EXPECT_TRUE(res.endpoints()[0].serivceCode == "sc");
EXPECT_TRUE(res.endpoints()[0].type == "t");
EXPECT_TRUE(res.endpoints()[0].protocols.size() == 2);
EXPECT_TRUE(res.endpoints()[0].protocols[0] == "p1");
EXPECT_TRUE(res.endpoints()[0].protocols[1] == "p2");
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/location_model_describeendpoints_result_ut.cc
|
C++
|
apache-2.0
| 2,275
|
#include <iostream>
#include <stdio.h>
#include "utils.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "alibabacloud/core/AlibabaCloud.h"
#include "alibabacloud/core/SimpleCredentialsProvider.h"
#include "alibabacloud/core/location/LocationClient.h"
using namespace std;
using namespace AlibabaCloud;
using namespace AlibabaCloud::Location;
using ::testing::_;
using ::testing::DefaultValue;
namespace {
class mockLocationClient : public LocationClient {
public:
mockLocationClient(const string& key, const string& secret, const ClientConfiguration& cfg):
LocationClient(key, secret, cfg) {}
mockLocationClient(const Credentials& credentials, const ClientConfiguration& cfg):
LocationClient(credentials, cfg) {}
mockLocationClient(const std::shared_ptr<CredentialsProvider> &credentialsProvider, const ClientConfiguration &configuration):
LocationClient(credentialsProvider, configuration) {}
MOCK_CONST_METHOD3(makeRequest, RpcServiceClient::JsonOutcome (const std::string &endpoint, const RpcServiceRequest &msg, HttpRequest::Method method));
};
TEST(LocationClient, sync_ak) {
ClientConfiguration configuration("cn-hangzhou");
Model::DescribeEndpointsRequest req;
req.setId("cn-hangzhou");
req.setServiceCode("ecs");
req.setType("openAPI");
mockLocationClient client("key", "secret", configuration);
RpcServiceClient::JsonOutcome xout("{\"Endpoints\":{\"Endpoint\":[{\"Protocols\":{\"Protocols\":[\"HTTP\",\"HTTPS\"]},\"Type\":\"test-type\",\"Namespace\":\"test-namespace\",\"Id\":\"cn-hangzhou\",\"SerivceCode\":\"test-servicecode\",\"Endpoint\":\"test-endpoint\"}]},\"RequestId\":\"test-request-id\",\"Success\":true}");
DefaultValue<RpcServiceClient::JsonOutcome>::Set(xout);
EXPECT_CALL(client, makeRequest(_, _, _));
LocationClient::DescribeEndpointsOutcome out = client.describeEndpoints(req);
EXPECT_TRUE(out.error().errorCode().empty());
EXPECT_TRUE(out.result().success());
EXPECT_TRUE(out.result().requestId() == "test-request-id");
EXPECT_TRUE(out.result().endpoints().size() == 1);
Model::DescribeEndpointsResult::Endpoint ep = out.result().endpoints()[0];
EXPECT_TRUE(ep.endpoint == "test-endpoint");
EXPECT_TRUE(ep.id == "cn-hangzhou");
EXPECT_TRUE(ep.namespace_ == "test-namespace");
EXPECT_TRUE(ep.type == "test-type");
EXPECT_TRUE(ep.protocols.size() == 2);
std::vector<std::string>::iterator it;
std::vector<std::string> protocols = ep.protocols;
it = std::find(protocols.begin(), protocols.end(), string("HTTP"));
EXPECT_TRUE(it != protocols.end());
it = std::find(protocols.begin(), protocols.end(), string("HTTPS"));
EXPECT_TRUE(it != protocols.end());
}
//{"Endpoints":{"Endpoint":[{"Protocols":{"Protocols":["HTTP","HTTPS"]},"Type":"openAPI","Namespace":"","Id":"cn-hangzhou","SerivceCode":"ecs","Endpoint":"ecs-cn-hangzhou.aliyuncs.com"}]},"RequestId":"test-request-id","Success":true}
TEST(LocationClient, sync_credentials) {
Credentials credentials("key", "secret");
ClientConfiguration configuration("cn-hangzhou");
Model::DescribeEndpointsRequest req;
req.setId("cn-hangzhou");
req.setServiceCode("ecs");
req.setType("openAPI");
mockLocationClient client(credentials, configuration);
RpcServiceClient::JsonOutcome xout("{\"Endpoints\":{\"Endpoint\":[{\"Protocols\":{\"Protocols\":[\"HTTP\",\"HTTPS\"]},\"Type\":\"test-type\",\"Namespace\":\"test-namespace\",\"Id\":\"cn-hangzhou\",\"SerivceCode\":\"test-servicecode\",\"Endpoint\":\"test-endpoint\"}]},\"RequestId\":\"test-request-id\",\"Success\":true}");
DefaultValue<RpcServiceClient::JsonOutcome>::Set(xout);
EXPECT_CALL(client, makeRequest(_, _, _));
LocationClient::DescribeEndpointsOutcome out = client.describeEndpoints(req);
EXPECT_TRUE(out.error().errorCode().empty());
EXPECT_TRUE(out.result().success());
EXPECT_TRUE(out.result().requestId() == "test-request-id");
EXPECT_TRUE(out.result().endpoints().size() == 1);
Model::DescribeEndpointsResult::Endpoint ep = out.result().endpoints()[0];
EXPECT_TRUE(ep.endpoint == "test-endpoint");
EXPECT_TRUE(ep.id == "cn-hangzhou");
EXPECT_TRUE(ep.namespace_ == "test-namespace");
EXPECT_TRUE(ep.type == "test-type");
EXPECT_TRUE(ep.protocols.size() == 2);
std::vector<std::string>::iterator it;
std::vector<std::string> protocols = ep.protocols;
it = std::find(protocols.begin(), protocols.end(), string("HTTP"));
EXPECT_TRUE(it != protocols.end());
it = std::find(protocols.begin(), protocols.end(), string("HTTPS"));
EXPECT_TRUE(it != protocols.end());
}
TEST(LocationClient, sync_credentials_ptr) {
Credentials credentials("key", "secret");
ClientConfiguration configuration("cn-hangzhou");
Model::DescribeEndpointsRequest req;
req.setId("cn-hangzhou");
req.setServiceCode("ecs");
req.setType("openAPI");
mockLocationClient client(std::make_shared<SimpleCredentialsProvider>(credentials), configuration);
RpcServiceClient::JsonOutcome xout("{\"Endpoints\":{\"Endpoint\":[{\"Protocols\":{\"Protocols\":[\"HTTP\",\"HTTPS\"]},\"Type\":\"test-type\",\"Namespace\":\"test-namespace\",\"Id\":\"cn-hangzhou\",\"SerivceCode\":\"test-servicecode\",\"Endpoint\":\"test-endpoint\"}]},\"RequestId\":\"test-request-id\",\"Success\":true}");
DefaultValue<RpcServiceClient::JsonOutcome>::Set(xout);
EXPECT_CALL(client, makeRequest(_, _, _));
LocationClient::DescribeEndpointsOutcome out = client.describeEndpoints(req);
EXPECT_TRUE(out.error().errorCode().empty());
EXPECT_TRUE(out.result().success());
EXPECT_TRUE(out.result().requestId() == "test-request-id");
EXPECT_TRUE(out.result().endpoints().size() == 1);
Model::DescribeEndpointsResult::Endpoint ep = out.result().endpoints()[0];
EXPECT_TRUE(ep.endpoint == "test-endpoint");
EXPECT_TRUE(ep.id == "cn-hangzhou");
EXPECT_TRUE(ep.namespace_ == "test-namespace");
EXPECT_TRUE(ep.type == "test-type");
EXPECT_TRUE(ep.protocols.size() == 2);
std::vector<std::string>::iterator it;
std::vector<std::string> protocols = ep.protocols;
it = std::find(protocols.begin(), protocols.end(), string("HTTP"));
EXPECT_TRUE(it != protocols.end());
it = std::find(protocols.begin(), protocols.end(), string("HTTPS"));
EXPECT_TRUE(it != protocols.end());
}
TEST(LocationClient, callable) {
InitializeSdk();
ClientConfiguration configuration("cn-hangzhou");
Model::DescribeEndpointsRequest req;
req.setId("cn-hangzhou");
req.setServiceCode("ecs");
req.setType("openAPI");
mockLocationClient client("key", "secret", configuration);
RpcServiceClient::JsonOutcome xout("{\"Endpoints\":{\"Endpoint\":[{\"Protocols\":{\"Protocols\":[\"HTTP\",\"HTTPS\"]},\"Type\":\"test-type\",\"Namespace\":\"test-namespace\",\"Id\":\"cn-hangzhou\",\"SerivceCode\":\"test-servicecode\",\"Endpoint\":\"test-endpoint\"}]},\"RequestId\":\"test-request-id\",\"Success\":true}");
DefaultValue<RpcServiceClient::JsonOutcome>::Set(xout);
EXPECT_CALL(client, makeRequest(_, _, _));
LocationClient::DescribeEndpointsOutcomeCallable cb = client.describeEndpointsCallable(req);
LocationClient::DescribeEndpointsOutcome out = cb.get();
EXPECT_TRUE(out.error().errorCode().empty());
EXPECT_TRUE(out.result().success());
EXPECT_TRUE(out.result().requestId() == "test-request-id");
EXPECT_TRUE(out.result().endpoints().size() == 1);
Model::DescribeEndpointsResult::Endpoint ep = out.result().endpoints()[0];
EXPECT_TRUE(ep.endpoint == "test-endpoint");
EXPECT_TRUE(ep.id == "cn-hangzhou");
EXPECT_TRUE(ep.namespace_ == "test-namespace");
EXPECT_TRUE(ep.type == "test-type");
EXPECT_TRUE(ep.protocols.size() == 2);
std::vector<std::string>::iterator it;
std::vector<std::string> protocols = ep.protocols;
it = std::find(protocols.begin(), protocols.end(), string("HTTP"));
EXPECT_TRUE(it != protocols.end());
it = std::find(protocols.begin(), protocols.end(), string("HTTPS"));
EXPECT_TRUE(it != protocols.end());
ShutdownSdk();
}
void cb(const LocationClient *client,
const Model::DescribeEndpointsRequest &req,
const LocationClient::DescribeEndpointsOutcome& out,
const std::shared_ptr<const AsyncCallerContext>& contex) {
EXPECT_FALSE(out.error().errorCode().empty());
}
TEST(LocationClient, async) {
InitializeSdk();
ClientConfiguration configuration("cn-hangzhou");
Model::DescribeEndpointsRequest req;
req.setId("cn-hangzhou");
req.setServiceCode("ecs");
req.setType("openAPI");
LocationClient client("key", "secret", configuration);
LocationClient::DescribeEndpointsOutcome out;
const AsyncCallerContext context;
LocationClient::DescribeEndpointsAsyncHandler handler(cb);
client.describeEndpointsAsync(req, handler, std::make_shared<const AsyncCallerContext>(context));
ShutdownSdk();
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/locationclient_ut.cc
|
C++
|
apache-2.0
| 9,046
|
#include "gtest/gtest.h"
#include "alibabacloud/core/NetworkProxy.h"
using namespace std;
using namespace AlibabaCloud;
TEST(NetworProxyTest, basic) {
NetworkProxy proxy(NetworkProxy::Http);
proxy.setHostName("abc.com");
proxy.setPassword("myPassword");
proxy.setPort(123);
proxy.setUser("tester");
EXPECT_TRUE(proxy.type() == NetworkProxy::Http);
proxy.setType(NetworkProxy::Socks5);
EXPECT_TRUE(proxy.type() == NetworkProxy::Socks5);
EXPECT_TRUE(proxy.hostName() == "abc.com");
EXPECT_TRUE(proxy.password() == "myPassword");
EXPECT_TRUE(proxy.user() == "tester");
EXPECT_TRUE(proxy.port() == 123);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/networkproxy_ut.cc
|
C++
|
apache-2.0
| 629
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/SimpleCredentialsProvider.h"
#include "alibabacloud/core/RoaServiceClient.h"
#include "alibabacloud/core/HttpMessage.h"
#include "alibabacloud/core/HttpRequest.h"
using namespace std;
using namespace AlibabaCloud;
namespace AlibabaCloud {
class TestRoaClient : public RoaServiceClient {
public:
TestRoaClient(const std::string & servicename, const std::shared_ptr<CredentialsProvider> &credentialsProvider,
const ClientConfiguration &configuration,
const std::shared_ptr<Signer> &signer = std::make_shared<HmacSha1Signer>()):
RoaServiceClient(servicename, credentialsProvider, configuration, signer)
{}
JsonOutcome makeRequest(const std::string &endpoint, const RoaServiceRequest &msg, HttpRequest::Method method = HttpRequest::Method::Get)const {
return RoaServiceClient::makeRequest(endpoint, msg, method);
}
HttpRequest buildHttpRequest(const std::string & endpoint, const ServiceRequest &msg, HttpRequest::Method method)const {
return RoaServiceClient::buildHttpRequest(endpoint, msg, method);
}
};
class TestRoaServiceRequest: public ServiceRequest {
public:
TestRoaServiceRequest(const std::string &product, const std::string &version):
ServiceRequest(product, version){}
using ServiceRequest::addParameter;
using ServiceRequest::parameter;
using ServiceRequest::removeParameter;
using ServiceRequest::setContent;
using ServiceRequest::setParameter;
using ServiceRequest::setParameters;
using ServiceRequest::setResourcePath;
using ServiceRequest::setProduct;
using ServiceRequest::setVersion;
};
}
TEST(RoaServiceClient, basic) {
const ClientConfiguration config;
std::string key = "accessKeyId";
std::string secret = "accessSecret";
std::string token = "sessionToken";
const Credentials credentials(key, secret, token);
TestRoaClient client("ecs", std::make_shared<SimpleCredentialsProvider>(credentials), config);
const string product = "ECS";
const string version = "1.0";
RoaServiceRequest roa_req(product, version);
RoaServiceClient::JsonOutcome out = client.makeRequest("cn-shanghai", roa_req, HttpRequest::Method::Get);
EXPECT_TRUE(out.error().errorCode() == "NetworkError");
RoaServiceRequest req(product, version);
req.setParameter("a", "b");
req.setScheme("");
req.setContent("123456789", 9);
HttpRequest http_req = client.buildHttpRequest("cn-shanghai", req, HttpRequest::Method::Get);
EXPECT_TRUE(http_req.url().toString() == "https://cn-shanghai/?a=b");
EXPECT_TRUE(http_req.header("Accept") == "application/json");
EXPECT_TRUE(http_req.header("Content-Length") == "9");
EXPECT_TRUE(http_req.header("Content-Type") == "application/octet-stream");
EXPECT_TRUE(http_req.header("Content-MD5") == "JfnnlDI7RTiF9RgfG2JNCw==");
const string date = "Fri, 11 Jan 2019 14:08:39 GMT";
EXPECT_TRUE(http_req.header("Date").length() == date.length());
EXPECT_TRUE(http_req.header("Host") == "cn-shanghai");
EXPECT_TRUE(http_req.header("x-sdk-cient") == "");
EXPECT_TRUE(http_req.header("x-acs-region-id") == "cn-hangzhou");
EXPECT_TRUE(http_req.header("x-acs-security-token") == token);
EXPECT_TRUE(http_req.header("x-acs-signature-method") == "HMAC-SHA1");
EXPECT_TRUE(http_req.header("x-acs-signature-version") == "1.0");
EXPECT_TRUE(http_req.header("x-acs-version") == "1.0");
const string nounce = "8a013b14-7bac-4652-8b5f-c02c8924e4ae";
EXPECT_TRUE(http_req.header("x-acs-signature-nonce").length() == nounce.length());
EXPECT_TRUE(http_req.header("Authorization").find("acs accessKeyId:") != string::npos);
req.setScheme("http");
req.setParameter("Accept", "tets-accept");
req.setParameter("Content-Type", "test-content-type");
http_req = client.buildHttpRequest("cn-shanghai", req, HttpRequest::Method::Get);
EXPECT_TRUE(http_req.url().toString() == "http://cn-shanghai/?Accept=tets-accept&Content-Type=test-content-type&a=b");
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/roaserviceclient_ut.cc
|
C++
|
apache-2.0
| 4,045
|
#include "gtest/gtest.h"
#include "alibabacloud/core/RoaServiceRequest.h"
using namespace std;
using namespace AlibabaCloud;
TEST(test_RoaServiceRequest, basic) {
const string product = "ECS";
const string version = "1.0";
RoaServiceRequest roa(product, version);
EXPECT_TRUE(roa.version() == version);
EXPECT_TRUE(roa.product() == product);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/roaservicerequest_ut.cc
|
C++
|
apache-2.0
| 359
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "alibabacloud/core/SimpleCredentialsProvider.h"
#include "alibabacloud/core/RpcServiceClient.h"
#include "alibabacloud/core/HttpMessage.h"
#include "alibabacloud/core/HttpClient.h"
#include "alibabacloud/core/HttpRequest.h"
using namespace std;
using namespace AlibabaCloud;
using ::testing::_;
using ::testing::DefaultValue;
namespace AlibabaCloud {
class mockRpcServiceClient : public RpcServiceClient {
public:
mockRpcServiceClient(const std::string & servicename, const std::shared_ptr<CredentialsProvider> &credentialsProvider,
const ClientConfiguration &configuration,
const std::shared_ptr<Signer> &signer = std::make_shared<HmacSha1Signer>()):
RpcServiceClient(servicename, credentialsProvider, configuration, signer)
{}
MOCK_CONST_METHOD3(AttemptRequest, HttpClient::HttpResponseOutcome (const std::string & endpoint, const ServiceRequest &request, HttpRequest::Method method));
using RpcServiceClient::makeRequest;
using RpcServiceClient::buildHttpRequest;
};
class mockServiceRequest: public ServiceRequest {
public:
mockServiceRequest(const std::string &product, const std::string &version):
ServiceRequest(product, version){}
using ServiceRequest::addParameter;
using ServiceRequest::parameter;
using ServiceRequest::removeParameter;
using ServiceRequest::setContent;
using ServiceRequest::setParameter;
using ServiceRequest::setParameters;
using ServiceRequest::setResourcePath;
using ServiceRequest::setProduct;
using ServiceRequest::setVersion;
};
}
TEST(RpcServiceClient, basic) {
const ClientConfiguration config;
std::string key = "fake-key";
std::string secret = "fake-secret";
std::string token = "fake-token";
const Credentials credentials(key, secret, token);
mockRpcServiceClient client("ecs", std::make_shared<SimpleCredentialsProvider>(credentials), config);
const string product = "ECS";
const string version = "1.0";
const string action = "fake-action";
const string endpoint = "test-cn-shanghai";
RpcServiceRequest req(product, version, action);
req.setScheme("");
HttpRequest http_req = client.buildHttpRequest(endpoint, req, HttpRequest::Method::Get);
EXPECT_TRUE(http_req.header("x-sdk-client") == std::string("CPP/").append(ALIBABACLOUD_VERSION_STR));
EXPECT_TRUE(http_req.header("Host") == endpoint);
EXPECT_TRUE(http_req.method() == HttpRequest::Method::Get);
EXPECT_TRUE(http_req.url().query().find("AccessKeySecret") == string::npos);
EXPECT_TRUE(http_req.url().query().find("AccessKeyId=fake-key") != string::npos);
EXPECT_TRUE(http_req.url().query().find("&SecurityToken=fake-token") != string::npos);
EXPECT_TRUE(http_req.url().query().find("&Action=fake-action") != string::npos);
EXPECT_TRUE(http_req.url().query().find("&Format=JSON") != string::npos);
EXPECT_TRUE(http_req.url().query().find("&RegionId=cn-hangzhou") != string::npos);
EXPECT_TRUE(http_req.url().query().find("&Signature=") != string::npos);
EXPECT_TRUE(http_req.url().query().find("&SignatureMethod=HMAC-SHA1") != string::npos);
EXPECT_TRUE(http_req.url().query().find("&SignatureNonce=") != string::npos);
EXPECT_TRUE(http_req.url().query().find("&SignatureVersion=1.0") != string::npos);
EXPECT_TRUE(http_req.url().query().find("&Version=1.0") != string::npos);
EXPECT_TRUE(http_req.url().query().find("&Timestamp=") != string::npos);
EXPECT_TRUE(http_req.url().scheme() == "https");
req.setScheme("http");
http_req = client.buildHttpRequest(endpoint, req, HttpRequest::Method::Get);
EXPECT_TRUE(http_req.url().scheme() == "http");
}
TEST(RpcServiceClient, mock) {
const string product = "ECS";
const string version = "1.0";
const string action = "fake-action";
const string endpoint = "test-cn-shanghai";
const string servicename = "fake-service-name";
const ClientConfiguration configuration;
std::string key = "fake-key";
std::string secret = "fake-secret";
std::string token = "fake-token";
const Credentials credentials(key, secret, token);
RpcServiceRequest rpc_req(product, version, action);
HttpClient::HttpResponseOutcome xout(Error("any-error-code", "any-error-message"));
DefaultValue<HttpClient::HttpResponseOutcome>::Set(xout);
mockRpcServiceClient client(servicename, std::make_shared<SimpleCredentialsProvider>(credentials), configuration);
EXPECT_CALL(client, AttemptRequest(_, _, _));
RpcServiceClient::JsonOutcome out = client.makeRequest(endpoint, rpc_req, HttpRequest::Method::Get);
EXPECT_TRUE(out.error().errorCode() == "any-error-code");
}
TEST(RpcServiceClient, mock_1) {
const string product = "ECS";
const string version = "1.0";
const string action = "fake-action";
const string endpoint = "test-cn-shanghai";
const string servicename = "fake-service-name";
const ClientConfiguration configuration;
std::string key = "fake-key";
std::string secret = "fake-secret";
std::string token = "fake-token";
const Credentials credentials(key, secret, token);
RpcServiceRequest rpc_req(product, version, action);
Url url;
url.setHost("example.com");
HttpRequest req(url, HttpRequest::Method::Post);
HttpResponse res(req);
res.setBody("any-body", 8);
HttpClient::HttpResponseOutcome xout(res);
DefaultValue<HttpClient::HttpResponseOutcome>::Set(xout);
mockRpcServiceClient client(servicename, std::make_shared<SimpleCredentialsProvider>(credentials), configuration);
EXPECT_CALL(client, AttemptRequest(_, _, _));
RpcServiceClient::JsonOutcome out = client.makeRequest(endpoint, rpc_req, HttpRequest::Method::Get);
EXPECT_TRUE(out.error().errorCode().empty());
EXPECT_TRUE(out.result() == "any-body");
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/rpcserviceclient_ut.cc
|
C++
|
apache-2.0
| 5,813
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/RpcServiceRequest.h"
using namespace std;
using namespace AlibabaCloud;
TEST(test_RpcServiceRequest, basic) {
const string product = "ECS";
const string version = "1.0";
const string action = "testAction";
RpcServiceRequest rpc(product, version, action);
EXPECT_TRUE(rpc.actionName() == action);
EXPECT_TRUE(rpc.product() == product);
EXPECT_TRUE(rpc.version() == version);
EXPECT_EQ(string("testAction"), rpc.getHeader(string("x-acs-action")));
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/rpcservicerequest_ut.cc
|
C++
|
apache-2.0
| 559
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/Runnable.h"
using namespace std;
using namespace AlibabaCloud;
static int nbr = 0;
void foo() {
nbr = 1;
}
// there should be no exception
TEST(Runnable, basic) {
std::function<void()> func(foo);
Runnable f(func);
EXPECT_TRUE(nbr == 0);
f.run();
EXPECT_TRUE(nbr == 1);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/runnable_ut.cc
|
C++
|
apache-2.0
| 379
|
#include <iostream>
#include <stdio.h>
#include <string.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/ServiceRequest.h"
#include "alibabacloud/core/AlibabaCloud.h"
using namespace std;
using namespace AlibabaCloud;
namespace {
class TestServiceRequest: public ServiceRequest {
public:
explicit TestServiceRequest(const std::string &product, const std::string &version):
ServiceRequest(product, version)
{}
explicit TestServiceRequest(const ServiceRequest &other):
ServiceRequest(other)
{}
explicit TestServiceRequest(ServiceRequest &&other):
ServiceRequest(other)
{}
using ServiceRequest::addParameter;
using ServiceRequest::coreParameter;
using ServiceRequest::parameter;
using ServiceRequest::removeParameter;
using ServiceRequest::setBodyParameter;
using ServiceRequest::setContent;
using ServiceRequest::setCoreParameter;
using ServiceRequest::setParameter;
using ServiceRequest::setParameters;
using ServiceRequest::setProduct;
using ServiceRequest::setResourcePath;
using ServiceRequest::setVersion;
};
TEST(ServiceRequest, basic) {
TestServiceRequest sr1("ECS", "1.0");
TestServiceRequest sr2(sr1);
EXPECT_EQ(string("1.0"), sr1.getHeader(string("x-acs-version")));
sr1.addParameter("k1", "v1");
sr2.addParameter("k2", "v2");
ServiceRequest::ParameterCollection p1 = sr1.parameters();
ServiceRequest::ParameterCollection p2 = sr2.parameters();
EXPECT_TRUE(sr1.parameter("k1") == "v1");
sr1.addParameter("kx", "vx");
EXPECT_TRUE(sr1.parameter("kx") == "vx");
EXPECT_TRUE(sr1.parameters().size() == 2);
sr1.removeParameter("k1");
EXPECT_TRUE(sr1.parameters().size() == 1);
sr1.setCoreParameter("kcore1", "vcore1");
EXPECT_TRUE(sr1.parameter("kcore1") == "vcore1");
EXPECT_TRUE(sr1.coreParameter("kcore1") == "vcore1");
sr1.setParameter("ka", "va");
EXPECT_TRUE(sr1.parameter("ka") == "va");
EXPECT_TRUE(sr1.coreParameter("ka") == "va");
sr1.setBodyParameter("name", "value");
sr1.setContent("123456", 6);
EXPECT_TRUE(sr1.contentSize() == 6);
EXPECT_TRUE(sr1.hasContent() == true);
EXPECT_TRUE(strncmp(sr1.content(), "123456", 6) == 0);
sr1.setContent("aliyunsdk", 9);
EXPECT_TRUE(sr1.contentSize() == 9);
EXPECT_TRUE(sr1.hasContent() == true);
EXPECT_TRUE(strncmp(sr1.content(), "aliyunsdk", 9) == 0);
sr1.setProduct("OSS");
EXPECT_TRUE(sr1.product() == "OSS");
sr1.setVersion("3.0");
EXPECT_TRUE(sr1.version() == "3.0");
sr1.setResourcePath("http://abc.com/a/b/c");
EXPECT_TRUE(sr1.resourcePath() == "http://abc.com/a/b/c");
ServiceRequest::ParameterCollection ps;
ps["km"] = "vm";
ps["kn"] = "vn";
sr1.setParameters(ps);
ServiceRequest::ParameterCollection pc = sr1.parameters();
EXPECT_TRUE(pc.at("km") == "vm");
EXPECT_TRUE(pc.at("kn") == "vn");
ServiceRequest::ParameterCollection bp = sr1.bodyParameters();
EXPECT_EQ(bp.at("name"), "value");
EXPECT_TRUE(sr1.connectTimeout() == kInvalidTimeout);
EXPECT_TRUE(sr1.readTimeout() == kInvalidTimeout);
sr1.setConnectTimeout(1234);
sr1.setReadTimeout(22233);
EXPECT_TRUE(sr1.connectTimeout() == 1234);
EXPECT_TRUE(sr1.readTimeout() == 22233);
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/servicerequest_ut.cc
|
C++
|
apache-2.0
| 3,330
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/ServiceResult.h"
using namespace std;
using namespace AlibabaCloud;
namespace AlibabaCloud{
class myServiceResult: public ServiceResult {
public:
myServiceResult(){}
void setRequestId(const string request_id) {
ServiceResult::setRequestId(request_id);
}
};
}
TEST(ServiceResult, basic) {
ServiceResult* service_result = new ServiceResult();
EXPECT_TRUE(service_result->requestId() == "");
myServiceResult* sr = new myServiceResult();
sr->setRequestId("testRequestId");
EXPECT_TRUE(sr->requestId() == "testRequestId");
delete(service_result);
delete(sr);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/serviceresult_ut.cc
|
C++
|
apache-2.0
| 692
|
#include "gtest/gtest.h"
#include "alibabacloud/core/Signer.h"
using namespace std;
using namespace AlibabaCloud;
namespace {
TEST(Signer, basic) {
HmacSha1Signer sig;
string sign = sig.generate("GET&%2F&AccessKeyId%3Dtestid%26Action%3DDescribeRegions"
"%26Format%3DXML%26RegionId%3Dregion1%26SignatureMethod%3DHMAC-SHA1"
"%26SignatureNonce%3DNwDAxvLU6tFE0DVb%26SignatureVersion%3D1.0"
"%26TimeStamp%3D2012-12-26T10%253A33%253A56Z%26Version%3D2013-01-10",
"testsecret&");
EXPECT_TRUE("axE3FUHgDyfm9/+Iep0HpZXrRwE=" == sign);
}
TEST(Signer, unicode) {
HmacSha1Signer sig;
string sign = sig.generate("GET&%2F&AccessKeyId%3Dtestid%26Action%3DDescribeRegions"
"%26TestUnicode%3DDescribeRegions啊啊啊"
"%26Format%3DXML%26RegionId%3Dregion1%26SignatureMethod%3DHMAC-SHA1"
"%26SignatureNonce%3DNwDAxvLU6tFE0DVb%26SignatureVersion%3D1.0"
"%26TimeStamp%3D2012-12-26T10%253A33%253A56Z%26Version%3D2013-01-10",
"testsecret&");
EXPECT_TRUE("axE3FUHgDyfm9/+Iep0HpZXrRwE=" == sign);
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/signer_ut.cc
|
C++
|
apache-2.0
| 1,084
|
#include "gtest/gtest.h"
#include "alibabacloud/core/Credentials.h"
#include "alibabacloud/core/sts/StsClient.h"
#include "alibabacloud/core/SimpleCredentialsProvider.h"
using namespace std;
using namespace AlibabaCloud;
TEST(SimpleCredentialsProvider, basic) {
const string access_key = "accessKeyId";
const string access_secret = "accessKeySecret";
Credentials credentials(access_key, access_secret);
SimpleCredentialsProvider p1(credentials);
SimpleCredentialsProvider p2(access_key, access_secret);
EXPECT_TRUE(p1.getCredentials().accessKeyId() == access_key);
EXPECT_TRUE(p1.getCredentials().accessKeySecret() == access_secret);
EXPECT_TRUE(p2.getCredentials().accessKeyId() == access_key);
EXPECT_TRUE(p2.getCredentials().accessKeySecret() == access_secret);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/simplecredentialsprovider_ut.cc
|
C++
|
apache-2.0
| 791
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/sts/model/AssumeRoleRequest.h"
using namespace std;
using namespace AlibabaCloud;
TEST(AssumeRoleRequest, basic) {
const string policy = "test_policy";
const string role_arn = "test_role_arn";
const string role_session_name = "test_role_session_name";
Sts::Model::AssumeRoleRequest req;
req.setDurationSeconds(100);
req.setPolicy(policy);
req.setRoleArn(role_arn);
req.setRoleSessionName(role_session_name);
EXPECT_TRUE(req.durationSeconds() == 100);
EXPECT_TRUE(req.policy() == policy);
EXPECT_TRUE(req.roleArn() == role_arn);
EXPECT_TRUE(req.roleSessionName() == role_session_name);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/sts_model_assumerole_request_ut.cc
|
C++
|
apache-2.0
| 705
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/sts/model/AssumeRoleResult.h"
using namespace std;
using namespace AlibabaCloud;
TEST(AssumeRoleResult, basic) {
const string payload = "{\"RequestId\":\"a-b-c-d\",\"AssumedRoleUser\":{\"AssumedRoleId\":\"test_assumed_role_id\",\"Arn\":\"test_arn\"},\"Credentials\":{\"AccessKeyId\":\"test_access_key_id\",\"AccessKeySecret\":\"test_access_key_secret\",\"Expiration\":\"100\",\"SecurityToken\":\"test_security_token\"}}";
Sts::Model::AssumeRoleResult res(payload);
string arn = "test_arn";
string assumed_role_id = "test_assumed_role_id";
string access_key_id = "test_access_key_id";
string access_key_secret = "test_access_key_secret";
string expiration = "100";
string security_token = "test_security_token";
EXPECT_TRUE(res.assumedRoleUser().arn == arn);
EXPECT_TRUE(res.assumedRoleUser().assumedRoleId == assumed_role_id);
EXPECT_TRUE(res.credentials().accessKeyId == access_key_id);
EXPECT_TRUE(res.credentials().accessKeySecret == access_key_secret);
EXPECT_TRUE(res.credentials().expiration == expiration);
EXPECT_TRUE(res.credentials().securityToken == security_token);
}
TEST(AssumeRoleResult, empty) {
Sts::Model::AssumeRoleResult res;
EXPECT_TRUE(res.assumedRoleUser().arn.empty());
EXPECT_TRUE(res.assumedRoleUser().assumedRoleId.empty());
EXPECT_TRUE(res.credentials().accessKeyId.empty());
EXPECT_TRUE(res.credentials().accessKeySecret.empty());
EXPECT_TRUE(res.credentials().expiration.empty());
EXPECT_TRUE(res.credentials().securityToken.empty());
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/sts_model_assumerole_result_ut.cc
|
C++
|
apache-2.0
| 1,611
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/sts/model/GetCallerIdentityRequest.h"
using namespace std;
using namespace AlibabaCloud;
TEST(GetCallerIdentityRequest, basic) {
Sts::Model::GetCallerIdentityRequest req;
EXPECT_TRUE(req.actionName() == "GetCallerIdentity");
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/sts_model_getcalleridentity_request_ut.cc
|
C++
|
apache-2.0
| 325
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/sts/model/GetCallerIdentityResult.h"
using namespace std;
using namespace AlibabaCloud;
TEST(GetCallerIdentityResult, basic) {
const string payload = "{\"Request\":\"test-request-id\",\"AccountId\":\"test_account_id\",\"Arn\":\"test_arn\",\"UserId\":\"test_user_id\"}";
Sts::Model::GetCallerIdentityResult res(payload);
string arn = "test_arn";
string account_id = "test_account_id";
string user_id = "test_user_id";
EXPECT_TRUE(res.accountId() == account_id);
EXPECT_TRUE(res.arn() == arn);
EXPECT_TRUE(res.userId() == user_id);
}
TEST(GetCallerIdentityResult, empty) {
Sts::Model::GetCallerIdentityResult res;
EXPECT_TRUE(res.accountId().empty());
EXPECT_TRUE(res.arn().empty());
EXPECT_TRUE(res.userId().empty());
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/sts_model_getcalleridentity_result_ut.cc
|
C++
|
apache-2.0
| 842
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "alibabacloud/core/AlibabaCloud.h"
#include "alibabacloud/core/sts/StsClient.h"
#include "alibabacloud/core/StsAssumeRoleCredentialsProvider.h"
using namespace std;
using namespace AlibabaCloud;
using namespace AlibabaCloud::Sts;
using ::testing::_;
using ::testing::DefaultValue;
namespace {
class mockStsAssumeRoleCredentialsProvider : public StsAssumeRoleCredentialsProvider {
public:
mockStsAssumeRoleCredentialsProvider(
const Credentials &credentials,
const ClientConfiguration &configuration,
const std::string &roleArn,
const std::string &roleSessionName,
const std::string &policy = "",
int durationSeconds = 3600):
StsAssumeRoleCredentialsProvider(credentials, configuration, roleArn, roleSessionName, policy, durationSeconds) {}
MOCK_CONST_METHOD1(assumeRole, StsClient::AssumeRoleOutcome(const Model::AssumeRoleRequest &request));
};
TEST(StsAssumeRoleCredentialsProvider, mock) {
ClientConfiguration configuration("cn-hangzhou");
const string sub_user_key = "key";
const string sub_user_secret = "secret";
const Credentials sub_user_credentials(sub_user_key, sub_user_secret);
const string arn = "acs:ram::1940345800212929:role/testassumerole";
const string session = "roleSessionName";
const string policy = "";
int duration = 1800;
const string payload = "{\"RequestId\":\"a-b-c-d\",\"AssumedRoleUser\":{\"AssumedRoleId\":\"test_assumed_role_id\",\"Arn\":\"test_arn\"},\"Credentials\":{\"AccessKeyId\":\"test_access_key_id\",\"AccessKeySecret\":\"test_access_key_secret\",\"Expiration\":\"100\",\"SecurityToken\":\"test_security_token\"}}";
Model::AssumeRoleResult res(payload);
mockStsAssumeRoleCredentialsProvider provider(sub_user_credentials, configuration, arn, session, policy, duration);
StsClient::AssumeRoleOutcome xout(res);
DefaultValue<StsClient::AssumeRoleOutcome>::Set(xout);
EXPECT_CALL(provider, assumeRole(_));
Credentials assumed_role_credentials = provider.getCredentials();
EXPECT_TRUE(assumed_role_credentials.accessKeyId() == "test_access_key_id");
EXPECT_TRUE(assumed_role_credentials.accessKeySecret() == "test_access_key_secret");
EXPECT_TRUE(assumed_role_credentials.sessionToken() == "test_security_token");
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/stsassumerolecredentialsprovider_ut.cc
|
C++
|
apache-2.0
| 2,395
|
#include <iostream>
#include <stdio.h>
#include "utils.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "alibabacloud/core/AlibabaCloud.h"
#include "alibabacloud/core/SimpleCredentialsProvider.h"
#include "alibabacloud/core/sts/StsClient.h"
using ::testing::_;
using ::testing::DefaultValue;
using namespace std;
using namespace AlibabaCloud;
using namespace AlibabaCloud::Sts;
namespace {
class mockStsClient : public StsClient {
public:
mockStsClient(const string& key, const string& secret, const ClientConfiguration& cfg):
StsClient(key, secret, cfg) {}
mockStsClient(const Credentials& credentials, const ClientConfiguration& cfg):
StsClient(credentials, cfg) {}
mockStsClient(const std::shared_ptr<CredentialsProvider> &credentialsProvider, const ClientConfiguration &configuration):
StsClient(credentialsProvider, configuration) {}
MOCK_CONST_METHOD3(makeRequest, RpcServiceClient::JsonOutcome (const std::string &endpoint, const RpcServiceRequest &msg, HttpRequest::Method method));
};
TEST(StsClient, getCallerIdentity_ak) {
ClientConfiguration configuration;
RpcServiceClient::JsonOutcome xout("{\"Request\":\"test-req-id\",\"AccountId\":\"123456789\",\"Arn\":\"any-arn\",\"UserId\":\"any-id\"}");
mockStsClient client("mock-key", "mock-secret", configuration);
DefaultValue<RpcServiceClient::JsonOutcome>::Set(xout);
EXPECT_CALL(client, makeRequest(_, _, _));
Model::GetCallerIdentityRequest req;
StsClient::GetCallerIdentityOutcome out = client.getCallerIdentity(req);
EXPECT_TRUE(out.error().errorCode().empty());
EXPECT_TRUE(out.result().accountId() == "123456789");
EXPECT_TRUE(out.result().userId() == "any-id");
EXPECT_TRUE(out.result().arn() == "any-arn");
}
TEST(StsClient, getCallerIdentity_credentials) {
ClientConfiguration configuration;
RpcServiceClient::JsonOutcome xout("{\"Request\":\"test-req-id\",\"AccountId\":\"123456789\",\"Arn\":\"any-arn\",\"UserId\":\"any-id\"}");
Credentials credentials("key", "secret");
mockStsClient client(credentials, configuration);
DefaultValue<RpcServiceClient::JsonOutcome>::Set(xout);
EXPECT_CALL(client, makeRequest(_, _, _));
Model::GetCallerIdentityRequest req;
StsClient::GetCallerIdentityOutcome out = client.getCallerIdentity(req);
EXPECT_TRUE(out.error().errorCode().empty());
EXPECT_TRUE(out.result().accountId() == "123456789");
EXPECT_TRUE(out.result().userId() == "any-id");
EXPECT_TRUE(out.result().arn() == "any-arn");
}
TEST(StsClient, getCallerIdentity_credentials_ptr) {
ClientConfiguration configuration;
RpcServiceClient::JsonOutcome xout("{\"Request\":\"test-req-id\",\"AccountId\":\"123456789\",\"Arn\":\"any-arn\",\"UserId\":\"any-id\"}");
Credentials credentials("key", "secret");
mockStsClient client(std::make_shared<SimpleCredentialsProvider>(credentials), configuration);
DefaultValue<RpcServiceClient::JsonOutcome>::Set(xout);
EXPECT_CALL(client, makeRequest(_, _, _));
Model::GetCallerIdentityRequest req;
StsClient::GetCallerIdentityOutcome out = client.getCallerIdentity(req);
EXPECT_TRUE(out.error().errorCode().empty());
EXPECT_TRUE(out.result().accountId() == "123456789");
EXPECT_TRUE(out.result().userId() == "any-id");
EXPECT_TRUE(out.result().arn() == "any-arn");
}
TEST(StsClient, getCallerIdentity_ak_error) {
InitializeSdk();
ClientConfiguration configuration;
RpcServiceClient::JsonOutcome xout(Error("any-error-code", "any-error-message"));
mockStsClient client("mock-key", "mock-secret", configuration);
DefaultValue<RpcServiceClient::JsonOutcome>::Set(xout);
EXPECT_CALL(client, makeRequest(_, _, _));
Model::GetCallerIdentityRequest req;
StsClient::GetCallerIdentityOutcome out = client.getCallerIdentity(req);
EXPECT_TRUE(out.error().errorCode() == "any-error-code");
ShutdownSdk();
}
TEST(StsClient, getCallerIdentity_callable) {
InitializeSdk();
ClientConfiguration configuration;
RpcServiceClient::JsonOutcome xout("{\"Request\":\"test-req-id\",\"AccountId\":\"123456789\",\"Arn\":\"any-arn\",\"UserId\":\"any-id\"}");
mockStsClient client("mock-key", "mock-secret", configuration);
DefaultValue<RpcServiceClient::JsonOutcome>::Set(xout);
EXPECT_CALL(client, makeRequest(_, _, _));
Model::GetCallerIdentityRequest req;
StsClient::GetCallerIdentityOutcomeCallable cb = client.getCallerIdentityCallable(req);
StsClient::GetCallerIdentityOutcome out = cb.get();
EXPECT_TRUE(out.error().errorCode().empty());
EXPECT_TRUE(out.result().accountId() == "123456789");
EXPECT_TRUE(out.result().userId() == "any-id");
EXPECT_TRUE(out.result().arn() == "any-arn");
ShutdownSdk();
}
void cb(const StsClient *client,
const Model::GetCallerIdentityRequest &req,
const StsClient::GetCallerIdentityOutcome& out,
const std::shared_ptr<const AsyncCallerContext>& contex) {
EXPECT_FALSE(out.error().errorCode().empty());
}
TEST(StsClient, getCallerIdentity_async) {
InitializeSdk();
ClientConfiguration configuration("cn-hangzhou");
Model::GetCallerIdentityRequest req;
StsClient client("key", "secret", configuration);
const AsyncCallerContext context;
StsClient::GetCallerIdentityAsyncHandler handler(cb);
client.getCallerIdentityAsync(req, handler, std::make_shared<const AsyncCallerContext>(context));
ShutdownSdk();
}
TEST(StsClient, assumeRole) {
ClientConfiguration configuration;
RpcServiceClient::JsonOutcome xout("{\"RequestId\":\"any-request-id\",\"success\":true,\"AssumedRoleUser\":{\"AssumedRoleId\":\"123456789\",\"Arn\":\"any-arn\"},\"Credentials\":{\"AccessKeyId\":\"any-key\",\"AccessKeySecret\":\"any-secret\",\"Expiration\":\"2019-01-15T16:31:10Z\",\"SecurityToken\":\"any-token\"}}");
mockStsClient client("mock-key", "mock-secret", configuration);
DefaultValue<RpcServiceClient::JsonOutcome>::Set(xout);
EXPECT_CALL(client, makeRequest(_, _, _));
Model::AssumeRoleRequest req;
StsClient::AssumeRoleOutcome out = client.assumeRole(req);
EXPECT_TRUE(out.error().errorCode().empty());
EXPECT_TRUE(out.result().assumedRoleUser().arn == "any-arn");
EXPECT_TRUE(out.result().assumedRoleUser().assumedRoleId == "123456789");
EXPECT_TRUE(out.result().credentials().accessKeyId == "any-key");
EXPECT_TRUE(out.result().credentials().accessKeySecret == "any-secret");
EXPECT_TRUE(out.result().credentials().expiration == "2019-01-15T16:31:10Z");
EXPECT_TRUE(out.result().credentials().securityToken == "any-token");
}
TEST(StsClient, assumeRole_callable) {
InitializeSdk();
ClientConfiguration configuration;
RpcServiceClient::JsonOutcome xout("{\"RequestId\":\"any-request-id\",\"success\":true,\"AssumedRoleUser\":{\"AssumedRoleId\":\"123456789\",\"Arn\":\"any-arn\"},\"Credentials\":{\"AccessKeyId\":\"any-key\",\"AccessKeySecret\":\"any-secret\",\"Expiration\":\"2019-01-15T16:31:10Z\",\"SecurityToken\":\"any-token\"}}");
mockStsClient client("mock-key", "mock-secret", configuration);
DefaultValue<RpcServiceClient::JsonOutcome>::Set(xout);
EXPECT_CALL(client, makeRequest(_, _, _));
Model::AssumeRoleRequest req;
StsClient::AssumeRoleOutcomeCallable cb = client.assumeRoleCallable(req);
StsClient::AssumeRoleOutcome out = cb.get();
EXPECT_TRUE(out.error().errorCode().empty());
EXPECT_TRUE(out.result().assumedRoleUser().arn == "any-arn");
EXPECT_TRUE(out.result().assumedRoleUser().assumedRoleId == "123456789");
EXPECT_TRUE(out.result().credentials().accessKeyId == "any-key");
EXPECT_TRUE(out.result().credentials().accessKeySecret == "any-secret");
EXPECT_TRUE(out.result().credentials().expiration == "2019-01-15T16:31:10Z");
EXPECT_TRUE(out.result().credentials().securityToken == "any-token");
ShutdownSdk();
}
TEST(StsClient, assumeRole_error) {
ClientConfiguration configuration;
RpcServiceClient::JsonOutcome xout(Error("any-error-code", "any-error-message"));
mockStsClient client("mock-key", "mock-secret", configuration);
DefaultValue<RpcServiceClient::JsonOutcome>::Set(xout);
EXPECT_CALL(client, makeRequest(_, _, _));
Model::AssumeRoleRequest req;
StsClient::AssumeRoleOutcome out = client.assumeRole(req);
EXPECT_TRUE(out.error().errorCode() == "any-error-code");
}
void assumerole_cb(const StsClient *client,
const Model::AssumeRoleRequest &req,
const StsClient::AssumeRoleOutcome& out,
const std::shared_ptr<const AsyncCallerContext>& contex) {
EXPECT_FALSE(out.error().errorCode().empty());
}
TEST(StsClient, assumeRole_async) {
InitializeSdk();
ClientConfiguration configuration("cn-hangzhou");
Model::AssumeRoleRequest req;
req.setRoleArn("acs:ram::1940345800212929:root");
req.setRoleSessionName("test_session");
req.setDurationSeconds(1000);
StsClient client("key", "secret", configuration);
const AsyncCallerContext context;
StsClient::AssumeRoleAsyncHandler handler(assumerole_cb);
client.assumeRoleAsync(req, handler, std::make_shared<const AsyncCallerContext>(context));
ShutdownSdk();
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/stsclient_ut.cc
|
C++
|
apache-2.0
| 9,280
|
#include <iostream>
#include <stdio.h>
#include "gtest/gtest.h"
#include "alibabacloud/core/Utils.h"
#include "alibabacloud/core/Config.h"
#include "alibabacloud/core/AlibabaCloud.h"
#include "alibabacloud/core/CommonClient.h"
#include "alibabacloud/core/CommonResponse.h"
#include "alibabacloud/core/CommonRequest.h"
#include "alibabacloud/core/SimpleCredentialsProvider.h"
#include "alibabacloud/core/RoaServiceClient.h"
#include "alibabacloud/core/RpcServiceClient.h"
using namespace std;
using namespace AlibabaCloud;
const std::string unreachableDomain = "192.168.111.111";
const std::string timeoutErrorCode = "OperationTimeoutError";
const std::string defaultErrorMessage =
"Timeout (connectTimeout: 5000ms, readTimeout: 10000ms) when connect or read data: GET http://192.168.111.111/";
long kClientConnectTimeout = 12;
long kClientReadTimeout = 234;
const std::string clientErrorMessage =
"Timeout (connectTimeout: 12ms, readTimeout: 234ms) when connect or read data: GET http://192.168.111.111/";
long kRequestConnectTimeout = 33;
long kRequestReadTimeout = 724;
const std::string requestErrorMessage =
"Timeout (connectTimeout: 33ms, readTimeout: 724ms) when connect or read data: GET http://192.168.111.111/";
TEST(timeout, DefaultCommonClientROA) {
ClientConfiguration configuration("cn-hangzhou");
CommonClient client("key", "secret", configuration);
CommonRequest request(CommonRequest::RoaPattern);
request.setScheme("http");
request.setDomain(unreachableDomain);
auto out = client.commonResponse(request);
EXPECT_TRUE(out.error().errorCode() == timeoutErrorCode);
EXPECT_TRUE(out.error().errorMessage() == defaultErrorMessage);
}
TEST(timeout, DefaultCommonClientRPC) {
ClientConfiguration configuration("cn-hangzhou");
CommonClient client("key", "secret", configuration);
CommonRequest request(CommonRequest::RpcPattern);
request.setScheme("http");
request.setDomain(unreachableDomain);
auto out = client.commonResponse(request);
EXPECT_TRUE(out.error().errorCode() == timeoutErrorCode);
EXPECT_TRUE(out.error().errorMessage().find(defaultErrorMessage) == 0);
}
TEST(timeout, clientCommonClientROA) {
ClientConfiguration configuration("cn-hangzhou");
configuration.setConnectTimeout(kClientConnectTimeout);
configuration.setReadTimeout(kClientReadTimeout);
CommonClient client("key", "secret", configuration);
CommonRequest request(CommonRequest::RoaPattern);
request.setScheme("http");
request.setDomain(unreachableDomain);
auto out = client.commonResponse(request);
EXPECT_TRUE(out.error().errorCode() == timeoutErrorCode);
EXPECT_TRUE(out.error().errorMessage() == clientErrorMessage);
}
TEST(timeout, clientCommonClientRPC) {
ClientConfiguration configuration("cn-hangzhou");
configuration.setConnectTimeout(kClientConnectTimeout);
configuration.setReadTimeout(kClientReadTimeout);
CommonClient client("key", "secret", configuration);
CommonRequest request(CommonRequest::RpcPattern);
request.setScheme("http");
request.setDomain(unreachableDomain);
auto out = client.commonResponse(request);
EXPECT_TRUE(out.error().errorCode() == timeoutErrorCode);
EXPECT_TRUE(out.error().errorMessage().find(clientErrorMessage) == 0);
}
TEST(timeout, requestCommonClientROA) {
ClientConfiguration configuration("cn-hangzhou");
CommonClient client("key", "secret", configuration);
CommonRequest request(CommonRequest::RoaPattern);
request.setScheme("http");
request.setDomain(unreachableDomain);
request.setConnectTimeout(kRequestConnectTimeout);
request.setReadTimeout(kRequestReadTimeout);
auto out = client.commonResponse(request);
EXPECT_TRUE(out.error().errorCode() == timeoutErrorCode);
EXPECT_TRUE(out.error().errorMessage() == requestErrorMessage);
}
TEST(timeout, requestCommonClientRPC) {
ClientConfiguration configuration("cn-hangzhou");
CommonClient client("key", "secret", configuration);
CommonRequest request(CommonRequest::RpcPattern);
request.setScheme("http");
request.setDomain(unreachableDomain);
request.setConnectTimeout(kRequestConnectTimeout);
request.setReadTimeout(kRequestReadTimeout);
auto out = client.commonResponse(request);
EXPECT_TRUE(out.error().errorCode() == timeoutErrorCode);
EXPECT_TRUE(out.error().errorMessage().find(requestErrorMessage) == 0);
}
TEST(timeout, clientRequestCommonClientROA) {
ClientConfiguration configuration("cn-hangzhou");
configuration.setConnectTimeout(kClientConnectTimeout);
configuration.setReadTimeout(kClientReadTimeout);
CommonClient client("key", "secret", configuration);
CommonRequest request(CommonRequest::RoaPattern);
request.setScheme("http");
request.setDomain(unreachableDomain);
request.setConnectTimeout(kRequestConnectTimeout);
request.setReadTimeout(kRequestReadTimeout);
auto out = client.commonResponse(request);
EXPECT_TRUE(out.error().errorCode() == timeoutErrorCode);
EXPECT_TRUE(out.error().errorMessage() == requestErrorMessage);
}
TEST(timeout, clientRequestCommonClientRPC) {
ClientConfiguration configuration("cn-hangzhou");
configuration.setConnectTimeout(kClientConnectTimeout);
configuration.setReadTimeout(kClientReadTimeout);
CommonClient client("key", "secret", configuration);
CommonRequest request(CommonRequest::RpcPattern);
request.setConnectTimeout(kRequestConnectTimeout);
request.setReadTimeout(kRequestReadTimeout);
request.setScheme("http");
request.setDomain(unreachableDomain);
auto out = client.commonResponse(request);
EXPECT_TRUE(out.error().errorCode() == timeoutErrorCode);
EXPECT_TRUE(out.error().errorMessage().find(requestErrorMessage) == 0);
}
class TestRoaClient : public RoaServiceClient {
public:
TestRoaClient(const std::string & servicename, const std::shared_ptr<CredentialsProvider> &credentialsProvider,
const ClientConfiguration &configuration,
const std::shared_ptr<Signer> &signer = std::make_shared<HmacSha1Signer>()):
RoaServiceClient(servicename, credentialsProvider, configuration, signer)
{}
JsonOutcome makeRequest(const std::string &endpoint, const RoaServiceRequest &msg, HttpRequest::Method method = HttpRequest::Method::Get)const {
return RoaServiceClient::makeRequest(endpoint, msg, method);
}
};
TEST(timeout, roaClientDefault) {
ClientConfiguration configuration("cn-hangzhou");
const Credentials credentials("key", "secret");
TestRoaClient client("any-service", std::make_shared<SimpleCredentialsProvider>(credentials), configuration);
RoaServiceRequest request("product", "version");
request.setScheme("http");
auto out = client.makeRequest(unreachableDomain, request, HttpRequest::Method::Get);
EXPECT_TRUE(out.error().errorCode() == timeoutErrorCode);
EXPECT_TRUE(out.error().errorMessage().find(defaultErrorMessage) == 0);
}
TEST(timeout, roaClientclient) {
ClientConfiguration configuration("cn-hangzhou");
configuration.setConnectTimeout(kClientConnectTimeout);
configuration.setReadTimeout(kClientReadTimeout);
const Credentials credentials("key", "secret");
TestRoaClient client("any-service", std::make_shared<SimpleCredentialsProvider>(credentials), configuration);
RoaServiceRequest request("product", "version");
request.setScheme("http");
auto out = client.makeRequest(unreachableDomain, request, HttpRequest::Method::Get);
EXPECT_TRUE(out.error().errorCode() == timeoutErrorCode);
EXPECT_TRUE(out.error().errorMessage().find(clientErrorMessage) == 0);
}
TEST(timeout, roaClientrequest) {
ClientConfiguration configuration("cn-hangzhou");
const Credentials credentials("key", "secret");
TestRoaClient client("any-service", std::make_shared<SimpleCredentialsProvider>(credentials), configuration);
RoaServiceRequest request("product", "version");
request.setScheme("http");
request.setConnectTimeout(kRequestConnectTimeout);
request.setReadTimeout(kRequestReadTimeout);
auto out = client.makeRequest(unreachableDomain, request, HttpRequest::Method::Get);
EXPECT_TRUE(out.error().errorCode() == timeoutErrorCode);
EXPECT_TRUE(out.error().errorMessage().find(requestErrorMessage) == 0);
}
TEST(timeout, roaClientclientrequest) {
ClientConfiguration configuration("cn-hangzhou");
configuration.setConnectTimeout(kClientConnectTimeout);
configuration.setReadTimeout(kClientReadTimeout);
const Credentials credentials("key", "secret");
TestRoaClient client("any-service", std::make_shared<SimpleCredentialsProvider>(credentials), configuration);
RoaServiceRequest request("product", "version");
request.setScheme("http");
request.setConnectTimeout(kRequestConnectTimeout);
request.setReadTimeout(kRequestReadTimeout);
auto out = client.makeRequest(unreachableDomain, request, HttpRequest::Method::Get);
EXPECT_TRUE(out.error().errorCode() == timeoutErrorCode);
EXPECT_TRUE(out.error().errorMessage().find(requestErrorMessage) == 0);
}
class TestRpcClient : public RpcServiceClient {
public:
TestRpcClient(const std::string & servicename, const std::shared_ptr<CredentialsProvider> &credentialsProvider,
const ClientConfiguration &configuration,
const std::shared_ptr<Signer> &signer = std::make_shared<HmacSha1Signer>()):
RpcServiceClient(servicename, credentialsProvider, configuration, signer)
{}
JsonOutcome makeRequest(const std::string &endpoint, const RpcServiceRequest &msg, HttpRequest::Method method = HttpRequest::Method::Get)const {
return RpcServiceClient::makeRequest(endpoint, msg, method);
}
};
TEST(timeout, rpcClientDefault) {
ClientConfiguration configuration("cn-hangzhou");
const Credentials credentials("key", "secret");
TestRpcClient client("any-service", std::make_shared<SimpleCredentialsProvider>(credentials), configuration);
RpcServiceRequest request("product", "version", "aciton");
request.setScheme("http");
auto out = client.makeRequest(unreachableDomain, request, HttpRequest::Method::Get);
EXPECT_TRUE(out.error().errorCode() == timeoutErrorCode);
EXPECT_TRUE(out.error().errorMessage().find(defaultErrorMessage) == 0);
}
TEST(timeout, rpcClientclient) {
ClientConfiguration configuration("cn-hangzhou");
configuration.setConnectTimeout(kClientConnectTimeout);
configuration.setReadTimeout(kClientReadTimeout);
const Credentials credentials("key", "secret");
TestRpcClient client("any-service", std::make_shared<SimpleCredentialsProvider>(credentials), configuration);
RpcServiceRequest request("product", "version", "aciton");
request.setScheme("http");
auto out = client.makeRequest(unreachableDomain, request, HttpRequest::Method::Get);
EXPECT_TRUE(out.error().errorCode() == timeoutErrorCode);
EXPECT_TRUE(out.error().errorMessage().find(clientErrorMessage) == 0);
}
TEST(timeout, rpcClientrequest) {
ClientConfiguration configuration("cn-hangzhou");
const Credentials credentials("key", "secret");
TestRpcClient client("any-service", std::make_shared<SimpleCredentialsProvider>(credentials), configuration);
RpcServiceRequest request("product", "version", "aciton");
request.setScheme("http");
request.setConnectTimeout(kRequestConnectTimeout);
request.setReadTimeout(kRequestReadTimeout);
auto out = client.makeRequest(unreachableDomain, request, HttpRequest::Method::Get);
EXPECT_TRUE(out.error().errorCode() == timeoutErrorCode);
EXPECT_TRUE(out.error().errorMessage().find(requestErrorMessage) == 0);
}
TEST(timeout, rpcClientclientrequest) {
ClientConfiguration configuration("cn-hangzhou");
configuration.setConnectTimeout(kClientConnectTimeout);
configuration.setReadTimeout(kClientReadTimeout);
const Credentials credentials("key", "secret");
TestRpcClient client("any-service", std::make_shared<SimpleCredentialsProvider>(credentials), configuration);
RpcServiceRequest request("product", "version", "aciton");
request.setScheme("http");
request.setConnectTimeout(kRequestConnectTimeout);
request.setReadTimeout(kRequestReadTimeout);
auto out = client.makeRequest(unreachableDomain, request, HttpRequest::Method::Get);
EXPECT_TRUE(out.error().errorCode() == timeoutErrorCode);
EXPECT_TRUE(out.error().errorMessage().find(requestErrorMessage) == 0);
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/timeout_ut.cc
|
C++
|
apache-2.0
| 12,160
|
#include "gtest/gtest.h"
#include "alibabacloud/core/Url.h"
using namespace std;
using namespace AlibabaCloud;
namespace {
TEST(UrlTest, assign) {
const string src = "abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1";
Url url;
url.setScheme("abc");
url.setUserName("username");
url.setPassword("password");
url.setHost("example.com");
url.setPath("/path/data");
url.setPort(123);
url.setQuery("key=value&key2=value2");
url.setFragment("fragid1");
EXPECT_TRUE(url.toString() == src);
EXPECT_TRUE(url.scheme() == "abc");
EXPECT_TRUE(url.userName() == "username");
EXPECT_TRUE(url.password() == "password");
EXPECT_TRUE(url.host() == "example.com");
EXPECT_TRUE(url.path() == "/path/data");
EXPECT_TRUE(url.port() == 123);
EXPECT_TRUE(url.query() == "key=value&key2=value2");
EXPECT_TRUE(url.fragment() == "fragid1");
url.clear();
EXPECT_TRUE(url.toString() == "");
EXPECT_TRUE(url.scheme() == "");
EXPECT_TRUE(url.userName() == "");
EXPECT_TRUE(url.password() == "");
EXPECT_TRUE(url.host() == "");
EXPECT_TRUE(url.path() == "");
EXPECT_TRUE(url.port() == -1);
EXPECT_TRUE(url.query() == "");
EXPECT_TRUE(url.fragment() == "");
url.fromString(src);
EXPECT_TRUE(url.scheme() == "abc");
EXPECT_TRUE(url.userName() == "username");
EXPECT_TRUE(url.password() == "password");
EXPECT_TRUE(url.host() == "example.com");
EXPECT_TRUE(url.path() == "/path/data");
EXPECT_TRUE(url.port() == 123);
EXPECT_TRUE(url.query() == "key=value&key2=value2");
EXPECT_TRUE(url.fragment() == "fragid1");
Url newurl = url;
EXPECT_TRUE(newurl.scheme() == "abc");
EXPECT_TRUE(newurl.userName() == "username");
EXPECT_TRUE(newurl.password() == "password");
EXPECT_TRUE(newurl.host() == "example.com");
EXPECT_TRUE(newurl.path() == "/path/data");
EXPECT_TRUE(newurl.port() == 123);
EXPECT_TRUE(newurl.query() == "key=value&key2=value2");
EXPECT_TRUE(newurl.fragment() == "fragid1");
}
TEST(UrlTest, from_string) {
const string src = "http://oss.example.com";
Url url(src);
EXPECT_TRUE(url.scheme() == "http");
EXPECT_TRUE(url.userName() == "");
EXPECT_TRUE(url.password() == "");
EXPECT_TRUE(url.host() == "oss.example.com");
EXPECT_TRUE(url.path() == "/");
EXPECT_TRUE(url.port() == -1);
EXPECT_TRUE(url.query() == "");
EXPECT_TRUE(url.fragment() == "");
}
TEST(UrlTest, abnormal) {
const string src = "http://oss.example.com";
Url url(src);
Url newurl = url;
newurl.setPort(12345);
EXPECT_TRUE(url.isEmpty() == false);
EXPECT_TRUE(url.isValid());
EXPECT_TRUE(newurl != url);
EXPECT_TRUE(newurl.port() == 12345);
}
TEST(UrlTest, abnormal_2) {
const string src = "";
Url empty_url;
empty_url.fromString(src);
EXPECT_TRUE(empty_url.isEmpty());
Url url(src);
Url newurl = url;
EXPECT_TRUE(url == newurl);
newurl.setPort(12345);
EXPECT_TRUE(url.isEmpty() == true);
EXPECT_TRUE(url.isValid() == false);
EXPECT_TRUE(url.authority() == "");
EXPECT_TRUE(newurl != url);
EXPECT_TRUE(newurl.port() == 12345);
newurl.setAuthority("");
EXPECT_TRUE(newurl.host() == "");
EXPECT_TRUE(newurl.port() == -1);
EXPECT_TRUE(newurl.userInfo() == "");
newurl.setScheme("");
EXPECT_TRUE(newurl.scheme() == "");
newurl.setUserInfo("userinfo");
EXPECT_TRUE(newurl.userName() == "userinfo");
newurl.setUserInfo("user:password");
EXPECT_TRUE(newurl.userName() == "user");
EXPECT_TRUE(newurl.password() == "password");
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/url_ut.cc
|
C++
|
apache-2.0
| 3,684
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
class utUtils {
public:
void get_dir_exec(char* dir, char* exec) {
#ifdef _WIN32
char BufferFileName[MAX_PATH];
memset(BufferFileName,0,MAX_PATH);
if (GetModuleFileName(NULL, BufferFileName, MAX_PATH)) {
if (exec) {
snprintf(exec, strlen(BufferFileName), "%s", BufferFileName);
}
std::string ss(BufferFileName);
int idx = ss.find_last_of("\\");
BufferFileName[idx] = '\0';
snprintf(dir, strlen(BufferFileName), "%s", BufferFileName);
}
return;
#else
char* filename = nullptr;
if (readlink("/proc/self/exe", dir, 1024) < 0) {
dir[0] = '\0';
return;
}
filename = strrchr(dir, '/');
if (filename == nullptr) {
dir[0] = '\0';
return;
}
++filename;
if (exec) {
sprintf(exec, "%s", filename);
}
*filename = '\0';
return;
#endif
}
std::string get_env(const std::string env) {
#ifdef _WIN32
char* buf = nullptr;
size_t sz = 0;
if (_dupenv_s(&buf, &sz, env.c_str()) == 0 && buf != nullptr) {
std::string var(buf);
free(buf);
return var;
} else {
return std::string();
}
#else
char* value = getenv(env.c_str());
if (value == nullptr) {
return std::string();
}
return std::string(value);
#endif
}
};
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/utils.h
|
C++
|
apache-2.0
| 1,400
|
#include "gtest/gtest.h"
#include "alibabacloud/core/Utils.h"
#include <stdlib.h>
using namespace std;
using namespace AlibabaCloud;
namespace {
TEST(UtilsTest, ComputeContentMD5) {
const std::string src = "abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1";
const std::string md5 = ComputeContentMD5(src.c_str(), src.size());
EXPECT_TRUE(md5 == "WL7+fwrxHSlBTsfU9WCSbA==");
}
TEST(UtilsTest, GenerateUuid) {
const std::string uuid1 = GenerateUuid();
const std::string uuid2 = GenerateUuid();
EXPECT_TRUE(uuid1 != uuid2);
}
TEST(UtilsTest, HttpMethodToString){
std::string method = HttpMethodToString(HttpRequest::Method::Head);
EXPECT_TRUE(method == "HEAD");
method = HttpMethodToString(HttpRequest::Method::Post);
EXPECT_TRUE(method == "POST");
method = HttpMethodToString(HttpRequest::Method::Put);
EXPECT_TRUE(method == "PUT");
method = HttpMethodToString(HttpRequest::Method::Delete);
EXPECT_TRUE(method == "DELETE");
method = HttpMethodToString(HttpRequest::Method::Connect);
EXPECT_TRUE(method == "CONNECT");
method = HttpMethodToString(HttpRequest::Method::Options);
EXPECT_TRUE(method == "OPTIONS");
method = HttpMethodToString(HttpRequest::Method::Patch);
EXPECT_TRUE(method == "PATCH");
method = HttpMethodToString(HttpRequest::Method::Trace);
EXPECT_TRUE(method == "TRACE");
method = HttpMethodToString(HttpRequest::Method::Get);
EXPECT_TRUE(method == "GET");
}
TEST(UtilsTest, StringReplace) {
std::string src = "abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1";
StringReplace(src, "abc", "http");
EXPECT_TRUE(src == "http://username:password@example.com:123/path/data?key=value&key2=value2#fragid1");
StringReplace(src, "value", "VALUE");
EXPECT_TRUE(src == "http://username:password@example.com:123/path/data?key=VALUE&key2=VALUE2#fragid1");
}
TEST(UtilsTest, Encode) {
const std::string url = "http://username:password@example.com:123/path/data?key=value&key2=value2#fragid1";
const std::string encoded = "http%3A%2F%2Fusername%3Apassword%40example.com%3A123%2Fpath%2Fdata%3Fkey%3Dvalue%26key2%3Dvalue2%23fragid1";
const std::string enc = UrlEncode(url);
EXPECT_TRUE(enc == encoded);
}
TEST(UtilsTest, Decode) {
const std::string url = "http://username:password@example.com:123/path/data?key=value&key2=value2#fragid1";
const std::string encoded = "http%3A%2F%2Fusername%3Apassword%40example.com%3A123%2Fpath%2Fdata%3Fkey%3Dvalue%26key2%3Dvalue2%23fragid1";
const std::string decoded = UrlDecode(encoded);
EXPECT_TRUE(decoded == url);
}
TEST(UtilsTest, MapToJson){
std::map<std::string, std::string> maps;
maps.insert(std::make_pair("foo", "bar"));
std::string jsonStr = MapToJson(maps);
EXPECT_EQ(jsonStr, "{\"foo\":\"bar\"}");
}
TEST(UtilsTest, JsonToMap){
std::map<std::string, std::string> targetMaps;
targetMaps.insert(std::make_pair("foo", "bar"));
targetMaps.insert(std::make_pair("int", "1"));
targetMaps.insert(std::make_pair("array","foo,bar"));
std::string jsonStr = "{\"foo\":\"bar\",\"int\":1,\"array\":[\"foo\",\"bar\"]}";
std::map<std::string, std::string> maps = JsonToMap(jsonStr);
EXPECT_EQ(targetMaps, maps);
}
TEST(Utils, GetEnv) {
const std::string var1 = GetEnv("PATH");
EXPECT_FALSE(var1.empty());
const std::string var2 = GetEnv("NOT_EXISTS_PATH");
EXPECT_TRUE(var2.empty());
#ifndef _WIN32
setenv("SDK", "ttt", 1);
EXPECT_TRUE(GetEnv("SDK") == "ttt");
#endif
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/core/utils_ut.cc
|
C++
|
apache-2.0
| 3,628
|
cmake_minimum_required(VERSION 2.8.2)
set(CMAKE_CXX_STANDARD 11)
include(CTest)
if (CMAKE_VERSION VERSION_LESS 3.2)
set(UPDATE_DISCONNECTED_IF_AVAILABLE "")
else()
set(UPDATE_DISCONNECTED_IF_AVAILABLE "UPDATE_DISCONNECTED 1")
endif()
include(DownloadProject.cmake)
download_project(PROJ googletest
PREFIX CMAKE_SOURCE_DIR/test/googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG master
${UPDATE_DISCONNECTED_IF_AVAILABLE}
)
# Prevent GoogleTest from overriding our compiler/linker options
# when building with Visual Studio
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR})
# When using CMake 2.8.11 or later, header path dependencies
# are automatically added to the gtest and gmock targets.
# For earlier CMake versions, we have to explicitly add the
# required directories to the header search path ourselves.
if (CMAKE_VERSION VERSION_LESS 2.8.11)
include_directories("${gtest_SOURCE_DIR}/include"
"${gmock_SOURCE_DIR}/include")
endif()
include_directories("../../../core/include/")
link_directories(${CMAKE_SOURCE_DIR}/ft_build/lib)
add_executable(core_ft
locationclient_ft.cc
)
set_target_properties(core_ft
PROPERTIES
OUTPUT_NAME ${TARGET_OUTPUT_NAME_PREFIX}core_ft
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
target_link_libraries(core_ft core gtest gmock_main)
add_test(NAME core_ft COMMAND core_ft)
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/function_test/core/CMakeLists.txt
|
CMake
|
apache-2.0
| 1,570
|
# Distributed under the OSI-approved MIT License. See accompanying
# file LICENSE or https://github.com/Crascit/DownloadProject for details.
cmake_minimum_required(VERSION 2.8.2)
project(${DL_ARGS_PROJ}-download NONE)
include(ExternalProject)
ExternalProject_Add(${DL_ARGS_PROJ}-download
${DL_ARGS_UNPARSED_ARGUMENTS}
SOURCE_DIR "${DL_ARGS_SOURCE_DIR}"
BINARY_DIR "${DL_ARGS_BINARY_DIR}"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
)
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/function_test/core/DownloadProject.CMakeLists.cmake.in
|
CMake
|
apache-2.0
| 644
|
# Distributed under the OSI-approved MIT License. See accompanying
# file LICENSE or https://github.com/Crascit/DownloadProject for details.
#
# MODULE: DownloadProject
#
# PROVIDES:
# download_project( PROJ projectName
# [PREFIX prefixDir]
# [DOWNLOAD_DIR downloadDir]
# [SOURCE_DIR srcDir]
# [BINARY_DIR binDir]
# [QUIET]
# ...
# )
#
# Provides the ability to download and unpack a tarball, zip file, git repository,
# etc. at configure time (i.e. when the cmake command is run). How the downloaded
# and unpacked contents are used is up to the caller, but the motivating case is
# to download source code which can then be included directly in the build with
# add_subdirectory() after the call to download_project(). Source and build
# directories are set up with this in mind.
#
# The PROJ argument is required. The projectName value will be used to construct
# the following variables upon exit (obviously replace projectName with its actual
# value):
#
# projectName_SOURCE_DIR
# projectName_BINARY_DIR
#
# The SOURCE_DIR and BINARY_DIR arguments are optional and would not typically
# need to be provided. They can be specified if you want the downloaded source
# and build directories to be located in a specific place. The contents of
# projectName_SOURCE_DIR and projectName_BINARY_DIR will be populated with the
# locations used whether you provide SOURCE_DIR/BINARY_DIR or not.
#
# The DOWNLOAD_DIR argument does not normally need to be set. It controls the
# location of the temporary CMake build used to perform the download.
#
# The PREFIX argument can be provided to change the base location of the default
# values of DOWNLOAD_DIR, SOURCE_DIR and BINARY_DIR. If all of those three arguments
# are provided, then PREFIX will have no effect. The default value for PREFIX is
# CMAKE_BINARY_DIR.
#
# The QUIET option can be given if you do not want to show the output associated
# with downloading the specified project.
#
# In addition to the above, any other options are passed through unmodified to
# ExternalProject_Add() to perform the actual download, patch and update steps.
# The following ExternalProject_Add() options are explicitly prohibited (they
# are reserved for use by the download_project() command):
#
# CONFIGURE_COMMAND
# BUILD_COMMAND
# INSTALL_COMMAND
# TEST_COMMAND
#
# Only those ExternalProject_Add() arguments which relate to downloading, patching
# and updating of the project sources are intended to be used. Also note that at
# least one set of download-related arguments are required.
#
# If using CMake 3.2 or later, the UPDATE_DISCONNECTED option can be used to
# prevent a check at the remote end for changes every time CMake is run
# after the first successful download. See the documentation of the ExternalProject
# module for more information. It is likely you will want to use this option if it
# is available to you. Note, however, that the ExternalProject implementation contains
# bugs which result in incorrect handling of the UPDATE_DISCONNECTED option when
# using the URL download method or when specifying a SOURCE_DIR with no download
# method. Fixes for these have been created, the last of which is scheduled for
# inclusion in CMake 3.8.0. Details can be found here:
#
# https://gitlab.kitware.com/cmake/cmake/commit/bdca68388bd57f8302d3c1d83d691034b7ffa70c
# https://gitlab.kitware.com/cmake/cmake/issues/16428
#
# If you experience build errors related to the update step, consider avoiding
# the use of UPDATE_DISCONNECTED.
#
# EXAMPLE USAGE:
#
# include(DownloadProject)
# download_project(PROJ googletest
# GIT_REPOSITORY https://github.com/google/googletest.git
# GIT_TAG master
# UPDATE_DISCONNECTED 1
# QUIET
# )
#
# add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR})
#
#========================================================================================
set(_DownloadProjectDir "${CMAKE_CURRENT_LIST_DIR}")
include(CMakeParseArguments)
function(download_project)
set(options QUIET)
set(oneValueArgs
PROJ
PREFIX
DOWNLOAD_DIR
SOURCE_DIR
BINARY_DIR
# Prevent the following from being passed through
CONFIGURE_COMMAND
BUILD_COMMAND
INSTALL_COMMAND
TEST_COMMAND
)
set(multiValueArgs "")
cmake_parse_arguments(DL_ARGS "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
# Hide output if requested
if (DL_ARGS_QUIET)
set(OUTPUT_QUIET "OUTPUT_QUIET")
else()
unset(OUTPUT_QUIET)
message(STATUS "Downloading/updating ${DL_ARGS_PROJ}")
endif()
# Set up where we will put our temporary CMakeLists.txt file and also
# the base point below which the default source and binary dirs will be.
# The prefix must always be an absolute path.
if (NOT DL_ARGS_PREFIX)
set(DL_ARGS_PREFIX "${CMAKE_BINARY_DIR}")
else()
get_filename_component(DL_ARGS_PREFIX "${DL_ARGS_PREFIX}" ABSOLUTE
BASE_DIR "${CMAKE_CURRENT_BINARY_DIR}")
endif()
if (NOT DL_ARGS_DOWNLOAD_DIR)
set(DL_ARGS_DOWNLOAD_DIR "${DL_ARGS_PREFIX}/${DL_ARGS_PROJ}-download")
endif()
# Ensure the caller can know where to find the source and build directories
if (NOT DL_ARGS_SOURCE_DIR)
set(DL_ARGS_SOURCE_DIR "${DL_ARGS_PREFIX}/${DL_ARGS_PROJ}-src")
endif()
if (NOT DL_ARGS_BINARY_DIR)
set(DL_ARGS_BINARY_DIR "${DL_ARGS_PREFIX}/${DL_ARGS_PROJ}-build")
endif()
set(${DL_ARGS_PROJ}_SOURCE_DIR "${DL_ARGS_SOURCE_DIR}" PARENT_SCOPE)
set(${DL_ARGS_PROJ}_BINARY_DIR "${DL_ARGS_BINARY_DIR}" PARENT_SCOPE)
# The way that CLion manages multiple configurations, it causes a copy of
# the CMakeCache.txt to be copied across due to it not expecting there to
# be a project within a project. This causes the hard-coded paths in the
# cache to be copied and builds to fail. To mitigate this, we simply
# remove the cache if it exists before we configure the new project. It
# is safe to do so because it will be re-generated. Since this is only
# executed at the configure step, it should not cause additional builds or
# downloads.
file(REMOVE "${DL_ARGS_DOWNLOAD_DIR}/CMakeCache.txt")
# Create and build a separate CMake project to carry out the download.
# If we've already previously done these steps, they will not cause
# anything to be updated, so extra rebuilds of the project won't occur.
# Make sure to pass through CMAKE_MAKE_PROGRAM in case the main project
# has this set to something not findable on the PATH.
configure_file("${_DownloadProjectDir}/DownloadProject.CMakeLists.cmake.in"
"${DL_ARGS_DOWNLOAD_DIR}/CMakeLists.txt")
execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}"
-D "CMAKE_MAKE_PROGRAM:FILE=${CMAKE_MAKE_PROGRAM}"
.
RESULT_VARIABLE result
${OUTPUT_QUIET}
WORKING_DIRECTORY "${DL_ARGS_DOWNLOAD_DIR}"
)
if(result)
message(FATAL_ERROR "CMake step for ${DL_ARGS_PROJ} failed: ${result}")
endif()
execute_process(COMMAND ${CMAKE_COMMAND} --build .
RESULT_VARIABLE result
${OUTPUT_QUIET}
WORKING_DIRECTORY "${DL_ARGS_DOWNLOAD_DIR}"
)
if(result)
message(FATAL_ERROR "Build step for ${DL_ARGS_PROJ} failed: ${result}")
endif()
endfunction()
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/function_test/core/DownloadProject.cmake
|
CMake
|
apache-2.0
| 8,043
|
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include "../utils.h"
#include "gtest/gtest.h"
#include "alibabacloud/core/AlibabaCloud.h"
#include "alibabacloud/core/SimpleCredentialsProvider.h"
#include "alibabacloud/core/location/LocationClient.h"
using namespace std;
using namespace AlibabaCloud;
using namespace AlibabaCloud::Location;
namespace
{
utUtils utils;
const string key = utils.get_env("ENV_AccessKeyId");
const string secret = utils.get_env("ENV_AccessKeySecret");
TEST(LocationClient, basic)
{
ClientConfiguration configuration("cn-hangzhou");
Model::DescribeEndpointsRequest req;
req.setId("cn-hangzhou");
req.setServiceCode("ecs");
req.setType("openAPI");
LocationClient client(key, secret, configuration);
LocationClient::DescribeEndpointsOutcome out = client.describeEndpoints(req);
EXPECT_TRUE(out.error().errorCode() == "");
EXPECT_TRUE(out.result().endpoints().size() == 1);
Model::DescribeEndpointsResult::Endpoint ep = out.result().endpoints()[0];
EXPECT_TRUE(ep.endpoint == "ecs-cn-hangzhou.aliyuncs.com");
EXPECT_TRUE(ep.id == "cn-hangzhou");
EXPECT_TRUE(ep.namespace_ == "26842" || ep.namespace_.empty());
EXPECT_TRUE(ep.type == "openAPI");
EXPECT_TRUE(ep.protocols.size() == 2);
std::vector<std::string>::iterator it;
std::vector<std::string> protocols = ep.protocols;
it = std::find(protocols.begin(), protocols.end(), string("HTTP"));
EXPECT_TRUE(it != protocols.end());
it = std::find(protocols.begin(), protocols.end(), string("HTTPS"));
EXPECT_TRUE(it != protocols.end());
EXPECT_TRUE(out.result().success());
const string req_id = "205302F3-6E1A-4D6F-82C5-2F165FB94038";
EXPECT_TRUE(out.result().requestId().length() == req_id.length());
}
TEST(LocationClient, credentials)
{
Credentials credentials(key, secret);
ClientConfiguration configuration("cn-hangzhou");
Model::DescribeEndpointsRequest req;
req.setId("cn-hangzhou");
req.setServiceCode("ecs");
req.setType("openAPI");
req.setMethod(HttpRequest::Post);
LocationClient client(credentials, configuration);
LocationClient::DescribeEndpointsOutcome out = client.describeEndpoints(req);
EXPECT_TRUE(out.error().errorCode() == "");
EXPECT_TRUE(out.result().endpoints().size() == 1);
Model::DescribeEndpointsResult::Endpoint ep = out.result().endpoints()[0];
EXPECT_TRUE(ep.endpoint == "ecs-cn-hangzhou.aliyuncs.com");
EXPECT_TRUE(ep.id == "cn-hangzhou");
EXPECT_TRUE(ep.namespace_ == "26842" || ep.namespace_.empty());
EXPECT_TRUE(ep.type == "openAPI");
EXPECT_TRUE(ep.protocols.size() == 2);
std::vector<std::string>::iterator it;
std::vector<std::string> protocols = ep.protocols;
it = std::find(protocols.begin(), protocols.end(), string("HTTP"));
EXPECT_TRUE(it != protocols.end());
it = std::find(protocols.begin(), protocols.end(), string("HTTPS"));
EXPECT_TRUE(it != protocols.end());
EXPECT_TRUE(out.result().success());
const string req_id = "205302F3-6E1A-4D6F-82C5-2F165FB94038";
EXPECT_TRUE(out.result().requestId().length() == req_id.length());
}
TEST(LocationClient, credentials_another)
{
Credentials credentials(key, secret);
ClientConfiguration configuration("cn-hangzhou");
configuration.setConnectTimeout(300000);
configuration.setReadTimeout(300000);
Model::DescribeEndpointsRequest req;
req.setId("cn-hangzhou");
req.setServiceCode("ecs");
req.setType("openAPI");
LocationClient client(std::make_shared<SimpleCredentialsProvider>(credentials), configuration);
LocationClient::DescribeEndpointsOutcome out = client.describeEndpoints(req);
EXPECT_EQ(out.error().errorCode(), "");
EXPECT_EQ(out.result().endpoints().size(), 1);
Model::DescribeEndpointsResult::Endpoint ep = out.result().endpoints()[0];
EXPECT_TRUE(ep.endpoint == "ecs-cn-hangzhou.aliyuncs.com");
EXPECT_TRUE(ep.id == "cn-hangzhou");
EXPECT_TRUE(ep.namespace_ == "26842" || ep.namespace_.empty());
EXPECT_TRUE(ep.type == "openAPI");
EXPECT_TRUE(ep.protocols.size() == 2);
std::vector<std::string>::iterator it;
std::vector<std::string> protocols = ep.protocols;
it = std::find(protocols.begin(), protocols.end(), string("HTTP"));
EXPECT_TRUE(it != protocols.end());
it = std::find(protocols.begin(), protocols.end(), string("HTTPS"));
EXPECT_TRUE(it != protocols.end());
EXPECT_TRUE(out.result().success());
const string req_id = "205302F3-6E1A-4D6F-82C5-2F165FB94038";
EXPECT_TRUE(out.result().requestId().length() == req_id.length());
}
TEST(LocationClient, callable)
{
InitializeSdk();
ClientConfiguration configuration("cn-hangzhou");
configuration.setConnectTimeout(300000);
configuration.setReadTimeout(300000);
Model::DescribeEndpointsRequest req;
req.setId("cn-hangzhou");
req.setServiceCode("ecs");
req.setType("openAPI");
LocationClient client(key, secret, configuration);
LocationClient::DescribeEndpointsOutcomeCallable cb = client.describeEndpointsCallable(req);
LocationClient::DescribeEndpointsOutcome out = cb.get();
EXPECT_EQ("", out.error().errorCode());
EXPECT_EQ(1, out.result().endpoints().size());
Model::DescribeEndpointsResult::Endpoint ep = out.result().endpoints()[0];
EXPECT_TRUE(ep.endpoint == "ecs-cn-hangzhou.aliyuncs.com");
EXPECT_TRUE(ep.id == "cn-hangzhou");
EXPECT_TRUE(ep.namespace_ == "26842" || ep.namespace_.empty());
EXPECT_TRUE(ep.type == "openAPI");
EXPECT_TRUE(ep.protocols.size() == 2);
std::vector<std::string>::iterator it;
std::vector<std::string> protocols = ep.protocols;
it = std::find(protocols.begin(), protocols.end(), string("HTTP"));
EXPECT_TRUE(it != protocols.end());
it = std::find(protocols.begin(), protocols.end(), string("HTTPS"));
EXPECT_TRUE(it != protocols.end());
EXPECT_TRUE(out.result().success());
const string req_id = "205302F3-6E1A-4D6F-82C5-2F165FB94038";
EXPECT_TRUE(out.result().requestId().length() == req_id.length());
ShutdownSdk();
}
void cb(const LocationClient *client,
const Model::DescribeEndpointsRequest &req,
const LocationClient::DescribeEndpointsOutcome &out,
const std::shared_ptr<const AsyncCallerContext> &contex)
{
EXPECT_EQ(out.error().errorCode(), "");
EXPECT_EQ(out.result().endpoints().size(), 1);
Model::DescribeEndpointsResult::Endpoint ep = out.result().endpoints()[0];
EXPECT_TRUE(ep.endpoint == "ecs-cn-hangzhou.aliyuncs.com");
EXPECT_TRUE(ep.id == "cn-hangzhou");
EXPECT_TRUE(ep.namespace_ == "26842" || ep.namespace_.empty());
EXPECT_TRUE(ep.type == "openAPI");
EXPECT_TRUE(ep.protocols.size() == 2);
std::vector<std::string>::iterator it;
std::vector<std::string> protocols = ep.protocols;
it = std::find(protocols.begin(), protocols.end(), string("HTTP"));
EXPECT_TRUE(it != protocols.end());
it = std::find(protocols.begin(), protocols.end(), string("HTTPS"));
EXPECT_TRUE(it != protocols.end());
EXPECT_TRUE(out.result().success());
const string req_id = "205302F3-6E1A-4D6F-82C5-2F165FB94038";
EXPECT_TRUE(out.result().requestId().length() == req_id.length());
}
TEST(LocationClient, async)
{
InitializeSdk();
ClientConfiguration configuration("cn-hangzhou");
Model::DescribeEndpointsRequest req;
req.setId("cn-hangzhou");
req.setServiceCode("ecs");
req.setType("openAPI");
LocationClient client(key, secret, configuration);
LocationClient::DescribeEndpointsOutcome out;
const AsyncCallerContext context;
LocationClient::DescribeEndpointsAsyncHandler handler(cb);
client.describeEndpointsAsync(req, handler, std::make_shared<const AsyncCallerContext>(context));
ShutdownSdk();
}
} // namespace
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/function_test/core/locationclient_ft.cc
|
C++
|
apache-2.0
| 7,622
|
cmake_minimum_required(VERSION 3.0)
project(demo)
set(CMAKE_CXX_STANDARD 11)
if(CMAKE_HOST_WIN32)
include_directories("C:\\Program Files (x86)\\alibabacloud-sdk\\include")
link_directories("C:\\Program Files (x86)\\alibabacloud-sdk\\lib")
endif()
# note ft_build is the dir you build sdk
include_directories("../../../core/include/")
link_directories(${CMAKE_SOURCE_DIR}/ft_build/lib)
add_executable(nlp_ft nlp_wordsegment_ft.cc)
target_link_libraries(nlp_ft alibabacloud-sdk-core)
target_link_libraries(nlp_ft core gtest gmock_main)
set_target_properties(nlp_ft
PROPERTIES
OUTPUT_NAME ${TARGET_OUTPUT_NAME_PREFIX}nlp_ft
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
add_test(NAME nlp_ft COMMAND nlp_ft)
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/function_test/nlp/CMakeLists.txt
|
CMake
|
apache-2.0
| 729
|
#include <iostream>
#include <cstdlib>
#include <cstring>
#include "gtest/gtest.h"
#include "../utils.h"
#include "alibabacloud/core/AlibabaCloud.h"
#include "alibabacloud/core/CommonClient.h"
#include "alibabacloud/core/HttpRequest.h"
using namespace std;
using namespace AlibabaCloud;
namespace {
TEST(nlp, wordsegment) {
utUtils utils;
string key = utils.get_env("ENV_AccessKeyId");
string secret = utils.get_env("ENV_AccessKeySecret");
AlibabaCloud::InitializeSdk();
ClientConfiguration configuration("cn-shanghai");
CommonClient client(key, secret, configuration);
// create request and assign parameters
CommonRequest request(CommonRequest::RoaPattern);
request.setScheme("http");
request.setDomain("nlp.cn-shanghai.aliyuncs.com");
request.setResourcePath("/nlp/api/wordsegment/general");
request.setHttpMethod(HttpRequest::Post);
const char * data = "{\"lang\":\"ZH\",\"text\":\"Iphone is a good choice 专用数据线\"}";
request.setContent(data, strlen(data));
request.setHeaderParameter("Content-Type", "application/json;chrset=utf-8");
request.setVersion("2018-04-08");
auto outcome = client.commonResponse(request);
EXPECT_TRUE(outcome.error().errorCode().empty());
const std::string expected = "{\"data\":[{\"id\":0,\"word\":\"Iphone\"},{\"id\":1,\"word\":\" \"},{\"id\":2,\"word\":\"is\"},{\"id\":3,\"word\":\" \"},{\"id\":4,\"word\":\"a\"},{\"id\":5,\"word\":\" \"},{\"id\":6,\"word\":\"good\"},{\"id\":7,\"word\":\" \"},{\"id\":8,\"word\":\"choice\"},{\"id\":9,\"word\":\" \"},{\"id\":10,\"word\":\"专用\"},{\"id\":11,\"word\":\"数据线\"}]}";
EXPECT_TRUE(outcome.result().payload() == expected);
AlibabaCloud::ShutdownSdk();
}
TEST(nlp, wordsegment_error) {
utUtils utils;
string key = utils.get_env("ENV_AccessKeyId");
string secret = utils.get_env("ENV_AccessKeySecret");
AlibabaCloud::InitializeSdk();
ClientConfiguration configuration("cn-shanghai");
CommonClient client(key, secret, configuration);
// create request and assign parameters
CommonRequest request(CommonRequest::RoaPattern);
request.setScheme("http");
request.setDomain("nlp.cn-shanghai.aliyuncs.com");
request.setResourcePath("/nlp/api/wordsegment/general");
request.setHttpMethod(HttpRequest::Post);
const char * data = "invlaid text";
request.setContent(data, strlen(data));
request.setHeaderParameter("Content-Type", "application/json;chrset=utf-8");
request.setVersion("2018-04-08");
auto outcome = client.commonResponse(request);
const string error = "{\"errorCode\":10007,\"errorMsg\":\"body json format invalid\"}";
EXPECT_TRUE(outcome.error().detail() == error);
AlibabaCloud::ShutdownSdk();
}
TEST(nlp, wordsegmentClientTimeout) {
utUtils utils;
string key = utils.get_env("ENV_AccessKeyId");
string secret = utils.get_env("ENV_AccessKeySecret");
AlibabaCloud::InitializeSdk();
ClientConfiguration configuration("cn-shanghai");
configuration.setConnectTimeout(1);
configuration.setReadTimeout(123);
CommonClient client(key, secret, configuration);
// create request and assign parameters
CommonRequest request(CommonRequest::RoaPattern);
request.setScheme("http");
request.setDomain("nlp.cn-shanghai.aliyuncs.com");
request.setResourcePath("/nlp/api/wordsegment/general");
request.setHttpMethod(HttpRequest::Post);
const char * data = "{\"lang\":\"ZH\",\"text\":\"Iphone is a good choice 专用数据线\"}";
request.setContent(data, strlen(data));
request.setHeaderParameter("Content-Type", "application/json;chrset=utf-8");
request.setVersion("2018-04-08");
auto outcome = client.commonResponse(request);
EXPECT_TRUE(outcome.error().errorCode() == "OperationTimeoutError");
EXPECT_TRUE(outcome.error().errorMessage().find("Timeout (connectTimeout: 1ms, readTimeout: 123ms) when connect or read") == 0);
AlibabaCloud::ShutdownSdk();
}
TEST(nlp, wordsegmentRequestTimeout) {
utUtils utils;
string key = utils.get_env("ENV_AccessKeyId");
string secret = utils.get_env("ENV_AccessKeySecret");
AlibabaCloud::InitializeSdk();
ClientConfiguration configuration("cn-shanghai");
CommonClient client(key, secret, configuration);
// create request and assign parameters
CommonRequest request(CommonRequest::RoaPattern);
request.setScheme("http");
request.setDomain("nlp.cn-shanghai.aliyuncs.com");
request.setConnectTimeout(11);
request.setReadTimeout(213);
request.setResourcePath("/nlp/api/wordsegment/general");
request.setHttpMethod(HttpRequest::Post);
const char * data = "{\"lang\":\"ZH\",\"text\":\"Iphone is a good choice 专用数据线\"}";
request.setContent(data, strlen(data));
request.setHeaderParameter("Content-Type", "application/json;chrset=utf-8");
request.setVersion("2018-04-08");
auto outcome = client.commonResponse(request);
EXPECT_TRUE(outcome.error().errorCode() == "OperationTimeoutError");
EXPECT_TRUE(outcome.error().errorMessage().find("Timeout (connectTimeout: 11ms, readTimeout: 213ms) when connect or read") == 0);
AlibabaCloud::ShutdownSdk();
}
TEST(nlp, wordsegmentClientRequestTimeout) {
utUtils utils;
string key = utils.get_env("ENV_AccessKeyId");
string secret = utils.get_env("ENV_AccessKeySecret");
AlibabaCloud::InitializeSdk();
ClientConfiguration configuration("cn-shanghai");
configuration.setConnectTimeout(1);
configuration.setReadTimeout(123);
CommonClient client(key, secret, configuration);
// create request and assign parameters
CommonRequest request(CommonRequest::RoaPattern);
request.setScheme("http");
request.setDomain("nlp.cn-shanghai.aliyuncs.com");
request.setConnectTimeout(11);
request.setReadTimeout(213);
request.setResourcePath("/nlp/api/wordsegment/general");
request.setHttpMethod(HttpRequest::Post);
const char * data = "{\"lang\":\"ZH\",\"text\":\"Iphone is a good choice 专用数据线\"}";
request.setContent(data, strlen(data));
request.setHeaderParameter("Content-Type", "application/json;chrset=utf-8");
request.setVersion("2018-04-08");
auto outcome = client.commonResponse(request);
EXPECT_TRUE(outcome.error().errorCode() == "OperationTimeoutError");
EXPECT_TRUE(outcome.error().errorMessage().find("Timeout (connectTimeout: 11ms, readTimeout: 213ms) when connect or read") == 0);
AlibabaCloud::ShutdownSdk();
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/function_test/nlp/nlp_wordsegment_ft.cc
|
C++
|
apache-2.0
| 6,557
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
class utUtils {
public:
void get_dir_exec(char *dir, char *exec) {
#ifdef _WIN32
char BufferFileName[MAX_PATH];
memset(BufferFileName, 0, MAX_PATH);
if (GetModuleFileName(NULL, BufferFileName, MAX_PATH)) {
if (exec) {
snprintf(exec, strlen(BufferFileName), "%s", BufferFileName);
}
std::string ss(BufferFileName);
int idx = ss.find_last_of("\\");
BufferFileName[idx] = '\0';
snprintf(dir, strlen(BufferFileName), "%s", BufferFileName);
}
return;
#else
char *filename = nullptr;
if (readlink("/proc/self/exe", dir, 1024) < 0) {
dir[0] = '\0';
return;
}
filename = strrchr(dir, '/');
if (filename == nullptr) {
dir[0] = '\0';
return;
}
++filename;
if (exec) {
sprintf(exec, "%s", filename);
}
*filename = '\0';
return;
#endif
}
std::string get_env(const std::string env) {
#ifdef _WIN32
char *buf = nullptr;
size_t sz = 0;
if (_dupenv_s(&buf, &sz, env.c_str()) == 0 && buf != nullptr) {
std::string var(buf);
free(buf);
return var;
} else {
return std::string();
}
#else
char *value = getenv(env.c_str());
if (value == nullptr) {
return std::string();
}
return std::string(value);
#endif
}
};
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/function_test/utils.h
|
C++
|
apache-2.0
| 1,436
|
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.listen(8021);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.text({ type: 'text/html' }))
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
app.use(bodyParser.json({ type: 'application/*+json' }))
app.get('*', function (req, res) {
console.log('GET req.params: ', req.params);
console.log('GET req.query: ', req.query);
if (req.params[0] === '/readTimeoutTest') {
setTimeout(function() {
res.send("something");
}, Number(req.query.timeout) + 100);
} else {
res.send(JSON.stringify(req.query));
}
});
app.post('*', function (req, res) {
console.log('POST req.params: ', req.params);
console.log('POST req.query: ', req.query);
console.log('POST req.body:', req.body);
res.send('POST: ' + req.body);
});
app.put('*', function (req, res) {
console.log('PUT req.params: ', req.params);
console.log('PUT req.query: ', req.query);
console.log('PUT req.body: ', req.body);
res.send('PUT: ' + req.body);
});
app.delete('*', function(req, res) {
console.log('DELETE req.params: ', req.params);
console.log('DELETE req.query: ', req.query);
console.log('DELETE req.body: ', req.body);
res.send("DELETE: " + req.body);
});
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/test/httpserver/http_test_server.js
|
JavaScript
|
apache-2.0
| 1,339
|
#!/bin/bash
cd `dirname $0`
echo '-------build unit test----------'
echo 'start a test http server'
NODE=`which nodejs`
if [ "$NODE" ]
then
echo ''
else
NODE=`which node`
fi
echo 'node binary path: ' $NODE
server=`ps -ef | grep http_test_server | grep -v grep`
echo "check server: " $server
if [ "$server" ]
then
echo "server is on"
else
echo "server is off, start it"
cd test/httpserver
npm i
nohup $NODE http_test_server.js &
cd -
fi
MAKE=make
if command -v python > /dev/null ; then
MAKE="make -j $(python -c 'import multiprocessing as mp; print(int(mp.cpu_count()))')"
fi
echo $MAKE
UT_BUILD_DIR=ut_build
rm -rf $UT_BUILD_DIR
mkdir $UT_BUILD_DIR
cd $UT_BUILD_DIR
cmake -DBUILD_FUNCTION_TESTS=OFF -DBUILD_UNIT_TESTS=ON -DENABLE_COVERAGE=ON ..
$MAKE core_ut
echo '------- run unit test -----------'
ctest --verbose
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/aliyun-openapi/unit_test.sh
|
Shell
|
apache-2.0
| 843
|
/*
* Copyright (C) 2021-2023 Alibaba Group Holding Limited
*/
#include <iostream>
#include <string.h>
#include "alibabacloud/core/AlibabaCloud.h"
#include "alibabacloud/core/CommonClient.h"
#include "model/common.h"
extern "C" {
using namespace std;
using namespace AlibabaCloud;
/*recognizing identity card has issue to be resolved*/
char *chatbot(char *pInstanceId, char *pSessionId, char *text)
{
InitializeSdk();
string key = getAccessKey();
string secret = getAccessSecret();
string instanceId = pInstanceId;
string utterance = text;
ClientConfiguration configuration;
configuration.setRegionId(CLOUD_AI_REGION_ID);
configuration.setEndpoint(CLOUD_AI_CHATBOT_ENDPOINT);
CommonClient client(key, secret, configuration);
CommonRequest request(CommonRequest::RpcPattern);
char *response = NULL;
request.setScheme("http");
request.setDomain(CLOUD_AI_CHATBOT_ENDPOINT);
request.setHttpMethod(HttpRequest::Get);
request.setQueryParameter("Action", "Chat");
request.setVersion("2017-10-11");
request.setQueryParameter("InstanceId", instanceId);
request.setQueryParameter("Utterance", utterance);
request.setQueryParameter("AccessKeyId", key);
if (pSessionId) {
string sessionId = pSessionId;
request.setQueryParameter("SessionId", sessionId);
}
auto outcome = client.commonResponse(request);
if (!outcome.isSuccess()) {
cout << "error code: " << outcome.error().errorCode() << endl;
cout << "error message: " << outcome.error().errorMessage() << endl;
cout << "error host: " << outcome.error().host() << endl;
cout << "error requestId: " << outcome.error().requestId() << endl;
cout << "error detail: " << outcome.error().detail() << endl;
ShutdownSdk();
return NULL;
}
cout << endl << "add item returns: " << outcome.result().payload() << endl << endl;
response = strdup(outcome.result().payload().c_str());
ShutdownSdk();
return response;
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/chatbot.cc
|
C++
|
apache-2.0
| 2,050
|
#include <iostream>
#include "alibabacloud/core/AlibabaCloud.h"
#include "alibabacloud/core/CommonClient.h"
#include "alibabacloud/core/Utils.h"
#include "ucloud_ai_common.h"
#include <ulog/ulog.h>
extern "C" {
using namespace std;
using namespace AlibabaCloud;
static string accessKey;
static string accessSecret;
#define USE_HTTPCLIENT
#define TAG "common"
#ifdef USE_HTTPCLIENT
int getResponseBodyByUrl(const char *url, const char **buffer)
{
int ret;
int recv_len;
ret = ucloud_ai_connect((char *)url);
if (ret < 0) {
LOGE(TAG, "ucloud_ai_connect failed, ret: %d\n", ret);
return -1;
}
recv_len = ucloud_ai_get_stream((char *)url, (char **)buffer);
ucloud_ai_disconnect();
if (!recv_len) {
LOGE(TAG, "recv_len is %d\n", recv_len);
return -1;
}
return recv_len;
}
#else
int getResponseBodyByUrl(const char *url, const char **buffer)
{
CurlHttpClient client;
HttpRequest request;
Url tmpUrl;
tmpUrl.setHost(url);
tmpUrl.setScheme("http");
request.setMethod(HttpRequest::Method::Get);
request.setUrl(tmpUrl);
request.setHeader("Accept", "*/*");
HttpClient::HttpResponseOutcome out = client.makeRequest(request);
*buffer = out.result().body();
return out.result().bodySize();
}
#endif
void setAccesskeyAndSecret(char *key, char *secret)
{
accessKey = key;
accessSecret = secret;
}
const char *getAccessKey(void)
{
return accessKey.c_str();
}
const char *getAccessSecret(void)
{
return accessSecret.c_str();
}
char *getTokenId(const char *domain, const char *regionId)
{
InitializeSdk();
string key = getAccessKey();
string secret = getAccessSecret();
string regionIdStr = regionId;
string domainStr = domain;
ClientConfiguration configuration;
configuration.setRegionId(regionIdStr);
configuration.setEndpoint(domainStr);
CommonClient client(key, secret, configuration);
CommonRequest request(CommonRequest::RpcPattern);
char *response = NULL;
request.setScheme("http");
request.setDomain(domainStr);
request.setHttpMethod(HttpRequest::Post);
request.setQueryParameter("Action", "CreateToken");
request.setVersion("2019-02-28");
auto outcome = client.commonResponse(request);
if (!outcome.isSuccess()) {
cout << "error code: " << outcome.error().errorCode() << endl;
cout << "error message: " << outcome.error().errorMessage() << endl;
cout << "error host: " << outcome.error().host() << endl;
cout << "error requestId: " << outcome.error().requestId() << endl;
cout << "error detail: " << outcome.error().detail() << endl;
ShutdownSdk();
return NULL;
}
cout << endl << "add item returns: " << outcome.result().payload() << endl << endl;
response = strdup(outcome.result().payload().c_str());
ShutdownSdk();
return response;
}
char *computeContentMD5(const char *data, size_t size)
{
return (char *)ComputeContentMD5(data, size).c_str();
}
char *generateUuid()
{
return (char *)GenerateUuid().c_str();
}
char *urlEncode(const char *src)
{
return (char *)UrlEncode(src).c_str();
}
char *urlDecode(const char *src)
{
return (char *)UrlDecode(src).c_str();
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/common.cc
|
C++
|
apache-2.0
| 3,289
|
#include <iostream>
#include "alibabacloud/core/AlibabaCloud.h"
#include "alibabacloud/facebody/FacebodyClient.h"
#include "alibabacloud/core/CommonClient.h"
#include "model/common.h"
extern "C" {
using namespace std;
using namespace AlibabaCloud;
using namespace AlibabaCloud::Facebody;
int compareFace(char *urlA, char *urlB, AIModelCBFunc cb)
{
InitializeSdk();
string key = getAccessKey();
string secret = getAccessSecret();
ClientConfiguration configuration;
configuration.setRegionId(CLOUD_AI_REGION_ID);
configuration.setEndpoint(CLOUD_AI_FACEBODY_ENDPOINT);
FacebodyClient client(key, secret, configuration);
Model::CompareFaceRequest request;
string tmpImageURLA, tmpImageURLB;
FacebodyResultStruct result;
float confidence;
int ret = 0;
tmpImageURLA = urlA;
tmpImageURLB = urlB;
request.setScheme("http");
request.setMethod(HttpRequest::Method::Post);
request.setImageURLA(tmpImageURLA);
request.setImageURLB(tmpImageURLB);
auto outcome = client.compareFace(request);
// cout << endl << "facebody describeInstances returned:" << endl;
// cout << "error code: " << outcome.error().errorCode() << endl;
// cout << "requestId: " << outcome.result().requestId() << endl << endl;
// cout << "confidence:" << outcome.result().getData().confidence << endl;
// cout << "x:" << outcome.result().getData().rectAList[0] << endl;
// cout << "y:" << outcome.result().getData().rectAList[1] << endl;
// cout << "w:" << outcome.result().getData().rectAList[2] << endl;
// cout << "h:" << outcome.result().getData().rectAList[3] << endl;
if (cb && outcome.error().errorCode().empty()) {
result.face.confidence = outcome.result().getData().confidence;
result.face.location.x = outcome.result().getData().rectAList[0];
result.face.location.y = outcome.result().getData().rectAList[1];
result.face.location.w = outcome.result().getData().rectAList[2];
result.face.location.h = outcome.result().getData().rectAList[3];
ret = cb((void *)&result);
} else {
cout << "error code: " << outcome.error().errorCode() << endl;
}
ShutdownSdk();
return ret;
}
int recognizeExpression(char *url, AIModelCBFunc cb)
{
InitializeSdk();
string key = getAccessKey();
string secret = getAccessSecret();
ClientConfiguration configuration;
configuration.setRegionId(CLOUD_AI_REGION_ID);
configuration.setEndpoint(CLOUD_AI_FACEBODY_ENDPOINT);
FacebodyClient client(key, secret, configuration);
Model::RecognizeExpressionRequest request;
string tmpImageURL;
string expression;
float faceProbability;
FacebodyResultStruct result;
int ret = 0;
tmpImageURL = url;
request.setScheme("http");
request.setMethod(HttpRequest::Method::Post);
request.setImageURL(tmpImageURL);
auto outcome = client.recognizeExpression(request);
cout << endl << "facebody describeInstances returned:" << endl;
cout << "error code: " << outcome.error().errorCode() << endl;
cout << "requestId: " << outcome.result().requestId() << endl << endl;
cout << "expression:" << outcome.result().getData().elements[0].expression << endl;
cout << "face probablility:" << outcome.result().getData().elements[0].faceProbability << endl;
cout << "x:" << outcome.result().getData().elements[0].faceRectangle.left << endl;
cout << "y:" << outcome.result().getData().elements[0].faceRectangle.top << endl;
cout << "w:" << outcome.result().getData().elements[0].faceRectangle.width << endl;
cout << "h:" << outcome.result().getData().elements[0].faceRectangle.height << endl;
if (cb) {
expression = outcome.result().getData().elements[0].expression;
if (!expression.empty()) {
result.expression.expression = (char *)expression.c_str();
cout << "expression:" << outcome.result().getData().elements[0].expression << endl;
result.expression.probability = outcome.result().getData().elements[0].faceProbability;
result.expression.location.x = 20; // outcome.result().getData().elements[0].faceRectangle.left;
result.expression.location.y = 20; // outcome.result().getData().elements[0].faceRectangle.top;
result.expression.location.w = outcome.result().getData().elements[0].faceRectangle.width;
result.expression.location.h = outcome.result().getData().elements[0].faceRectangle.height;
ret = cb((void *)&result);
}
}
ShutdownSdk();
return ret;
}
int generateHumanAnimeStyle(char *url, AIModelCBFunc cb)
{
InitializeSdk();
string key = getAccessKey();
string secret = getAccessSecret();
ClientConfiguration configuration;
configuration.setRegionId(CLOUD_AI_REGION_ID);
configuration.setEndpoint(CLOUD_AI_FACEBODY_ENDPOINT);
FacebodyClient client(key, secret, configuration);
Model::GenerateHumanAnimeStyleRequest request;
string tmpImageURL;
FacebodyResultStruct result;
string outImageUrl;
int len;
int ret = 0;
tmpImageURL = url;
request.setScheme("http");
request.setMethod(HttpRequest::Method::Post);
request.setImageURL(tmpImageURL);
auto outcome = client.generateHumanAnimeStyle(request);
cout << endl << "facebody describeInstances returned:" << endl;
cout << "error code: " << outcome.error().errorCode() << endl;
cout << "requestId: " << outcome.result().requestId() << endl << endl;
cout << "image url:" << outcome.result().getData().imageURL << endl;
outImageUrl = outcome.result().getData().imageURL;
if (outImageUrl.size() > 0) {
result.anime.url = (char *)outImageUrl.c_str();
result.anime.imageLen = getResponseBodyByUrl(result.anime.url, &result.anime.image);
}
if (result.anime.image && cb) {
ret = cb((void *)&result);
}
ShutdownSdk();
return ret;
}
int detectPedestrian(char *url, AIModelCBFunc cb)
{
InitializeSdk();
string key = getAccessKey();
string secret = getAccessSecret();
ClientConfiguration configuration;
configuration.setRegionId(CLOUD_AI_REGION_ID);
configuration.setEndpoint(CLOUD_AI_FACEBODY_ENDPOINT);
FacebodyClient client(key, secret, configuration);
Model::DetectPedestrianRequest request;
string tmpImageURL;
string expression;
string type;
double left, top, right, bottom;
FacebodyResultStruct result;
int ret = 0, i;
tmpImageURL = url;
request.setScheme("http");
request.setMethod(HttpRequest::Method::Post);
request.setImageURL(tmpImageURL);
auto outcome = client.detectPedestrian(request);
// cout << endl << "facebody describeInstances returned:" << endl;
// cout << "error code: " << outcome.error().errorCode() << endl;
// cout << "requestId: " << outcome.result().requestId() << endl << endl;
// cout << "results size: " << outcome.result().getData().elements.size() << endl;
for (i = 0; i < outcome.result().getData().elements.size(); i++) {
// cout << i << "height: " << outcome.result().getData().height << endl;
// cout << i << "width: " << outcome.result().getData().width << endl;
// cout << i << "left: " << outcome.result().getData().elements[i].boxes[0] << endl;
// cout << i << "top: " << outcome.result().getData().elements[i].boxes[1] << endl;
// cout << i << "right: " << outcome.result().getData().elements[i].boxes[2] << endl;
// cout << i << "bottom: " << outcome.result().getData().elements[i].boxes[3] << endl;
// cout << i << "type: " << outcome.result().getData().elements[i].type << endl;
// cout << i << "score: " << outcome.result().getData().elements[i].score << endl;
type = outcome.result().getData().elements[i].type;
left = atof(outcome.result().getData().elements[i].boxes[0].c_str());
top = atof(outcome.result().getData().elements[i].boxes[1].c_str());
right = atof(outcome.result().getData().elements[i].boxes[2].c_str());
bottom = atof(outcome.result().getData().elements[i].boxes[3].c_str());
result.pedestrian.type = (char *)type.c_str();
result.pedestrian.score = outcome.result().getData().elements[i].score;
result.pedestrian.box.x = left;
result.pedestrian.box.y = top;
result.pedestrian.box.w = right - left;
result.pedestrian.box.h = bottom - top;
if (cb) {
ret = cb((void *)&result);
}
}
ShutdownSdk();
return ret;
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/facebody.cc
|
C++
|
apache-2.0
| 8,610
|
#include <iostream>
#include "alibabacloud/core/AlibabaCloud.h"
#include "alibabacloud/imageenhan/ImageenhanClient.h"
#include "alibabacloud/core/CommonClient.h"
#include "model/common.h"
extern "C" {
using namespace std;
using namespace AlibabaCloud;
using namespace AlibabaCloud::Imageenhan;
int erasePerson(char *imageUrl, char *userMaskUrl, AIModelCBFunc cb)
{
InitializeSdk();
string key = getAccessKey();
string secret = getAccessSecret();
ClientConfiguration configuration;
configuration.setRegionId(CLOUD_AI_REGION_ID);
configuration.setEndpoint(CLOUD_AI_IMAGEENHAN_ENDPOINT);
ImageenhanClient client(key, secret, configuration);
Model::ErasePersonRequest request;
string imageURL, userMaskURL;
ImageEnhanResultStruct result;
string url;
int ret = 0;
imageURL = imageUrl;
userMaskURL = userMaskUrl;
request.setScheme("http");
request.setMethod(HttpRequest::Method::Post);
request.setImageURL(imageURL);
request.setUserMask(userMaskURL);
auto outcome = client.erasePerson(request);
cout << endl << "result erasePerson describeInstances returned:" << endl;
cout << "error code: " << outcome.error().errorCode() << endl;
cout << "requestId: " << outcome.result().requestId() << endl << endl;
cout << "imageUrl: " << outcome.result().getData().imageUrl << endl;
url = outcome.result().getData().imageUrl;
if (url.size() > 0) {
result.person.url = (char *)url.c_str();
result.person.imageLen = getResponseBodyByUrl(result.person.url, &result.person.image);
if (result.person.image && cb) {
ret = cb((void *)&result);
}
}
ShutdownSdk();
return ret;
}
int extendImageStyle(char *majorUrl, char *styleUrl, AIModelCBFunc cb)
{
InitializeSdk();
string key = getAccessKey();
string secret = getAccessSecret();
ClientConfiguration configuration;
configuration.setRegionId(CLOUD_AI_REGION_ID);
configuration.setEndpoint(CLOUD_AI_IMAGEENHAN_ENDPOINT);
ImageenhanClient client(key, secret, configuration);
Model::ExtendImageStyleRequest request;
string inMajorURL, outMajorURL;
string styleURL, outImageURL;
ImageEnhanResultStruct result;
int ret = 0;
inMajorURL = majorUrl;
styleURL = styleUrl;
request.setScheme("http");
request.setMethod(HttpRequest::Method::Post);
request.setMajorUrl(inMajorURL);
request.setStyleUrl(styleURL);
auto outcome = client.extendImageStyle(request);
cout << endl << "imageenhan extendImageStyle describeInstances returned:" << endl;
cout << "error code: " << outcome.error().errorCode() << endl;
cout << "requestId: " << outcome.result().requestId() << endl << endl;
cout << "outMajorURL: " << outcome.result().getData().majorUrl << endl;
cout << "outImageURL: " << outcome.result().getData().url << endl;
outMajorURL = outcome.result().getData().majorUrl;
outImageURL = outcome.result().getData().url;
if (outMajorURL.size() > 0 && cb) {
result.style.majorUrl = (char *)outMajorURL.c_str();
result.style.majorImageLen = getResponseBodyByUrl(outMajorURL.c_str(), &result.style.majorImage);
ret = cb((void *)&result);
} else if (outImageURL.size() > 0 && cb) {
result.style.majorUrl = NULL;
result.style.outImageUrl = (char *)outImageURL.c_str();
result.style.outImageLen = getResponseBodyByUrl(outImageURL.c_str(), &result.style.outImage);
ret = cb((void *)&result);
}
ShutdownSdk();
return ret;
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/imageenhan.cc
|
C++
|
apache-2.0
| 3,575
|
#include <iostream>
#include "alibabacloud/core/AlibabaCloud.h"
#include "alibabacloud/imagerecog/ImagerecogClient.h"
#include "alibabacloud/core/CommonClient.h"
#include "model/common.h"
extern "C" {
using namespace std;
using namespace AlibabaCloud;
using namespace AlibabaCloud::Imagerecog;
int classifyingRubbish(char *url, AIModelCBFunc cb)
{
InitializeSdk();
string key = getAccessKey();
string secret = getAccessSecret();
ClientConfiguration configuration;
configuration.setRegionId(CLOUD_AI_REGION_ID);
configuration.setEndpoint(CLOUD_AI_IMAGERECOG_ENDPOINT);
ImagerecogClient client(key, secret, configuration);
Model::ClassifyingRubbishRequest request;
string imageURL;
ImageRecogResultStruct result;
string rubbish, category;
int ret = 0, i;
imageURL = url;
request.setScheme("http");
request.setMethod(HttpRequest::Method::Post);
request.setImageURL(imageURL);
auto outcome = client.classifyingRubbish(request);
cout << endl << "imageseg describeInstances returned:" << endl;
cout << "error code: " << outcome.error().errorCode() << endl;
cout << "requestId: " << outcome.result().requestId() << endl << endl;
cout << "sensitive: " << outcome.result().getData().sensitive << endl;
for (i = 0; i < outcome.result().getData().elements.size(); i++) {
cout << i << "rubbish: " << outcome.result().getData().elements[i].rubbish << endl;
cout << i << "category: " << outcome.result().getData().elements[i].category << endl;
cout << i << "categoryScore: " << outcome.result().getData().elements[i].categoryScore << endl;
cout << i << "rubbishScore: " << outcome.result().getData().elements[i].rubbishScore << endl;
rubbish = outcome.result().getData().elements[i].rubbish;
category = outcome.result().getData().elements[i].category;
result.rubbish.rubbish = rubbish.c_str();
result.rubbish.category = category.c_str();
result.rubbish.categoryScore = outcome.result().getData().elements[i].categoryScore;
result.rubbish.rubbishScore = outcome.result().getData().elements[i].rubbishScore;
if (cb) {
ret = cb((void *)&result);
}
}
ShutdownSdk();
return ret;
}
int detectFruits(char *url, AIModelCBFunc cb)
{
InitializeSdk();
string key = getAccessKey();
string secret = getAccessSecret();
ClientConfiguration configuration;
configuration.setRegionId(CLOUD_AI_REGION_ID);
configuration.setEndpoint(CLOUD_AI_IMAGERECOG_ENDPOINT);
ImagerecogClient client(key, secret, configuration);
Model::DetectFruitsRequest request;
ImageRecogResultStruct result;
string imageURL;
string name;
int ret = 0, i;
imageURL = url;
request.setScheme("http");
request.setMethod(HttpRequest::Method::Post);
request.setImageURL(imageURL);
auto outcome = client.detectFruits(request);
// cout << endl << "imageseg describeInstances returned:" << endl;
// cout << "error code: " << outcome.error().errorCode() << endl;
// cout << "requestId: " << outcome.result().requestId() << endl << endl;
for (i = 0; i < outcome.result().getData().elements.size(); i++) {
// cout << i << "score: " << outcome.result().getData().elements[i].score << endl;
// cout << i << "name: " << outcome.result().getData().elements[i].name << endl;
result.fruits.score = outcome.result().getData().elements[i].score;
name = outcome.result().getData().elements[i].name;
result.fruits.name = (char *)name.c_str();
// cout << "box.xmin: " << outcome.result().getData().elements[i].box[0] << endl;
// cout << "box.ymin: " << outcome.result().getData().elements[i].box[1] << endl;
// cout << "box.xmax: " << outcome.result().getData().elements[i].box[2] << endl;
// cout << "box.ymax: " << outcome.result().getData().elements[i].box[3] << endl;
result.fruits.box.x = atoi(outcome.result().getData().elements[i].box[0].c_str());
result.fruits.box.y = atoi(outcome.result().getData().elements[i].box[1].c_str());
result.fruits.box.w = atoi(outcome.result().getData().elements[i].box[2].c_str()) - result.fruits.box.x;
result.fruits.box.h = atoi(outcome.result().getData().elements[i].box[3].c_str()) - result.fruits.box.y;
if (cb) {
ret = cb((void *)&result);
}
}
ShutdownSdk();
return ret;
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/imagerecog.cc
|
C++
|
apache-2.0
| 4,488
|
#include <iostream>
#include "alibabacloud/core/AlibabaCloud.h"
#include "alibabacloud/imageseg/ImagesegClient.h"
#include "alibabacloud/core/CommonClient.h"
#include "model/common.h"
extern "C" {
using namespace std;
using namespace AlibabaCloud;
using namespace AlibabaCloud::Imageseg;
int segmentCommonImage(char *url, AIModelCBFunc cb)
{
InitializeSdk();
string key = getAccessKey();
string secret = getAccessSecret();
ClientConfiguration configuration;
configuration.setRegionId(CLOUD_AI_REGION_ID);
configuration.setEndpoint(CLOUD_AI_IMAGESEG_ENDPOINT);
ImagesegClient client(key, secret, configuration);
Model::SegmentCommonImageRequest request;
string inImageURL;
ImageSegResultStruct result;
string outImageUrl;
int ret = 0;
inImageURL = url;
request.setScheme("http");
request.setMethod(HttpRequest::Method::Post);
request.setImageURL(inImageURL);
request.setReturnForm("whiteBK"); // set png format, mask or whiteBK, please refer to parameters of vision platform
auto outcome = client.segmentCommonImage(request);
cout << endl << "imageseg describeInstances returned:" << endl;
cout << "error code: " << outcome.error().errorCode() << endl;
cout << "requestId: " << outcome.result().requestId() << endl << endl;
cout << "image url: " << outcome.result().getData().imageURL << endl;
outImageUrl = outcome.result().getData().imageURL;
if (outImageUrl.size() > 0) {
result.common.url = (char *)outImageUrl.c_str();
result.common.imageLen = getResponseBodyByUrl(outcome.result().getData().imageURL.c_str(), &result.common.image);
if (result.common.image && cb) {
ret = cb((void *)&result);
}
}
ShutdownSdk();
return ret;
}
int segmentFace(char *url, AIModelCBFunc cb)
{
InitializeSdk();
string key = getAccessKey();
string secret = getAccessSecret();
ClientConfiguration configuration;
configuration.setRegionId(CLOUD_AI_REGION_ID);
configuration.setEndpoint(CLOUD_AI_IMAGESEG_ENDPOINT);
ImagesegClient client(key, secret, configuration);
Model::SegmentFaceRequest request;
string inImageURL;
ImageSegResultStruct result;
string outImageUrl;
int ret = 0, i = 0;
inImageURL = url;
request.setScheme("http");
request.setMethod(HttpRequest::Method::Post);
request.setImageURL(inImageURL);
auto outcome = client.segmentFace(request);
cout << endl << "imageseg describeInstances returned:" << endl;
cout << "error code: " << outcome.error().errorCode() << endl;
cout << "requestId: " << outcome.result().requestId() << endl << endl;
if (outcome.result().getData().elements.size() == 0)
return -1;
// for (i = 0; i < outcome.result().getData().elements.size(); i++)
{
cout << i << "image url: " << outcome.result().getData().elements[i].imageURL << endl;
cout << i << "width: " << outcome.result().getData().elements[i].width << endl;
cout << i << "height: " << outcome.result().getData().elements[i].height << endl;
cout << i << "x: " << outcome.result().getData().elements[i].x << endl;
cout << i << "y: " << outcome.result().getData().elements[i].y << endl;
outImageUrl = outcome.result().getData().elements[i].imageURL;
if (outImageUrl.size() > 0) {
result.face.url = (char *)outImageUrl.c_str();
result.face.imageLen = getResponseBodyByUrl(result.face.url, &result.face.image);
if (result.face.image && cb) {
result.face.location.x = outcome.result().getData().elements[i].x;
result.face.location.y = outcome.result().getData().elements[i].y;
result.face.location.w = outcome.result().getData().elements[i].width;
result.face.location.h = outcome.result().getData().elements[i].height;
ret = cb((void *)&result);
}
}
}
ShutdownSdk();
return ret;
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/imageseg.cc
|
C++
|
apache-2.0
| 4,023
|
#include <iostream>
#include "alibabacloud/core/AlibabaCloud.h"
#include "alibabacloud/objectdet/ObjectdetClient.h"
#include "alibabacloud/core/CommonClient.h"
#include "model/common.h"
extern "C" {
using namespace std;
using namespace AlibabaCloud;
using namespace AlibabaCloud::Objectdet;
int detectObject(char *url, AIModelCBFunc cb)
{
InitializeSdk();
string key = getAccessKey();
string secret = getAccessSecret();
ClientConfiguration configuration;
configuration.setRegionId(CLOUD_AI_REGION_ID);
configuration.setEndpoint(CLOUD_AI_OBJECTDET_ENDPOINT);
ObjectdetClient client(key, secret, configuration);
Model::DetectObjectRequest request;
string tmpImageURL;
ObjectDetResultStruct result;
string type;
double left, top, right, bottom;
int ret = 0;
int objectNum, i;
tmpImageURL = url;
request.setScheme("http");
request.setMethod(HttpRequest::Method::Post);
request.setImageURL(tmpImageURL);
auto outcome = client.detectObject(request);
cout << endl << "objectdet describeInstances returned:" << endl;
cout << "error code: " << outcome.error().errorCode() << endl;
// cout << "requestId: " << outcome.result().requestId() << endl << endl;
cout << "object num:" << outcome.result().getData().elements.size() << endl;
cout << "object height:" << outcome.result().getData().height << endl;
cout << "object width:" << outcome.result().getData().width << endl;
objectNum = outcome.result().getData().elements.size();
for (i = 0; i < objectNum; i++) {
cout << "object score:" << outcome.result().getData().elements[i].score << endl;
cout << "object type:" << outcome.result().getData().elements[i].type << endl;
cout << "object boxes.left:" << outcome.result().getData().elements[i].boxes[0] << endl;
cout << "object boxes.top:" << outcome.result().getData().elements[i].boxes[1] << endl;
cout << "object boxes.right:" << outcome.result().getData().elements[i].boxes[2] << endl;
cout << "object boxes.bottom:" << outcome.result().getData().elements[i].boxes[3] << endl;
type = outcome.result().getData().elements[i].type;
left = outcome.result().getData().elements[i].boxes[0];
top = outcome.result().getData().elements[i].boxes[1];
right = outcome.result().getData().elements[i].boxes[2];
bottom = outcome.result().getData().elements[i].boxes[3];
result.object.type = (char *)type.c_str();
result.object.score = outcome.result().getData().elements[i].score;
result.object.box.x = left;
result.object.box.y = top;
result.object.box.w = right - left;
result.object.box.h = bottom - top;
if (cb) {
ret = cb((void *)&result);
}
}
ShutdownSdk();
return ret;
}
int detectMainBody(char *url, AIModelCBFunc cb)
{
InitializeSdk();
string key = getAccessKey();
string secret = getAccessSecret();
ClientConfiguration configuration;
configuration.setRegionId(CLOUD_AI_REGION_ID);
configuration.setEndpoint(CLOUD_AI_OBJECTDET_ENDPOINT);
ObjectdetClient client(key, secret, configuration);
Model::DetectMainBodyRequest request;
string tmpImageURL;
ObjectDetResultStruct result;
int ret = 0;
tmpImageURL = url;
request.setScheme("http");
request.setMethod(HttpRequest::Method::Post);
request.setImageURL(tmpImageURL);
auto outcome = client.detectMainBody(request);
cout << endl << "objectdet detectMainBody describeInstances returned:" << endl;
cout << "error code: " << outcome.error().errorCode() << endl;
cout << "requestId: " << outcome.result().requestId() << endl << endl;
cout << "object x:" << outcome.result().getData().location.x << endl;
cout << "object y:" << outcome.result().getData().location.y << endl;
cout << "object width:" << outcome.result().getData().location.width << endl;
cout << "object height:" << outcome.result().getData().location.height << endl;
result.mainbody.location.x = outcome.result().getData().location.x;
result.mainbody.location.y = outcome.result().getData().location.y;
result.mainbody.location.w = outcome.result().getData().location.width;
result.mainbody.location.h = outcome.result().getData().location.height;
if (cb) {
ret = cb((void *)&result);
}
ShutdownSdk();
return ret;
}
}
|
YifuLiu/AliOS-Things
|
components/ucloud_ai/src/model/objectdet.cc
|
C++
|
apache-2.0
| 4,443
|