post_request_json.cc 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright (C) 2016 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. #include <http/post_request_json.h>
  7. using namespace isc::data;
  8. namespace isc {
  9. namespace http {
  10. PostHttpRequestJson::PostHttpRequestJson()
  11. : PostHttpRequest(), json_() {
  12. requireHeaderValue("Content-Type", "application/json");
  13. }
  14. void
  15. PostHttpRequestJson::finalize() {
  16. if (!created_) {
  17. create();
  18. }
  19. // Parse JSON body and store.
  20. parseBodyAsJson();
  21. finalized_ = true;
  22. }
  23. void
  24. PostHttpRequestJson::reset() {
  25. PostHttpRequest::reset();
  26. json_.reset();
  27. }
  28. ConstElementPtr
  29. PostHttpRequestJson::getBodyAsJson() {
  30. checkFinalized();
  31. return (json_);
  32. }
  33. ConstElementPtr
  34. PostHttpRequestJson::getJsonElement(const std::string& element_name) {
  35. typedef std::map<std::string, ConstElementPtr> MapElementType;
  36. try {
  37. ConstElementPtr body = getBodyAsJson();
  38. if (body) {
  39. const MapElementType& map_value = body->mapValue();
  40. MapElementType::const_iterator map_element =
  41. map_value.find(element_name);
  42. if (map_element != map_value.end()) {
  43. return (map_element->second);
  44. }
  45. }
  46. } catch (const std::exception& ex) {
  47. isc_throw(HttpRequestJsonError, "unable to get JSON element "
  48. << element_name << ": " << ex.what());
  49. }
  50. return (ConstElementPtr());
  51. }
  52. void
  53. PostHttpRequestJson::parseBodyAsJson() {
  54. try {
  55. // Only parse the body if it hasn't been parsed yet.
  56. if (!json_ && !context_->body_.empty()) {
  57. json_ = Element::fromJSON(context_->body_);
  58. }
  59. } catch (const std::exception& ex) {
  60. isc_throw(HttpRequestJsonError, "unable to parse the body of the HTTP"
  61. " request: " << ex.what());
  62. }
  63. }
  64. } // namespace http
  65. } // namespace isc