<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

#include <TChain.h>
#include <TFile.h>

#include "AliTender.h"
#include "AliTenderSupply.h"
#include "AliAnalysisManager.h"
#include "AliCDBManager.h"
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"
#include "AliLog.h"

ClassImp(AliTender)

//______________________________________________________________________________
AliTender::AliTender():
           AliAnalysisTask(),
           fDebug(0),
           fRun(0),
           fRunChanged(kFALSE),
           fCDBkey(0),
           fDefaultStorage(),
           fCDB(NULL),
           fESDhandler(NULL),
           fESD(NULL),
           fSupplies(NULL)
{
// Dummy constructor
}

//______________________________________________________________________________
AliTender::AliTender(const char* name):
           AliAnalysisTask(name, "ESD analysis tender car"),
           fDebug(0),
           fRun(0),
           fRunChanged(kFALSE),
           fCDBkey(0),
           fDefaultStorage(),
           fCDB(NULL),
           fESDhandler(NULL),
           fESD(NULL),
           fSupplies(NULL)
{
// Default constructor
  DefineInput (0, TChain::Class());
  DefineOutput(0,  AliESDEvent::Class());
}

//______________________________________________________________________________
AliTender::~AliTender()
{
// Destructor
  if (fSupplies) {
    fSupplies->Delete();
    delete fSupplies;
  }
}

//______________________________________________________________________________
void AliTender::AddSupply(AliTenderSupply *supply)
{
// Addition of supplies.
  if (!fSupplies) fSupplies = new TObjArray();
  if (fSupplies->FindObject(supply)) {
     Error("AddSupply", "Tender supply %s already connected.", supply->GetName());
     return;
  }
  fSupplies->Add(supply);
  supply->SetTender(this);
}

//______________________________________________________________________________
void AliTender::ConnectInputData(Option_t* /*option*/)
{
// Connect the input data, create CDB manager.
  if (fDebug > 1) Printf("AliTender::ConnectInputData()\n");
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) AliFatal("No tender without an analysis manager");
  fESDhandler = dynamic_cast<AliESDInputHandler *>(mgr->GetInputEventHandler());

  if (fESDhandler) {
     fESD = fESDhandler->GetEvent();
  } else {
     AliFatal("No ESD input event handler connected") ;
  }
  // Create CDB manager
  if (!fDefaultStorage.Length()) AliFatal("Default CDB storage not set.");
  fCDB = AliCDBManager::Instance();
  // SetDefault storage. Specific storages must be set by AliTenderSupply::Init()
  fCDB->SetDefaultStorage(fDefaultStorage);
  fRun = fESD->GetRunNumber();
  // Unlock CDB
  fCDBkey = fCDB->SetLock(kFALSE, fCDBkey);
  fCDB->SetRun(fRun);
  TIter next(fSupplies);
  AliTenderSupply *supply;
  while ((supply=(AliTenderSupply*)next())) supply->Init();
  // Lock CDB
  fCDBkey = fCDB->SetLock(kTRUE, fCDBkey);
}

//______________________________________________________________________________
void AliTender::CreateOutputObjects()
{
// Nothing for the moment, but we may need ESD event replication here.
  if (fDebug > 1) Printf("AliTender::CreateOutputObjects()\n");
}

//______________________________________________________________________________
void AliTender::Exec(Option_t* /*option*/)
{
//
// Execute all supplied analysis of one event. Notify run change via RunChanged().
  if (fDebug > 1) {
    Long_t entry = fESDhandler->GetReadEntry();
    Printf("AliTender::Exec() %s ==> processing event %lld\n", fESDhandler->GetTree()->GetCurrentFile()->GetName(),entry);
  }
  fESD = fESDhandler->GetEvent();

// Call the user analysis
  // Unlock CDB
  fCDBkey = fCDB->SetLock(kFALSE, fCDBkey);
  // Intercept when the run number changed
  if (fRun != fESD->GetRunNumber()) {
    fRunChanged = kTRUE;
    fRun = fESD->GetRunNumber();
    fCDB->SetRun(fRun);
  }
  TIter next(fSupplies);
  AliTenderSupply *supply;
  while ((supply=(AliTenderSupply*)next())) supply->ProcessEvent();
  fRunChanged = kFALSE;
  // Lock CDB
  fCDBkey = fCDB->SetLock(kTRUE, fCDBkey);
  PostData(0, fESD);
}

//______________________________________________________________________________
void AliTender::SetDefaultCDBStorage(const char *dbString)
{
// Set default CDB storage
   fDefaultStorage = dbString;
}
<commit_msg>Initialization of variable fixed<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

#include <TChain.h>
#include <TFile.h>

#include "AliTender.h"
#include "AliTenderSupply.h"
#include "AliAnalysisManager.h"
#include "AliCDBManager.h"
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"
#include "AliLog.h"

ClassImp(AliTender)

//______________________________________________________________________________
AliTender::AliTender():
           AliAnalysisTask(),
           fDebug(0),
           fRun(0),
           fRunChanged(kFALSE),
           fCDBkey(0),
           fDefaultStorage(),
           fCDB(NULL),
           fESDhandler(NULL),
           fESD(NULL),
           fSupplies(NULL),
           fCDBSettings(NULL)
{
// Dummy constructor
}

//______________________________________________________________________________
AliTender::AliTender(const char* name):
           AliAnalysisTask(name, "ESD analysis tender car"),
           fDebug(0),
           fRun(0),
           fRunChanged(kFALSE),
           fCDBkey(0),
           fDefaultStorage(),
           fCDB(NULL),
           fESDhandler(NULL),
           fESD(NULL),
           fSupplies(NULL),
           fCDBSettings(NULL)
{
// Default constructor
  DefineInput (0, TChain::Class());
  DefineOutput(0,  AliESDEvent::Class());
}

//______________________________________________________________________________
AliTender::~AliTender()
{
// Destructor
  if (fSupplies) {
    fSupplies->Delete();
    delete fSupplies;
  }
}

//______________________________________________________________________________
void AliTender::AddSupply(AliTenderSupply *supply)
{
// Addition of supplies.
  if (!fSupplies) fSupplies = new TObjArray();
  if (fSupplies->FindObject(supply)) {
     Error("AddSupply", "Tender supply %s already connected.", supply->GetName());
     return;
  }
  fSupplies->Add(supply);
  supply->SetTender(this);
}

//______________________________________________________________________________
void AliTender::ConnectInputData(Option_t* /*option*/)
{
// Connect the input data, create CDB manager.
  if (fDebug > 1) Printf("AliTender::ConnectInputData()\n");
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) AliFatal("No tender without an analysis manager");
  fESDhandler = dynamic_cast<AliESDInputHandler *>(mgr->GetInputEventHandler());

  if (fESDhandler) {
     fESD = fESDhandler->GetEvent();
  } else {
     AliFatal("No ESD input event handler connected") ;
  }
  // Create CDB manager
  if (!fDefaultStorage.Length()) AliFatal("Default CDB storage not set.");
  fCDB = AliCDBManager::Instance();
  // SetDefault storage. Specific storages must be set by AliTenderSupply::Init()
  fCDB->SetDefaultStorage(fDefaultStorage);
  fRun = fESD->GetRunNumber();
  // Unlock CDB
  fCDBkey = fCDB->SetLock(kFALSE, fCDBkey);
  fCDB->SetRun(fRun);
  TIter next(fSupplies);
  AliTenderSupply *supply;
  while ((supply=(AliTenderSupply*)next())) supply->Init();
  // Lock CDB
  fCDBkey = fCDB->SetLock(kTRUE, fCDBkey);
}

//______________________________________________________________________________
void AliTender::CreateOutputObjects()
{
// Nothing for the moment, but we may need ESD event replication here.
  if (fDebug > 1) Printf("AliTender::CreateOutputObjects()\n");
}

//______________________________________________________________________________
void AliTender::Exec(Option_t* /*option*/)
{
//
// Execute all supplied analysis of one event. Notify run change via RunChanged().
  if (fDebug > 1) {
    Long_t entry = fESDhandler->GetReadEntry();
    Printf("AliTender::Exec() %s ==> processing event %lld\n", fESDhandler->GetTree()->GetCurrentFile()->GetName(),entry);
  }
  fESD = fESDhandler->GetEvent();

// Call the user analysis
  // Unlock CDB
  fCDBkey = fCDB->SetLock(kFALSE, fCDBkey);
  // Intercept when the run number changed
  if (fRun != fESD->GetRunNumber()) {
    fRunChanged = kTRUE;
    fRun = fESD->GetRunNumber();
    fCDB->SetRun(fRun);
  }
  TIter next(fSupplies);
  AliTenderSupply *supply;
  while ((supply=(AliTenderSupply*)next())) supply->ProcessEvent();
  fRunChanged = kFALSE;
  // Lock CDB
  fCDBkey = fCDB->SetLock(kTRUE, fCDBkey);
  PostData(0, fESD);
}

//______________________________________________________________________________
void AliTender::SetDefaultCDBStorage(const char *dbString)
{
// Set default CDB storage
   fDefaultStorage = dbString;
}
<|endoftext|>


<commit_before>#include <signal.h>

#include "gen/wsdd.nsmap"
#include "wsddapi.h"

const char* host = "239.255.255.250";
int port = 3702;
const int _metadataVersion = 1;
const char* _xaddr="http://localhost/service";
const char* _type="\"http://schemas.xmlsoap.org/ws/2006/02/devprof\":device";

bool stop = false;
void sighandler(int sig)
{
	std::cout<< "Signal caught..." << std::endl;
	stop = true;
}

int mainloop(soap* serv)
{
	return soap_wsdd_listen(serv, -1000000);
}

