Rework book server and client.

This commit is contained in:
Chunting Gu
2019-09-06 17:40:46 +08:00
parent f1ad97b227
commit 2a25340ce4
24 changed files with 1120 additions and 301 deletions
+12
View File
@@ -0,0 +1,12 @@
set(SRCS
book.cc
book.h
book_json.cc
book_json.h
book_client.cc
book_client.h
main.cc
)
add_executable(book_client ${SRCS})
target_link_libraries(book_client ${EXAMPLE_LIBS} jsoncpp)
+11
View File
@@ -0,0 +1,11 @@
#include "book.h"
#include <iostream>
const Book kNullBook{};
std::ostream& operator<<(std::ostream& os, const Book& book) {
os << "{ " << book.id << ", " << book.title << ", " << book.price << ", "
<< book.photo << " }";
return os;
}
+22
View File
@@ -0,0 +1,22 @@
#ifndef BOOK_H_
#define BOOK_H_
#include <iosfwd>
#include <string>
struct Book {
std::string id;
std::string title;
double price;
std::string photo; // Name only
bool IsNull() const {
return id.empty();
}
};
std::ostream& operator<<(std::ostream& os, const Book& book);
extern const Book kNullBook;
#endif // BOOK_H_
+194
View File
@@ -0,0 +1,194 @@
#include "book_client.h"
#include <iostream>
#include "boost/algorithm/string/predicate.hpp"
#include "boost/filesystem/operations.hpp"
#include "json/json.h"
#include "book_json.h"
BookClient::BookClient(const std::string& url, int timeout)
: url_(url), session_(timeout) {
// Default Content-Type for requests who have a body.
session_.set_media_type("application/json");
session_.set_charset("utf-8");
}
bool BookClient::Query(std::list<Book>* books) {
try {
auto r = session_.Send(WEBCC_GET(url_).Path("books")());
if (!CheckStatus(r, webcc::Status::kOK)) {
// Response HTTP status error.
return false;
}
Json::Value json = StringToJson(r->data());
if (!json.isArray()) {
return false; // Should be a JSON array of books.
}
for (Json::ArrayIndex i = 0; i < json.size(); ++i) {
books->push_back(JsonToBook(json[i]));
}
return true;
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::Create(const std::string& title, double price,
std::string* id) {
Json::Value req_json;
req_json["title"] = title;
req_json["price"] = price;
try {
auto r = session_.Send(WEBCC_POST(url_).Path("books").
Body(JsonToString(req_json))());
if (!CheckStatus(r, webcc::Status::kCreated)) {
return false;
}
Json::Value rsp_json = StringToJson(r->data());
*id = rsp_json["id"].asString();
if (id->empty()) {
return false;
}
return true;
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::Get(const std::string& id, Book* book) {
try {
auto r = session_.Send(WEBCC_GET(url_).Path("books").Path(id)());
if (!CheckStatus(r, webcc::Status::kOK)) {
return false;
}
return JsonStringToBook(r->data(), book);
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::Set(const std::string& id, const std::string& title,
double price) {
Json::Value json;
json["title"] = title;
json["price"] = price;
try {
auto r = session_.Send(WEBCC_PUT(url_).Path("books").Path(id).
Body(JsonToString(json))());
if (!CheckStatus(r, webcc::Status::kOK)) {
return false;
}
return true;
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::Delete(const std::string& id) {
try {
auto r = session_.Send(WEBCC_DELETE(url_).Path("books").Path(id)());
if (!CheckStatus(r, webcc::Status::kOK)) {
return false;
}
return true;
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::GetPhoto(const std::string& id, const bfs::path& path) {
try {
auto r = session_.Send(WEBCC_GET(url_).
Path("books").Path(id).Path("photo")(),
true); // Save to temp file
if (!CheckStatus(r, webcc::Status::kOK)) {
return false;
}
r->file_body()->Move(path);
return true;
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::SetPhoto(const std::string& id, const bfs::path& path) {
try {
if (!CheckPhoto(path)) {
return false;
}
auto r = session_.Send(WEBCC_PUT(url_).
Path("books").Path(id).Path("photo").
File(path)());
if (!CheckStatus(r, webcc::Status::kOK)) {
return false;
}
return true;
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::CheckPhoto(const bfs::path& photo) {
if (photo.empty()) {
return false;
}
if (!bfs::is_regular_file(photo) || !bfs::exists(photo)) {
return false;
}
auto ext = photo.extension().string();
if (!boost::iequals(ext, ".jpg") && !boost::iequals(ext, ".jpeg")) {
return false;
}
return true;
}
bool BookClient::CheckStatus(webcc::ResponsePtr response, int expected_status) {
if (response->status() != expected_status) {
std::cerr << "HTTP status error (actual: " << response->status()
<< "expected: " << expected_status << ")." << std::endl;
return false;
}
return true;
}
+49
View File
@@ -0,0 +1,49 @@
#ifndef BOOK_CLIENT_H_
#define BOOK_CLIENT_H_
#include <list>
#include <string>
#include "boost/filesystem/path.hpp"
#include "json/json-forwards.h"
#include "webcc/client_session.h"
#include "book.h"
namespace bfs = boost::filesystem;
class BookClient {
public:
explicit BookClient(const std::string& url, int timeout = 0);
~BookClient() = default;
bool Query(std::list<Book>* books);
bool Create(const std::string& title, double price, std::string* id);
bool Get(const std::string& id, Book* book);
bool Set(const std::string& id, const std::string& title, double price);
bool Delete(const std::string& id);
// Get photo, save to the given path.
bool GetPhoto(const std::string& id, const bfs::path& path);
// Set photo using the file of the given path.
bool SetPhoto(const std::string& id, const bfs::path& path);
private:
bool CheckPhoto(const bfs::path& photo);
// Check HTTP response status.
bool CheckStatus(webcc::ResponsePtr response, int expected_status);
private:
std::string url_;
webcc::ClientSession session_;
};
#endif // BOOK_CLIENT_H_
+59
View File
@@ -0,0 +1,59 @@
#include "book_json.h"
#include <iostream>
#include <sstream>
#include "json/json.h"
#include "book.h"
std::string JsonToString(const Json::Value& json) {
Json::StreamWriterBuilder builder;
return Json::writeString(builder, json);
}
Json::Value StringToJson(const std::string& str) {
Json::Value json;
Json::CharReaderBuilder builder;
std::stringstream stream(str);
std::string errs;
if (!Json::parseFromStream(builder, stream, &json, &errs)) {
std::cerr << errs << std::endl;
}
return json;
}
Json::Value BookToJson(const Book& book) {
Json::Value json;
json["id"] = book.id;
json["title"] = book.title;
json["price"] = book.price;
json["photo"] = book.photo;
return json;
}
Book JsonToBook(const Json::Value& json) {
return {
json["id"].asString(),
json["title"].asString(),
json["price"].asDouble(),
json["photo"].asString(),
};
}
std::string BookToJsonString(const Book& book) {
return JsonToString(BookToJson(book));
}
bool JsonStringToBook(const std::string& json_str, Book* book) {
Json::Value json = StringToJson(json_str);
if (!json) {
return false;
}
*book = JsonToBook(json);
return true;
}
+22
View File
@@ -0,0 +1,22 @@
#ifndef BOOK_JSON_H_
#define BOOK_JSON_H_
#include <string>
#include "json/json-forwards.h"
struct Book;
std::string JsonToString(const Json::Value& json);
Json::Value StringToJson(const std::string& str);
Json::Value BookToJson(const Book& book);
Book JsonToBook(const Json::Value& json);
std::string BookToJsonString(const Book& book);
bool JsonStringToBook(const std::string& json_str, Book* book);
#endif // BOOK_JSON_H_
+141
View File
@@ -0,0 +1,141 @@
#include <iostream>
#include "boost/filesystem/operations.hpp"
#include "webcc/logger.h"
#include "book_client.h"
// Memory leak detection with VLD.
#if (defined(_WIN32) || defined(_WIN64))
#if defined(_DEBUG) && defined(WEBCC_ENABLE_VLD)
#pragma message ("< include vld.h >")
#include "vld/vld.h"
#pragma comment(lib, "vld")
#endif
#endif
// -----------------------------------------------------------------------------
void PrintSeparator() {
static const std::string s_line(80, '-');
std::cout << s_line << std::endl;
}
void PrintBook(const Book& book) {
std::cout << "Book: " << book << std::endl;
}
void PrintBookList(const std::list<Book>& books) {
std::cout << "Book list: " << books.size() << std::endl;
for (const Book& book : books) {
std::cout << " Book: " << book << std::endl;
}
}
// -----------------------------------------------------------------------------
int main(int argc, char* argv[]) {
if (argc < 3) {
std::cout << "usage: book_client <url> <photo_dir>" << std::endl;
std::cout << "e.g.," << std::endl;
std::cout << " $ book_client http://localhost:8080 path/to/photo_dir"
<< std::endl;
return 1;
}
std::string url = argv[1];
bfs::path photo_dir = argv[2];
if (!bfs::is_directory(photo_dir) || !bfs::exists(photo_dir)) {
std::cerr << "Invalid photo dir!" << std::endl;
return 1;
}
std::cout << "Test photo dir: " << photo_dir << std::endl;
WEBCC_LOG_INIT("", webcc::LOG_CONSOLE_FILE_OVERWRITE);
BookClient client(url);
PrintSeparator();
std::list<Book> books;
if (client.Query(&books)) {
PrintBookList(books);
} else {
return 1;
}
PrintSeparator();
std::string id;
if (client.Create("1984", 12.3, &id)) {
std::cout << "Book ID: " << id << std::endl;
} else {
return 1;
}
if (!client.SetPhoto(id, photo_dir / "1984.jpg")) {
return 1;
}
PrintSeparator();
books.clear();
if (client.Query(&books)) {
PrintBookList(books);
} else {
return 1;
}
PrintSeparator();
Book book;
if (client.Get(id, &book)) {
PrintBook(book);
} else {
return 1;
}
PrintSeparator();
std::cout << "Press any key to continue...";
std::getchar();
if (!client.Set(id, "1Q84", 32.1)) {
return 1;
}
if (!client.SetPhoto(id, photo_dir / "1Q84.jpg")) {
return 1;
}
PrintSeparator();
if (client.Get(id, &book)) {
PrintBook(book);
} else {
return 1;
}
PrintSeparator();
std::cout << "Press any key to continue...";
std::getchar();
if (!client.Delete(id)) {
return 1;
}
PrintSeparator();
books.clear();
if (client.Query(&books)) {
PrintBookList(books);
}
std::cout << "Press any key to continue...";
std::getchar();
return 0;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+316
View File
@@ -0,0 +1,316 @@
#include <iostream>
#include <list>
#include "boost/algorithm/string/predicate.hpp"
#include "boost/filesystem/operations.hpp"
#include "json/json.h"
#include "webcc/client_session.h"
#include "webcc/logger.h"
#include "examples/common/book.h"
#include "examples/common/book_json.h"
#if (defined(_WIN32) || defined(_WIN64))
#if defined(_DEBUG) && defined(WEBCC_ENABLE_VLD)
#pragma message ("< include vld.h >")
#include "vld/vld.h"
#pragma comment(lib, "vld")
#endif
#endif
namespace bfs = boost::filesystem;
// -----------------------------------------------------------------------------
class BookClient {
public:
explicit BookClient(const std::string& url, int timeout = 0);
~BookClient() = default;
bool ListBooks(std::list<Book>* books);
bool CreateBook(const std::string& title, double price,
const bfs::path& photo, std::string* id);
bool GetBook(const std::string& id, Book* book);
bool UpdateBook(const std::string& id, const std::string& title,
double price);
bool DeleteBook(const std::string& id);
private:
bool CheckPhoto(const bfs::path& photo);
// Check HTTP response status.
bool CheckStatus(webcc::ResponsePtr response, int expected_status);
private:
std::string url_;
webcc::ClientSession session_;
};
// -----------------------------------------------------------------------------
BookClient::BookClient(const std::string& url, int timeout)
: url_(url), session_(timeout) {
// If the request has body, default to this content type.
// Optional.
session_.set_media_type("application/json");
session_.set_charset("utf-8");
}
bool BookClient::ListBooks(std::list<Book>* books) {
try {
auto r = session_.Send(WEBCC_GET(url_).Path("books")());
if (!CheckStatus(r, webcc::Status::kOK)) {
// Response HTTP status error.
return false;
}
Json::Value rsp_json = StringToJson(r->data());
if (!rsp_json.isArray()) {
return false; // Should be a JSON array of books.
}
for (Json::ArrayIndex i = 0; i < rsp_json.size(); ++i) {
books->push_back(JsonToBook(rsp_json[i]));
}
return true;
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::CreateBook(const std::string& title, double price,
const bfs::path& photo, std::string* id) {
Json::Value req_json;
req_json["title"] = title;
req_json["price"] = price;
try {
auto r = session_.Send(WEBCC_POST(url_).Path("books").
Body(JsonToString(req_json))());
if (!CheckStatus(r, webcc::Status::kCreated)) {
return false;
}
Json::Value rsp_json = StringToJson(r->data());
*id = rsp_json["id"].asString();
if (id->empty()) {
return false;
}
if (CheckPhoto(photo)) {
r = session_.Send(WEBCC_PUT(url_).Path("books").Path(*id).Path("photo").
File(photo)());
if (!CheckStatus(r, webcc::Status::kOK)) {
return false;
}
}
return true;
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::GetBook(const std::string& id, Book* book) {
try {
auto r = session_.Send(WEBCC_GET(url_).Path("books").Path(id)());
if (!CheckStatus(r, webcc::Status::kOK)) {
return false;
}
return JsonStringToBook(r->data(), book);
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::UpdateBook(const std::string& id, const std::string& title,
double price) {
Json::Value json;
json["title"] = title;
json["price"] = price;
try {
auto r = session_.Send(WEBCC_PUT(url_).Path("books").Path(id).
Body(JsonToString(json))());
if (!CheckStatus(r, webcc::Status::kOK)) {
return false;
}
return true;
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::DeleteBook(const std::string& id) {
try {
auto r = session_.Send(WEBCC_DELETE(url_).Path("books").Path(id)());
if (!CheckStatus(r, webcc::Status::kOK)) {
return false;
}
return true;
} catch (const webcc::Error& error) {
std::cerr << error << std::endl;
return false;
}
}
bool BookClient::CheckPhoto(const bfs::path& photo) {
if (photo.empty()) {
return false;
}
if (!bfs::is_regular_file(photo) || !bfs::exists(photo)) {
return false;
}
auto ext = photo.extension().string();
if (!boost::iequals(ext, ".jpg") && !boost::iequals(ext, ".jpeg")) {
return false;
}
return true;
}
bool BookClient::CheckStatus(webcc::ResponsePtr response, int expected_status) {
if (response->status() != expected_status) {
LOG_ERRO("HTTP status error (actual: %d, expected: %d).",
response->status(), expected_status);
return false;
}
return true;
}
// -----------------------------------------------------------------------------
void PrintSeparator() {
static const std::string s_line(80, '-');
std::cout << s_line << std::endl;
}
void PrintBook(const Book& book) {
std::cout << "Book: " << book << std::endl;
}
void PrintBookList(const std::list<Book>& books) {
std::cout << "Book list: " << books.size() << std::endl;
for (const Book& book : books) {
std::cout << " Book: " << book << std::endl;
}
}
// -----------------------------------------------------------------------------
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cout << "usage: rest_book_client <url>" << std::endl;
std::cout << "examples:" << std::endl;
std::cout << " $ rest_book_client http://localhost:8080" << std::endl;
return 1;
}
std::string url = argv[1];
WEBCC_LOG_INIT("", webcc::LOG_CONSOLE_FILE_OVERWRITE);
BookClient client(url);
PrintSeparator();
// List all books.
std::list<Book> books;
if (client.ListBooks(&books)) {
PrintBookList(books);
} else {
return 1;
}
PrintSeparator();
// Create a new book.
std::string id;
if (client.CreateBook("1984", 12.3, "", &id)) {
std::cout << "Book ID: " << id << std::endl;
} else {
return 1;
}
PrintSeparator();
books.clear();
if (client.ListBooks(&books)) {
PrintBookList(books);
} else {
return 1;
}
PrintSeparator();
Book book;
if (client.GetBook(id, &book)) {
PrintBook(book);
} else {
return 1;
}
PrintSeparator();
if (!client.UpdateBook(id, "1Q84", 32.1)) {
return 1;
}
PrintSeparator();
if (client.GetBook(id, &book)) {
PrintBook(book);
} else {
return 1;
}
PrintSeparator();
if (!client.DeleteBook(id)) {
return 1;
}
PrintSeparator();
books.clear();
if (client.ListBooks(&books)) {
PrintBookList(books);
}
std::cout << "Press any key to exit: ";
std::getchar();
return 0;
}