1// Copyright 2014 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <brillo/dbus/dbus_method_response.h>
6
7#include <brillo/dbus/utils.h>
8
9namespace brillo {
10namespace dbus_utils {
11
12DBusMethodResponseBase::DBusMethodResponseBase(dbus::MethodCall* method_call,
13                                               ResponseSender sender)
14    : sender_(sender), method_call_(method_call) {
15}
16
17DBusMethodResponseBase::~DBusMethodResponseBase() {
18  if (method_call_) {
19    // Response hasn't been sent by the handler. Abort the call.
20    Abort();
21  }
22}
23
24void DBusMethodResponseBase::ReplyWithError(const brillo::Error* error) {
25  CheckCanSendResponse();
26  auto response = GetDBusError(method_call_, error);
27  SendRawResponse(std::move(response));
28}
29
30void DBusMethodResponseBase::ReplyWithError(
31    const tracked_objects::Location& location,
32    const std::string& error_domain,
33    const std::string& error_code,
34    const std::string& error_message) {
35  ErrorPtr error;
36  Error::AddTo(&error, location, error_domain, error_code, error_message);
37  ReplyWithError(error.get());
38}
39
40void DBusMethodResponseBase::Abort() {
41  SendRawResponse(std::unique_ptr<dbus::Response>());
42}
43
44void DBusMethodResponseBase::SendRawResponse(
45    std::unique_ptr<dbus::Response> response) {
46  CheckCanSendResponse();
47  method_call_ = nullptr;  // Mark response as sent.
48  sender_.Run(std::move(response));
49}
50
51std::unique_ptr<dbus::Response>
52DBusMethodResponseBase::CreateCustomResponse() const {
53  return dbus::Response::FromMethodCall(method_call_);
54}
55
56bool DBusMethodResponseBase::IsResponseSent() const {
57  return (method_call_ == nullptr);
58}
59
60void DBusMethodResponseBase::CheckCanSendResponse() const {
61  CHECK(method_call_) << "Response already sent";
62}
63
64}  // namespace dbus_utils
65}  // namespace brillo
66