void sendHello()
{
	struct soap* soap = soap_new1(SOAP_IO_UDP);
	printf("call soap_wsdd_Hello\n");
	int res = soap_wsdd_Hello(soap,
	  SOAP_WSDD_ADHOC,      // mode
	  "soap.udp://239.255.255.250:3702",         // address of TS
	  soap_wsa_rand_uuid(soap),                   // message ID
	  NULL,
	  NULL,
	  NULL,
	  _type,
	  NULL,
	  _xaddr,
          _metadataVersion);
	if (res != SOAP_OK)
	{
		soap_print_fault(soap, stderr);
	}
	soap_end(soap);
}

void sendBye()
{
	struct soap* soap = soap_new1(SOAP_IO_UDP);
	printf("call soap_wsdd_Bye\n");
	int res = soap_wsdd_Bye(soap,
	  SOAP_WSDD_ADHOC,      // mode
	  "soap.udp://239.255.255.250:3702",         // address of TS
	  soap_wsa_rand_uuid(soap),                   // message ID
	  NULL,
	  NULL,
	  _type,
	  NULL,
	  _xaddr,
          _metadataVersion);
	if (res != SOAP_OK)
	{
		soap_print_fault(soap, stderr);
	}
	soap_end(soap);
}

int main(int argc, char** argv)
{
	struct soap* serv = soap_new1(SOAP_IO_UDP | SOAP_IO_KEEPALIVE);
	serv->bind_flags=SO_REUSEADDR;
	serv->connect_flags = SO_BROADCAST;
	if (!soap_valid_socket(soap_bind(serv, NULL, port, 1000)))
	{
		soap_print_fault(serv, stderr);
		exit(1);
	}

	ip_mreq mcast;
	mcast.imr_multiaddr.s_addr = inet_addr(host);
	mcast.imr_interface.s_addr = htonl(INADDR_ANY);
	if (setsockopt(serv->master, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mcast, sizeof(mcast))<0)
	{
		std::cout << "group membership failed:" << strerror(errno) << std::endl;
	}

	sendHello();
	mainloop(serv);

	signal(SIGINT, &sighandler);
	while (!stop)
	{
		mainloop(serv);
	}

	sendBye();
	mainloop(serv);

	return 0;
}

void wsdd_event_ProbeMatches(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, struct wsdd__ProbeMatchesType *matches)
{
	printf("wsdd_event_ProbeMatches nbMatch:%d\n", matches->__sizeProbeMatch);
}

void wsdd_event_ResolveMatches(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, struct wsdd__ResolveMatchType *match)
{
	printf("wsdd_event_ResolveMatches\n");
}

void wsdd_event_Hello(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, const char *EndpointReference, const char *Types, const char *Scopes, const char *MatchBy, const char *XAddrs, unsigned int MetadataVersion)
{
	printf("wsdd_event_Hello id=%s EndpointReference=%s XAddrs=%s\n", MessageID, EndpointReference, XAddrs);
}

void wsdd_event_Bye(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, const char *EndpointReference, const char *Types, const char *Scopes, const char *MatchBy, const char *XAddrs, unsigned int *MetadataVersion)
{
	printf("wsdd_event_Bye id=%s EndpointReference=%s XAddrs=%s\n", MessageID, EndpointReference, XAddrs);
}

soap_wsdd_mode wsdd_event_Resolve(struct soap *soap, const char *MessageID, const char *ReplyTo, const char *EndpointReference, struct wsdd__ResolveMatchType *match)
{
	printf("wsdd_event_Resolve  id=%s replyTo=%s\n", MessageID, ReplyTo);
	return SOAP_WSDD_ADHOC;
}

soap_wsdd_mode wsdd_event_Probe(struct soap *soap, const char *MessageID, const char *ReplyTo, const char *Types, const char *Scopes, const char *MatchBy, struct wsdd__ProbeMatchesType *matches)
{
	printf("wsdd_event_Probe id=%s replyTo=%s types=%s scopes=%s\n", MessageID, ReplyTo, Types, Scopes);
	soap_wsdd_init_ProbeMatches(soap,matches);
	soap_wsdd_add_ProbeMatch(soap, matches, "soap.udp://239.255.255.250:3702", _type, NULL, NULL, _xaddr, _metadataVersion);
	soap_wsdd_ProbeMatches(soap, "soap.udp://239.255.255.250:3702", soap_wsa_rand_uuid(soap) , MessageID, ReplyTo, matches);
	return SOAP_WSDD_ADHOC;
}

<commit_msg>Hello/Bye need an endpoint not NULL<commit_after>#include <signal.h>

#include "gen/wsdd.nsmap"
#include "wsddapi.h"

const char* host = "239.255.255.250";
int port = 3702;
const int _metadataVersion = 1;
const char* _xaddr="http://localhost/service";
const char* _type="\"http://schemas.xmlsoap.org/ws/2006/02/devprof\":device";
const char* _endpoint="urn";

bool stop = false;
void sighandler(int sig)
{
	std::cout<< "Signal caught..." << std::endl;
	stop = true;
}

int mainloop(soap* serv)
{
	return soap_wsdd_listen(serv, -1000000);
}

void sendHello()
{
	struct soap* soap = soap_new1(SOAP_IO_UDP);
	printf("call soap_wsdd_Hello\n");
	int res = soap_wsdd_Hello(soap,
	  SOAP_WSDD_ADHOC,      // mode
	  "soap.udp://239.255.255.250:3702",         // address of TS
	  soap_wsa_rand_uuid(soap),                   // message ID
	  NULL,
	  _endpoint,
	  NULL,
	  _type,
	  NULL,
	  _xaddr,
          _metadataVersion);
	if (res != SOAP_OK)
	{
		soap_print_fault(soap, stderr);
	}
	soap_end(soap);
}

void sendBye()
{
	struct soap* soap = soap_new1(SOAP_IO_UDP);
	printf("call soap_wsdd_Bye\n");
	int res = soap_wsdd_Bye(soap,
	  SOAP_WSDD_ADHOC,      // mode
	  "soap.udp://239.255.255.250:3702",         // address of TS
	  soap_wsa_rand_uuid(soap),                   // message ID
	  _endpoint,
	  NULL,
	  _type,
	  NULL,
	  _xaddr,
          _metadataVersion);
	if (res != SOAP_OK)
	{
		soap_print_fault(soap, stderr);
	}
	soap_end(soap);
}

int main(int argc, char** argv)
{
	struct soap* serv = soap_new1(SOAP_IO_UDP | SOAP_IO_KEEPALIVE);
	serv->bind_flags=SO_REUSEADDR;
	serv->connect_flags = SO_BROADCAST;
	if (!soap_valid_socket(soap_bind(serv, NULL, port, 1000)))
	{
		soap_print_fault(serv, stderr);
		exit(1);
	}

	ip_mreq mcast;
	mcast.imr_multiaddr.s_addr = inet_addr(host);
	mcast.imr_interface.s_addr = htonl(INADDR_ANY);
	if (setsockopt(serv->master, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mcast, sizeof(mcast))<0)
	{
		std::cout << "group membership failed:" << strerror(errno) << std::endl;
	}

	sendHello();
	mainloop(serv);

	signal(SIGINT, &sighandler);
	while (!stop)
	{
		mainloop(serv);
	}

	sendBye();
	mainloop(serv);

	return 0;
}

void wsdd_event_ProbeMatches(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, struct wsdd__ProbeMatchesType *matches)
{
	printf("wsdd_event_ProbeMatches nbMatch:%d\n", matches->__sizeProbeMatch);
}

void wsdd_event_ResolveMatches(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, struct wsdd__ResolveMatchType *match)
{
	printf("wsdd_event_ResolveMatches\n");
}

void wsdd_event_Hello(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, const char *EndpointReference, const char *Types, const char *Scopes, const char *MatchBy, const char *XAddrs, unsigned int MetadataVersion)
{
	printf("wsdd_event_Hello id=%s EndpointReference=%s XAddrs=%s\n", MessageID, EndpointReference, XAddrs);
}

void wsdd_event_Bye(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, const char *EndpointReference, const char *Types, const char *Scopes, const char *MatchBy, const char *XAddrs, unsigned int *MetadataVersion)
{
	printf("wsdd_event_Bye id=%s EndpointReference=%s XAddrs=%s\n", MessageID, EndpointReference, XAddrs);
}

soap_wsdd_mode wsdd_event_Resolve(struct soap *soap, const char *MessageID, const char *ReplyTo, const char *EndpointReference, struct wsdd__ResolveMatchType *match)
{
	printf("wsdd_event_Resolve  id=%s replyTo=%s\n", MessageID, ReplyTo);
	return SOAP_WSDD_ADHOC;
}

soap_wsdd_mode wsdd_event_Probe(struct soap *soap, const char *MessageID, const char *ReplyTo, const char *Types, const char *Scopes, const char *MatchBy, struct wsdd__ProbeMatchesType *matches)
{
	printf("wsdd_event_Probe id=%s replyTo=%s types=%s scopes=%s\n", MessageID, ReplyTo, Types, Scopes);
	soap_wsdd_init_ProbeMatches(soap,matches);
	soap_wsdd_add_ProbeMatch(soap, matches, "soap.udp://239.255.255.250:3702", _type, NULL, NULL, _xaddr, _metadataVersion);
	soap_wsdd_ProbeMatches(soap, "soap.udp://239.255.255.250:3702", soap_wsa_rand_uuid(soap) , MessageID, ReplyTo, matches);
	return SOAP_WSDD_ADHOC;
}

<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/views/controls/webview/webview.h"

#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "ipc/ipc_message.h"
#include "ui/base/accessibility/accessible_view_state.h"
#include "ui/base/accessibility/accessibility_types.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/focus/focus_manager.h"

