1// Copyright (c) 2011 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 "net/socket_stream/socket_stream_job_manager.h"
6
7#include "base/memory/singleton.h"
8
9namespace net {
10
11SocketStreamJobManager::SocketStreamJobManager() {
12}
13
14SocketStreamJobManager::~SocketStreamJobManager() {
15}
16
17// static
18SocketStreamJobManager* SocketStreamJobManager::GetInstance() {
19  return Singleton<SocketStreamJobManager>::get();
20}
21
22SocketStreamJob* SocketStreamJobManager::CreateJob(
23    const GURL& url, SocketStream::Delegate* delegate) const {
24  // If url is invalid, create plain SocketStreamJob, which will close
25  // the socket immediately.
26  if (!url.is_valid()) {
27    SocketStreamJob* job = new SocketStreamJob();
28    job->InitSocketStream(new SocketStream(url, delegate));
29    return job;
30  }
31
32  const std::string& scheme = url.scheme();  // already lowercase
33
34  base::AutoLock locked(lock_);
35  FactoryMap::const_iterator found = factories_.find(scheme);
36  if (found != factories_.end()) {
37    SocketStreamJob* job = found->second(url, delegate);
38    if (job)
39      return job;
40  }
41  SocketStreamJob* job = new SocketStreamJob();
42  job->InitSocketStream(new SocketStream(url, delegate));
43  return job;
44}
45
46SocketStreamJob::ProtocolFactory*
47SocketStreamJobManager::RegisterProtocolFactory(
48    const std::string& scheme, SocketStreamJob::ProtocolFactory* factory) {
49  base::AutoLock locked(lock_);
50
51  SocketStreamJob::ProtocolFactory* old_factory;
52  FactoryMap::iterator found = factories_.find(scheme);
53  if (found != factories_.end()) {
54    old_factory = found->second;
55  } else {
56    old_factory = NULL;
57  }
58  if (factory) {
59    factories_[scheme] = factory;
60  } else if (found != factories_.end()) {
61    factories_.erase(found);
62  }
63  return old_factory;
64}
65
66}  // namespace net
67