blob: 641019a09ce7462632a6565db9dec8eb81f6e534 [file] [log] [blame]
Alex Vakulenkoae29f7d2015-12-21 16:30:37 -08001// Copyright 2016 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "common/binder_utils.h"
16
17#include <base/json/json_reader.h>
18#include <base/json/json_writer.h>
Alex Vakulenkoe9a83852016-01-28 14:34:04 -080019#include <weave/error.h>
Alex Vakulenkoae29f7d2015-12-21 16:30:37 -080020
21namespace weaved {
22namespace binder_utils {
23
24android::binder::Status ToStatus(bool success, weave::ErrorPtr* error) {
25 if (success)
26 return android::binder::Status::ok();
27 return android::binder::Status::fromServiceSpecificError(
28 1, android::String8{error->get()->GetMessage().c_str()});
29}
30
31bool StatusToError(android::binder::Status status, brillo::ErrorPtr* error) {
32 if (status.isOk())
33 return true;
34 brillo::Error::AddTo(error, FROM_HERE, "binder",
35 std::to_string(status.exceptionCode()),
36 status.exceptionMessage().string());
37 return false;
38}
39
40android::String16 ToString16(const base::Value& value) {
41 std::string json;
42 base::JSONWriter::Write(value, &json);
43 return ToString16(json);
44}
45
46android::binder::Status ParseDictionary(
47 const android::String16& json,
48 std::unique_ptr<base::DictionaryValue>* dict) {
49 int error = 0;
50 std::string message;
51 std::unique_ptr<base::Value> value{
52 base::JSONReader::ReadAndReturnError(ToString(json), base::JSON_PARSE_RFC,
53 &error, &message)
54 .release()};
55 base::DictionaryValue* dict_value = nullptr;
56 if (!value || !value->GetAsDictionary(&dict_value)) {
57 return android::binder::Status::fromServiceSpecificError(
58 error, android::String8{message.c_str()});
59 }
60 dict->reset(dict_value);
61 value.release(); // |dict| now owns the object.
62 return android::binder::Status::ok();
63}
64
65} // namespace binder_utils
66} // namespace weaved