namespace views {

// static
const char WebView::kViewClassName[] =
    "ui/views/WebView";

////////////////////////////////////////////////////////////////////////////////
// WebView, public:

WebView::WebView(content::BrowserContext* browser_context)
    : wcv_holder_(new NativeViewHost),
      web_contents_(NULL),
      browser_context_(browser_context) {
  AddChildView(wcv_holder_);
}

WebView::~WebView() {
}

content::WebContents* WebView::GetWebContents() {
  CreateWebContentsWithSiteInstance(NULL);
  return web_contents_;
}

void WebView::CreateWebContentsWithSiteInstance(
    content::SiteInstance* site_instance) {
  if (!web_contents_) {
    wc_owner_.reset(content::WebContents::Create(browser_context_,
                                                 site_instance,
                                                 MSG_ROUTING_NONE,
                                                 NULL,
                                                 NULL));
    web_contents_ = wc_owner_.get();
    web_contents_->SetDelegate(this);
    AttachWebContents();
  }
}

void WebView::SetWebContents(content::WebContents* web_contents) {
  if (web_contents == web_contents_)
    return;
  DetachWebContents();
  wc_owner_.reset();
  web_contents_ = web_contents;
  AttachWebContents();
}

void WebView::LoadInitialURL(const GURL& url) {
  GetWebContents()->GetController().LoadURL(
      url, content::Referrer(), content::PAGE_TRANSITION_START_PAGE,
      std::string());
}

void WebView::SetFastResize(bool fast_resize) {
  wcv_holder_->set_fast_resize(fast_resize);
}

void WebView::OnWebContentsFocused(content::WebContents* web_contents) {
  FocusManager* focus_manager = GetFocusManager();
  if (focus_manager)
    focus_manager->SetFocusedView(this);
}

////////////////////////////////////////////////////////////////////////////////
// WebView, View overrides:

std::string WebView::GetClassName() const {
  return kViewClassName;
}

void WebView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
  wcv_holder_->SetSize(bounds().size());
}

void WebView::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
  if (is_add)
    AttachWebContents();
}

bool WebView::SkipDefaultKeyEventProcessing(const views::KeyEvent& event) {
  // Don't look-up accelerators or tab-traversal if we are showing a non-crashed
  // TabContents.
  // We'll first give the page a chance to process the key events.  If it does
  // not process them, they'll be returned to us and we'll treat them as
  // accelerators then.
  return web_contents_ && !web_contents_->IsCrashed();
}

bool WebView::IsFocusable() const {
  // We need to be focusable when our contents is not a view hierarchy, as
  // clicking on the contents needs to focus us.
  return !!web_contents_;
}

void WebView::OnFocus() {
  if (web_contents_)
    web_contents_->Focus();
}

void WebView::AboutToRequestFocusFromTabTraversal(bool reverse) {
  if (web_contents_)
    web_contents_->FocusThroughTabTraversal(reverse);
}

void WebView::GetAccessibleState(ui::AccessibleViewState* state) {
  state->role = ui::AccessibilityTypes::ROLE_GROUPING;
}

gfx::NativeViewAccessible WebView::GetNativeViewAccessible() {
  if (web_contents_) {
    content::RenderWidgetHostView* host_view =
        web_contents_->GetRenderWidgetHostView();
    if (host_view)
      return host_view->GetNativeViewAccessible();
  }
  return View::GetNativeViewAccessible();
}

////////////////////////////////////////////////////////////////////////////////
// WebView, content::NotificationObserver implementation:

void WebView::Observe(int type,
                      const content::NotificationSource& source,
                      const content::NotificationDetails& details) {
  if (type == content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED) {
    std::pair<content::RenderViewHost*, content::RenderViewHost*>*
        switched_details =
            content::Details<std::pair<content::RenderViewHost*,
                                       content::RenderViewHost*> >(
                details).ptr();
    RenderViewHostChanged(switched_details->first,
                          switched_details->second);
  } else if (type == content::NOTIFICATION_WEB_CONTENTS_DESTROYED) {
    WebContentsDestroyed(content::Source<content::WebContents>(source).ptr());
  } else {
    NOTREACHED();
  }
}

////////////////////////////////////////////////////////////////////////////////
// WebView, content::WebContentsDelegate implementation:

void WebView::WebContentsFocused(content::WebContents* web_contents) {
  DCHECK(wc_owner_.get());
  // The WebView is only the delegate of WebContentses it creates itself.
  OnWebContentsFocused(web_contents_);
}

////////////////////////////////////////////////////////////////////////////////
// WebView, private:

void WebView::AttachWebContents() {
  // Prevents attachment if the WebView isn't already in a Widget, or it's
  // already attached.
  if (!GetWidget() || !web_contents_ ||
      wcv_holder_->native_view() == web_contents_->GetNativeView()) {
    return;
  }

  if (web_contents_) {
    wcv_holder_->Attach(web_contents_->GetNativeView());

    // The WebContentsView will not be focused automatically when it is
    // attached, so we need to pass on focus to it if the FocusManager thinks
    // the WebView is focused.
    if (GetFocusManager()->GetFocusedView() == this)
      web_contents_->Focus();

    registrar_.Add(
        this,
        content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
        content::Source<content::NavigationController>(
            &web_contents_->GetController()));
    registrar_.Add(
        this,
        content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
        content::Source<content::WebContents>(web_contents_));
  }
}

void WebView::DetachWebContents() {
  if (web_contents_) {
    wcv_holder_->Detach();
#if defined(OS_WIN) && !defined(USE_AURA)
    // TODO(beng): This should either not be necessary, or be done implicitly by
    //             NativeViewHostWin on Detach(). As it stands, this is needed
    //             so that the view of the detached contents knows to tell the
    //             renderer its been hidden.
    ShowWindow(web_contents_->GetNativeView(), SW_HIDE);
#endif
  }
  registrar_.RemoveAll();
}

void WebView::RenderViewHostChanged(content::RenderViewHost* old_host,
                                    content::RenderViewHost* new_host) {
  if (GetFocusManager()->GetFocusedView() == this)
    web_contents_->Focus();
}

void WebView::WebContentsDestroyed(content::WebContents* web_contents) {
  DCHECK(web_contents == web_contents_);
  SetWebContents(NULL);
}

}  // namespace views
<commit_msg>Revert 133490 - Make sure the WebContents has focus after being attached to a WebView, if that WebView was focused.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/views/controls/webview/webview.h"

#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "ipc/ipc_message.h"
#include "ui/base/accessibility/accessible_view_state.h"
#include "ui/base/accessibility/accessibility_types.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/focus/focus_manager.h"

namespace views {

// static
const char WebView::kViewClassName[] =
    "ui/views/WebView";

////////////////////////////////////////////////////////////////////////////////
// WebView, public:

WebView::WebView(content::BrowserContext* browser_context)
    : wcv_holder_(new NativeViewHost),
      web_contents_(NULL),
      browser_context_(browser_context) {
  AddChildView(wcv_holder_);
}

WebView::~WebView() {
}

content::WebContents* WebView::GetWebContents() {
  CreateWebContentsWithSiteInstance(NULL);
  return web_contents_;
}

void WebView::CreateWebContentsWithSiteInstance(
    content::SiteInstance* site_instance) {
  if (!web_contents_) {
    wc_owner_.reset(content::WebContents::Create(browser_context_,
                                                 site_instance,
                                                 MSG_ROUTING_NONE,
                                                 NULL,
                                                 NULL));
    web_contents_ = wc_owner_.get();
    web_contents_->SetDelegate(this);
    AttachWebContents();
  }
}

void WebView::SetWebContents(content::WebContents* web_contents) {
  if (web_contents == web_contents_)
    return;
  DetachWebContents();
  wc_owner_.reset();
  web_contents_ = web_contents;
  AttachWebContents();
}

void WebView::LoadInitialURL(const GURL& url) {
  GetWebContents()->GetController().LoadURL(
      url, content::Referrer(), content::PAGE_TRANSITION_START_PAGE,
      std::string());
}

void WebView::SetFastResize(bool fast_resize) {
  wcv_holder_->set_fast_resize(fast_resize);
}

void WebView::OnWebContentsFocused(content::WebContents* web_contents) {
  FocusManager* focus_manager = GetFocusManager();
  if (focus_manager)
    focus_manager->SetFocusedView(this);
}

////////////////////////////////////////////////////////////////////////////////
// WebView, View overrides:

std::string WebView::GetClassName() const {
  return kViewClassName;
}

void WebView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
  wcv_holder_->SetSize(bounds().size());
}

void WebView::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
  if (is_add)
    AttachWebContents();
}

bool WebView::SkipDefaultKeyEventProcessing(const views::KeyEvent& event) {
  // Don't look-up accelerators or tab-traversal if we are showing a non-crashed
  // TabContents.
  // We'll first give the page a chance to process the key events.  If it does
  // not process them, they'll be returned to us and we'll treat them as
  // accelerators then.
  return web_contents_ && !web_contents_->IsCrashed();
}

bool WebView::IsFocusable() const {
  // We need to be focusable when our contents is not a view hierarchy, as
  // clicking on the contents needs to focus us.
  return !!web_contents_;
}

void WebView::OnFocus() {
  if (web_contents_)
    web_contents_->Focus();
}

void WebView::AboutToRequestFocusFromTabTraversal(bool reverse) {
  if (web_contents_)
    web_contents_->FocusThroughTabTraversal(reverse);
}

void WebView::GetAccessibleState(ui::AccessibleViewState* state) {
  state->role = ui::AccessibilityTypes::ROLE_GROUPING;
}

gfx::NativeViewAccessible WebView::GetNativeViewAccessible() {
  if (web_contents_) {
    content::RenderWidgetHostView* host_view =
        web_contents_->GetRenderWidgetHostView();
    if (host_view)
      return host_view->GetNativeViewAccessible();
  }
  return View::GetNativeViewAccessible();
}

////////////////////////////////////////////////////////////////////////////////
// WebView, content::NotificationObserver implementation:

