1// Copyright (c) 2012 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. 4 5#include "chrome/test/chromedriver/net/net_util.h" 6 7#include "base/basictypes.h" 8#include "base/bind.h" 9#include "base/bind_helpers.h" 10#include "base/compiler_specific.h" 11#include "base/memory/scoped_ptr.h" 12#include "base/message_loop/message_loop.h" 13#include "base/strings/stringprintf.h" 14#include "base/synchronization/waitable_event.h" 15#include "chrome/test/chromedriver/net/url_request_context_getter.h" 16#include "net/url_request/url_fetcher.h" 17#include "net/url_request/url_fetcher_delegate.h" 18#include "url/gurl.h" 19 20namespace { 21 22class SyncUrlFetcher : public net::URLFetcherDelegate { 23 public: 24 SyncUrlFetcher(const GURL& url, 25 URLRequestContextGetter* getter, 26 std::string* response) 27 : url_(url), getter_(getter), response_(response), event_(false, false) {} 28 29 virtual ~SyncUrlFetcher() {} 30 31 bool Fetch() { 32 getter_->GetNetworkTaskRunner()->PostTask( 33 FROM_HERE, 34 base::Bind(&SyncUrlFetcher::FetchOnIOThread, base::Unretained(this))); 35 event_.Wait(); 36 return success_; 37 } 38 39 void FetchOnIOThread() { 40 fetcher_.reset(net::URLFetcher::Create(url_, net::URLFetcher::GET, this)); 41 fetcher_->SetRequestContext(getter_); 42 fetcher_->Start(); 43 } 44 45 virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE { 46 success_ = (source->GetResponseCode() == 200); 47 if (success_) 48 success_ = source->GetResponseAsString(response_); 49 fetcher_.reset(); // Destroy the fetcher on IO thread. 50 event_.Signal(); 51 } 52 53 private: 54 GURL url_; 55 URLRequestContextGetter* getter_; 56 std::string* response_; 57 base::WaitableEvent event_; 58 scoped_ptr<net::URLFetcher> fetcher_; 59 bool success_; 60}; 61 62} // namespace 63 64NetAddress::NetAddress() : port_(-1) {} 65 66NetAddress::NetAddress(int port) : host_("127.0.0.1"), port_(port) {} 67 68NetAddress::NetAddress(const std::string& host, int port) 69 : host_(host), port_(port) {} 70 71NetAddress::~NetAddress() {} 72 73bool NetAddress::IsValid() const { 74 return port_ >= 0 && port_ < (1 << 16); 75} 76 77std::string NetAddress::ToString() const { 78 return host_ + base::StringPrintf(":%d", port_); 79} 80 81const std::string& NetAddress::host() const { 82 return host_; 83} 84 85int NetAddress::port() const { 86 return port_; 87} 88 89bool FetchUrl(const std::string& url, 90 URLRequestContextGetter* getter, 91 std::string* response) { 92 return SyncUrlFetcher(GURL(url), getter, response).Fetch(); 93} 94