Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 4f5383d4e6
Fetching contributors…

Cannot retrieve contributors at this time

328 lines (275 sloc) 9.836 kb
//
// RowFormatter.cpp
//
// $Id: //poco/Main/Data/samples/RecordSet/src/RowFormatter.cpp#2 $
//
// This a sample demonstrating the Data library recordset row formatting
// and streaming capabilities that was used at the 2012 Silicon Valley
// Code Camp conference.
//
// Copyright (c) 2008, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include "Poco/SharedPtr.h"
#include "Poco/URI.h"
#include "Poco/Path.h"
#include "Poco/File.h"
#include "Poco/FileStream.h"
#include "Poco/Data/SessionFactory.h"
#include "Poco/Data/Session.h"
#include "Poco/Data/Statement.h"
#include "Poco/Data/RecordSet.h"
#include "Poco/Data/RowFormatter.h"
#include "Poco/Data/SQLite/Connector.h"
#include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/ServerSocket.h"
#include <iostream>
using namespace Poco::Data::Keywords;
using Poco::URI;
using Poco::Path;
using Poco::File;
using Poco::FileInputStream;
using Poco::Data::Session;
using Poco::Data::Statement;
using Poco::Data::RecordSet;
using Poco::Data::RowFormatter;
using Poco::Net::ServerSocket;
using Poco::Net::HTTPRequestHandler;
using Poco::Net::HTTPRequestHandlerFactory;
using Poco::Net::HTTPServer;
using Poco::Net::HTTPServerRequest;
using Poco::Net::HTTPServerResponse;
using Poco::Net::HTTPServerParams;
using Poco::Net::HTTPResponse;
#define ROOT_DIR "C:\\trunk\\Data\\samples\\RowFormatter\\bin\\"
std::string getSQL(const std::string& file = ROOT_DIR"simpsons.sql")
{
Poco::FileInputStream fis(file);
std::string read, tmp;
while (!fis.eof()) { fis >> tmp; tmp += ' '; read += tmp; }
return read;
}
bool fileExists(const HTTPServerRequest& request, std::string& fullPath)
{
std::string root = ROOT_DIR;
URI uri(request.getURI());
std::string path = uri.getPath();
Poco::Path requestPath(path, Poco::Path::PATH_UNIX);
Poco::Path localPath(root);
localPath.makeDirectory();
for (int i = 0; i < requestPath.depth(); i++)
localPath.pushDirectory(requestPath[i]);
localPath.setFileName(requestPath.getFileName());
Poco::File localFile(localPath.toString());
std::cout << "Path: " << localPath.toString() << std::endl;
if (localFile.exists())
{
fullPath = localPath.toString();
return true;
}
return false;
}
class NotFoundRequestHandler: public HTTPRequestHandler
{
public:
void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
{
response.setStatusAndReason(HTTPResponse::HTTP_NOT_FOUND);
response.send();
}
};
class FileRequestHandler: public HTTPRequestHandler
{
public:
FileRequestHandler(const std::string& file): _file(file) { }
void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
{
response.setChunkedTransferEncoding(true);
//response.setContentType("text/html");
Path path(_file);
if (File(path).exists())
{
std::string mime = "application/binary";
std::string ext = path.getExtension();
if (ext == "html" || ext == "htm" || ext == "js" || ext == "css" || ext == "xml")
mime = "text/" + ext;
response.sendFile(_file, mime);
}
else
{
response.setStatusAndReason(HTTPResponse::HTTP_NOT_FOUND);
response.send();
}
}
private:
std::string _file;
};
class HTMLTableFormatter : public RowFormatter
{
public:
HTMLTableFormatter()
{
std::ostringstream os;
os << "<TABLE border=\"1\" cellspacing=\"0\">" << std::endl;
setPrefix(os.str());
os.str("");
os << "</TABLE>" << std::endl;
setPostfix(os.str());
}
std::string& formatNames(const NameVecPtr pNames, std::string& formattedNames)
{
std::ostringstream str;
str << "\t<TR>" << std::endl;
NameVec::const_iterator it = pNames->begin();
NameVec::const_iterator end = pNames->end();
for (; it != end; ++it) str << "\t\t<TH align=\"center\">" << *it << "</TH>" << std::endl;
str << "\t</TR>" << std::endl;
return formattedNames = str.str();
}
std::string& formatValues(const ValueVec& vals, std::string& formattedValues)
{
std::ostringstream str;
str << "\t<TR>" << std::endl;
ValueVec::const_iterator it = vals.begin();
ValueVec::const_iterator end = vals.end();
for (; it != end; ++it)
{
if (it->isNumeric())
str << "\t\t<TD align=\"right\">";
else
str << "\t\t<TD align=\"left\">";
str << it->convert<std::string>() << "</TD>" << std::endl;
}
str << "\t</TR>" << std::endl;
return formattedValues = str.str();
}
};
class XMLFormatter : public RowFormatter
{
public:
XMLFormatter() : _pNames(0)
{
std::ostringstream os;
os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl << "<Items>" << std::endl;
setPrefix(os.str());
os.str("");
os << "</Items>" << std::endl;
setPostfix(os.str());
}
std::string& formatNames(const NameVecPtr pNames, std::string& formattedNames)
{
_pNames = pNames;
return formattedNames;
}
std::string& formatValues(const ValueVec& vals, std::string& formattedValues)
{
if (!_pNames) return formattedValues;
std::ostringstream str;
str << "\t<Item>" << std::endl;
ValueVec::const_iterator it = vals.begin();
ValueVec::const_iterator end = vals.end();
NameVec::const_iterator nIt = _pNames->begin();
for (; it != end; ++it, ++nIt)
{
str << "\t\t<" << *nIt
<< '>' << it->convert<std::string>()
<< "</" << *nIt << '>' << std::endl;
}
str << "\t</Item>" << std::endl;
return formattedValues = str.str();
}
private:
NameVecPtr _pNames;
};
class DataRequestHandler: public HTTPRequestHandler
{
public:
void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
{
response.setChunkedTransferEncoding(true);
URI uri(request.getURI());
std::string path = uri.getPath();
std::string sql = getSQL();
std:: cout << "Executing;[" << sql << ']' << std::endl;
if (path == "/html")
{
response.setContentType("text/html");
response.send() << RecordSet(Session("SQLite", "simpsons.db"), sql, new HTMLTableFormatter);
}
else if (path == "/xml")
{
response.setContentType("text/xml");
response.send() << RecordSet(Session("SQLite", "simpsons.db"), sql, new XMLFormatter);
}
}
};
class DataRequestHandlerFactory: public HTTPRequestHandlerFactory
{
public:
HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request)
{
std::string localPath;
std::string uriPath = URI(request.getURI()).getPath();
if (fileExists(request, localPath)) // request for a file
return new FileRequestHandler(localPath);
else if ((uriPath == "/html") || (uriPath == "/xml")) // request for data
return new DataRequestHandler();
else // sorry ...
return new NotFoundRequestHandler();
}
};
int main()
{
Poco::Data::SQLite::Connector::registerConnector();
HTTPServer srv(new DataRequestHandlerFactory, 8080);
srv.start();
getchar();
srv.stop();
return 0;
}
/* code to create table is below
ExtJS example is in bin/js/ext/examples/grid/simpsons.*
// drop sample table, if it exists
session << "DROP TABLE IF EXISTS Simpsons", now;
// (re)create table
session << "CREATE TABLE Simpsons (Name VARCHAR(30), Address VARCHAR, Age INTEGER(3))", now;
// insert some rows
session << "INSERT INTO Simpsons VALUES('Homer Simpson', 'Springfield', 42)", now;
session << "INSERT INTO Simpsons VALUES('Marge Simpson', 'Springfield', 38)", now;
session << "INSERT INTO Simpsons VALUES('Bart Simpson', 'Springfield', 12)", now;
session << "INSERT INTO Simpsons VALUES('Lisa Simpson', 'Springfield', 10)", now;
// Note: The code above is divided into individual steps for clarity purpose.
// The four lines can be reduced to the following single line of code:
std::cout << RecordSet(session, "SELECT * FROM Simpsons", new HTMLTableFormatter);
// simple formatting example (uses the default SimpleRowFormatter provided by framework)
std::cout << std::endl << "Simple formatting:" << std::endl << std::endl;
std::cout << RecordSet(session, "SELECT * FROM Simpsons");
*/
Jump to Line
Something went wrong with that request. Please try again.