void WebView::Observe(int type,
                      const content::NotificationSource& source,
                      const content::NotificationDetails& details) {
  if (type == content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED) {
    std::pair<content::RenderViewHost*, content::RenderViewHost*>*
        switched_details =
            content::Details<std::pair<content::RenderViewHost*,
                                       content::RenderViewHost*> >(
                details).ptr();
    RenderViewHostChanged(switched_details->first,
                          switched_details->second);
  } else if (type == content::NOTIFICATION_WEB_CONTENTS_DESTROYED) {
    WebContentsDestroyed(content::Source<content::WebContents>(source).ptr());
  } else {
    NOTREACHED();
  }
}

////////////////////////////////////////////////////////////////////////////////
// WebView, content::WebContentsDelegate implementation:

void WebView::WebContentsFocused(content::WebContents* web_contents) {
  DCHECK(wc_owner_.get());
  // The WebView is only the delegate of WebContentses it creates itself.
  OnWebContentsFocused(web_contents_);
}

////////////////////////////////////////////////////////////////////////////////
// WebView, private:

void WebView::AttachWebContents() {
  // Prevents attachment if the WebView isn't already in a Widget, or it's
  // already attached.
  if (!GetWidget() || !web_contents_ ||
      wcv_holder_->native_view() == web_contents_->GetNativeView()) {
    return;
  }

  if (web_contents_) {
    wcv_holder_->Attach(web_contents_->GetNativeView());

    registrar_.Add(
        this,
        content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
        content::Source<content::NavigationController>(
            &web_contents_->GetController()));
    registrar_.Add(
        this,
        content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
        content::Source<content::WebContents>(web_contents_));
  }
}

void WebView::DetachWebContents() {
  if (web_contents_) {
    wcv_holder_->Detach();
#if defined(OS_WIN) && !defined(USE_AURA)
    // TODO(beng): This should either not be necessary, or be done implicitly by
    //             NativeViewHostWin on Detach(). As it stands, this is needed
    //             so that the view of the detached contents knows to tell the
    //             renderer its been hidden.
    ShowWindow(web_contents_->GetNativeView(), SW_HIDE);
#endif
  }
  registrar_.RemoveAll();
}

void WebView::RenderViewHostChanged(content::RenderViewHost* old_host,
                                    content::RenderViewHost* new_host) {
  if (GetFocusManager()->GetFocusedView() == this)
    web_contents_->Focus();
}

void WebView::WebContentsDestroyed(content::WebContents* web_contents) {
  DCHECK(web_contents == web_contents_);
  SetWebContents(NULL);
}

}  // namespace views
<|endoftext|>


<commit_before>/**
 * @file protocol.hpp
 * @brief Communication protocol used in the image search.
 * @author Paolo D'Apice
 */

#ifndef VIS_PROTOCOL_HPP
#define VIS_PROTOCOL_HPP

#include <boost/asio/streambuf.hpp>
#include <iostream>
#include <vector>

namespace vis {

enum RequestType { // TODO move into Request
    OFFLINE,
    REALTIME,
    UPLOAD
};

enum QueryType { // TODO move into Request
    COLOR,
    SHAPE,
    COLOR_SHAPE
};

typedef size_t id_type; // XXX vis::Index::id_type

struct Request {
    RequestType type;
    std::string category;
    QueryType queryType;
    unsigned numResults;

// TODO boost::variant?
    id_type id; // offline
    std::vector<float> descriptors; // realtime
    // TODO opencv image

};

enum ResponseStatus { // TODO move into Response
    OK,
    ERROR,
    NO_CATEGORY,
    NO_QUERY_TYPE
};

struct Match { // TODO move into Response
    id_type id;
    std::string path;
};

struct Response {
    ResponseStatus status;
    std::vector<Match> results;
};

inline bool
operator==(const Request& left, const Request& right) {
    bool b = left.type == right.type
        and left.category == right.category
        and left.queryType == right.queryType
        and left.numResults == right.numResults;
    if (!b) return false;

    switch(left.type) {
        case vis::RequestType::OFFLINE:
            return left.id == right.id;
        case vis::RequestType::REALTIME:
            return left.descriptors == right.descriptors;
        case vis::RequestType::UPLOAD:
            // TODO
            return true;
    }
}

inline bool
operator==(const vis::Match& left, const vis::Match& right) {
    return left.id == right.id and left.path == right.path;
}

inline bool
operator==(const vis::Response& left, const vis::Response& right) {
    return left.status == right.status and left.results == right.results;
}

template <typename T>
inline std::ostream&
operator<<(std::ostream& os, const std::vector<T>& v) {
    std::copy(v.begin(), v.end(), std::ostream_iterator<T>(os, " "));
    return os;
}

template <typename T>
inline std::istream&
operator>>(std::istream& is, std::vector<T>& v) {
    std::copy(std::istream_iterator<T>(is), std::istream_iterator<T>(), std::back_inserter(v));
    return is;
}

template <typename E>
typename std::enable_if<std::is_enum<E>::value, std::istream&>::type
operator>>(std::istream& is, E& e) {
    unsigned int value = 0;
    if (is >> value)
        e = static_cast<E>(value);
    return is;
}

inline std::ostream&
operator<<(std::ostream& os, const vis::Match& m) {
    return os << m.id << " " << m.path;
}

inline std::istream&
operator>>(std::istream& is, vis::Match& m) {
    return is >> m.id >> m.path;
}

inline std::ostream&
operator<<(std::ostream& os, const vis::Request& r) {
    os << r.type << ' ' << r.category << ' '
        << r.queryType << ' ' << r.numResults << ' ';
    switch (r.type) {
        case vis::RequestType::OFFLINE:
            os << r.id;
            break;
        case vis::RequestType::REALTIME:
            os << r.descriptors;
            break;
        case vis::RequestType::UPLOAD:
            // TODO
            break;
    }
    return os;
}

inline std::istream&
operator>>(std::istream& is, vis::Request& r) {
    is >> r.type >> r.category >> r.queryType >> r.numResults;
    switch (r.type) {
        case vis::RequestType::OFFLINE:
            is >> r.id;
            break;
        case vis::RequestType::REALTIME:
            is >> r.descriptors;
            break;
        case vis::RequestType::UPLOAD:
            // TODO
            break;
    }
    return is;
}

inline std::ostream&
operator<<(std::ostream& os, const vis::Response& r) {
    os << r.status << " " << r.results;
    return os;
}

inline std::istream&
operator>>(std::istream& is, vis::Response& r) {
    is >> r.status >> r.results;
    return is;
}

template <typename Object>
void
put(boost::asio::streambuf& buf, const Object& obj) {
    std::ostream os(&buf);
    os << obj;
}

template <typename Object>
void
get(boost::asio::streambuf& buf, Object& obj) {
    std::istream is(&buf);
    is >> obj;
}

} // namespace vis

#endif // VIS_PROTOCOL_HPP

<commit_msg>Fix missing header<commit_after>/**
 * @file protocol.hpp
 * @brief Communication protocol used in the image search.
 * @author Paolo D'Apice
 */

#ifndef VIS_PROTOCOL_HPP
#define VIS_PROTOCOL_HPP

#include <boost/asio/streambuf.hpp>
#include <iostream>
#include <iterator>
#include <vector>

namespace vis {

enum RequestType { // TODO move into Request
    OFFLINE,
    REALTIME,
    UPLOAD
};

enum QueryType { // TODO move into Request
    COLOR,
    SHAPE,
    COLOR_SHAPE
};

typedef size_t id_type; // XXX vis::Index::id_type

struct Request {
    RequestType type;
    std::string category;
    QueryType queryType;
    unsigned numResults;

// TODO boost::variant?
    id_type id; // offline
    std::vector<float> descriptors; // realtime
    // TODO opencv image

};

enum ResponseStatus { // TODO move into Response
    OK,
    ERROR,
    NO_CATEGORY,
    NO_QUERY_TYPE
};

struct Match { // TODO move into Response
    id_type id;
    std::string path;
};

struct Response {
    ResponseStatus status;
    std::vector<Match> results;
};

inline bool
operator==(const Request& left, const Request& right) {
    bool b = left.type == right.type
        and left.category == right.category
        and left.queryType == right.queryType
        and left.numResults == right.numResults;
    if (!b) return false;

    switch(left.type) {
        case vis::RequestType::OFFLINE:
            return left.id == right.id;
        case vis::RequestType::REALTIME:
            return left.descriptors == right.descriptors;
        case vis::RequestType::UPLOAD:
            // TODO
            return true;
    }
}

inline bool
operator==(const vis::Match& left, const vis::Match& right) {
    return left.id == right.id and left.path == right.path;
}

inline bool
operator==(const vis::Response& left, const vis::Response& right) {
    return left.status == right.status and left.results == right.results;
}

template <typename T>
inline std::ostream&
operator<<(std::ostream& os, const std::vector<T>& v) {
    std::copy(v.begin(), v.end(), std::ostream_iterator<T>(os, " "));
    return os;
}

template <typename T>
inline std::istream&
operator>>(std::istream& is, std::vector<T>& v) {
    std::copy(std::istream_iterator<T>(is), std::istream_iterator<T>(), std::back_inserter(v));
    return is;
}

template <typename E>
typename std::enable_if<std::is_enum<E>::value, std::istream&>::type
operator>>(std::istream& is, E& e) {
    unsigned int value = 0;
    if (is >> value)
        e = static_cast<E>(value);
    return is;
}

inline std::ostream&
operator<<(std::ostream& os, const vis::Match& m) {
    return os << m.id << " " << m.path;
}

inline std::istream&
operator>>(std::istream& is, vis::Match& m) {
    return is >> m.id >> m.path;
}

inline std::ostream&
operator<<(std::ostream& os, const vis::Request& r) {
    os << r.type << ' ' << r.category << ' '
        << r.queryType << ' ' << r.numResults << ' ';
    switch (r.type) {
        case vis::RequestType::OFFLINE:
            os << r.id;
            break;
        case vis::RequestType::REALTIME:
            os << r.descriptors;
            break;
        case vis::RequestType::UPLOAD:
            // TODO
            break;
    }
    return os;
}

inline std::istream&
operator>>(std::istream& is, vis::Request& r) {
    is >> r.type >> r.category >> r.queryType >> r.numResults;
    switch (r.type) {
        case vis::RequestType::OFFLINE:
            is >> r.id;
            break;
        case vis::RequestType::REALTIME:
            is >> r.descriptors;
            break;
        case vis::RequestType::UPLOAD:
            // TODO
            break;
    }
    return is;
}

inline std::ostream&
operator<<(std::ostream& os, const vis::Response& r) {
    os << r.status << " " << r.results;
    return os;
}

inline std::istream&
operator>>(std::istream& is, vis::Response& r) {
    is >> r.status >> r.results;
    return is;
}

template <typename Object>
void
put(boost::asio::streambuf& buf, const Object& obj) {
    std::ostream os(&buf);
    os << obj;
}

template <typename Object>
void
get(boost::asio::streambuf& buf, Object& obj) {
    std::istream is(&buf);
    is >> obj;
}

} // namespace vis

