$darkmode
resource_handler.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2020 Robert Bosch GmbH
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  * SPDX-License-Identifier: Apache-2.0
17  */
22 #pragma once
23 
24 #include <fstream>
25 #include <string> // for string
26 
27 #include <cloe/handler.hpp> // for Request, Response
28 #include <cloe/utility/resource.hpp> // for ResourceHandler
29 
30 #ifndef NDEBUG
31 #include <cloe/core.hpp> // for Logger
32 #endif
33 
34 #define RESOURCE_HANDLER(resource, ct) ::cloe::utility::ResourceHandler(RESOURCE(resource), ct)
35 #define RESOURCE_LOADER(resource) ::cloe::utility::ResourceLoader(RESOURCE(resource))
36 
37 namespace cloe {
38 namespace utility {
39 
46  public:
47  explicit ResourceLoader(Resource r) : res_(r) {}
48 
49  std::string to_string() const {
50 #ifndef NDEBUG
51  // Check if the file given in path exists, and if so, load it.
52  std::ifstream ifs{res_.filepath()};
53  std::string data;
54  if (ifs.is_open()) {
55  data = static_cast<std::stringstream const&>(std::stringstream() << ifs.rdbuf()).str();
56  } else {
57  logger::get("cloe")->warn("File does not exist: {}", res_.filepath());
58  data = res_.to_string();
59  }
60  return data;
61 #else
62  return res_.to_string();
63 #endif
64  }
65 
66  friend void to_json(cloe::Json& j, const ResourceLoader& c);
67 
68  private:
69  Resource res_;
70 };
71 
73  public:
74  ResourceHandler(Resource r, ContentType t) : resl_(r), type_(t) {}
75  void operator()(const Request&, Response& r) { r.set_body(resl_.to_string(), type_); }
76 
77  private:
78  ResourceLoader resl_;
79  ContentType type_;
80 };
81 
87 void to_json(cloe::Json& j, const ResourceLoader& c) {
88  try {
89  j = fable::parse_json(c.to_string());
90  } catch (cloe::Json::type_error& e) {
91  j = {c.res_.filepath(), c.to_string()};
92  }
93 }
94 
95 } // namespace utility
96 } // namespace cloe
Definition: resource.hpp:53
Definition: handler.hpp:94
Definition: handler.hpp:196
void set_body(const std::string &s, ContentType type)
Definition: handler.hpp:264
Definition: resource_handler.hpp:72
Definition: resource_handler.hpp:45
friend void to_json(cloe::Json &j, const ResourceLoader &c)
Definition: resource_handler.hpp:87
ContentType
Definition: handler.hpp:71