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 
9 namespace brillo {
10 namespace dbus_utils {
11 
DBusMethodResponseBase(dbus::MethodCall * method_call,ResponseSender sender)12 DBusMethodResponseBase::DBusMethodResponseBase(dbus::MethodCall* method_call,
13                                                ResponseSender sender)
14     : sender_(sender), method_call_(method_call) {
15 }
16 
~DBusMethodResponseBase()17 DBusMethodResponseBase::~DBusMethodResponseBase() {
18   if (method_call_) {
19     // Response hasn't been sent by the handler. Abort the call.
20     Abort();
21   }
22 }
23 
ReplyWithError(const brillo::Error * error)24 void DBusMethodResponseBase::ReplyWithError(const brillo::Error* error) {
25   CheckCanSendResponse();
26   auto response = GetDBusError(method_call_, error);
27   SendRawResponse(std::move(response));
28 }
29 
ReplyWithError(const tracked_objects::Location & location,const std::string & error_domain,const std::string & error_code,const std::string & error_message)30 void 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 
Abort()40 void DBusMethodResponseBase::Abort() {
41   SendRawResponse(std::unique_ptr<dbus::Response>());
42 }
43 
SendRawResponse(std::unique_ptr<dbus::Response> response)44 void DBusMethodResponseBase::SendRawResponse(
45     std::unique_ptr<dbus::Response> response) {
46   CheckCanSendResponse();
47   method_call_ = nullptr;  // Mark response as sent.
48   sender_.Run(scoped_ptr<dbus::Response>{response.release()});
49 }
50 
51 std::unique_ptr<dbus::Response>
CreateCustomResponse() const52 DBusMethodResponseBase::CreateCustomResponse() const {
53   return std::unique_ptr<dbus::Response>{
54       dbus::Response::FromMethodCall(method_call_).release()};
55 }
56 
IsResponseSent() const57 bool DBusMethodResponseBase::IsResponseSent() const {
58   return (method_call_ == nullptr);
59 }
60 
CheckCanSendResponse() const61 void DBusMethodResponseBase::CheckCanSendResponse() const {
62   CHECK(method_call_) << "Response already sent";
63 }
64 
65 }  // namespace dbus_utils
66 }  // namespace brillo
67