OSDN Git Service

Session load and save.
[fukui-no-namari/dialektos.git] / src / http_get.cxx
1 /*
2  * Copyright (C) 2009 by Aiwota Programmer
3  * aiwotaprog@tetteke.tk
4  *
5  * This file is part of Dialektos.
6  *
7  * Dialektos is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * Dialektos is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with Dialektos.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21
22 #include "http_get.hxx"
23
24 #include <sigc++/functors/mem_fun.h>
25 #include <boost/asio/io_service.hpp>
26 #include <boost/thread/locks.hpp>
27 #include <boost/thread/thread.hpp>
28 #include <boost/function.hpp>
29 #include <string>
30 #include "http_client.hxx"
31
32
33 namespace dialektos {
34
35 namespace http {
36
37
38 GetInThread::GetInThread(const std::string& uri,
39     const Header& request_header) :
40       dispatcher_(), signal_end_(),
41       mutex_(), cancel_(false), thread_(),
42       uri_(uri), request_header_(request_header), response_(), err_(),
43       io_service_() {
44   dispatcher_.connect(sigc::mem_fun(*this, &GetInThread::on_end_dispather));
45 }
46
47 GetInThread::~GetInThread() {
48   if (thread_) {
49     cancel();
50     thread_->join();
51   }
52 }
53
54 void GetInThread::cancel() {
55   boost::mutex::scoped_lock lock(mutex_);
56   if (io_service_) {
57     io_service_->stop();
58     cancel_ = true;
59   }
60 }
61
62 bool GetInThread::run() {
63   if (thread_) return false;
64   thread_.reset(new boost::thread(boost::ref(*this)));
65   return true;
66 }
67
68 namespace {
69 struct ScopeExit {
70   ScopeExit(boost::function<void ()> f) : function(f) {}
71   ~ScopeExit() { function(); }
72   boost::function<void ()> function;
73 };
74 }
75
76 void GetInThread::operator()() {
77   ScopeExit scope_exit(boost::ref(dispatcher_));
78   {
79     boost::mutex::scoped_lock lock(mutex_);
80     io_service_.reset(new boost::asio::io_service);
81   }
82   AsyncClient client(*io_service_, uri_, request_header_);
83   io_service_->run();
84   response_.reset(new Response(client.get_response()));
85   err_ = client.get_error();
86 }
87
88 void GetInThread::on_end_dispather() {
89   thread_.reset(0);
90   io_service_.reset(0);
91   signal_end_(!cancel_);
92 }
93
94
95 } // namespace http
96
97 } // namespace dialektos