blob: 2c5f8132eb17917c9573ceaba971e255641f4efa [file] [log] [blame]
Yifan Hong2272bf82017-04-28 14:37:56 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_VINTF_UTILS_H
18#define ANDROID_VINTF_UTILS_H
19
20#include <fstream>
21#include <iostream>
22#include <sstream>
23
24#include <android-base/logging.h>
25#include <utils/Errors.h>
26
27#include "parse_xml.h"
28
29namespace android {
30namespace vintf {
31namespace details {
32
Michael Schwartz97dc0f92017-05-08 14:07:14 -070033// Return the file from the given location as a string.
34//
35// This class can be used to create a mock for overriding.
36class FileFetcher {
37 public:
38 virtual ~FileFetcher() {}
39 virtual status_t fetch(const std::string& path, std::string& fetched) {
40 std::ifstream in;
41
42 in.open(path);
43 if (!in.is_open()) {
44 LOG(WARNING) << "Cannot open " << path;
45 return INVALID_OPERATION;
46 }
47
48 std::stringstream ss;
49 ss << in.rdbuf();
50 fetched = ss.str();
51
52 return OK;
Yifan Hong2272bf82017-04-28 14:37:56 -070053 }
Michael Schwartz97dc0f92017-05-08 14:07:14 -070054};
55
56extern FileFetcher* gFetcher;
57
58template <typename T>
59status_t fetchAllInformation(const std::string& path, const XmlConverter<T>& converter,
60 T* outObject) {
61 std::string info;
62
63 if (gFetcher == nullptr) {
64 // Should never happen.
65 return NO_INIT;
66 }
67
68 status_t result = gFetcher->fetch(path, info);
69
70 if (result != OK) {
71 return result;
72 }
73
74 bool success = converter(outObject, info);
Yifan Hong2272bf82017-04-28 14:37:56 -070075 if (!success) {
76 LOG(ERROR) << "Illformed file: " << path << ": "
77 << converter.lastError();
78 return BAD_VALUE;
79 }
80 return OK;
81}
82
83} // namespace details
84} // namespace vintf
85} // namespace android
86
87
88
89#endif