-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathput.cpp
115 lines (107 loc) · 3.13 KB
/
put.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <fstream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fastcgi++/request.hpp>
#include <fastcgi++/manager.hpp>
#include <fastcgi++/http.hpp>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include "connector.hpp"
void error_log(const char* msg)
{
using namespace std;
using namespace boost;
static ofstream error;
if(!error.is_open())
{
error.open("/tmp/errlog", ios_base::out | ios_base::app);
error.imbue(locale(error.getloc(), new posix_time::time_facet()));
}
error << '[' << posix_time::second_clock::local_time() << "] " << msg << endl;
}
class PutBook : public Connector
{
inline void sendError(const std::string& errorMsg)
{
out << "{ \"success\" : 0, \"message\" : \"" + errorMsg + "\" }" << std::endl;
}
inline void sendSuccess()
{
out << "{ \"success\" : 1 }" << std::endl;
}
bool response()
{
out << "Content-Type: application/json; charset=ISO-8859-1\r\n\r\n";
std::map<std::string, std::string> parameters;
for (Fastcgipp::Http::Environment<char>::Posts::const_iterator it = environment().posts.begin(); it != environment().posts.end(); ++it)
{
parameters[it->first] = it->second.value;
}
if (parameters.find("id") == parameters.end())
{
sendError("Missing id");
}
else
{
std::map<std::string, std::string> columns;
if (parameters.find("name") != parameters.end())
{
columns["name"] = "\"" + parameters["name"] + "\"";
}
if (parameters.find("publisher") != parameters.end())
{
columns["publisher"] = "\"" + parameters["publisher"] + "\"";
}
if (parameters.find("date") != parameters.end())
{
columns["date"] = "FROM_UNIXTIME('" + parameters["date"] + "')";
}
if (parameters.find("edition") != parameters.end())
{
columns["edition"] = parameters["edition"];
}
if (columns.empty())
{
sendError("There is no column to be updated");
}
else
{
std::string query = "UPDATE book SET ";
for (std::map<std::string, std::string>::iterator it = columns.begin(); it != columns.end(); ++it)
{
if (it != columns.begin()) query += ", ";
query += it->first + "=" + it->second;
}
query += " WHERE id=" + parameters["id"];
sql::Statement* stmt = con->createStatement();
try
{
stmt->execute(query);
sendSuccess();
} catch (sql::SQLException& e)
{
sendError(e.what());
}
delete stmt;
}
}
return true;
}
};
int main()
{
try
{
Fastcgipp::Manager<PutBook> fcgi;
fcgi.handler();
}
catch (std::exception& e)
{
error_log(e.what());
}
return 0;
}