summaryrefslogtreecommitdiffstats
path: root/remoting/host/json_host_config.cc
blob: 1f22adf5ef03da50561d657f36337c3f0b24b3e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/host/json_host_config.h"

#include "base/bind.h"
#include "base/file_util.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/location.h"
#include "base/memory/scoped_ptr.h"
#include "base/values.h"

namespace remoting {

JsonHostConfig::JsonHostConfig(const FilePath& filename)
    : filename_(filename) {
}

JsonHostConfig::~JsonHostConfig() {}

bool JsonHostConfig::Read() {
  DCHECK(CalledOnValidThread());

  // TODO(sergeyu): Implement better error handling here.
  std::string file_content;
  if (!file_util::ReadFileToString(filename_, &file_content)) {
    LOG(WARNING) << "Failed to read " << filename_.value();
    return false;
  }

  scoped_ptr<Value> value(
      base::JSONReader::Read(file_content, base::JSON_ALLOW_TRAILING_COMMAS));
  if (value.get() == NULL || !value->IsType(Value::TYPE_DICTIONARY)) {
    LOG(WARNING) << "Failed to parse " << filename_.value();
    return false;
  }

  DictionaryValue* dictionary = static_cast<DictionaryValue*>(value.release());
  values_.reset(dictionary);
  return true;
}

bool JsonHostConfig::Save() {
  DCHECK(CalledOnValidThread());

  std::string file_content = GetSerializedData();
  // TODO(sergeyu): Move ImportantFileWriter to base and use it here.
  int result = file_util::WriteFile(filename_, file_content.data(),
                                    file_content.size());
  return result == static_cast<int>(file_content.size());
}

std::string JsonHostConfig::GetSerializedData() {
  std::string data;
  base::JSONWriter::Write(values_.get(), &data);
  return data;
}

}  // namespace remoting