本文整理汇总了C++中writer函数的典型用法代码示例。如果您正苦于以下问题:C++ writer函数的具体用法?C++ writer怎么用?C++ writer使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了writer函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: main
int main(){
time_t t;
srand((unsigned)(2));
int n=5;
pid_t child[5];
int i,k,m,response[5];
int fd1[5][2],fd2[5][2];
int random_no,element;
/*creating 2 pipes followed by fork to provide 2 pipes between each parent and child pair and then loading the child.c file into each child
fd1 is file descriptor for parent->child pipe
fd2 is file descriptor for child->parent pipe
index 0 => reading endfile descriptor
index 1 => writing end file descriptor*/
for(i=0;i<5;i++){
while(pipe(fd1[i])!=0)
perror("ERROR ");
while(pipe(fd2[i])!=0)
perror("ERROR ");
child[i]=fork();
if(child[i]==0){
char *argv[8];
int j;
for (j = 0; j < 7; j++)
argv[j]=(char*)malloc(11*sizeof(char));
sprintf(argv[0],"%s","child");
sprintf(argv[1],"%s","child");
sprintf(argv[2],"%s%d%s","data_",i+1,".txt");
sprintf(argv[3],"%d",fd1[i][0]);
sprintf(argv[4],"%d",fd1[i][1]);
sprintf(argv[5],"%d",fd2[i][0]);
sprintf(argv[6],"%d",fd2[i][1]);
argv[7]=NULL;
if(execv(argv[0],argv)==-1)
perror("ERROR ");
}
}
//closing unused ends of pipe
for(i=0;i<5;i++){
close(fd1[i][0]);
close(fd2[i][1]);
}
//alloting id's to the children
for(i=0;i<5;i++){
char buf[MAX];
sprintf(buf,"%d",i+1);
writer(fd1[i],buf);
}
//waiting to receive READY signal from children
for(i=0;i<5;i++){
char buf[MAX];
reader(fd2[i],buf);
}
printf("Parent READY\n");
k=(n%2==0)?(n*5)/2-1:(n*5+1)/2-1;
// finding median
while(1){
// randomly asking for a pivot element from a child
do{
char bufr[MAX];
random_no = rand()%5;
printf("Parent sends REQUEST to child %d\n",random_no+1);
sprintf(bufr,"%d",REQUEST);
writer(fd1[random_no],bufr);
char bufw[MAX];
reader(fd2[random_no],bufw);
element=atoi(bufw);
printf("Parent receives PIVOT %d from child %d\n",element,random_no+1);
}while(element==-1);
//sending pivot element to each child
printf("Parent broadcasts PIVOT %d to all children\n",element);
for(i=0;i<5;i++){
char buf[MAX],sig[MAX];
sprintf(buf,"%d",element);
sprintf(sig,"%d",PIVOT);
writer(fd1[i],sig);
writer(fd1[i],buf);
}
//finding total no of elements larger than the current pivot among all the children
m=0;
for(i=0;i<5;i++){
char buf[MAX];
reader(fd2[i],buf);
response[i]=atoi(buf);
m+=response[i];
}
//.........这里部分代码省略.........
示例2: d_calloc
/**
* @brief SDSMemoryNode::reciveMns
* @param mns
*/
void SDSMemoryNode::reciveMns(char * message){
cout<<message<<endl;
Document doc;
doc.ParseInsitu(message);
if(doc.IsObject()){
if(doc.HasMember("protocolo")){
if(doc["protocolo"].IsString()){
string comando;
comando=doc["protocolo"].GetString();
if(comando=="d_calloc"){
if(doc.HasMember("pSize")){
if(doc["pSize"].IsInt()){
int pSize= doc["pSize"].GetInt();
d_calloc(pSize);
}
}
}
else if(comando=="d_status"){
d_status();
}
else{
d_pointer_size pointerSize;
if(doc.HasMember("dir")){
if(doc["dir"].IsInt()){
int pDir= doc["dir"].GetInt();
pointerSize.pointer.dirMemory=pDir;
}
}
if(doc.HasMember("pSize")){
if(doc["pSize"].IsInt()){
int pSize= doc["pSize"].GetInt();
pointerSize.bytes=pSize;
}
}
if(comando=="d_free"){
d_free(pointerSize);
}
else{
//Documento para en caso de que se quiera obtener el dato
StringBuffer s;
Writer<StringBuffer> writer(s);
writer.StartObject();
writer.String("dato");
int status;
bystream statusBystream;
if(doc.HasMember("tipo")){
if(doc["tipo"].IsString()){
string tipo= doc["tipo"].GetString();
if(tipo=="char"){
if(comando=="d_set"){
if(doc.HasMember("dato")){
if(doc["dato"].IsString()){
//Parsear a char
char pData =*(const_cast<char *>(doc["dato"].GetString()));
status= Manejador.setearDatoChar(pointerSize,pData);
}
}
}
if(comando=="d_get"){
statusBystream=Manejador.obtenerDatoChar(pointerSize);
writer.String(&(statusBystream.datachar));
}
}
else if(tipo=="int"){
if(comando=="d_set"){
if(doc.HasMember("dato")){
if(doc["dato"].IsInt()){
//Parsear a int
int pData =doc["dato"].GetInt();
status= Manejador.setearDatoInt(pointerSize,pData);
}
}
}
if(comando=="d_get"){
statusBystream=Manejador.obtenerDatoInt(pointerSize);
//.........这里部分代码省略.........
示例3: main
int main(int argc, char* argv[]) {
std::string output_filename;
static struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"output", required_argument, 0, 'o'},
{0, 0, 0, 0}
};
while (1) {
int c = getopt_long(argc, argv, "ho:", long_options, 0);
if (c == -1)
break;
switch (c) {
case 'h':
print_help();
exit(return_code_ok);
case 'o':
output_filename = optarg;
break;
default:
exit(return_code_fatal);
}
}
if (output_filename.empty()) {
std::cerr << "Missing -o/--output=OSMFILE option\n";
exit(return_code_cmdline);
}
if (optind != argc - 1) {
std::cerr << "Usage: osmcoastline_filter [OPTIONS] OSMFILE\n";
exit(return_code_cmdline);
}
osmium::io::Header header;
header.set("generator", "osmcoastline_filter");
header.add_box(osmium::Box(-180.0, -90.0, 180.0, 90.0));
osmium::io::File infile(argv[optind]);
try {
osmium::io::Writer writer(output_filename, header);
std::set<osmium::object_id_type> ids;
osmium::memory::Buffer output_buffer(10240);
{
osmium::io::Reader reader(infile, osmium::osm_entity_bits::way);
while (auto input_buffer = reader.read()) {
for (auto it = input_buffer.begin<const osmium::Way>(); it != input_buffer.end<const osmium::Way>(); ++it) {
const char* natural = it->get_value_by_key("natural");
if (natural && !strcmp(natural, "coastline")) {
output_buffer.add_item(*it);
output_buffer.commit();
if (output_buffer.committed() >= 10240) {
osmium::memory::Buffer new_buffer(10240);
std::swap(output_buffer, new_buffer);
writer(std::move(new_buffer));
}
for (const auto& nr : it->nodes()) {
ids.insert(nr.ref());
}
}
}
}
reader.close();
}
{
osmium::io::Reader reader(infile, osmium::osm_entity_bits::node);
while (auto input_buffer = reader.read()) {
for (auto it = input_buffer.begin<const osmium::Node>(); it != input_buffer.end<const osmium::Node>(); ++it) {
const char* natural = it->get_value_by_key("natural");
if ((ids.find(it->id()) != ids.end()) || (natural && !strcmp(natural, "coastline"))) {
output_buffer.add_item(*it);
output_buffer.commit();
if (output_buffer.committed() >= 10240) {
osmium::memory::Buffer new_buffer(10240);
std::swap(output_buffer, new_buffer);
writer(std::move(new_buffer));
}
}
}
}
reader.close();
}
if (output_buffer.committed() > 0) {
writer(std::move(output_buffer));
}
writer.close();
} catch (osmium::io_error& e) {
std::cerr << "io error: " << e.what() << "'\n";
exit(return_code_fatal);
}
google::protobuf::ShutdownProtobufLibrary();
//.........这里部分代码省略.........
示例4: printTo
size_t printTo(Print &print) const {
JsonWriter writer(print);
downcast().writeTo(writer);
return writer.bytesWritten();
}
示例5: stream
void WriterTest::testWriterOstreamConfig(void)
{
std::stringstream stream("");
Config config;
Writer writer(stream, config);
}
示例6: openFABMAP
//.........这里部分代码省略.........
//ensure not overwriting results
std::ifstream checker;
checker.open(resultsPath.c_str());
if(checker.is_open()) {
std::cerr << resultsPath << ": Results already present" << std::endl;
checker.close();
return -1;
}
//load the vocabulary
std::cout << "Loading Vocabulary" << std::endl;
fs.open(vocabPath, cv::FileStorage::READ);
cv::Mat vocab;
fs["Vocabulary"] >> vocab;
if (vocab.empty()) {
std::cerr << vocabPath << ": Vocabulary not found" << std::endl;
return -1;
}
fs.release();
//load the test data
fs.open(testPath, cv::FileStorage::READ);
cv::Mat testImageDescs;
fs["BOWImageDescs"] >> testImageDescs;
if(testImageDescs.empty()) {
std::cerr << testPath << ": Test data not found" << std::endl;
return -1;
}
fs.release();
//running openFABMAP
std::cout << "Running openFABMAP" << std::endl;
std::vector<of2::IMatch> matches;
std::vector<of2::IMatch>::iterator l;
cv::Mat confusion_mat(testImageDescs.rows, testImageDescs.rows, CV_64FC1);
confusion_mat.setTo(0); // init to 0's
if (!addNewOnly) {
//automatically comparing a whole dataset
fabmap->compare(testImageDescs, matches, true);
for(l = matches.begin(); l != matches.end(); l++) {
if(l->imgIdx < 0) {
confusion_mat.at<double>(l->queryIdx, l->queryIdx) = l->match;
} else {
confusion_mat.at<double>(l->queryIdx, l->imgIdx) = l->match;
}
}
} else {
//criteria for adding locations used
for(int i = 0; i < testImageDescs.rows; i++) {
matches.clear();
//compare images individually
fabmap->compare(testImageDescs.row(i), matches);
bool new_place_max = true;
for(l = matches.begin(); l != matches.end(); l++) {
if(l->imgIdx < 0) {
//add the new place to the confusion matrix 'diagonal'
confusion_mat.at<double>(i, matches.size()-1) = l->match;
} else {
//add the score to the confusion matrix
confusion_mat.at<double>(i, l->imgIdx) = l->match;
}
//test for new location maximum
if(l->match > matches.front().match) {
new_place_max = false;
}
}
if(new_place_max) {
fabmap->add(testImageDescs.row(i));
}
}
}
//save the result as plain text for ease of import to Matlab
std::ofstream writer(resultsPath.c_str());
for(int i = 0; i < confusion_mat.rows; i++) {
for(int j = 0; j < confusion_mat.cols; j++) {
writer << confusion_mat.at<double>(i, j) << " ";
}
writer << std::endl;
}
writer.close();
return 0;
}
示例7: main
int main(int argc, char **argv)
{
pugi::xml_document svg_xml;
TCLAP::UnlabeledValueArg<std::string> svg_filename( "svg_filename", "SVG file name", true, "", "PipelineFile" );
TCLAP::UnlabeledValueArg<std::string> vtu_filename( "vtu_filename", "SVG file name", true, "", "PipelineFile" );
try
{
TCLAP::CmdLine cmd("SVG to vtu converter", ' ', "1.0");
cmd.add( svg_filename );
cmd.add( vtu_filename );
cmd.parse( argc, argv );
pugi::xml_parse_result result = svg_xml.load_file( svg_filename.getValue().c_str() );
if (!result)
{
std::cerr << "Error loading or parsing XML file " << svg_filename.getValue().c_str() << std::endl;
std::cerr << "XML error: " << result.description() << std::endl;
return 0;
}
}
catch (TCLAP::ArgException &e) // catch any exceptions
{
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
}
MeshType mesh;
pugi::xml_node svg_node = svg_xml.child("svg");
pugi::xml_node g_node = svg_node.child("g");
for (pugi::xml_node path_node = g_node.child("path");
path_node;
path_node = path_node.next_sibling("path"))
{
std::string tmp = path_node.attribute("d").as_string();
std::cout << tmp << std::endl;
PointType translate = viennagrid::make_point(0,0);
pugi::xml_attribute transform_attribute = path_node.attribute("transform");
if ( !transform_attribute.empty() )
{
std::string transform_str = transform_attribute.as_string();
if (transform_str.find("translate") != std::string::npos)
{
// std::cout << "translate x = " << ) << std::endl;
// std::cout << "translate y = " << transform_str.substr( transform_str.find(",")+1, transform_str.find(")")-transform_str.find(",")-1 ) << std::endl;
double x = atof( transform_str.substr( transform_str.find("(")+1, transform_str.find(",")-transform_str.find("(")-1 ).c_str() );
double y = atof( transform_str.substr( transform_str.find(",")+1, transform_str.find(")")-transform_str.find(",")-1 ).c_str() );
translate = viennagrid::make_point(x,y);
}
else
{
std::cerr << transform_str << " is an invalid transform (currently only translate is supported)" << std::endl;
return 0;
}
}
add_svg_polyline(mesh, tmp, translate);
}
int fixes = 0;
do
{
MeshType tmp;
fixes = eliminate_nonconformities(mesh, tmp);
mesh = tmp;
std::cout << "Fix count = " << fixes << std::endl;
} while (fixes != 0);
std::string output_filename = vtu_filename.getValue().c_str();
if (output_filename.find(".vtu"))
output_filename = output_filename.substr( 0, output_filename.find(".vtu") );
if (output_filename.find(".pvd"))
output_filename = output_filename.substr( 0, output_filename.find(".pvd") );
viennagrid::io::vtk_writer<MeshType> writer;
writer(mesh, output_filename);
// viennamesh::context_handle context;
//
// viennamesh::algorithm_handle mesher = context.make_algorithm("triangle_make_mesh");
// mesher.set_input( "mesh", mesh.internal() );
// mesher.set_input("cell_size", 10.0);
// {
// viennamesh::LoggingStack s("tetgen_make_mesh");
//.........这里部分代码省略.........
示例8: dbName
void BenchmarkAnalogsReader::run(const int &groupNum, const int &analogsNum)
{
const QString dbName(QString::number(groupNum) + "_"
+ QString::number(analogsNum) + "_"
+ "_BAR_tdb");
const QString fileName(QString::number(groupNum) + "_"
+ QString::number(analogsNum) + "_"
+ "_BAR_tf.csv");
DataBaseInfo info;
info.setDataBaseName(dbName);
info.setUserName("root");
info.setPassword("1234");
QThread::msleep(100);
qInfo() << "-------Benchmark for write and read analogs-------";
qInfo() << groupNum << " groupNum, "
<< analogsNum << " analogsNum";
if(!DataBase::remDataBase(info))
{
qWarning() << "cannot remove test-db in begin of Benchmark";
return;
}
if(!TestUtility::removeFile(fileName))
{
qWarning() << "cannot remove test-file in begin of Benchmark";
return;
}
QList<ID> IdList;
{//запись в файл
AnalogsTable table = AnalogsTableGenerator::generateTable(groupNum,
analogsNum);
IdList = AnalogsTableGenerator::generateRandomIdList(table);
const bool isWritedToFile = CsvFile::write(table, fileName);
if(!isWritedToFile)
{
qWarning() << "cannot write table to file";
return;
}
}
QElapsedTimer timer;
bool isImported = false;
{//импорт из файла
AnalogsWriter writer(info);
timer.start();
isImported = writer.importFromFile(fileName);
qInfo() << "import from file " << timer.elapsed();
}
if(!isImported)
{
DataBase::remDataBase(info);
TestUtility::removeFile(fileName);
qWarning() << "cannot import from file";
return;
}
{//чтение из базы
AnalogsReader reader(info);
timer.start();
const AnalogsTable table = reader.fetch(IdList);
Q_UNUSED(table)
qInfo() << "read from db " << timer.elapsed();
}
if(!DataBase::remDataBase(info))
{
qWarning() << "cannot remove test-db in end of Benchmark";
return;
}
if(!TestUtility::removeFile(fileName))
{
qWarning() << "cannot remove test-file in end of Benchmark";
return;
}
qInfo() << "----End of benchmark for write and read analogs---" << endl;
}
示例9: kDebug
KoFilter::ConversionStatus EpubFile::writeOpf(KoStore *epubStore,
QHash<QString, QString> &metadata)
{
if (!epubStore->open(pathPrefix() + "content.opf")) {
kDebug(30503) << "Can not create content.opf .";
return KoFilter::CreationError;
}
KoStoreDevice opfDevice(epubStore);
KoXmlWriter writer(&opfDevice);
//FIXME: Write <?xml version="1.0"?> -> FIXED
writer.startDocument(NULL,NULL,NULL);
// FIXME: Get the unique identifier
writer.startElement("package");
writer.addAttribute("version", "2.0");
writer.addAttribute("xmlns", "http://www.idpf.org/2007/opf");
writer.addAttribute("xmlns:dc", "http://purl.org/dc/elements/1.1/");
writer.addAttribute("xmlns:opf", "http://www.idpf.org/2007/opf");
writer.addAttribute("unique-identifier", "BookId"); // FIXME: Where to get this?
// ==== metadata ====
writer.startElement("metadata");
// Required elements are: title, language and identifier
writer.startElement("dc:title");
writer.addTextNode(metadata.value("title"));
writer.endElement(); // dc:title
writer.startElement("meta");
writer.addAttribute("name", "cover");
writer.addAttribute("content", "cover-image");
writer.endElement();
writer.startElement("dc:language");
if (!metadata.value("language").isEmpty())
writer.addTextNode(metadata.value("language"));
else
writer.addTextNode("en");
writer.endElement(); // dc:language
writer.startElement("dc:identifier");
writer.addAttribute("id", "BookId");
writer.addAttribute("opf:scheme", "ISBN");
writer.addTextNode("123456789X"); // FIXME: Where to get this?
writer.endElement(); // dc:identifier
writer.startElement("dc:creator");
writer.addTextNode(metadata.value("creator")); // It's the "Author" profile name
writer.endElement(); // dc:creator
writer.startElement("dc:subject");
writer.addTextNode(""); // FIXME: Here should come suject info with form : Fiction & Fantasy & ...
writer.endElement(); // dc:subject
// FIXME: many more (optional)
writer.endElement(); // metadata
// ==== manifest ====
writer.startElement("manifest");
// Write manifest entry for each embedded file.
foreach(FileInfo *file, files()) {
// Since paths are relative from where this file is, remove
// the common prefix from the reference.
QString relativeFilename = file->m_fileName;
if (relativeFilename.startsWith(pathPrefix()))
relativeFilename = relativeFilename.right(relativeFilename.size()
- pathPrefix().size());
writer.startElement("item");
writer.addAttribute("id", file->m_id);
writer.addAttribute("href", relativeFilename);
writer.addAttribute("media-type", file->m_mimetype);
writer.endElement(); // item
}
示例10: root
void indri::api::Parameters::write( std::string& text ) {
std::auto_ptr<indri::xml::XMLNode> root( toXML() );
indri::xml::XMLWriter writer( root.get() );
writer.write( text );
}
示例11: writer
void
Config::save()
{
Writer writer("config");
writer.start_list("supertux-config");
writer.write("profile", profile);
writer.write("show_fps", show_fps);
writer.write("developer", developer_mode);
if(is_christmas()) {
writer.write("christmas", christmas_mode);
}
writer.write("transitions_enabled", transitions_enabled);
writer.write("locale", locale);
writer.start_list("video");
writer.write("fullscreen", use_fullscreen);
writer.write("video", VideoSystem::get_video_string(video));
writer.write("vsync", try_vsync);
writer.write("fullscreen_width", fullscreen_size.width);
writer.write("fullscreen_height", fullscreen_size.height);
writer.write("fullscreen_refresh_rate", fullscreen_refresh_rate);
writer.write("window_width", window_size.width);
writer.write("window_height", window_size.height);
writer.write("aspect_width", aspect_size.width);
writer.write("aspect_height", aspect_size.height);
writer.write("magnification", magnification);
writer.end_list("video");
writer.start_list("audio");
writer.write("sound_enabled", sound_enabled);
writer.write("music_enabled", music_enabled);
writer.end_list("audio");
writer.start_list("control");
{
writer.start_list("keymap");
keyboard_config.write(writer);
writer.end_list("keymap");
writer.start_list("joystick");
joystick_config.write(writer);
writer.end_list("joystick");
}
writer.end_list("control");
writer.start_list("addons");
for(auto addon : addons)
{
writer.start_list("addon");
writer.write("id", addon.id);
writer.write("enabled", addon.enabled);
writer.end_list("addon");
}
writer.end_list("addons");
writer.end_list("supertux-config");
}
示例12: reader
bool PointDLists::Editor::read(yarp::os::ConnectionReader& connection) {
if (!isValid()) return false;
yarp::os::idl::WireReader reader(connection);
reader.expectAccept();
if (!reader.readListHeader()) return false;
int len = reader.getLength();
if (len==0) {
yarp::os::idl::WireWriter writer(reader);
if (writer.isNull()) return true;
if (!writer.writeListHeader(1)) return false;
writer.writeString("send: 'help' or 'patch (param1 val1) (param2 val2)'");
return true;
}
std::string tag;
if (!reader.readString(tag)) return false;
if (tag=="help") {
yarp::os::idl::WireWriter writer(reader);
if (writer.isNull()) return true;
if (!writer.writeListHeader(2)) return false;
if (!writer.writeTag("many",1, 0)) return false;
if (reader.getLength()>0) {
std::string field;
if (!reader.readString(field)) return false;
if (field=="name") {
if (!writer.writeListHeader(1)) return false;
if (!writer.writeString("std::string name")) return false;
}
if (field=="firstList") {
if (!writer.writeListHeader(1)) return false;
if (!writer.writeString("std::vector<PointD> firstList")) return false;
}
if (field=="secondList") {
if (!writer.writeListHeader(1)) return false;
if (!writer.writeString("std::vector<PointD> secondList")) return false;
}
}
if (!writer.writeListHeader(4)) return false;
writer.writeString("*** Available fields:");
writer.writeString("name");
writer.writeString("firstList");
writer.writeString("secondList");
return true;
}
bool nested = true;
bool have_act = false;
if (tag!="patch") {
if ((len-1)%2 != 0) return false;
len = 1 + ((len-1)/2);
nested = false;
have_act = true;
}
for (int i=1; i<len; i++) {
if (nested && !reader.readListHeader(3)) return false;
std::string act;
std::string key;
if (have_act) {
act = tag;
} else {
if (!reader.readString(act)) return false;
}
if (!reader.readString(key)) return false;
// inefficient code follows, bug paulfitz to improve it
if (key == "name") {
will_set_name();
if (!obj->nested_read_name(reader)) return false;
did_set_name();
} else if (key == "firstList") {
will_set_firstList();
if (!obj->nested_read_firstList(reader)) return false;
did_set_firstList();
} else if (key == "secondList") {
will_set_secondList();
if (!obj->nested_read_secondList(reader)) return false;
did_set_secondList();
} else {
// would be useful to have a fallback here
}
}
reader.accept();
yarp::os::idl::WireWriter writer(reader);
if (writer.isNull()) return true;
writer.writeListHeader(1);
writer.writeVocab(VOCAB2('o','k'));
return true;
}
示例13: writer
bool PointDLists::write(yarp::os::ConnectionWriter& connection) const {
yarp::os::idl::WireWriter writer(connection);
if (!writer.writeListHeader(3)) return false;
return write(writer);
}
示例14: REQUEST_ECHO_TEXT
/// handles requests for EchoService
void EchoService::operator()(HTTPRequestPtr& request, TCPConnectionPtr& tcp_conn)
{
// this web service uses static text to test the mixture of "copied" with
// "static" (no-copy) text
static const std::string REQUEST_ECHO_TEXT("[Request Echo]");
static const std::string REQUEST_HEADERS_TEXT("[Request Headers]");
static const std::string QUERY_PARAMS_TEXT("[Query Parameters]");
static const std::string COOKIE_PARAMS_TEXT("[Cookie Parameters]");
static const std::string POST_CONTENT_TEXT("[POST Content]");
static const std::string USER_INFO_TEXT("[USER Info]");
// Set Content-type to "text/plain" (plain ascii text)
HTTPResponseWriterPtr writer(HTTPResponseWriter::create(tcp_conn, *request,
boost::bind(&TCPConnection::finish, tcp_conn)));
writer->getResponse().setContentType(HTTPTypes::CONTENT_TYPE_TEXT);
// write request information
writer->writeNoCopy(REQUEST_ECHO_TEXT);
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
writer
<< "Request method: "
<< request->getMethod()
<< HTTPTypes::STRING_CRLF
<< "Resource originally requested: "
<< request->getOriginalResource()
<< HTTPTypes::STRING_CRLF
<< "Resource delivered: "
<< request->getResource()
<< HTTPTypes::STRING_CRLF
<< "Query string: "
<< request->getQueryString()
<< HTTPTypes::STRING_CRLF
<< "HTTP version: "
<< request->getVersionMajor() << '.' << request->getVersionMinor()
<< HTTPTypes::STRING_CRLF
<< "Content length: "
<< (unsigned long)request->getContentLength()
<< HTTPTypes::STRING_CRLF
<< HTTPTypes::STRING_CRLF;
// write request headers
writer->writeNoCopy(REQUEST_HEADERS_TEXT);
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
std::for_each(request->getHeaders().begin(), request->getHeaders().end(),
boost::bind(&writeDictionaryTerm, writer, _1, false));
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
// write query parameters
writer->writeNoCopy(QUERY_PARAMS_TEXT);
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
std::for_each(request->getQueryParams().begin(), request->getQueryParams().end(),
boost::bind(&writeDictionaryTerm, writer, _1, true));
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
// write cookie parameters
writer->writeNoCopy(COOKIE_PARAMS_TEXT);
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
std::for_each(request->getCookieParams().begin(), request->getCookieParams().end(),
boost::bind(&writeDictionaryTerm, writer, _1, false));
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
// write POST content
writer->writeNoCopy(POST_CONTENT_TEXT);
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
if (request->getContentLength() != 0) {
writer->write(request->getContent(), request->getContentLength());
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
}
// if authenticated, write user info
PionUserPtr user = request->getUser();
if (user) {
writer->writeNoCopy(USER_INFO_TEXT);
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
writer << "User authenticated, username: " << user->getUsername();
writer->writeNoCopy(HTTPTypes::STRING_CRLF);
}
// send the writer
writer->send();
}
示例15: writer_init
void writer_init(void* arg) {
int ret = writer();
corethread_exit((void *)ret);
return;
}