#endif // VIS_PROTOCOL_HPP

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: confignode.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2006-07-25 09:51:18 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef INCLUDED_UNOTOOLSDLLAPI_H
#include "unotools/unotoolsdllapi.h"
#endif

#ifndef _UNOTOOLS_CONFIGNODE_HXX_
#define _UNOTOOLS_CONFIGNODE_HXX_

#ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_
#include <com/sun/star/container/XHierarchicalNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCHANGESBATCH_HPP_
#include <com/sun/star/util/XChangesBatch.hpp>
#endif
#ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_
#include <unotools/eventlisteneradapter.hxx>
#endif

//........................................................................
namespace utl
{
//........................................................................

    //========================================================================
    //= OConfigurationNode
    //========================================================================
    class OConfigurationTreeRoot;
    /** a small wrapper around a configuration node.

        Nodes in the terminology used herein are inner nodes of a configuration
        tree, which means no leafs.
    */
    class UNOTOOLS_DLLPUBLIC OConfigurationNode : public ::utl::OEventListenerAdapter
    {
    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XHierarchicalNameAccess >
                    m_xHierarchyAccess;     /// accessing children grandchildren (mandatory interface of our UNO object)
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >
                    m_xDirectAccess;        /// accessing children  (mandatory interface of our UNO object)
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace >
                    m_xReplaceAccess;       /// replacing child values
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >
                    m_xContainerAccess;     /// modifying set nodes  (optional interface of our UNO object)
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
                    m_xProvider;            /// the configuration provider which supplied the nodes of the hierarchy we're a part of
        sal_Bool    m_bEscapeNames;         /// escape names before accessing children ?

        ::rtl::OUString
                    m_sCompletePath;

        OConfigurationNode  insertNode(const ::rtl::OUString& _rName,const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _xNode) const throw();
    protected:
        /// constructs a node object with an interface representing a node
        OConfigurationNode(
            const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxNode,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxProvider);

    public:
        /// constructs an empty and invalid node object
        OConfigurationNode() :m_bEscapeNames(sal_False) { }
        /// copy ctor
        OConfigurationNode(const OConfigurationNode& _rSource);

        /// assigment
        const OConfigurationNode& operator=(const OConfigurationNode& _rSource);

        /// dtor
        ~OConfigurationNode();

        /** open a sub node
            @param      _rPath      access path of the to-be-opened sub node. May be a hierarchical path.
        */
        OConfigurationNode  openNode(const ::rtl::OUString& _rPath) const throw();

        /** create a new child node

            If the object represents a set node, this method may be used to create a new child. For non-set-nodes, the
            method will fail.

            Unless the respective operations on the pure configuration API, the to-be-created node immediately
            becomes a part of it's hierarchy, no explicit insertion is necessary.
            @param      _rName      name for the new child. Must be level-1-depth.
        */
        OConfigurationNode  createNode(const ::rtl::OUString& _rName) const throw();
        /** appends a node under a new name

            If the object represents a set node, this method may be used to create a new child. For non-set-nodes, the
            method will fail.

            Unless the respective operations on the pure configuration API, the to-be-created node immediately
            becomes a part of it's hierarchy, no explicit insertion is necessary.
            @param      _rName      name for the new child. Must be level-1-depth.
            @param      _aNewNode   the node which should be appended
        */
        OConfigurationNode  appendNode(const ::rtl::OUString& _rName,const OConfigurationNode& _aNewNode) const throw();

        /** remove an existent child node

            If the object represents a set node, this method may be used to delete an existent child. For non-set-nodes,
            the method will fail.
        */
        sal_Bool            removeNode(const ::rtl::OUString& _rName) const throw();

        /** retrieves the content of a descendant

            the returned value may contain anything from an interface (if <arg>_rPath</arg> refers to inner node of
            the configuration tree) to any explicit value (e.g. string, integer) or even void.

            Unfortunately, this implies that if a void value is returned, you won't have a clue if this means
            "the path does not exist" (besides the assertion made :), or if the value is really void.
        */
        ::com::sun::star::uno::Any
                            getNodeValue(const ::rtl::OUString& _rPath) const throw();

        /** write a node value

            The value given is written into the node specified by the given relative path.

            In opposite to <method>getNodeValue</method>, _rName must refer to a leaf in the configuration tree, not an inner
            node.
            @return     sal_True if and only if the write was successfull.
        */
        sal_Bool            setNodeValue(const ::rtl::OUString& _rPath, const ::com::sun::star::uno::Any& _rValue) const throw();

        /// return the names of the existing children
        ::com::sun::star::uno::Sequence< ::rtl::OUString >
                            getNodeNames() const throw();

        /** enables or disables name escaping when accessing direct children

            Escaping is disabled by default, usually you enable it for set nodes (e.g. with calling setEscape(isSetNode)).
            Once escaping is enabled, you should not access indirect children (e.g. openNode("child/grandchild"), 'cause
            escaping for such names may not be supported by the underlying API objects.
            @see getEscape
        */
        void        setEscape(sal_Bool _bEnable = sal_True);
        /** get the flag specifying the current escape behaviour
            @see setEscape
        */
        sal_Bool    getEscape() const { return m_bEscapeNames; }

        /** clone the object, creating a new hierarchy where the root represents the same node as the object
            where this method is called does.

            The new hierarchy does not share any updates with the one the object is a part of, i.e. any changes made
            in the existing hierarchy are not visible to the newly created one until committed (and vice versa).
            @param      _rRoot      out parameter. upon return, contains the object representing the root of the new hierarchy.
        */
        OConfigurationTreeRoot cloneAsRoot() const throw();

        /// invalidate the object
        virtual void clear() throw();

    // -----------------------
    // meta informations about the node
        /// checks whether or not the object represents a set node.
        sal_Bool isSetNode() const;
        /// checks whether or not a direct child with a given name exists
        sal_Bool hasByName(const ::rtl::OUString& _rName) const throw();
        /// checks whether or not a descendent (no matter if direct or indirect) with the given name exists
        sal_Bool hasByHierarchicalName( const ::rtl::OUString& _rName ) const throw();
        /// check if the objects represents a valid configuration node
        sal_Bool isValid() const { return m_xHierarchyAccess.is(); }
        /// check whether the object is read-only of updatable
        sal_Bool isReadonly() const { return !m_xReplaceAccess.is(); }

    protected:
        // OEventListenerAdapter
        virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource );

    protected:
        enum NAMEORIGIN
        {
            NO_CONFIGURATION,       /// the name came from a configuration node
            NO_CALLER               /// the name came from a client of this class
        };
        ::rtl::OUString normalizeName(const ::rtl::OUString& _rName, NAMEORIGIN _eOrigin) const;
    };

    //========================================================================
    //= OConfigurationTreeRoot
    //========================================================================
    /** a specialized version of a OConfigurationNode, representing the root
        of a configuration sub tree

        Only this class is able to commit any changes made any any OConfigurationNode
        objects.
    */
    class UNOTOOLS_DLLPUBLIC OConfigurationTreeRoot : public OConfigurationNode
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::util::XChangesBatch >
                                m_xCommitter;
    protected:
        /** ctor

        */
        OConfigurationTreeRoot(
            const ::com::sun::star::uno::Reference< ::com::sun::star::util::XChangesBatch >& _rxRootNode,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxProvider);

        /** ctor for a readonly node
        */
        OConfigurationTreeRoot(
            const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxRootNode,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxProvider);

    public:
        /// modes to used when creating a top-level node object
        enum CREATION_MODE
        {
            CM_READONLY,            /// open the node (i.e. sub tree) for read access only
            CM_UPDATABLE,           /// open the node (i.e. sub tree) for read and write access
            CM_PREFER_UPDATABLE     /// open the node (i.e. sub tree) for read and write access, if this fails, open it for read acces
        };

    public:
        /** default ctor

            The object constructed here is invalid (i.e. <method>isValid</method> will return sal_False).
        */
        OConfigurationTreeRoot() :OConfigurationNode() { }

        /// copy ctor
        OConfigurationTreeRoot(const OConfigurationTreeRoot& _rSource)
            :OConfigurationNode(_rSource), m_xCommitter(_rSource.m_xCommitter) { }

        /** open a new top-level configuration node

            opens a new node which is the root if an own configuration sub tree. This is what "top level" means: The
            node does not have a parent. It does not mean that the node represents a module tree (like org.openoffice.Office.Writer
            or such).

            In opposite to <method>createWithServiceFactory</method>, createWithProvider expects a configuration provider
            to work with.
            @see    createWithServiceFactory
            @param      _rxConfProvider configuration provider to use when retrieving the node.
            @param      _rPath          path to the node the object should represent
            @param      _nDepth         depth for node retrieval
            @param      _eMode          specifies which privileges should be applied when retrieving the node
        */
        static OConfigurationTreeRoot createWithProvider(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxConfProvider,
            const ::rtl::OUString& _rPath, sal_Int32 _nDepth = -1, CREATION_MODE _eMode = CM_PREFER_UPDATABLE, sal_Bool _bLazyWrite = sal_True);

        /** open a new top-level configuration node

            opens a new node which is the root if an own configuration sub tree. This is what "top level" means: The
            node does not have a parent. It does not mean that the node represents a module tree (like org.openoffice.Office.Writer
            or such).

            In opposite to <method>createWithProvider</method>, createWithProvider expects a service factory. This factory
            is used to create a configuration provider, and this provider is used to retrieve the node
            @see    createWithProvider
            @param      _rxORB          service factory to use to create the configuration provider.
            @param      _rPath          path to the node the object should represent
            @param      _nDepth         depth for node retrieval
            @param      _eMode          specifies which privileges should be applied when retrieving the node
        */
        static OConfigurationTreeRoot createWithServiceFactory(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
            const ::rtl::OUString& _rPath, sal_Int32 _nDepth = -1, CREATION_MODE _eMode = CM_PREFER_UPDATABLE, sal_Bool _bLazyWrite = sal_True);

        /** tolerant version of the <member>createWithServiceFactory</member>

No assertions are thrown in case of an failure to initialize the configuration service, but once
            the configuration could be initialized, errors in the creation of the specific node (e.g. because the
            given node path does not exist) are still asserted.

        */
        static OConfigurationTreeRoot tryCreateWithServiceFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
            const ::rtl::OUString& _rPath, sal_Int32 _nDepth = -1, CREATION_MODE _eMode = CM_PREFER_UPDATABLE, sal_Bool _bLazyWrite = sal_True );

        /** commit all changes made on the subtree the object is the root for

            All changes made on any <type>OConfigurationNode</type> object retrieved (maybe indirect) from this root
            object are committed when calling this method.
            @return     sal_True if and only if the commit was successfull
        */
        sal_Bool commit() const throw();

        /// invalidate the object
        virtual void clear() throw();
    };

