1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "third_party/libaddressinput/chromium/chrome_downloader_impl.h"
7 #include "base/logging.h"
8 #include "base/memory/scoped_ptr.h"
9 #include "net/base/io_buffer.h"
10 #include "net/base/load_flags.h"
11 #include "net/base/net_errors.h"
12 #include "net/http/http_status_code.h"
13 #include "net/url_request/url_fetcher.h"
14 #include "net/url_request/url_fetcher_response_writer.h"
21 // A URLFetcherResponseWriter that writes into a provided buffer.
22 class UnownedStringWriter
: public net::URLFetcherResponseWriter
{
24 UnownedStringWriter(std::string
* data
) : data_(data
) {}
25 virtual ~UnownedStringWriter() {}
27 virtual int Initialize(const net::CompletionCallback
& callback
) OVERRIDE
{
32 virtual int Write(net::IOBuffer
* buffer
,
34 const net::CompletionCallback
& callback
) OVERRIDE
{
35 data_
->append(buffer
->data(), num_bytes
);
39 virtual int Finish(const net::CompletionCallback
& callback
) OVERRIDE
{
44 std::string
* data_
; // weak reference.
46 DISALLOW_COPY_AND_ASSIGN(UnownedStringWriter
);
51 ChromeDownloaderImpl::ChromeDownloaderImpl(net::URLRequestContextGetter
* getter
)
54 ChromeDownloaderImpl::~ChromeDownloaderImpl() {
55 STLDeleteValues(&requests_
);
58 void ChromeDownloaderImpl::Download(const std::string
& url
,
59 const Callback
& downloaded
) const {
60 const_cast<ChromeDownloaderImpl
*>(this)->DoDownload(url
, downloaded
);
63 void ChromeDownloaderImpl::OnURLFetchComplete(const net::URLFetcher
* source
) {
64 std::map
<const net::URLFetcher
*, Request
*>::iterator request
=
65 requests_
.find(source
);
66 DCHECK(request
!= requests_
.end());
68 bool ok
= source
->GetResponseCode() == net::HTTP_OK
;
69 scoped_ptr
<std::string
> data(new std::string());
71 data
->swap(request
->second
->data
);
72 request
->second
->callback(ok
, request
->second
->url
, data
.release());
74 delete request
->second
;
75 requests_
.erase(request
);
78 ChromeDownloaderImpl::Request::Request(const std::string
& url
,
79 scoped_ptr
<net::URLFetcher
> fetcher
,
80 const Callback
& callback
)
82 fetcher(fetcher
.Pass()),
85 void ChromeDownloaderImpl::DoDownload(const std::string
& url
,
86 const Callback
& downloaded
) {
88 if (!resource
.SchemeIsSecure()) {
89 downloaded(false, url
, NULL
);
93 scoped_ptr
<net::URLFetcher
> fetcher(
94 net::URLFetcher::Create(resource
, net::URLFetcher::GET
, this));
95 fetcher
->SetLoadFlags(
96 net::LOAD_DO_NOT_SEND_COOKIES
| net::LOAD_DO_NOT_SAVE_COOKIES
);
97 fetcher
->SetRequestContext(getter_
);
99 Request
* request
= new Request(url
, fetcher
.Pass(), downloaded
);
100 request
->fetcher
->SaveResponseWithWriter(
101 scoped_ptr
<net::URLFetcherResponseWriter
>(
102 new UnownedStringWriter(&request
->data
)));
103 requests_
[request
->fetcher
.get()] = request
;
104 request
->fetcher
->Start();
107 } // namespace autofill