blob: 6f660401ab26f8dba55ff31cf8b7c621a8a8e63d [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>
19
20namespace weaved {
21namespace binder_utils {
22
23android::binder::Status ToStatus(bool success, weave::ErrorPtr* error) {
24 if (success)
25 return android::binder::Status::ok();
26 return android::binder::Status::fromServiceSpecificError(
27 1, android::String8{error->get()->GetMessage().c_str()});
28}
29
30bool StatusToError(android::binder::Status status, brillo::ErrorPtr* error) {
31 if (status.isOk())
32 return true;
33 brillo::Error::AddTo(error, FROM_HERE, "binder",
34 std::to_string(status.exceptionCode()),
35 status.exceptionMessage().string());
36 return false;
37}
38
39android::String16 ToString16(const base::Value& value) {
40 std::string json;
41 base::JSONWriter::Write(value, &json);
42 return ToString16(json);
43}
44
45android::binder::Status ParseDictionary(
46 const android::String16& json,
47 std::unique_ptr<base::DictionaryValue>* dict) {
48 int error = 0;
49 std::string message;
50 std::unique_ptr<base::Value> value{
51 base::JSONReader::ReadAndReturnError(ToString(json), base::JSON_PARSE_RFC,
52 &error, &message)
53 .release()};
54 base::DictionaryValue* dict_value = nullptr;
55 if (!value || !value->GetAsDictionary(&dict_value)) {
56 return android::binder::Status::fromServiceSpecificError(
57 error, android::String8{message.c_str()});
58 }
59 dict->reset(dict_value);
60 value.release(); // |dict| now owns the object.
61 return android::binder::Status::ok();
62}
63
64} // namespace binder_utils
65} // namespace weaved