//........................................................................
}   // namespace utl
//........................................................................

#endif // _UNOTOOLS_CONFIGNODE_HXX_

<commit_msg>INTEGRATION: CWS oihelp (1.7.18); FILE MERGED 2006/11/16 09:25:41 fs 1.7.18.1: moved include, so that the include protection really is the first line<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: confignode.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-13 11:42:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _UNOTOOLS_CONFIGNODE_HXX_
#define _UNOTOOLS_CONFIGNODE_HXX_

#ifndef INCLUDED_UNOTOOLSDLLAPI_H
#include "unotools/unotoolsdllapi.h"
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_
#include <com/sun/star/container/XHierarchicalNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCHANGESBATCH_HPP_
#include <com/sun/star/util/XChangesBatch.hpp>
#endif
#ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_
#include <unotools/eventlisteneradapter.hxx>
#endif

//........................................................................
namespace utl
{
//........................................................................

    //========================================================================
    //= OConfigurationNode
    //========================================================================
    class OConfigurationTreeRoot;
    /** a small wrapper around a configuration node.

        Nodes in the terminology used herein are inner nodes of a configuration
        tree, which means no leafs.
    */
    class UNOTOOLS_DLLPUBLIC OConfigurationNode : public ::utl::OEventListenerAdapter
    {
    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XHierarchicalNameAccess >
                    m_xHierarchyAccess;     /// accessing children grandchildren (mandatory interface of our UNO object)
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >
                    m_xDirectAccess;        /// accessing children  (mandatory interface of our UNO object)
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace >
                    m_xReplaceAccess;       /// replacing child values
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >
                    m_xContainerAccess;     /// modifying set nodes  (optional interface of our UNO object)
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
                    m_xProvider;            /// the configuration provider which supplied the nodes of the hierarchy we're a part of
        sal_Bool    m_bEscapeNames;         /// escape names before accessing children ?

        ::rtl::OUString
                    m_sCompletePath;

        OConfigurationNode  insertNode(const ::rtl::OUString& _rName,const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _xNode) const throw();
    protected:
        /// constructs a node object with an interface representing a node
        OConfigurationNode(
            const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxNode,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxProvider);

    public:
        /// constructs an empty and invalid node object
        OConfigurationNode() :m_bEscapeNames(sal_False) { }
        /// copy ctor
        OConfigurationNode(const OConfigurationNode& _rSource);

        /// assigment
        const OConfigurationNode& operator=(const OConfigurationNode& _rSource);

        /// dtor
        ~OConfigurationNode();

        /** open a sub node
            @param      _rPath      access path of the to-be-opened sub node. May be a hierarchical path.
        */
        OConfigurationNode  openNode(const ::rtl::OUString& _rPath) const throw();

        /** create a new child node

            If the object represents a set node, this method may be used to create a new child. For non-set-nodes, the
            method will fail.

            Unless the respective operations on the pure configuration API, the to-be-created node immediately
            becomes a part of it's hierarchy, no explicit insertion is necessary.
            @param      _rName      name for the new child. Must be level-1-depth.
        */
        OConfigurationNode  createNode(const ::rtl::OUString& _rName) const throw();
        /** appends a node under a new name

            If the object represents a set node, this method may be used to create a new child. For non-set-nodes, the
            method will fail.

            Unless the respective operations on the pure configuration API, the to-be-created node immediately
            becomes a part of it's hierarchy, no explicit insertion is necessary.
            @param      _rName      name for the new child. Must be level-1-depth.
            @param      _aNewNode   the node which should be appended
        */
        OConfigurationNode  appendNode(const ::rtl::OUString& _rName,const OConfigurationNode& _aNewNode) const throw();

        /** remove an existent child node

            If the object represents a set node, this method may be used to delete an existent child. For non-set-nodes,
            the method will fail.
        */
        sal_Bool            removeNode(const ::rtl::OUString& _rName) const throw();

        /** retrieves the content of a descendant

            the returned value may contain anything from an interface (if <arg>_rPath</arg> refers to inner node of
            the configuration tree) to any explicit value (e.g. string, integer) or even void.

            Unfortunately, this implies that if a void value is returned, you won't have a clue if this means
            "the path does not exist" (besides the assertion made :), or if the value is really void.
        */
        ::com::sun::star::uno::Any
                            getNodeValue(const ::rtl::OUString& _rPath) const throw();

        /** write a node value

            The value given is written into the node specified by the given relative path.

            In opposite to <method>getNodeValue</method>, _rName must refer to a leaf in the configuration tree, not an inner
            node.
            @return     sal_True if and only if the write was successfull.
        */
        sal_Bool            setNodeValue(const ::rtl::OUString& _rPath, const ::com::sun::star::uno::Any& _rValue) const throw();

        /// return the names of the existing children
        ::com::sun::star::uno::Sequence< ::rtl::OUString >
                            getNodeNames() const throw();

        /** enables or disables name escaping when accessing direct children

            Escaping is disabled by default, usually you enable it for set nodes (e.g. with calling setEscape(isSetNode)).
            Once escaping is enabled, you should not access indirect children (e.g. openNode("child/grandchild"), 'cause
            escaping for such names may not be supported by the underlying API objects.
            @see getEscape
        */
        void        setEscape(sal_Bool _bEnable = sal_True);
        /** get the flag specifying the current escape behaviour
            @see setEscape
        */
        sal_Bool    getEscape() const { return m_bEscapeNames; }

        /** clone the object, creating a new hierarchy where the root represents the same node as the object
            where this method is called does.

            The new hierarchy does not share any updates with the one the object is a part of, i.e. any changes made
            in the existing hierarchy are not visible to the newly created one until committed (and vice versa).
            @param      _rRoot      out parameter. upon return, contains the object representing the root of the new hierarchy.
        */
        OConfigurationTreeRoot cloneAsRoot() const throw();

        /// invalidate the object
        virtual void clear() throw();

    // -----------------------
    // meta informations about the node
        /// checks whether or not the object represents a set node.
        sal_Bool isSetNode() const;
        /// checks whether or not a direct child with a given name exists
        sal_Bool hasByName(const ::rtl::OUString& _rName) const throw();
        /// checks whether or not a descendent (no matter if direct or indirect) with the given name exists
        sal_Bool hasByHierarchicalName( const ::rtl::OUString& _rName ) const throw();
        /// check if the objects represents a valid configuration node
        sal_Bool isValid() const { return m_xHierarchyAccess.is(); }
        /// check whether the object is read-only of updatable
        sal_Bool isReadonly() const { return !m_xReplaceAccess.is(); }

    protected:
        // OEventListenerAdapter
        virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource );

    protected:
        enum NAMEORIGIN
        {
            NO_CONFIGURATION,       /// the name came from a configuration node
            NO_CALLER               /// the name came from a client of this class
        };
        ::rtl::OUString normalizeName(const ::rtl::OUString& _rName, NAMEORIGIN _eOrigin) const;
    };

    //========================================================================
    //= OConfigurationTreeRoot
    //========================================================================
    /** a specialized version of a OConfigurationNode, representing the root
        of a configuration sub tree

        Only this class is able to commit any changes made any any OConfigurationNode
        objects.
    */
    class UNOTOOLS_DLLPUBLIC OConfigurationTreeRoot : public OConfigurationNode
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::util::XChangesBatch >
                                m_xCommitter;
    protected:
        /** ctor

        */
        OConfigurationTreeRoot(
            const ::com::sun::star::uno::Reference< ::com::sun::star::util::XChangesBatch >& _rxRootNode,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxProvider);

        /** ctor for a readonly node
        */
        OConfigurationTreeRoot(
            const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxRootNode,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxProvider);

    public:
        /// modes to used when creating a top-level node object
        enum CREATION_MODE
        {
            CM_READONLY,            /// open the node (i.e. sub tree) for read access only
            CM_UPDATABLE,           /// open the node (i.e. sub tree) for read and write access
            CM_PREFER_UPDATABLE     /// open the node (i.e. sub tree) for read and write access, if this fails, open it for read acces
        };

    public:
        /** default ctor

            The object constructed here is invalid (i.e. <method>isValid</method> will return sal_False).
        */
        OConfigurationTreeRoot() :OConfigurationNode() { }

        /// copy ctor
        OConfigurationTreeRoot(const OConfigurationTreeRoot& _rSource)
            :OConfigurationNode(_rSource), m_xCommitter(_rSource.m_xCommitter) { }

        /** open a new top-level configuration node

            opens a new node which is the root if an own configuration sub tree. This is what "top level" means: The
            node does not have a parent. It does not mean that the node represents a module tree (like org.openoffice.Office.Writer
            or such).

            In opposite to <method>createWithServiceFactory</method>, createWithProvider expects a configuration provider
            to work with.
            @see    createWithServiceFactory
            @param      _rxConfProvider configuration provider to use when retrieving the node.
            @param      _rPath          path to the node the object should represent
            @param      _nDepth         depth for node retrieval
            @param      _eMode          specifies which privileges should be applied when retrieving the node
        */
        static OConfigurationTreeRoot createWithProvider(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxConfProvider,
            const ::rtl::OUString& _rPath, sal_Int32 _nDepth = -1, CREATION_MODE _eMode = CM_PREFER_UPDATABLE, sal_Bool _bLazyWrite = sal_True);

        /** open a new top-level configuration node

            opens a new node which is the root if an own configuration sub tree. This is what "top level" means: The
            node does not have a parent. It does not mean that the node represents a module tree (like org.openoffice.Office.Writer
            or such).

            In opposite to <method>createWithProvider</method>, createWithProvider expects a service factory. This factory
            is used to create a configuration provider, and this provider is used to retrieve the node
            @see    createWithProvider
            @param      _rxORB          service factory to use to create the configuration provider.
            @param      _rPath          path to the node the object should represent
            @param      _nDepth         depth for node retrieval
            @param      _eMode          specifies which privileges should be applied when retrieving the node
        */
        static OConfigurationTreeRoot createWithServiceFactory(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
            const ::rtl::OUString& _rPath, sal_Int32 _nDepth = -1, CREATION_MODE _eMode = CM_PREFER_UPDATABLE, sal_Bool _bLazyWrite = sal_True);

        /** tolerant version of the <member>createWithServiceFactory</member>

No assertions are thrown in case of an failure to initialize the configuration service, but once
            the configuration could be initialized, errors in the creation of the specific node (e.g. because the
            given node path does not exist) are still asserted.

        */
        static OConfigurationTreeRoot tryCreateWithServiceFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,
            const ::rtl::OUString& _rPath, sal_Int32 _nDepth = -1, CREATION_MODE _eMode = CM_PREFER_UPDATABLE, sal_Bool _bLazyWrite = sal_True );

        /** commit all changes made on the subtree the object is the root for

            All changes made on any <type>OConfigurationNode</type> object retrieved (maybe indirect) from this root
            object are committed when calling this method.
            @return     sal_True if and only if the commit was successfull
        */
        sal_Bool commit() const throw();

        /// invalidate the object
        virtual void clear() throw();
    };

//........................................................................
}   // namespace utl
//........................................................................

#endif // _UNOTOOLS_CONFIGNODE_HXX_

<|endoftext|>


<commit_before>#include "config.h"
#include <phosphor-logging/elog.hpp>

namespace phosphor
{
namespace logging
{

void commit(std::string&& e)
{
    constexpr auto MAPPER_BUSNAME = "xyz.openbmc_project.ObjectMapper";
    constexpr auto MAPPER_PATH = "/xyz/openbmc_project/ObjectMapper";
    constexpr auto MAPPER_INTERFACE = "xyz.openbmc_project.ObjectMapper";

    constexpr auto IFACE_INTERNAL("xyz.openbmc_project.Logging.Internal.Manager");

    // Transaction id is located at the end of the string separated by a period.

    auto b = sdbusplus::bus::new_default();
    auto mapper = b.new_method_call(
            MAPPER_BUSNAME,
            MAPPER_PATH,
            MAPPER_INTERFACE,
            "GetObject");
    mapper.append(OBJ_INTERNAL, std::vector<std::string>({IFACE_INTERNAL}));

    auto mapperResponseMsg = b.call(mapper);
    if (mapperResponseMsg.is_method_error())
    {
        log<level::ERR>("Error in mapper call");
        return;
    }

    std::map<std::string, std::vector<std::string>> mapperResponse;
    mapperResponseMsg.read(mapperResponse);
    if (mapperResponse.empty())
    {
        log<level::ERR>("Error reading mapper response");
        return;
    }

    const auto& host = mapperResponse.cbegin()->first;
    auto m = b.new_method_call(
            host.c_str(),
            OBJ_INTERNAL,
            IFACE_INTERNAL,
            "Commit");
    uint64_t id = sdbusplus::server::transaction::get_id();
    m.append(id, std::forward<std::string>(e));
    b.call_noreply(m);
}

} // namespace logging
} // namespace phosphor

<commit_msg>Move object_mapper per dbus path conventions.<commit_after>#include "config.h"
#include <phosphor-logging/elog.hpp>

namespace phosphor
{
namespace logging
{

void commit(std::string&& e)
{
    constexpr auto MAPPER_BUSNAME = "xyz.openbmc_project.ObjectMapper";
    constexpr auto MAPPER_PATH = "/xyz/openbmc_project/object_mapper";
    constexpr auto MAPPER_INTERFACE = "xyz.openbmc_project.ObjectMapper";

    constexpr auto IFACE_INTERNAL("xyz.openbmc_project.Logging.Internal.Manager");

    // Transaction id is located at the end of the string separated by a period.

    auto b = sdbusplus::bus::new_default();
    auto mapper = b.new_method_call(
            MAPPER_BUSNAME,
            MAPPER_PATH,
            MAPPER_INTERFACE,
            "GetObject");
    mapper.append(OBJ_INTERNAL, std::vector<std::string>({IFACE_INTERNAL}));

    auto mapperResponseMsg = b.call(mapper);
    if (mapperResponseMsg.is_method_error())
    {
        log<level::ERR>("Error in mapper call");
        return;
    }

    std::map<std::string, std::vector<std::string>> mapperResponse;
    mapperResponseMsg.read(mapperResponse);
    if (mapperResponse.empty())
    {
        log<level::ERR>("Error reading mapper response");
        return;
    }

    const auto& host = mapperResponse.cbegin()->first;
    auto m = b.new_method_call(
            host.c_str(),
            OBJ_INTERNAL,
            IFACE_INTERNAL,
            "Commit");
    uint64_t id = sdbusplus::server::transaction::get_id();
    m.append(id, std::forward<std::string>(e));
    b.call_noreply(m);
}

} // namespace logging
} // namespace phosphor

<|endoftext|>


<commit_before>/*
    main.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB

    Kleopatra is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Kleopatra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <config-kleopatra.h>

#include "aboutdata.h"
#include "kleopatraapplication.h"
#include "mainwindow.h"

#include <commands/reloadkeyscommand.h>
#include <commands/selftestcommand.h>

#include <utils/gnupg-helper.h>

#ifdef HAVE_USABLE_ASSUAN
# include <uiserver/uiserver.h>
# include <uiserver/assuancommand.h>
# include <uiserver/echocommand.h>
# include <uiserver/decryptcommand.h>
# include <uiserver/verifycommand.h>
# include <uiserver/decryptverifyfilescommand.h>
# include <uiserver/decryptfilescommand.h>
# include <uiserver/verifyfilescommand.h>
# include <uiserver/prepencryptcommand.h>
# include <uiserver/encryptcommand.h>
# include <uiserver/signcommand.h>
# include <uiserver/signencryptfilescommand.h>
# include <uiserver/selectcertificatecommand.h>
#else
namespace Kleo {
    class UiServer;
}
#endif

#include <kcmdlineargs.h>
#include <klocale.h>
#include <kiconloader.h>
#include <ksplashscreen.h>
#include <KDebug>

#include <QTextDocument> // for Qt::escape
#include <QStringList>
#include <QMessageBox>
#include <QTimer>
#include <QEventLoop>
#include <QThreadPool>

#include <boost/shared_ptr.hpp>

#include <cassert>

using namespace boost;

namespace {
    template <typename T>
    boost::shared_ptr<T> make_shared_ptr( T * t ) {
        return t ? boost::shared_ptr<T>( t ) : boost::shared_ptr<T>() ;
    }
}

static bool selfCheck( KSplashScreen & splash ) {
    splash.showMessage( i18n("Performing Self-Check...") );
    Kleo::Commands::SelfTestCommand cmd( 0 );
    cmd.setAutoDelete( false );
    cmd.setAutomaticMode( true );
    cmd.setSplashScreen( &splash );
    QEventLoop loop;
    QObject::connect( &cmd, SIGNAL(finished()), &loop, SLOT(quit()) );
    QObject::connect( &cmd, SIGNAL(info(QString)), &splash, SLOT(showMessage(QString)) );
    QTimer::singleShot( 0, &cmd, SLOT(start()) ); // start() may emit finished()...
    loop.exec();
    if ( cmd.isCanceled() ) {
        splash.showMessage( i18nc("didn't pass", "Self-Check Failed") );
        return false;
    } else {
        splash.showMessage( i18n("Self-Check Passed") );
        return true;
    }
}

static void fillKeyCache( KSplashScreen * splash, Kleo::UiServer * server ) {

  QEventLoop loop;
  Kleo::ReloadKeysCommand * cmd = new Kleo::ReloadKeysCommand( 0 );
  QObject::connect( cmd, SIGNAL(finished()), &loop, SLOT(quit()) );
#ifdef HAVE_USABLE_ASSUAN
  QObject::connect( cmd, SIGNAL(finished()), server, SLOT(enableCryptoCommands()) );
#else
  Q_UNUSED( server );
#endif
  splash->showMessage( i18n("Loading certificate cache...") );
  cmd->start();
  loop.exec();
  splash->showMessage( i18n("Certificate cache loaded.") );
}

int main( int argc, char** argv )
{
  {
      const unsigned int threads = QThreadPool::globalInstance()->maxThreadCount();
      QThreadPool::globalInstance()->setMaxThreadCount( qMin( 2U, threads ) );
  }

  AboutData aboutData;

  KCmdLineArgs::init(argc, argv, &aboutData);

  KCmdLineArgs::addCmdLineOptions( KleopatraApplication::commandLineOptions() );

  KleopatraApplication app;

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  KSplashScreen splash( UserIcon( "kleopatra_splashscreen" ), Qt::WindowStaysOnTopHint );

  int rc;
#ifdef HAVE_USABLE_ASSUAN
  try {
      Kleo::UiServer server( args->getOption("uiserver-socket") );

      QObject::connect( &server, SIGNAL(startKeyManagerRequested()),
                        &app, SLOT(openOrRaiseMainWindow()) );

#define REGISTER( Command ) server.registerCommandFactory( boost::shared_ptr<Kleo::AssuanCommandFactory>( new Kleo::GenericAssuanCommandFactory<Kleo::Command> ) )
      REGISTER( DecryptCommand );
      REGISTER( DecryptFilesCommand );
      REGISTER( DecryptVerifyFilesCommand );
      REGISTER( EchoCommand );
      REGISTER( EncryptCommand );
      REGISTER( EncryptFilesCommand );
      REGISTER( EncryptSignFilesCommand );
      REGISTER( PrepEncryptCommand );
      REGISTER( SelectCertificateCommand );
      REGISTER( SignCommand );
      REGISTER( SignEncryptFilesCommand );
      REGISTER( SignFilesCommand );
      REGISTER( VerifyCommand );
      REGISTER( VerifyFilesCommand );
#undef REGISTER

      server.start();
#endif

      const bool daemon = args->isSet("daemon");

      if ( !daemon )
          splash.show();
      if ( !selfCheck( splash ) )
          return 1;
#ifdef HAVE_USABLE_ASSUAN
      fillKeyCache( &splash, &server );
#else
      fillKeyCache( &splash, 0 );
#endif

      app.setIgnoreNewInstance( false );

      if ( !daemon ) {
          app.newInstance();
          splash.finish( app.mainWindow() );
      }

      rc = app.exec();

#ifdef HAVE_USABLE_ASSUAN
      app.setIgnoreNewInstance( true );
      QObject::disconnect( &server, SIGNAL(startKeyManagerRequested()),
                           &app, SLOT(openOrRaiseMainWindow()) );

      server.stop();
      server.waitForStopped();
  } catch ( const std::exception & e ) {
      QMessageBox::information( 0, i18n("GPG UI Server Error"),
                                i18n("<qt>The Kleopatra GPG UI Server Module couldn't be initialized.
"
                                     "The error given was: %1
"
                                     "You can use Kleopatra as a certificate manager, but cryptographic plugins that "
                                     "rely on a GPG UI Server being present might not work correctly, or at all.</qt>",
                                     Qt::escape( QString::fromUtf8( e.what() ) ) ));
      app.setIgnoreNewInstance( false );
      rc = app.exec();
      app.setIgnoreNewInstance( true );
  }
#endif

    return rc;
}
<commit_msg>argh<commit_after>/*
    main.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB

    Kleopatra is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Kleopatra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <config-kleopatra.h>

#include "aboutdata.h"
#include "kleopatraapplication.h"
#include "mainwindow.h"

#include <commands/reloadkeyscommand.h>
#include <commands/selftestcommand.h>

#include <utils/gnupg-helper.h>

#ifdef HAVE_USABLE_ASSUAN
# include <uiserver/uiserver.h>
# include <uiserver/assuancommand.h>
# include <uiserver/echocommand.h>
# include <uiserver/decryptcommand.h>
# include <uiserver/verifycommand.h>
# include <uiserver/decryptverifyfilescommand.h>
# include <uiserver/decryptfilescommand.h>
# include <uiserver/verifyfilescommand.h>
# include <uiserver/prepencryptcommand.h>
# include <uiserver/encryptcommand.h>
# include <uiserver/signcommand.h>
# include <uiserver/signencryptfilescommand.h>
# include <uiserver/selectcertificatecommand.h>
#else
namespace Kleo {
    class UiServer;
}
#endif

#include <kcmdlineargs.h>
#include <klocale.h>
#include <kiconloader.h>
#include <ksplashscreen.h>
#include <KDebug>

#include <QTextDocument> // for Qt::escape
#include <QStringList>
#include <QMessageBox>
#include <QTimer>
#include <QEventLoop>
#include <QThreadPool>

#include <boost/shared_ptr.hpp>

#include <cassert>

using namespace boost;

namespace {
    template <typename T>
    boost::shared_ptr<T> make_shared_ptr( T * t ) {
        return t ? boost::shared_ptr<T>( t ) : boost::shared_ptr<T>() ;
    }
}

static bool selfCheck( KSplashScreen & splash ) {
    splash.showMessage( i18n("Performing Self-Check...") );
    Kleo::Commands::SelfTestCommand cmd( 0 );
    cmd.setAutoDelete( false );
    cmd.setAutomaticMode( true );
    cmd.setSplashScreen( &splash );
    QEventLoop loop;
    QObject::connect( &cmd, SIGNAL(finished()), &loop, SLOT(quit()) );
    QObject::connect( &cmd, SIGNAL(info(QString)), &splash, SLOT(showMessage(QString)) );
    QTimer::singleShot( 0, &cmd, SLOT(start()) ); // start() may emit finished()...
    loop.exec();
    if ( cmd.isCanceled() ) {
        splash.showMessage( i18nc("didn't pass", "Self-Check Failed") );
        return false;
    } else {
        splash.showMessage( i18n("Self-Check Passed") );
        return true;
    }
}

static void fillKeyCache( KSplashScreen * splash, Kleo::UiServer * server ) {

  QEventLoop loop;
  Kleo::ReloadKeysCommand * cmd = new Kleo::ReloadKeysCommand( 0 );
  QObject::connect( cmd, SIGNAL(finished()), &loop, SLOT(quit()) );
#ifdef HAVE_USABLE_ASSUAN
  QObject::connect( cmd, SIGNAL(finished()), server, SLOT(enableCryptoCommands()) );
#else
  Q_UNUSED( server );
#endif
  splash->showMessage( i18n("Loading certificate cache...") );
  cmd->start();
  loop.exec();
  splash->showMessage( i18n("Certificate cache loaded.") );
}

int main( int argc, char** argv )
{
  {
      const unsigned int threads = QThreadPool::globalInstance()->maxThreadCount();
      QThreadPool::globalInstance()->setMaxThreadCount( qMax( 2U, threads ) );
  }

  AboutData aboutData;

  KCmdLineArgs::init(argc, argv, &aboutData);

  KCmdLineArgs::addCmdLineOptions( KleopatraApplication::commandLineOptions() );

  KleopatraApplication app;

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  KSplashScreen splash( UserIcon( "kleopatra_splashscreen" ), Qt::WindowStaysOnTopHint );

  int rc;
#ifdef HAVE_USABLE_ASSUAN
  try {
      Kleo::UiServer server( args->getOption("uiserver-socket") );

      QObject::connect( &server, SIGNAL(startKeyManagerRequested()),
                        &app, SLOT(openOrRaiseMainWindow()) );

#define REGISTER( Command ) server.registerCommandFactory( boost::shared_ptr<Kleo::AssuanCommandFactory>( new Kleo::GenericAssuanCommandFactory<Kleo::Command> ) )
      REGISTER( DecryptCommand );
      REGISTER( DecryptFilesCommand );
      REGISTER( DecryptVerifyFilesCommand );
      REGISTER( EchoCommand );
      REGISTER( EncryptCommand );
      REGISTER( EncryptFilesCommand );
      REGISTER( EncryptSignFilesCommand );
      REGISTER( PrepEncryptCommand );
      REGISTER( SelectCertificateCommand );
      REGISTER( SignCommand );
      REGISTER( SignEncryptFilesCommand );
      REGISTER( SignFilesCommand );
      REGISTER( VerifyCommand );
      REGISTER( VerifyFilesCommand );
#undef REGISTER

      server.start();
#endif

      const bool daemon = args->isSet("daemon");

      if ( !daemon )
          splash.show();
      if ( !selfCheck( splash ) )
          return 1;
#ifdef HAVE_USABLE_ASSUAN
      fillKeyCache( &splash, &server );
#else
      fillKeyCache( &splash, 0 );
#endif

      app.setIgnoreNewInstance( false );

      if ( !daemon ) {
          app.newInstance();
          splash.finish( app.mainWindow() );
      }

      rc = app.exec();

#ifdef HAVE_USABLE_ASSUAN
      app.setIgnoreNewInstance( true );
      QObject::disconnect( &server, SIGNAL(startKeyManagerRequested()),
                           &app, SLOT(openOrRaiseMainWindow()) );

      server.stop();
      server.waitForStopped();
  } catch ( const std::exception & e ) {
      QMessageBox::information( 0, i18n("GPG UI Server Error"),
                                i18n("<qt>The Kleopatra GPG UI Server Module couldn't be initialized.
"
                                     "The error given was: %1
"
                                     "You can use Kleopatra as a certificate manager, but cryptographic plugins that "
                                     "rely on a GPG UI Server being present might not work correctly, or at all.</qt>",
                                     Qt::escape( QString::fromUtf8( e.what() ) ) ));
      app.setIgnoreNewInstance( false );
      rc = app.exec();
      app.setIgnoreNewInstance( true );
  }
#endif

    return rc;
}
<|endoftext|>